环境:python 3 , tensorflow 1.1
"""
python 3
tensorflow 1.1
"""
import tensorflow as tf
import numpy as np
tf.set_random_seed(100)
np.random.seed(100)
x = np.linspace(-1,1,100)[:,np.newaxis]
noise = np.random.normal(0,0.1,x.shape)
y = np.power(x,3) + noise
with tf.variable_scope('inputs'):
xs = tf.placeholder(tf.float32,x.shape,name='x')
ys = tf.placeholder(tf.float32,y.shape,name='y')
with tf.variable_scope('neural_network'):
l1 = tf.layers.dense(xs,10,tf.nn.relu,name='hidden_layer')
output = tf.layers.dense(l1,1,name='output_layer')
tf.summary.histogram('layer1',l1)
tf.summary.histogram('output',output)
loss = tf.losses.mean_squared_error(y,output,scope='loss')
train = tf.train.GradientDescentOptimizer(learning_rate=0.5).minimize(loss)
tf.summary.scalar('loss',loss)
with tf.Session() as sess:
init = tf.global_variables_initializer()
sess.run(init)
merged = tf.summary.merge_all()
writer = tf.summary.FileWriter('./tensorflow1.1_logs',sess.graph)
for step in range(100):
_,result = sess.run([train,merged],feed_dict={xs:x,ys:y})
writer.add_summary(result,step)
运行结果
![这里写图片描述](https://img-blog.csdn.net/20170706152712550?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvc3pqX2h1aHU=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
![这里写图片描述](https://img-blog.csdn.net/20170706152726304?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvc3pqX2h1aHU=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)