1. 程式人生 > >AI - TensorFlow -

AI - TensorFlow -

序列化 註意 except 化工 range glob 定義 cto 名稱

# coding=utf-8
from __future__ import print_function
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import os

os.environ[‘TF_CPP_MIN_LOG_LEVEL‘] = ‘2‘

# ### 添加神經層


def add_layer(inputs, in_size, out_size, activation_function=None):
    with tf.name_scope(‘layer‘):  # 使用with tf.name_scope定義圖層,並指定在可視化圖層中的顯示名稱
        with tf.name_scope(‘weights‘):  # 定義圖層並指定名稱,註意這裏是上一圖層的子圖層
            Weights = tf.Variable(tf.random_normal([in_size, out_size]), name=‘W‘)  # 參數name指定名稱
        with tf.name_scope(‘biases‘):  # 定義圖層並指定名稱
            biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, name=‘b‘)  # 參數name指定名稱
        with tf.name_scope(‘Wx_plus_b‘):  # 定義圖層並指定名稱
            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


# ### 構建數據
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

# ### 搭建網絡
with tf.name_scope(‘inputs‘):  # 定義圖層並指定名稱
    xs = tf.placeholder(tf.float32, [None, 1], name=‘x_input‘)  # 指定名稱為x_input,也就是在可視化圖層中的顯示名稱
    ys = tf.placeholder(tf.float32, [None, 1], name=‘y_input‘)  # 指定名稱為y_input

h1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)  # 隱藏層
prediction = add_layer(h1, 10, 1, activation_function=None)  # 輸出層

with tf.name_scope(‘loss‘):  # 定義圖層並指定名稱
    loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),
                                        reduction_indices=[1]))

with tf.name_scope(‘train‘):  # 定義圖層並指定名稱
    train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)


sess = tf.Session()
writer = tf.summary.FileWriter("logs/", sess.graph)  # 創建FileWriter對象和event文件,指定event文件的存放目錄
init = tf.global_variables_initializer()
sess.run(init)

# ### 結果可視化
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.scatter(x_data, y_data)
plt.ion()
plt.show()

# ### 訓練
for i in range(1001):
    sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
    if i % 50 == 0:
        result = sess.run(loss, feed_dict={xs: x_data, ys: y_data})
        print("Steps:{}  Loss:{}".format(i, result))
        try:
            ax.lines.remove(lines[0])
        except Exception:
            pass
        prediction_value = sess.run(prediction, feed_dict={xs: x_data})
        lines = ax.plot(x_data, prediction_value, ‘r-‘, lw=5)
        plt.pause(0.2)

# ### TensorBoard
# TensorFlow自帶的可視化工具:
#   - 可視化學習:https://www.tensorflow.org/guide/summaries_and_tensorboard
#   - 圖的直觀展示:https://www.tensorflow.org/guide/graph_viz;
#   - 直方圖信息中心:https://www.tensorflow.org/guide/tensorboard_histograms
# 能夠以直觀的流程圖的方式,清楚展示出整個神經網絡的結構和框架,便於理解模型和發現問題;
# 使用tf.name_scope()形成圖層,圖層名字就是方法裏的參數;
#
# ### 啟動TensorBoard
# 使用命令“tensorboard --logdir=path/to/log-directory”(或者“python -m tensorboard.main”);
# 參數logdir指向FileWriter將數據序列化的目錄,建議在logdir上一級目錄執行此命令;
# TensorBoard運行後,在瀏覽器輸入“localhost:6006”即可查看TensorBoard;

  

AI - TensorFlow -