Giter VIP home page Giter VIP logo

human-activity-recognition-using-cnn's Introduction

CNN for Human Activity Recognition

Python notebook for blog post Implementing a CNN for Human Activity Recognition in Tensorflow.

Tools Required

Python 2.7 is used during development and following libraries are required to run the code provided in the notebook:

  • Tensorflow
  • Numpy
  • Matplotlib
  • Pandas

Dataset

The WISDM Actitracker dataset used for model training, can be downloaded from the following [link]

Related Problem

User identification from walking activity. Accelerometer dataset from 22 indivduals can be downloaded from the following [link]

human-activity-recognition-using-cnn's People

Contributors

aaqibsaeed avatar aqibsaeed avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

human-activity-recognition-using-cnn's Issues

change the name

Also please change the name, because there is few android app that serves for tensorflow model, specially as you are not working in the image,

because I couldnt find your page by searching github I faced with that in your webpage

org.tensorflow.TensorFlowException: Op type not registered 'NonMaxSuppressionV3' in binary running on localhost. Make sure the Op and Kernel are registered in the binary running in this process.

What did you do to register your Op types?
I am working with a model that is already frozen but when I initialize it in my android activity I get the TensorFlowException.
Did you make extra steps?
Thanks in advance.

This can not be considered as issue but since I did not find any other place I could contact you I am writing you here.

file does not exist in

when I am opening your program in android studio says:
It runs without error now, but the page does not show in the emulator

ActivityRecognition has stopped

may please check to see every thing being uploaded correctly

The code runs for too long ?

dataset['z-axis'] = feature_normalize(dataset['z-axis'])

The code run for a very long time, and did not output yet. I used debug found out that this line of code dataset['z-axis'] = feature_normalize(dataset['z-axis']) might be to blamed.

Is that normal? should I wait a little longer, or there were something wrong with that code?

Tensor Shape Issue

Can you help me to solve this error.?
2018-04-10 11:53:45.778484: I C:\tf_jenkins\workspace\rel-win\M\windows\PY\36\tensorflow\core\platform\cpu_feature_guard.cc:140] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
Traceback (most recent call last):
File "D:/Sardar.Khan/Courses/TensorFlow Course/Building and Deploy Deep Learning/Ex_Files_TensorFlow/Exercise Files/03/Model/main.py", line 195, in
_, c = session.run([optimizer, loss], feed_dict={X: batch_x, Y: batch_y})
File "D:\Sardar.Khan\Courses\TensorFlow Course\Building and Deploy Deep Learning\Ex_Files_TensorFlow\Exercise Files\venv\lib\site-packages\tensorflow\python\client\session.py", line 905, in run
run_metadata_ptr)
File "D:\Sardar.Khan\Courses\TensorFlow Course\Building and Deploy Deep Learning\Ex_Files_TensorFlow\Exercise Files\venv\lib\site-packages\tensorflow\python\client\session.py", line 1113, in _run
str(subfeed_t.get_shape())))
ValueError: Cannot feed value of shape (10, 1) for Tensor 'Placeholder_1:0', which has shape '(?, 6)'

Process finished with exit code 1
at this line..
_, c = session.run([optimizer, loss], feed_dict={X: batch_x, Y: batch_y})

with tf.Session() as session:
session.run(tf.global_variables_initializer())
for epoch in range(training_epochs):
for b in range(total_batches):
offset = (b * batch_size) % (train_y.shape[0] - batch_size)
batch_x = train_x[offset:(offset + batch_size), :, :, :]
batch_y = train_y[offset:(offset + batch_size), :]
_, c = session.run([optimizer, loss], feed_dict={X: batch_x, Y: batch_y})
cost_history = np.append(cost_history, c)
print("Epoch: ", epoch, " Training Loss: ",c, " Training Accuracy: ",session.run(accuracy, feed_dict={X: train_x, Y: train_y}))
print("Testing Accuracy:", session.run(accuracy, feed_dict={X: test_x, Y: test_y}))

