深入理解TensorFlow架構設計與實現原理 3 :基礎概念

CopperDong發表於2018-05-28

1、程式設計正規化:資料流圖

   宣告式程式設計與指令式程式設計的對比討論

   資料流圖: tensorflow 1.2.0

2、資料載體:張量

   張量:Tensor

   稀疏張量:SparseTensor類,以鍵值對的形式表示高維稀疏資料,它包含indices、values和dense_shape這3個屬性。

3、模型載體:操作

    計算節點:Operation類定義在tensorflow/python/framework/ops.py

    儲存節點:Variable類定義在tensorflow/python/ops/variables.py

    資料節點:tf.placeholder操作

4、執行環境:會話

   普通會話:Session類定義在tensorflow/python/client/session.py

   互動式會話:InteractiveSession,使用者可以不借助with上下文語句塊,直接使用Tensor.eval和Operation.run方法求解張量、執行操作

5、訓練工具:優化器

    損失函式和優化演算法:

    優化器概述:

6、一元線性迴歸模型的最佳實踐

     Y = W^T * X + b

可分為8個步驟:

(1)定義超引數:

(2)輸入資料:

(3)構建模型:

(4)定義損失函式:

(5)建立優化器:

(6)定義單步訓練操作:

(7)建立會話:

(8)迭代訓練:

import tensorflow as tf
import matplotlib.pyplot as plt
# 1 超引數
learning_rate = 0.01
max_train_steps = 1000
log_step = 10
# 2 輸入資料
train_X = np.array([[3.3],[4.4],[5.5],[6.71],[6.93],[4.168],[9.779],
                    [6.182],[7.59],[2.167],[7.042],[10.791],[5.313],
                    [7.997],[5.654],[9.27],[3.1]], dtype=np.float32)
train_Y = np.array([[1.7],[2.76],[2.09],[3.19],[1.694],[1.573],[3.366],
                    [2.596],[2.53],[1.221],[2.827],[3.465],[1.65],[2.904],
                    [2.42],[2.94],[1.3]], dtype=np.float32)
total_samples = train_X.shape[0]
# 3 構建模型
X = tf.placeholder(tf.float32, [None, 1])
W = tf.Variable(tf.random_normal([1,1]), name="weight")
b = tf.Variable(tf.zeros([1]), name="bias")
Y = tf.matmul(X, W) + b
# 4 定義損失函式
Y_ = tf.placeholder(tf.float32, [None, 1])
loss = tf.reduce_sum(tf.pow(Y-Y_, 2))/(total_samples)
# 5 建立優化器
optimizer = tf.train.GradientDescentOptimizer(learning_rate)
# 6 定義單步訓練操作
train_op = optimizer.minimize(loss)
# 7 建立會話
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    # 8 迭代訓練
    print("Start training:")
    for step in xrange(max_train_steps):
        sess.run(train_op, feed_dict={X: train_X, Y_: train_Y})
        # 每隔 log_step 步列印一次日誌
        if step % log_step == 0:
            c = sess.run(loss, feed_dict={X: train_X, Y_: train_Y})
            print("Step:%d, loss==%.4f, W==%.4f, b==%.4f" %
                 (step, c, sess.run(W), sess.run(b)))
    # 輸出指標
    final_loss = sess.run(loss, feed_dict={X: train_X, Y_: train_Y})
    # 訓練完畢的模型引數
    weight, bias = sess.run([W, b])
    print("Step:%d, loss==%.4f, W==%.4f, b==%.4f" %
         (max_train_steps, final_loss, sess.run(W), sess.run(b)))
    print("Linear Regression Model: Y==%.4f*X+%.4f" % (weight, bias))
# 9 視覺化
#初始化後端
%matplotlib
plt.plot(train_X, train_Y, 'ro', label='Training data')
plt.plot(train_X, weight*train_X + bias, label='Fitted line')
plt.legend()
plt.show()

Step:1000, loss==0.1545, W==0.2621, b==0.7246
Linear Regression Model: Y==0.2621*X+0.7246



相關文章