tensorflow学习笔记二——建立一个简单的神经网络
来源:互联网 发布:建筑大数据分析 编辑:程序博客网 时间:2024/06/02 19:01
本笔记目的是通过tensorflow实现一个两层的神经网络。目的是实现一个二次函数的拟合。
如何添加一层网络
代码如下:
def add_layer(inputs, in_size, out_size, activation_function=None): # add one more layer and return the output of this layer Weights = 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, Weights) + biases if activation_function is None: outputs = Wx_plus_b else: outputs = activation_function(Wx_plus_b) return outputs
注意该函数中是xW+b,而不是Wx+b。所以要注意乘法的顺序。x应该定义为[类别数量, 数据数量], W定义为[数据类别,类别数量]。
创建一些数据
# Make up some real datax_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
numpy的linspace函数能够产生等差数列。start,stop决定等差数列的起止值。endpoint参数指定包不包括终点值。
numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)[source]
Return evenly spaced numbers over a specified interval.
Returns num evenly spaced samples, calculated over the interval [start, stop].
noise函数为添加噪声所用,这样二次函数的点不会与二次函数曲线完全重合。
numpy的newaxis可以新增一个维度而不需要重新创建相应的shape在赋值,非常方便,如上面的例子中就将x_data从一维变成了二维。
添加占位符,用作输入
# define placeholder for inputs to networkxs = tf.placeholder(tf.float32, [None, 1])ys = tf.placeholder(tf.float32, [None, 1])
添加隐藏层和输出层
# add hidden layerl1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)# add output layerprediction = add_layer(l1, 10, 1, activation_function=None)
计算误差,并用梯度下降使得误差最小
# the error between prediciton and real dataloss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),reduction_indices=[1]))train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
完整代码如下:
from __future__ import print_functionimport tensorflow as tfimport numpy as npimport matplotlib.pyplot as pltdef add_layer(inputs, in_size, out_size, activation_function=None): # add one more layer and return the output of this layer Weights = 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, Weights) + biases if activation_function is None: outputs = Wx_plus_b else: outputs = activation_function(Wx_plus_b) return outputs# Make up some real datax_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# define placeholder for inputs to networkxs = tf.placeholder(tf.float32, [None, 1])ys = tf.placeholder(tf.float32, [None, 1])# add hidden layerl1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)# add output layerprediction = add_layer(l1, 10, 1, activation_function=None)# the error between prediciton and real dataloss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), reduction_indices=[1]))train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)# important stepinit = tf.initialize_all_variables()sess = tf.Session()sess.run(init)# plot the real datafig = plt.figure()ax = fig.add_subplot(1,1,1)ax.scatter(x_data, y_data)plt.ion()plt.show()for i in range(1000): # training sess.run(train_step, feed_dict={xs: x_data, ys: y_data}) if i % 50 == 0: # to visualize the result and improvement try: ax.lines.remove(lines[0]) except Exception: pass prediction_value = sess.run(prediction, feed_dict={xs: x_data}) # plot the prediction lines = ax.plot(x_data, prediction_value, 'r-', lw=5) plt.pause(0.1)
运行结果:
0 0
- tensorflow学习笔记二——建立一个简单的神经网络
- tensorflow学习笔记二——建立一个简单的神经网络拟合二次函数
- tensorflow学习:建立一个最简单的神经网络
- tensorflow笔记(二)之构造一个简单的神经网络
- tensorflow笔记(二)之构造一个简单的神经网络
- Tensorflow学习:单层神经网络的建立
- TensorFlow学习笔记(二):实现神经网络
- Tensorflow构建一个简单的神经网络
- Tensorflow 构造一个简单的神经网络
- 利用tensorflow构造一个简单的神经网络
- 神经网络和深度学习(二)——一个简单的手写数字分类网络
- 深度学习笔记 (二) 在TensorFlow上训练一个多层卷积神经网络
- 深度学习笔记 (二) 在TensorFlow上训练一个多层卷积神经网络
- 深度学习笔记 (二) 在TensorFlow上训练一个多层卷积神经网络
- 深度学习笔记——TensorFlow学习笔记(三)使用TensorFlow实现的神经网络进行MNIST手写体数字识别
- Tensorflow简单的神经网络
- Tensorflow深度学习之二:简单卷积神经网络CNN
- TensorFlow学习笔记(4)——深层神经网络
- elasticsearch java api 之搜索功能
- android使用PullToRefresh实现上拉加载和下拉刷新效果
- POJ2034 线性筛+DFS(下午第二节课给小裴和诗洋同学表演手打一遍过...)
- 欢迎使用CSDN-markdown编辑器
- Swift - 给UITextView添加自定义链接,以及链接的点击响应
- tensorflow学习笔记二——建立一个简单的神经网络
- http中GET和POST的区别
- 数据库中字段类型对应的C#中的数据类型
- 学习Android CoordinatorLayout(二)
- 获取List中的数据的实现方法
- 多线程的相关知识及代码的实现
- 选择排序(java)
- C#调用C++的DLL搜集整理的所有数据类型转换方式
- nginx配置:(二)Location配置总结