@aqibsaeed I follow your tutorial but its shows the error is there any thing i am missing.?

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
import tensorflow as tf

def read_data(file_path):
    column_names = ['user-id', 'activity', 'timestamp', 'x-axis', 'y-axis', 'z-axis']
    data = pd.read_csv(file_path, header=None, names=column_names)
    return data


def feature_normalize(dataset):
    mu = np.mean(dataset, axis=0)
    sigma = np.std(dataset, axis=0)
    return (dataset - mu) / sigma


def plot_axis(ax, x, y, title):
    ax.plot(x, y)
    ax.set_title(title)
    ax.xaxis.set_visible(False)
    ax.set_ylim([min(y) - np.std(y), max(y) + np.std(y)])
    ax.set_xlim([min(x), max(x)])
    ax.grid(True)


def plot_activity(activity, data):
    fig, (ax0, ax1, ax2) = plt.subplots(nrows=3, figsize=(15, 10), sharex=True)
    plot_axis(ax0, data['timestamp'], data['x-axis'], 'x-axis')
    plot_axis(ax1, data['timestamp'], data['y-axis'], 'y-axis')
    plot_axis(ax2, data['timestamp'], data['z-axis'], 'z-axis')
    plt.subplots_adjust(hspace=0.2)
    fig.suptitle(activity)
    plt.subplots_adjust(top=0.90)
    plt.show()


def windows(data, size):
    start = 0
    while start < data.count():
        yield int(start), int(start + size)
        start += (size / 2)


def segment_signal(data, window_size=90):
    segments = np.empty((0, window_size, 3))
    labels = np.empty((0))
    for (start, end) in windows(data['timestamp'], window_size):
        x = data["x-axis"][start:end]
        y = data["y-axis"][start:end]
        z = data["z-axis"][start:end]
        if (len(dataset['timestamp'][start:end]) == window_size):
            segments = np.vstack([segments, np.dstack([x, y, z])])
            labels = np.append(labels, stats.mode(data["activity"][start:end])[0][0])
    return segments, labels


def weight_variable(shape):
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)


def bias_variable(shape):
    initial = tf.constant(0.0, shape=shape)
    return tf.Variable(initial)


def depthwise_conv2d(x, W):
    return tf.nn.depthwise_conv2d(x, W, [1, 1, 1, 1], padding='VALID')


def apply_depthwise_conv(x, kernel_size, num_channels, depth):
    weights = weight_variable([1, kernel_size, num_channels, depth])
    biases = bias_variable([depth * num_channels])
    return tf.nn.relu(tf.add(depthwise_conv2d(x, weights), biases))


def apply_max_pool(x, kernel_size, stride_size):
    return tf.nn.max_pool(x, ksize=[1, 1, kernel_size, 1],
                          strides=[1, 1, stride_size, 1], padding='VALID')

    plt.style.use('ggplot')



 dataset = read_data('WISDM_at_v2.0_raw.txt')


dataset['x-axis'] = feature_normalize(dataset['x-axis'])
dataset['y-axis'] = feature_normalize(dataset['y-axis'])
dataset['z-axis'] = feature_normalize(dataset['z-axis'])

unique_activities = pd.unique(dataset["activity"])

for activity in unique_activities[:6]:
    subset = dataset[dataset["activity"] == activity][:180]
#   plot_activity(activity,subset)

segments, labels = segment_signal(dataset)
labels = np.asarray(pd.get_dummies(labels), dtype=np.int8)

reshaped_segments = segments.reshape(len(segments), 1, 90, 3)

train_test_split = np.random.rand(len(reshaped_segments)) < 0.70
train_x = reshaped_segments[train_test_split]
train_y = labels[train_test_split]
test_x = reshaped_segments[~train_test_split]
test_y = labels[~train_test_split]

