import tensorflow as tf import numpy as np # 创建添加层 def add_layer(inputs,in_size,out_size,activation_fuction = None): Weight = tf.Variable(tf.random.normal([in_size,out_size])) biases = tf.Variable(tf.zeros([1,out_size])+0.1) wx = tf.matmul(inputs,Weight)+biases if activation_fuction is None: output = wx else : output = activation_fuction(wx) return output 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]) ys = tf.placeholder(tf.float32, [None, 1]) hidden = add_layer(xs,1,10,activation_fuction =tf.nn.relu) prediction = add_layer(hidden,10,1,activation_fuction = None) loss = tf.reduce_mean(tf.reduce_sum(tf.square(prediction - ys),reduction_indices=[1])) train = tf.train.GradientDescentOptimizer(0.2).minimize(loss) init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) for i in range(1000): # # training train_step 和 loss 都是由 placeholder 定义的运算,所以这里要用 feed 传入参数 sess.run(train, feed_dict={xs: x_data, ys: y_data}) if i%50 == 0: print(sess.run(loss,feed_dict={xs:x_data,ys:y_data}))
1、输入数据
2、创建模型
3、求loss , 训练loss最小化