1 import tensorflow as tf 2 import numpy as np 3 def addLayer(inputData,inSize,outSize,activity_function = None): 4 Weights = tf.Variable(tf.random_normal([inSize,outSize])) 5 basis = tf.Variable(tf.zeros([1,outSize])+0.1) 6 weights_plus_b = tf.matmul(inputData,Weights)+basis 7 if activity_function is None: 8 ans = weights_plus_b 9 else: 10 ans = activity_function(weights_plus_b) 11 return ans 12 x_data = np.linspace(-1,1,300)[:,np.newaxis] # 转为列向量 13 noise = np.random.normal(0,0.05,x_data.shape) 14 y_data = np.square(x_data)+0.5+noise 15 xs = tf.placeholder(tf.float32,[None,1]) # 样本数未知,特征数为1,占位符最后要以字典形式在运行中填入 16 ys = tf.placeholder(tf.float32,[None,1]) 17 l1 = addLayer(xs,1,10,activity_function=tf.nn.relu) # relu是激励函数的一种 18 l2 = addLayer(l1,10,1,activity_function=None) 19 loss = tf.reduce_mean(tf.reduce_sum(tf.square((ys-l2)),reduction_indices = [1]))#需要向相加索引号,redeuc执行跨纬度操作 20 train = tf.train.GradientDescentOptimizer(0.1).minimize(loss) # 选择梯度下降法 21 init = tf.initialize_all_variables() 22 sess = tf.Session() 23 sess.run(init) 24 for i in range(10000): 25 sess.run(train,feed_dict={xs:x_data,ys:y_data}) 26 if i%50 == 0: 27 print sess.run(loss,feed_dict={xs:x_data,ys:y_data}) 28
另一种实现https://www.cnblogs.com/cloud-ken/p/8436436.html