input_height = 1
input_width = 90
num_labels = 6
num_channels = 3

batch_size = 10
kernel_size = 60
depth = 60
num_hidden = 1000

learning_rate = 0.0001
training_epochs = 8

total_batches = train_x.shape[0] // batch_size



X = tf.placeholder(tf.float32, shape=[None, input_height, input_width, num_channels])
Y = tf.placeholder(tf.float32, shape=[None, num_labels])

c = apply_depthwise_conv(X, kernel_size, num_channels, depth)
p = apply_max_pool(c, 20, 2)

c = apply_depthwise_conv(p, 6, depth * num_channels, depth // 10)


shape = c.get_shape().as_list()
c_flat = tf.reshape(c, [-1, shape[1] * shape[2] * shape[3]])

f_weights_l1 = weight_variable([shape[1] * shape[2] * depth * num_channels * (depth // 10), num_hidden])
f_biases_l1 = bias_variable([num_hidden])
f = tf.nn.tanh(tf.add(tf.matmul(c_flat, f_weights_l1), f_biases_l1))

out_weights = weight_variable([num_hidden, num_labels])
out_biases = bias_variable([num_labels])
y_ = tf.nn.softmax(tf.matmul(f, out_weights) + out_biases)

loss = -tf.reduce_sum(Y * tf.log(y_))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss)

correct_prediction = tf.equal(tf.argmax(y_, 1), tf.argmax(Y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

cost_history = np.empty(shape=[1], dtype=float)

with tf.Session() as session:
    session.run(tf.global_variables_initializer())
    for epoch in range(training_epochs):
        for b in range(total_batches):
            offset = (b * batch_size) % (train_y.shape[0] - batch_size)
            batch_x = train_x[offset:(offset + batch_size), :, :, :]
            batch_y = train_y[offset:(offset + batch_size), :]
            _, c = session.run([optimizer, loss], feed_dict={X: batch_x, Y: batch_y})
            cost_history = np.append(cost_history, c)
        print("Epoch: ", epoch, " Training Loss: ", c, " Training Accuracy: ",
              session.run(accuracy, feed_dict={X: train_x, Y: train_y}))
    print("Testing Accuracy:", session.run(accuracy, feed_dict={X: test_x, Y: test_y}))

Help!!!

Basically,i encounter two problem:
First,the instability , i run this very well and stable at around 90% ,but some groupmate and tutor run and stay and 5% or 30%
Secondly,i want to convert the numpy to gpu backend ,but meet more questions,cupy happen to be out of my gpu memory,and minpy results in data form incompatible
Can anyone help?thx

CNN part error with too many indices for array

Hello,

error

CNN part is giving an error
File "", line 8, in
batch_y = train_y[offset:(offset + batch_size), :]

IndexError: too many indices for array

follow up test, that has been done by me

print(X)
Tensor("Placeholder_2:0", shape=(?, 1, 90, 3), dtype=float32)

print(Y)
Tensor("Placeholder_3:0", shape=(?, 6), dtype=float32)

print(c_flat)
Tensor("Reshape_1:0", shape=(?, 1080), dtype=float32)

print(shape)
[None, 1, 1, 1080]

I have not changed your code at any point, as I'm in the learning and understanding the CNN.

It would be great if you could help me in this regard

thanks in advance for your valuable time

Loss is not decreasing

Hello!

I launched source code without changes.The loss had almost the same value during all epochs.

Epoch:  0  Training Loss:  10.845988  Training Accuracy:  0.054814555
Epoch:  1  Training Loss:  10.845994  Training Accuracy:  0.054814555
Epoch:  2  Training Loss:  10.845989  Training Accuracy:  0.054814555
Epoch:  3  Training Loss:  10.84598  Training Accuracy:  0.054814555
Epoch:  4  Training Loss:  10.845976  Training Accuracy:  0.054814555
Epoch:  5  Training Loss:  10.845982  Training Accuracy:  0.054814555
Epoch:  6  Training Loss:  10.845993  Training Accuracy:  0.054814555
Epoch:  7  Training Loss:  10.845982  Training Accuracy:  0.054814555
Testing Accuracy: 0.05404296

Tensorflow code does not work

I tried to follow the example as is, but get the following error.
ValueError Traceback (most recent call last)
in ()
8 batch_x = train_x[offset:(offset + batch_size), :, :, :]
9 batch_y = train_y[offset:(offset + batch_size), :]
---> 10 _, c = session.run([optimizer, loss],feed_dict={X: batch_x, Y : batch_y})
11 cost_history = np.append(cost_history,c)
12 print("Epoch: ",epoch," Training Loss: ",c," Training Accuracy: ",

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
875 try:
876 result = self._run(None, fetches, feed_dict, options_ptr,
--> 877 run_metadata_ptr)
878 if run_metadata:
879 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
1074 'which has shape %r' %
1075 (np_val.shape, subfeed_t.name,
-> 1076 str(subfeed_t.get_shape())))
1077 if not self.graph.is_feedable(subfeed_t):
1078 raise ValueError('Tensor %s may not be fed.' % subfeed_t)

ValueError: Cannot feed value of shape (10, 4) for Tensor 'Placeholder_1:0', which has shape '(?, 6)'

inaccurate

The results are very inaccurate, the probability of upstairs has been great, please confirm the code is correct

Source code for Deploying the model on Android

Hi @aqibsaeed,

I've read the tutorial here. I still don't get how to modify the code using these lines:

X = tf.placeholder(tf.float32, shape=[None,input_width * num_channels], name="input")
X_reshaped = tf.reshape(X,[-1,1,90,3]) 

Where and how should we use X_reshaped afterward? Are other changes required as well? Can you post the complete source code needed to train the model for the Android app?

Thanks!

when i run the code,there are some problems

Traceback (most recent call last):
File "D:\Anaconda\lib\site-packages\pandas\core\nanops.py", line 738, in _ensure_numeric
x = float(x)
ValueError: could not convert string to float: '0.503952860.95342433-0.081722093.02371727.205164
During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "D:\Anaconda\lib\site-packages\pandas\core\nanops.py", line 741, in _ensure_numeric
x = complex(x)
ValueError: complex() arg is a malformed string

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "D:\Anaconda\lib\site-packages\pandas\core\nanops.py", line 100, in f
result = alt(values, axis=axis, skipna=skipna, **kwds)
File "D:\Anaconda\lib\site-packages\pandas\core\nanops.py", line 293, in nanmean
the_sum = _ensure_numeric(values.sum(axis, dtype=dtype_sum))
File "D:\Anaconda\lib\site-packages\pandas\core\nanops.py", line 743, in _ensure_numeric
raise TypeError('Could not convert %s to numeric' % str(x))
TypeError: Could not convert 0.503952860.95342433-0.081722093.02371727.205164-6.5105265.7069267.05534035.
During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "D:\Anaconda\lib\site-packages\pandas\core\nanops.py", line 738, in _ensure_numeric
x = float(x)
ValueError: could not convert string to float: '0.503952860.95342433-0.08172209
During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "D:\Anaconda\lib\site-packages\pandas\core\nanops.py", line 741, in _ensure_numeric
x = complex(x)
ValueError: complex() arg is a malformed string

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "D:/Anaconda/network/.idea/wisdm.py", line 75, in
dataset['z-axis'] = feature_normalize(dataset['z-axis'])
File "D:/Anaconda/network/.idea/wisdm.py", line 13, in feature_normalize
mu = np.mean(dataset, axis=0)
File "D:\Anaconda\lib\site-packages\numpy\core\fromnumeric.py", line 2906, in mean
return mean(axis=axis, dtype=dtype, out=out, **kwargs)
File "D:\Anaconda\lib\site-packages\pandas\core\generic.py", line 5310, in stat_func
numeric_only=numeric_only)
File "D:\Anaconda\lib\site-packages\pandas\core\series.py", line 2245, in _reduce
return op(delegate, skipna=skipna, **kwds)
File "D:\Anaconda\lib\site-packages\pandas\core\nanops.py", line 44, in _f
return f(*args, **kwargs)
File "D:\Anaconda\lib\site-packages\pandas\core\nanops.py", line 103, in f
result = alt(values, axis=axis, skipna=skipna, **kwds)
File "D:\Anaconda\lib\site-packages\pandas\core\nanops.py", line 293, in nanmean
the_sum = _ensure_numeric(values.sum(axis, dtype=dtype_sum))
File "D:\Anaconda\lib\site-packages\pandas\core\nanops.py", line 743, in _ensure_numeric
raise TypeError('Could not convert %s to numeric' % str(x))
TypeError: Could not convert 0.503952860.95342433-0.081722093.02371727.205164; to numeric

Because the number is too large, I have omitted a part of the number. The above is an error prompt when I run the code. Thank you very much

Exported Model Issue in Android

After Exporting Model is use this code for export model.

save the graph

tf.train.write_graph(session.graph_def, '.',input_graph_path)
#save a checkpoint file
save_path = saver.save(session,checkpoint_path)
# show path of saved model
print("Model saved: {}".format(save_path))

input_saver_def_path = ""
input_binary = False
restore_op_name = "save/restore_all"
filename_tensor_name = "save/Const:0"

output_frozen_graph_name = 'frozen_'+MODEL_NAME+'.pb'

output_optimized_graph_name = 'optimized_'+MODEL_NAME+'.pb'

clear_devices = True

freeze_graph.freeze_graph(input_graph = input_graph_path, input_saver = "",
input_binary = False, input_checkpoint = checkpoint_path, output_node_names = "y_",
restore_op_name = "save/restore_all", filename_tensor_name = "save/Const:0",
output_graph = "frozen_har_khan.pb", clear_devices = True, initializer_nodes = "")

input_graph_def = tf.GraphDef()
with tf.gfile.Open("frozen_har_khan.pb",'rb') as f:
input_graph_def.ParseFromString(f.read())

output_graph_def = optimize_for_inference_lib.optimize_for_inference(
input_graph_def,
["input"],
["y_"],
tf.float32.as_datatype_enum)

with tf.gfile.FastGFile("optimized_har_khan.pb", "wb") as f:
f.write(output_graph_def.SerializeToString())

print("Graph Saved")

After sucessfully export the model i place the model in assets folder of android studio and
this error occured..

FATAL EXCEPTION: main
Process: io.github.aqibsaeed.activityrecognition, PID: 14407
java.lang.RuntimeException: Unable to start activity ComponentInfo{io.github.aqibsaeed.activityrecognition/io.github.aqibsaeed.activityrecognition.MainActivity}: java.lang.RuntimeException: Failed to load model from 'file:///android_asset/optimized_har_khan.pb'
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.RuntimeException: Failed to load model from 'file:///android_asset/optimized_har_khan.pb'
at org.tensorflow.contrib.android.TensorFlowInferenceInterface.(TensorFlowInferenceInterface.java:100)
at io.github.aqibsaeed.activityrecognition.ActivityInference.(ActivityInference.java:35)
at io.github.aqibsaeed.activityrecognition.MainActivity.onCreate(MainActivity.java:53)
at android.app.Activity.performCreate(Activity.java:6251)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Caused by: java.io.IOException: Not a valid TensorFlow Graph serialization: NodeDef mentions attr 'dilations' not in Op<name=DepthwiseConv2dNative; signature=input:T, filter:T -> output:T; attr=T:type,allowed=[DT_FLOAT, DT_DOUBLE]; attr=strides:list(int); attr=padding:string,allowed=["SAME", "VALID"]; attr=data_format:string,default="NHWC",allowed=["NHWC", "NCHW"]>; NodeDef: depthwise = DepthwiseConv2dNative[T=DT_FLOAT, data_format="NHWC", dilations=[1, 1, 1, 1], padding="VALID", strides=[1, 1, 1, 1]](input, Variable). (Check whether your GraphDef-interpreting binary is up to date with your GraphDef-generating binary.).
at org.tensorflow.contrib.android.TensorFlowInferenceInterface.loadGraph(TensorFlowInferenceInterface.java:392)
at org.tensorflow.contrib.android.TensorFlowInferenceInterface.(TensorFlowInferenceInterface.java:96)
at io.github.aqibsaeed.activityrecognition.ActivityInference.(ActivityInference.java:35) 
at io.github.aqibsaeed.activityrecognition.MainActivity.onCreate(MainActivity.java:53) 
at android.app.Activity.performCreate(Activity.java:6251) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 

Kindly Check this. Thanks

name is not in subgraph

hi and thanks for your code,
when I am freezing it all the times raises an error that
extract_sub_graph
assert d in name_to_node_map, "%s is not in graph" % d
AssertionError: predictions is not in graph,

do you have any idea of this

Problem freezing the model.

2018-04-05 10:00:50.604122: I tensorflow/core/platform/cpu_feature_guard.cc:140] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
Converted 8 variables to const ops.
Traceback (most recent call last):
  File "/home/aawesh/PycharmProjects/Human-Activity-Recognition-using-CNN/Freeze.py", line 19, in <module>
    tf.float32.as_datatype_enum)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/tools/optimize_for_inference_lib.py", line 109, in optimize_for_inference
    placeholder_type_enum)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/tools/strip_unused_lib.py", line 83, in strip_unused
    raise KeyError("The following input nodes were not found: %s\n" % not_found)
KeyError: "The following input nodes were not found: set(['input'])\n"

Process finished with exit code 1

I got the above error. There is no name called "input" while training the model. But we are trying to use the name "input" while freezing. It is also used in android code. Could you please clarify?

Always UPSTAIRS

Hi,could you explain to me,why is the prediction always upstairs? What does it mean it was made for demonstration purposes? Have you used the model with low accuracy? I think i understand the code quite well so why it's not working properly.

Why is the phone showing the stairs info, I mean the phone has correct measurements,so where is the mistake?

I would be honored to receive your help.

The app can not run

Because we have no the file named "optimized_frozen_har.pb". I try to use your sample codes to create "optimized_frozen_har.pb" ,but failed.

After training

freeze_graph.freeze_graph(input_graph="../har.pbtxt", input_saver="",
input_binary=False, input_checkpoint="../har.ckpt", output_node_names="y_",
restore_op_name="save/restore_all", filename_tensor_name="save/Const:0",
output_graph="frozen_har.pb", clear_devices=True, initializer_nodes="")

output_frozen_graph_name='../har.pbtxt'
input_graph_def = tf.GraphDef()
with tf.gfile.Open(output_frozen_graph_name, "r") as f:
    data = f.read()
    input_graph_def.ParseFromString(data)

output_graph_def = optimize_for_inference_lib.optimize_for_inference(
    input_graph_def,
    ["input"],
    ["y_"],
    tf.float32.as_datatype_enum)

f = tf.gfile.FastGFile("optimized_frozen_har.pb", "w")
f.write(output_graph_def.SerializeToString())

I got a error "'y_', does not exist in the graph" .

Since it is not so easy to create the "optimized_frozen_har.pb", can you upload this file? Thanks.

normalizing raw data in the App

private void normalize()
{
float x_m = 0.662868f; float y_m = 7.255639f; float z_m = 0.411062f;
float x_s = 6.849058f; float y_s = 6.746204f; float z_s = 4.754109f;

Just curious, where did these values came from?(Min-Max values from the entire dataset?)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.