tensorflow 案例
import tensorflow as tf import numpy as np #添加一层inputs输入的数据,in_size为输入节点数,out_size为输出节点数,下一个为激励函数 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)[:,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]) #输出占位符 #l1=add_layer(x_data,1,10,activation_function=tf.nn.relu) l1=add_layer(xs,1,10,activation_function=tf.nn.relu) #添加一层中间计算层,使用激励函数 prediction=add_layer(l1,10,1,activation_function=None) #添加输出层, #loss 是估计值和真实值之映射到某一空间的误差 #loss=tf.reduce_mean(tf.reduce_sum(tf.square(y_data-predition),reduction_indices=[1])) 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.initialize_all_variable() sess = tf.Session() sess.run(init) for i in range(1000): sess.run(train_step,feed_dict={xs:x_data,ys:y_data}) if i % 50: print(sess.run(loss,feed_dict={xs:x_data,ys:y_data}))