Tensorflow小样例-神经网络

来源:互联网 发布:怎么看淘宝关注的人 编辑:程序博客网 时间:2024/04/30 15:02

这个例子是用Tensorflow构建一个简单的两层神经网络

import tensorflow as tfimport numpy as npimport matplotlib.pyplot as plt# 增加网络层的函数def add_layer(inputs, int_size,out_size,activation_function=None):    # 神经元权重初值:从正态分布中输出随机值,shape为[int_size,out_size]    Weights = tf.Variable(tf.random_normal([int_size,out_size]))    # 偏差初值    biases = tf.Variable(tf.zeros([1,out_size]) + 0.1)    Wx_plus_b = tf.matmul(inputs, Weights) + biases    # 激活函数    if activation_function is None:        outputs = Wx_plus_b    else:        outputs = activation_function(Wx_plus_b)    return outputs# linspace函数可以生成元素为-1到1的等间隔数列。而前两个参数分别是数列的开头与结尾。如果写入第三个参数,可以制定数列的元素个数# numpy的newaxis可以新增一个维度而不需要重新创建相应的shape在赋值,非常方便,如上面的例子中就将x_data从一维变成了二维。x_data = np.linspace(-1,1,300)[:,np.newaxis]# 定义噪声,目的为了模拟真实数据中存在的偏差noise = np.random.normal(0,0.05,x_data.shape)# 得到因变量y_data = np.square(x_data) - 0.5 + noise# 添加占位符,用作输入xs = tf.placeholder(tf.float32,[None,1]) #None 表示无论给多少个例子都可以ys = tf.placeholder(tf.float32,[None,1])# 添加隐藏层和输出层# 输入值是 xs,在隐藏层有 10 个神经元l1 = add_layer(xs,1,10,activation_function=tf.nn.relu)# 输入值是隐藏层 l1,在预测层输出 1 个结果prediction = add_layer(l1,10,1,activation_function=None)# 定义损失函数,reduction_indices是指沿tensor的哪些维度求和,reduction_indices=0时,按列;reduction_indices=1时,按行loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction),        reduction_indices=[1]))# 构建优化器,并用梯度下降使得误差最小,train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)# 对所有变量进行初始化(还没有真正执行)init = tf.initialize_all_variables()# 构建对话sess = tf.Session()# 对所有变量进行初始化sess.run(init)# 生成图片框fig = plt.figure()# 不能通过空Figure绘图。必须用add_subplot创建一个或多个subplot才行,声明1*1个图像的,且当前选中的是subplot中的第一个(编号从1开始)ax = fig.add_subplot(1,1,1)# 绘制散点图,其中,x_data和y_data是相同长度的数组序列ax.scatter(x_data,y_data)# 打开交互模式,为了不让画图暂停plt.ion()# 显示图像(此处的图像为训练集的散点图)plt.show()# 迭代 1000 次学习for i in range(1000):    # training train_step 和 loss 都是由 placeholder 定义的运算,所以这里要用 feed 传入参数    sess.run(train_step,feed_dict={xs:x_data,ys:y_data})    # 训练    # 每训练50次显示一次当前的损失函数的值    if i % 50 == 0:        print(sess.run(loss,feed_dict={xs:x_data,ys:y_data}))    # 在画当前的拟合曲线前,先删除上一条的拟合曲线    try:        ax.lines.remove(lines[0])    except Exception:        pass    # 预测    prediction_value = sess.run(prediction,feed_dict={xs:x_data,ys:y_data})    # 绘制当前的拟合曲线,曲线为红色直线,线宽为5    lines = ax.plot(x_data,prediction_value,'r-',lw=5)    # 停止0.1s再绘制    plt.pause(0.1)

结果如下:

这里写图片描述

这里写图片描述

原创粉丝点击