行人拿着手机,手机记录了行人行走时的加速度数据,本文从加速度数据中学习出行人行走的步长。训练数据的是经过步平滑滤波和步频探测提取出来的。x是[步频,加速度方差],y是[步长]。
import tensorflow as tf
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from R_my_datas_loader import load_data_tf
fn = r'C:\Users\hyl\Desktop\data_library\stepLength_study\3q_2.csv'
fm = r'C:\Users\hyl\Desktop\data_library\stepLength_study\1q_2.csv'
train = pd.read_csv(fn)
test = pd.read_csv(fm)
flag = 1
if flag: # 用频率和加速度方差数据
test_x,test_y = load_data_tf(test,1)
train = train[['frequence','var','StepLength']].values
num = 141
else: # 用频率差和加速度方差差数据
test_x,test_y = load_data_tf(test,0)
train = train[['df','dv','StepLength']].values
num = 140
batch_size = 47
n_batch = int(len(train)/batch_size)
X = tf.placeholder(tf.float32,[None,2])
Y = tf.placeholder(tf.float32,[None,1])
w = tf.Variable(tf.random_normal([2,10]))
b = tf.Variable(tf.zeros([10]))
z = tf.matmul(X,w)+b
L1 = tf.nn.tanh(z)
w2 = tf.Variable(tf.random_normal([10,1]))
b2 = tf.Variable(tf.zeros([1,1]))
z2 = tf.matmul(L1,w2)+b2
pre = tf.nn.tanh(z2)
loss = tf.reduce_mean(tf.square(Y-pre))
train_step = tf.train.GradientDescentOptimizer(0.05).minimize(loss)
# 结果存放在一个布尔型列表中
correct_prediction = tf.abs(Y - pre)
# 求准确率
accuracy = tf.reduce_mean(correct_prediction)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
# for _ in range(2000):
# sess.run(train_step,feed_dict={X:x,Y:y})
#
# predict_value = sess.run(pre,feed_dict={X:test_x})
# acc = sess.run(accuracy,feed_dict={X:test_x,Y:test_y}) # 测试精度
# print('Accuracy: '+str(acc))
for epoch in range(100):
np.random.shuffle(train)
tr_x,tr_y = train[:,:2],train[:,2].reshape((-1,1))
for batch in range(n_batch-1):
trd_i = tr_x[batch_size*batch:batch_size*(batch+1)]
trd_y_i = tr_y[batch_size*batch:batch_size*(batch+1)]
sess.run(train_step,feed_dict={X:trd_i,Y:trd_y_i})
predict_value = sess.run(pre,feed_dict={X:test_x})
acc = sess.run(accuracy,feed_dict={X:test_x,Y:test_y}) # 测试精度
print('Iter'+str(epoch)+',Accuracy: '+str(acc))
print('end')
plt.figure()
t = np.linspace(0,141,num)
plt.plot(t,test_y,t,predict_value)
plt.legend(['true','predicted'])
plt.show()
结果:
Iter90,Accuracy: 0.0462659
Iter91,Accuracy: 0.0463651
Iter92,Accuracy: 0.0461478
Iter93,Accuracy: 0.0461444
Iter94,Accuracy: 0.0461006
Iter95,Accuracy: 0.0461389
Iter96,Accuracy: 0.0462584
Iter97,Accuracy: 0.0461152
Iter98,Accuracy: 0.0459695
Iter99,Accuracy: 0.0460013
误差变化曲线:
平均误差:0.046米