TensorFlow技术解析与实战 第8章: 第一个tensor
TensorFlow的运行方式分如下4步:
(1)加载数据及定义超参数
(2)构建网络
(3)训练模型
(4)评估模型和进行预测
# -*- coding: utf-8 -*-
import sys
import importlib
importlib.reload(sys)
#sys.setdefaultencoding('utf-8')
import tensorflow as tf
import numpy as np
# y = x^2 - 0.5
# 生成及加载数据
x_data = np.linspace(-1, 1, 300)[:, np.newaxis] #构建了300个点
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])
# 构建网络模型
# y = weights*x + biases
def add_layer(inputs, in_size, out_size, activation_function=None):
weights = tf.Variable(tf.random_normal([in_size, out_size])) # in_size * out_size 大小的矩阵
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1) # 1 X out_size 的矩阵
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
# 构建隐藏层,假设隐藏层有10个神经元
h1 = add_layer(xs, 1, 20, activation_function=tf.nn.relu)
# 构建输出层,假设输出层和输入层一样,有1个神经元
prediction = add_layer(h1, 20, 1, activation_function=None)
# 计算预测值和真实值间的误差
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.global_variables_initializer() #初始化所有变量
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 == 0:
print(sess.run(loss, feed_dict={xs:x_data, ys:y_data}))