Building a Neural Network
import tensorflow.compat.v1 as tf tf.disable_v2_behavior() import numpy as np from matplotlib import pyplot as plt #添加层 def add_layer(inputs, in_size, out_size, activation_function=None): 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 #建造神经网络 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 plt.scatter(x_data,y_data) xs = tf.placeholder(tf.float32, [None, 1]) #需要定义dtype ys = tf.placeholder(tf.float32, [None, 1]) #不把程序写死 通常神经层都包括输入层、隐藏层和输出层。这里的输入层只有一个属性, 所以我们就只有一个输入;隐藏层我们可以自己假设,这里我们假设隐藏层有10个神经元; 输出层和输入层的结构是一样的,所以我们的输出层也是只有一层。 所以,我们构建的是——输入层1个、隐藏层10个、输出层1个的神经网络。 输入层即X特征矩阵,特征有多少个,则输入层的神经元有多少个 #d定义隐藏层 l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu) #定义输出层 prediction = add_layer(l1, 10, 1, activation_function=None) #计算预测值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() sess = tf.Session() sess.run(init) #学习 for i in range(1000): # training sess.run(train_step, feed_dict={xs: x_data, ys: y_data}) #通过feed进行传递参数 if i % 50 == 0: # to see the step improvement print(sess.run(loss, feed_dict={xs: x_data, ys: y_data}))