深度学习之Tensorflow基础——基本开发步骤。
1、提到深度学习往往会让人想到人工智能,准确的讲深度学习是实现人工智能的一种方式。而TensorFlow是谷歌开源的一个深度学习框架。里面封装了多种实现神经网络家族的函数,可以把我们的想法快速的变现。同时TensorFlow也是目前最火的深度学习框架。TensorFlow是用c++语言开发的,支持c,python,java等多种语言。目前主流的开发语言是python。因其快速的开发效率被广大开发者青睐。
2、接下来我们将从一个简单的BP神经网络入手,逐渐展开讨论和认识神经网络家族。
第一步:准备数据。https://download.csdn.net/download/qq_36581957/10796906。这个是我用的数据集。数据分成训练数据(train.txt)和测试数据(test.txt),其中字段”V0”-“V37”,这38个字段是作为特征变量,”target”作为目标变量。选手利用训练数据训练出模型,预测测试数据的目标变量。下面是部分数据的截图。
V0 V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20 V21 V22 V23 V24 V25 V26 V27 V28 V29 V30 V31 V32 V33 V34 V35 V36 V37 target
0.566 0.016 -0.143 0.407 0.452 -0.901 -1.812 -2.36 -0.436 -2.114 -0.94 -0.307 -0.073 0.55 -0.484 0.0 -1.707 -1.162 -0.573 -0.991 0.61 -0.4 -0.063 0.356 0.8 -0.223 0.796 0.168 -0.45 0.136 0.109 -0.615 0.327 -4.627 -4.789 -5.101 -2.608 -3.508 0.175
0.968 0.437 0.066 0.566 0.194 -0.893 -1.566 -2.36 0.332 -2.114 0.188 -0.455 -0.134 1.109 -0.488 0.0 -0.977 -1.162 -0.571 -0.836 0.588 -0.802 -0.063 0.357 0.801 -0.144 1.057 0.338 0.671 -0.128 0.124 0.032 0.6 -0.843 0.16 0.364 -0.335 -0.73 0.676
1.013 0.568 0.235 0.37 0.112 -0.797 -1.367 -2.36 0.396 -2.114 0.874 -0.051 -0.072 0.767 -0.493 -0.212 -0.618 -0.897 -0.564 -0.558 0.576 -0.477 -0.063 0.355 0.961 -0.067 0.915 0.326 1.287 -0.009 0.361 0.277 -0.116 -0.843 0.16 0.364 0.765 -0.589 0.633
0.733 0.368 0.283 0.165 0.599 -0.679 -1.2 -2.086 0.403 -2.114 0.011 0.102 -0.014 0.769 -0.371 -0.162 -0.429 -0.897 -0.574 -0.564 0.272 -0.491 -0.063 0.352 1.435 0.113 0.898 0.277 1.298 0.015 0.417 0.279 0.603 -0.843 -0.065 0.364 0.333 -0.112 0.206
0.684 0.638 0.26 0.209 0.337 -0.454 -1.073 -2.086 0.314 -2.114 -0.251 0.57 0.199 -0.349 -0.342 -0.138 -0.391 -0.897 -0.572 -0.394 0.106 0.309 -0.259 0.352 0.881 0.221 0.386 0.332 1.289 0.183 1.078 0.328 0.418 -0.843 -0.215 0.364 -0.28 -0.028 0.384
0.445 0.627 0.408 0.22 0.458 -1.056 -1.009 -1.896 0.481 -2.114 -0.511 -0.564 0.294 0.912 -0.345 0.111 -0.333 -1.029 -0.573 -0.516 0.029 -0.56 -0.096 0.349 0.798 0.245 0.643 0.356 1.296 0.454 0.674 0.358 0.618 -0.843 -0.29 0.364 -0.191 -0.883 0.06
0.889 0.416 0.64 0.356 0.224 -0.893 -0.812 -1.823 0.729 -2.114 -0.256 -0.278 0.425 0.632 -0.3 0.111 -0.333 -1.428 -0.586 -0.544 0.156 -0.34 -0.063 0.352 0.801 0.389 0.5 0.401 2.15 0.454 0.081 0.243 0.468 -0.843 -0.29 0.364 -0.155 -1.318 0.415
0.984 0.529 0.704 0.438 0.258 -0.917 -0.682 -1.721 0.753 -2.114 -0.067 -0.24 0.272 0.78 -0.387 0.244 0.065 -1.162 -0.579 -0.465 0.254 -0.442 -0.259 0.366 0.798 0.56 0.423 0.409 2.153 0.139 -0.05 0.428 -0.119 -0.843 -0.29 0.364 0.1 -0.899 0.609
0.948 0.85 0.584 0.459 0.591 -0.523 -0.591 -1.524 0.763 -2.114 0.205 0.422 0.387 -0.288 -0.264 0.293 0.166 -1.162 -0.566 -0.173 0.25 0.31 -0.259 0.366 0.798 0.577 -0.035 0.49 0.511 0.188 0.467 0.597 -0.057 -0.843 -0.29 0.364 0.053 -0.553 0.981
1.157 1.055 0.638 0.617 1.483 -0.731 -0.612 -1.524 0.968 -2.114 0.145 0.179 0.688 -0.14 -0.289 0.317 0.195 -0.897 -0.567 -0.557 0.263 0.241 -0.259 0.358 -0.612 0.493 -0.172 0.512 0.511 0.86 0.456 0.916 0.039 -0.843 -0.29 0.364 0.151 -1.157 0.818
1.116 1.112 0.612 0.639 0.919 -0.895 -0.656 -1.418 0.891 -2.114 0.122 -0.275 1.083 0.429 -0.256 1.017 0.161 -0.963 -0.575 -0.381 0.22 -0.173 -0.259 0.367 -1.312 0.317 -0.335 0.521 0.042 0.86 -0.097 0.795 -0.452 -0.843 -0.29 0.364 -0.054 -0.426 0.877
1.093 1.12 0.522 0.797 0.953 -0.619 -0.591 -1.39 1.044 -2.114 0.817 0.431 1.472 -0.45 -0.332 1.112 0.282 -1.118 -0.568 0.51 0.176 1.156 -0.259 -0.618 -1.313 0.267 -0.54 0.326 0.743 1.654 0.755 0.903 -0.627 -0.843 -2.315 -0.289 -0.054 0.079 1.077
-0.632 -0.959 -0.474 1.194 -0.17 -0.572 -0.779 -1.35 -1.034 -2.114 0.025 0.514 -0.419 -0.099 -0.371 1.592 0.293 -0.897 -0.583 0.466 -0.649 2.259 -0.063 -0.619 -1.314 0.055 -0.479 -0.272 0.189 1.873 -0.613 -0.949 -0.716 -0.843 -2.315 -0.289 0.41 1.837 -1.099
-0.999 -1.343 -0.454 1.156 -0.523 -0.786 -0.988 -1.463 -1.948 -2.114 -1.603 0.036 -0.751 0.569 -0.402 2.064 -0.929 -0.897 0.064 0.423 -0.72 1.76 -0.063 -0.631 -1.314 -0.161 -0.26 -0.181 -0.457 1.873 0.023 -1.803 -0.512 -0.441 -0.918 -0.943 -0.737 1.314 -1.656
有了数据集,我们接下来是把数据集读到我们的程序里面。
import numpy as np;
import pandas as pd;
def NumpyReadData(filepath):#filepath是文件所在路径。
train_data=np.loadtxt(filepath,dtype=str)
train_data=train_data[1:]
trainfloat=train_data.astype(np.float)#把字符串转为float类型
#把训练集为两部分,x_train作为输入,y_train作为输出。
x_train=trainfloat[:,0:38];
y_train=trainfloat[:,38:];
print("x_train:{}".format(x_train.shape))
print("y_train:{}".format(y_train.shape))
print("train_data[0]:{}".format(x_train[0]))
print("train_data[1]:{}".format(y_train[0]))
return x_train,y_train;
NumpyReadData("./zhengqi/zhengqi_train.txt")
运行结果为:
x_train:(2888, 38)
y_train:(2888, 1)
train_data[0]:[ 0.566 0.016 -0.143 0.407 0.452 -0.901 -1.812 -2.36 -0.436 -2.114
-0.94 -0.307 -0.073 0.55 -0.484 0. -1.707 -1.162 -0.573 -0.991
0.61 -0.4 -0.063 0.356 0.8 -0.223 0.796 0.168 -0.45 0.136
0.109 -0.615 0.327 -4.627 -4.789 -5.101 -2.608 -3.508]
train_data[1]:[0.175]
我们从结果中可以看出,训练集的数据为2889*39。numpy的loadtxt方法读取的数据默认是float类型,但本数据集中第一行有字符,无法读取。所以在读的时候要设置成字符串,然后在作切片处理,把我们需要的数据切出来转为数值型。
第二步:搭建神经网络模型:
def BPTrain(x_train,y_train):
#定义占位符
x=tf.placeholder(tf.float32,[None,38]);#x的输入是38列
y=tf.placeholder(tf.float32,[None,1])#y的输入时1列
#定义网络第一隐层
w1=tf.Variable(tf.random_normal([38,70],stddev=0.1))#隐含层20个神经元
b1=tf.Variable(tf.zeros([70]));
w1_b1=tf.matmul(x,w1)+b1
#定义第一层激活函数
l1=tf.nn.sigmoid(w1_b1)
#定义神经网络第二隐层
w2=tf.Variable(tf.random_normal([70,20],stddev=0.1))
b2=tf.Variable(tf.zeros([20]));
w2_b2=tf.matmul(l1,w2)+b2;
#定义第二层激活函数
l2=tf.nn.tanh(w2_b2);
#定义神经网络第三隐层
w3=tf.Variable(tf.random_normal([20,1]))
b3=tf.Variable(tf.zeros([1]));
w3_b3=tf.matmul(l2,w3)+b3;
l3=tf.nn.sigmoid(w3_b3);
#定义代价函数
loss=tf.reduce_mean(tf.square(y-l3));
train_step=tf.train.GradientDescentOptimizer(0.001).minimize(loss)#学习率为0.001
#存放批次值和损失值
plotdata={"batchsise":[],"loss":[]}
#变量初始化
init=tf.global_variables_initializer();
with tf.Session() as sess:
sess.run(init)
for i in range(20000):
sess.run(train_step,feed_dict={x:x_train,y:y_train})
if i%200==0:
p=sess.run(loss,feed_dict={x:x_train,y:y_train})
print(i,"p:",p)
if not (p=="NA"):
plotdata["batchsise"].append(i)
plotdata["loss"].append(p)
plt.figure(1)
plt.plot(plotdata["batchsise"],plotdata["loss"],"b--")
plt.xlabel("x")
plt.ylabel("y")
plt.show()
看看运行结果:
0 p: 1.0114381
200 p: 0.92745763
400 p: 0.824224
600 p: 0.7562797
800 p: 0.7178874
1000 p: 0.69434476
1200 p: 0.67865855
1400 p: 0.66752356
上面是loss的部分值,我们看看他的折线图:

