TensorFlow的運行方式分如下4步:
(1)加載數(shù)據(jù)及定義超參數(shù)
(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
# 生成及加載數(shù)據(jù)
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}))