简单的神经网络
这周的任务是系统的学习谷歌深度学习平台 tensorflow,通过对莫烦python课程的学习,收获不小。
tensorflow模块的一些基本操作
首先学习了tf模块的一些基本概念
- Variable:tensorflow中定义变量的语句
state=tf.Variable(0,name='counter')
- constant:定义常量
matrixl2=tf.constant([[2],[2]])
- assign_add:于等号不同的是,assign是在原来的节点上赋值,并不创建新的节点。
- 初始化变量:
init=tf.global_variables_initializer()
- session:会话,是调用tensorflow的必备语句,可以又两种用法来打开session.
# first way
state=tf.Variable(0,name='counter')
#print(satae.name)
one=tf.constant(1)
new_value=tf.add(state,one)
update=tf.assign(state,new_value)
init=tf.global_variables_initializer()
# second way
with tf.Session() as sess:
sess.run(init)
for _ in range(3):
sess.run(update)
print(sess.run(state))
- placeholder:可以理解为占位符,placeholder()函数是在神经网络构建graph的时候在模型中的占位,此时并没有把要输入的数据传入模型,它只会分配必要的内存。等建立session,在会话中,运行模型的时候通过feed_dict()函数向占位符赋值。
tf.placeholder(
dtype,
shape=None,
name=None
)
实例如下:
input1=tf.placeholder(tf.float32)
input2=tf.placeholder(tf.float32)
output=tf.multiply(input2,input1)
with tf.Session() as sess:
print(sess.run(output,feed_dict={input1:[7.],input2:[2.]}))
- feed_dict:用于给占位符赋值的字典,具体用法在上面的代码里。
- 初始化:
tf.global_variables_initializer()
定义变量后要统一初始化,这个语句是最新版的初始化,run一下就好。
构建一个简单的网络层
构建一个layer,需要输入数据,输入格式,输出格式,激活函数,这几个参数,激活函数默认为线性函数,即,不用做任何操作。
def add_layer(inputs,in_size,out_size,activation_function=None):
Weight=tf.Variable(tf.random_normal([in_size,out_size]))
biases=tf.Variable(tf.zeros([1,out_size])+0.1)
Wx_plus_b=tf.matmul(inputs,Weight)+biases
if activation_function is None:
outputs=Wx_plus_b
else:
outputs=activation_function(Wx_plus_b)
return(outputs)
这里的输出输入数据要与size相符合
构建一个简单的神经网络
直接上代码把,注释里进行讲解。由于汉语的编码可能有问题,尽量使用英文。
x_data=np.linspace(-1,1,300)[:,np.newaxis] #newaxis can trans the matrixl
noise=np.random.normal(0,0.05,x_data.shape) #give the data some noise signal
y_data=np.square(x_data)-0.5+noise
xs=tf.placeholder(tf.float32,[None,1]) #make a place holder
ys=tf.placeholder(tf.float32,[None,1])
l1=add_layer(xs,1,10,tf.nn.relu) #use add_layer function to creat a layer that input size 1 and output 10
prediction=add_layer(l1,10,1,activation_function=None) #input 10 and output 1
loss=tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction),reduction_indices=[1]))
#loss function, used to optimizer
train_step=tf.train.GradientDescentOptimizer(0.1).minimize(loss)
tf.Session()
init=tf.global_variables_initializer()
sess.run(init)
for i in range(1000):
sess.run(train_step,feed_dict={xs:x_data,ys:y_data})
if i%50==0:
print(sess.run(loss,feed_dict={xs:x_data,ys:y_data}))
运行结果如下,可见loss函数值逐渐减少,学习目的达成。
使用matplotlib来可视化优化过程
还是以刚才的神经网络为例,调用matplotlib来动态展示优化的过程。
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
def add_layer(inputs, in_size, out_size, activation_function=None):
with tf.name_scope('layer'):
with tf.name_scope('Weight'):
Weight = tf.Variable(tf.random_normal([in_size, out_size]),name='Weight')
with tf.name_scope('biases'):
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1,name='b')
with tf.name_scope('Wx_plus_b'):
Wx_plus_b = tf.matmul(inputs, Weight) + biases
if activation_function is None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b)
return (outputs)
x_data = np.linspace(-1, 1, 300)[:, np.newaxis] # newaxis can trans the matrixl
noise = np.random.normal(0, 0.05, x_data.shape)
y_data = np.square(x_data) - 0.5 + noise
with tf.name_scope('inputs'):
xs = tf.placeholder(tf.float32, [None, 1],name='x_input')
ys = tf.placeholder(tf.float32, [None, 1],name='y_input')
l1 = add_layer(xs, 1, 10, tf.nn.relu)
prediction = add_layer(l1, 10, 1, activation_function=None)
with tf.name_scope('loss'):
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), reduction_indices=[1]),name='loss')
with tf.name_scope('train'):
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
writer=tf.summary.FileWriter('/tmp/lstm_logs',sess.graph)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.scatter(x_data, y_data)
plt.ion() # do not block
plt.show()
for i in range(1000):
sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
if i % 50 == 0:
try:
ax.lines.remove(lines[0])
except Exception:
pass
print('lalal')
prediction_value = sess.run(prediction, feed_dict={xs: x_data})
lines = ax.plot(x_data, prediction_value, 'r-', lw=5)
#ax.lines.remove(lines[0])
plt.pause(0.1)
运行的结果如下,可以动态的显示优化的过程。
使用tensorboard模块输出
其实刚才的代码已经可以输出tensorboard了,因为我把代码写到了一起实现。
tensorboard的实现需要给每个节点进行命名,比如
with tf.name_scope('inputs'):
xs = tf.placeholder(tf.float32, [None, 1],name='x_input')
ys = tf.placeholder(tf.float32, [None, 1],name='y_input')
命名后的节点将会出现在tensorboard里。这里重点说一下这个报错。
运行出现未知的错误,原来是tensorboard源码出现问题
当python程序使用writer = tf.summary.FileWriter("logs/", sess.graph)
将tensorboard写入指定文件中。查看文件夹
会出现一个这样的文件,(因为我的电脑用户是galaxy,大家不要在意)这里不用管,使用命令行。
tensorboard.exe --logdir=logs
这里加不加exe都行,主要是添加环境变量就行,还有的博客说是要先激活,那就直接activate一个就好,然后不管怎么样都是这个报错。。。
之后发现是源码的问题,大家需要改一下这个manager.py文件,找到文件 把(dt - datetime.datetime.fromtimestamp(0)).total_seconds()),
改成
(dt - datetime.datetime.fromtimestamp(86400)).total_seconds()),
这个错误简直了,我纠错好长时间,结果是源码的问题,我还差点重装了。。
运行成功,返回一个url
大家这里直接访问本地6006端口就行,http://localhost:6006
或者http://127.0.0.1:6006
都可以。
纠错一下午的我,看到这个图都快泪崩了。这里也希望大家早日搭建完成自己的神经网络。