有图中我们可以看出,loss下降到大概0.61的时候下降就很慢了,要想继续寻优,就需要我们修改网络结构和参数。或者对数据的特征进行分析。至于优化的部分咱们暂时先不考虑。
网络训练好以后,我们接下来要做的就是保存网络。
第三步:保存模型。tensorflow提供了专门用来保存模型的函数。
#变量初始化
init=tf.global_variables_initializer();
saver=tf.train.Saver();
saver_path="log/"
with tf.Session() as sess:
sess.run(init)
for i in range(20000):
sess.run(train_step,feed_dict={x:x_train,y:y_train})
if i%200==0:
p=sess.run(loss,feed_dict={x:x_train,y:y_train})
print(i,"p:",p)
if not (p=="NA"):
plotdata["batchsise"].append(i)
plotdata["loss"].append(p)
saver.save(sess,saver_path+"model.cpkt");
这一段可以结合上面的看,比第二步的代码多了3行。运行结束后,会在指定的log文件夹下出现四个文件。截图如下:

第四步:模型保存好以后,我们接下来就是加载模型,传入数据进行预测。
import numpy as np;
import pandas as pd;
import tensorflow as tf;
import matplotlib.pyplot as plt;
def NumpyReadData(filepath):#filepath是文件所在路径。
test_data=np.loadtxt(filepath,dtype=str)
test_data=test_data[1:]
trainfloat=test_data.astype(np.float)#把字符串转为float类型
#把训练集为两部分,x_train作为输入,y_train作为输出。
x_test=trainfloat[:,0:38];
return x_test;
def BPTrain(x_test):
#定义占位符
x=tf.placeholder(tf.float32,[None,38]);#x的输入是38列
y=tf.placeholder(tf.float32,[None,1])#y的输入时1列
#定义网络第一隐层
w1=tf.Variable(tf.random_normal([38,70],stddev=0.1))#隐含层20个神经元
b1=tf.Variable(tf.zeros([70]));
w1_b1=tf.matmul(x,w1)+b1
#定义第一层激活函数
l1=tf.nn.sigmoid(w1_b1)
#定义神经网络第二隐层
w2=tf.Variable(tf.random_normal([70,20],stddev=0.1))
b2=tf.Variable(tf.zeros([20]));
w2_b2=tf.matmul(l1,w2)+b2;
#定义第二层激活函数
l2=tf.nn.tanh(w2_b2);
#定义神经网络第三隐层
w3=tf.Variable(tf.random_normal([20,1]))
b3=tf.Variable(tf.zeros([1]));
w3_b3=tf.matmul(l2,w3)+b3;
l3=tf.nn.sigmoid(w3_b3);
#定义代价函数
loss=tf.reduce_mean(tf.square(y-l3));
train_step=tf.train.GradientDescentOptimizer(0.001).minimize(loss)#学习率为0.001
#变量初始化
init=tf.global_variables_initializer();
saver=tf.train.Saver();
saver_path="log/"
with tf.Session() as sess:
sess.run(init)
saver.restore(sess,saver_path+"model.cpkt");
prediction_value = sess.run(l3, feed_dict={x: x_test})
prediction = np.around(prediction_value, decimals=3)
pre=prediction.astype(str).tolist();
f2 = open('prediction.txt', 'r+')
for i in range(len(pre)):
f2.write("".join(pre[i])+"\n")
f2.close()
#np.savetxt("prediction.txt",pre,fmt="%f")
x_test=NumpyReadData("./zhengqi/zhengqi_test.txt")
BPTrain(x_test);
执行上面代码,会把运行的结果保存在prediction.txt文件中。
至此,一个简单的BP神经网络就算完成了。
更多推荐


所有评论(0)