使用 Tensorflow 实现一个简单的神经网络
输入数据:
输入数据的形状是[300, 1], 也就是每个元素有一个特征, 所以输入神经元是一个.
隐藏层:
输出神经元 10 个. 输出数据会成为 [300, 10] 的形状. 也就是 300 个元素, 每个元素的特征变成了 10 个.
激活函数使用 Relu
输出层:
输出数据是[300, 1]
不使用激活函数
- import tensorflow as tf
- import numpy as np
- import matplotlib.pyplot as plt
- # 添加层(输入层, 隐藏层, 输出层)
- # inputs, 输入数据
- # insize, 输入神经数, out_size, 输出神经数
- # activation_function, 激活函数, None 就是不作处理
- def add_layer(inputs, in_size, out_size, activation_function=None):
- # (1,10) 正态分布随机数
- 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
- # np.newaxis, 增加一维,[300, 1]
- x_data = np.linspace(-1, 1, 300, dtype=np.float32)[:, np.newaxis]
- # 躁点
- noise = np.random.normal(0, 0.05, x_data.shape).astype(np.float32)
- y_data = np.square(x_data) - 0.5 + noise
- # 占位符
- # [None,1], 任意行, 1 列
- xs = tf.placeholder(tf.float32, [None, 1])
- ys = tf.placeholder(tf.float32, [None, 1])
- # 隐藏层
- # 激活函数使用 Relu, 非线性化函数
- # 为什么使用激活函数参考
- # https://www.cnblogs.com/silence-tommy/p/7113405.html
- l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)
- # 输出层
- prediction = add_layer(l1, 10, 1, activation_function=None)
- # 损失函数
- # reduct_sum, axis=[1] , 将整行的所有列相加
- loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), axis=[1]))
- # 优化, 梯度下降, 减少损失函数的值
- # 得到使损失函数最低的 W, 也就是最优解
- train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
- init = tf.global_variables_initializer()
- with tf.Session() as sess:
- 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}))
- fig = plt.figure()
- ax = fig.add_subplot(1,1,1)
- ax.scatter(x_data, y_data)
- plt.show()
相关方法
tf:
tf.random_normal, 取正态分布分布的随机值, 得到一个列表
tf.Variable,tf 中定义变量需要用这个方法, 不能直接声明
tf.zeros, 类似于 np.zeros
tf.matmul, 矩阵点积
tf.placeholder, 占位符
tf.reduce_mean, tf.reduce_sum, tf.square, 和 numpy 类似
tf.train.GradientDescentOptimizer, 优化方法使用梯度下降方法
np:
np.linspace, 做等分, 得到一个一维的 array
[:, np.newaxis], array 后面接这个, 表示增加一个维度. 例如作用在一维数组上(100,), 会得到 [ 100,1 ]
np.random.normal, 正态分布随机数
astype, 拷贝一份制定类型的数组
- Reference:
- https://www.cnblogs.com/silence-tommy/p/7113405.html
- https://morvanzhou.github.io/tutorials/machine-learning/tensorflow/
来源: http://www.bubuko.com/infodetail-2657541.html