import sys
print(sys.version)
'''
3.5.3 |Continuum Analytics, Inc.| (default, May 15 2017, 10:43:23) [MSC v.1900 64 bit (AMD64)]
'''
import tensorflow as tf
import numpy as np
def add_layer(inputs, in_size, out_size,n_layer, activation_function=None):
layer_name = 'layer%s' % n_layer ## define a new var
with tf.name_scope('layer'):
with tf.name_scope('weights'):
Weights = tf.Variable(
tf.random_normal([in_size, out_size]),
name='W')
tf.summary.histogram(layer_name + '/weights', Weights) # tensorflow >= 0.12
with tf.name_scope('biases'):
biases = tf.Variable(
tf.zeros([1, out_size]) + 0.1,
name='b')
tf.summary.histogram(layer_name + '/biases', biases) # Tensorflow >= 0.12
with tf.name_scope('Wx_plus_b'):
Wx_plus_b = tf.add(
tf.matmul(inputs, Weights),
biases)
if activation_function is None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b)
tf.summary.histogram(layer_name + '/outputs', outputs) # Tensorflow >= 0.12
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
#这里的None代表无论输入有多少都可以,因为输入只有一个特征,所以这里是1
with tf.name_scope('inputs'):
xs = tf.placeholder(tf.float32, [None, 1],name='x_in')
ys = tf.placeholder(tf.float32, [None, 1],name='y_in')
#通常神经层都包括输入层、隐藏层和输出层。这里的输入层只有一个属性, 所以我们就只有一个输入;隐藏层我们可以自己假设,这里我们假设隐藏层有10个神经元;
# 输出层和输入层的结构是一样的,所以我们的输出层也是只有一层。 所以,我们构建的是——输入层1个、隐藏层10个、输出层1个的神经网络。
l1 = add_layer(xs, 1, 10, n_layer=1, activation_function=tf.nn.relu)
#接着,定义输出层。此时的输入就是隐藏层的输出——l1,输入有10层(隐藏层的输出层),输出有1层。
prediction = add_layer(l1, 10, 1, n_layer=2, activation_function=None)
#对二者差的平方求和再取平均
with tf.name_scope('loss'):
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),reduction_indices=[1]))
tf.summary.scalar('loss', loss) # tensorflow >= 0.12
#接下来,是很关键的一步,如何让机器学习提升它的准确率。tf.train.GradientDescentOptimizer()中的值通常都小于1,这里取的是0.1,代表以0.1的效率来最小化误差loss。
with tf.name_scope('train'):
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
init = tf.global_variables_initializer()
sess = tf.Session()
merged = tf.summary.merge_all() # tensorflow >= 0.12
writer = tf.summary.FileWriter("logs/", sess.graph)
sess.run(init)
for i in range(1000):
sess.run(train_step, feed_dict={xs:x_data, ys:y_data})
if i%50 == 0:
rs = sess.run(merged,feed_dict={xs:x_data,ys:y_data})
writer.add_summary(rs, i)
网友评论