程序功能:使用y= x^2 - 0.5加噪声生成1000个<x, y>样本点,然后搭建一个最简单的神经网络学习
import tensorflow as tf
import numpy as np
def add_layer(input_data, input_size, output_size, activation_function = None):
'''
input_data:输入数据
input_size:输入的神经元个数
output_size:输出的神经元个数
activation_function:激励函数
'''
#产生input_size行output_size列的随机数
Weights = tf.Variable(tf.random_normal([input_size, output_size]))
#产生一行output_size列全为0.1的数
biases = tf.Variable(tf.zeros([1, output_size]) + 0.1)
#input_data * weights + biases
Wx_plus_b = tf.matmul(input_data, Weights) + biases
if activation_function is None:
output = Wx_plus_b
else:
output = activation_function(Wx_plus_b)
return output
#在-1到1之间均匀产生1000个数的list,并将其转成列向量
x_data = np.linspace(-1, 1, 1000)[:, 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])
ys = tf.placeholder(tf.float32, [None, 1])
#隐藏层输出10个神经单元,现在还不知道该怎么设置这个神经单元数比较好
layer1 = add_layer(xs, 1, 10, tf.nn.relu)
prediction = add_layer(layer1, 10, 1, None)
#add_layer函数不需要自己实现,直接调下面函数也能达到相同的效果
# layer1_new = tf.layers.dense(xs, 10, tf.nn.relu)
# prediction_new = tf.layers.dense(layer1_new, 1)
#这两个loss到底有什么区别
loss = tf.reduce_mean(tf.square(ys - prediction))
# 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.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for step in range(1001):
#这个地方是用所有的数据进行梯度下降,这样做不合适
sess.run(train_step, feed_dict = {xs: x_data, ys: y_data})
if step % 50 == 0:
print(step, sess.run(loss, feed_dict = {xs: x_data, ys:y_data}))