14-TensorFlow入門和基本模型

一.什么是TensorFlow

Tensor(張量)意味著 N 維數(shù)組,F(xiàn)low(流)意味著基于數(shù)據(jù)流圖的計(jì)算,TensorFlow即為張量從圖的一端流動(dòng)到另一端;
支持CNN(卷積神經(jīng)網(wǎng)絡(luò))、RNN(循環(huán)神經(jīng)網(wǎng)絡(luò))和LSTM(長(zhǎng)短期記憶網(wǎng)絡(luò))算法,是目前在 Image,NLP 最流行的深度神經(jīng)網(wǎng)絡(luò)模型.

二.TensorFlow優(yōu)點(diǎn)

第一,基于Python,寫的很快并且具有可讀性。
第二,在CPU或GPU系統(tǒng)上的都可運(yùn)行。
第三,代碼編譯效率較高。
第四,社區(qū)發(fā)展的非常迅速并且活躍。
第五,能夠生成顯示網(wǎng)絡(luò)拓?fù)浣Y(jié)構(gòu)和性能的可視化圖--tensorboard。

三.TensorFlow原理

TensorFlow是用數(shù)據(jù)流圖(data flow graphs)技術(shù)來(lái)進(jìn)行數(shù)值計(jì)算的。
數(shù)據(jù)流圖是描述有向圖中的數(shù)值計(jì)算過(guò)程。
有向圖中,節(jié)點(diǎn)通常代表數(shù)學(xué)運(yùn)算,邊表示節(jié)點(diǎn)之間的某種聯(lián)系,它負(fù)責(zé)傳輸多維數(shù)據(jù)(Tensors)。


原理圖.png

四.TensorFlow使用

使用圖(graph)來(lái)表示任務(wù);
被稱之為會(huì)話(Session)的上下文(context)中執(zhí)行圖;
使用tensor表示數(shù)據(jù);
通過(guò)變量(Variable)維護(hù)狀態(tài)f(x) = w*x + b;
使用feed和fetches可以為任意操作(arbitrary operation)賦值或者從其中獲取數(shù)據(jù).

五.TensorFlow:Helloworld

#導(dǎo)包
import tensorflow as tf
#聲明常量
hello = tf.constant('Hello, TensorFlow!')
#創(chuàng)建會(huì)話
sess = tf.Session()
#執(zhí)行
print(sess.run(hello))

sess.close()

六.TensorFlow:基本操作

  • Basic constant operations
import tensorflow as tf

a = tf.constant(2)
b = tf.constant(3)

with tf.Session() as sess:
    print("a: %i" % sess.run(a), "b: %i" % sess.run(b))
    print("Addition with constants: %i" % sess.run(a+b))
    print("Multiplication with constants: %i" % sess.run(a*b))
  • 賦值assign操作
v = tf.Variable(0,name = 'a')

add = tf.assign_add(v,10)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(v))
    for i in range(5):
        print(sess.run(add))
  • Basic Operations with variable as graph input
import tensorflow as tf

a = tf.placeholder(tf.int16)
b = tf.placeholder(tf.int16)

add = tf.add(a, b)
mul = tf.multiply(a, b)

with tf.Session() as sess:
    # Run every operation with variable input
    print("Addition with variables: %i" % sess.run(add, feed_dict={a: 2, b: 3}))
    print("Multiplication with variables: %i" % sess.run(mul, feed_dict={a: 2, b: 3}))
  • 矩陣操作
matrix1 = tf.constant([[1., 6.]])

matrix2 = tf.constant([[3.],[2.]])

product = tf.matmul(matrix1, matrix2)

with tf.Session() as sess:
    result = sess.run(product)
    print(result)
  • 根據(jù)Graph完成操作


    Graph.png

七.TensorFlow:基本模型

  • 梯度下降
#梯度下降示例
import numpy as np
import matplotlib.pyplot as plt
import time
x=np.arange(-5, 5, 0.001)
y=x**4-3*x**3+2

plt.plot(x,y)
plt.show()

old = 0
# 范圍就是-5 到5
new= 5

# 步幅
step = 0.001

# 精確度
precision = 0.001

# 導(dǎo)數(shù)
def derivative(x):
    return 4*x**3-9*x**2

# 進(jìn)行梯度下降
while abs(new - old) > precision:
    print('------------------------------>',new)
    time.sleep(1)
    old = new
    new = new - step * derivative(new)

print (new)
  • 線性回歸
#導(dǎo)包
mport tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
rng = numpy.random
#定義常量
##定義訓(xùn)練次數(shù)learning_epochs,卷曲神經(jīng)的學(xué)習(xí)率learning_rate顯示打印數(shù)據(jù)的步幅display_step
learning_rate = 0.01
training_epochs = 1000
display_step = 50
#訓(xùn)練數(shù)據(jù)
train_X = np.linspace(0,10,num= 20)+np.random.randn(20)
train_Y = np.linspace(1,4,num = 20)+np.random.randn(20)
n_samples = train_X.shape[0]
#線性模型
pred = tf.add(tf.multiply(X, W), b)
#創(chuàng)建TensorFlow均方誤差cost以及梯度下降優(yōu)化器optimizer
# 均方誤差,平均誤差
cost = tf.reduce_sum(tf.pow(pred-Y, 2))/n_samples
# 實(shí)現(xiàn)梯度下降算法的優(yōu)化器
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
線性回歸.png
#TensorFlow進(jìn)行初始化
init = tf.global_variables_initializer()
#進(jìn)行訓(xùn)練
# 訓(xùn)練開始
with tf.Session() as sess:
    sess.run(init)

    # 訓(xùn)練所有數(shù)據(jù)
    for epoch in range(training_epochs):
        for (x, y) in zip(train_X, train_Y):
            sess.run(optimizer, feed_dict={X: x, Y: y})

        #每執(zhí)行50次顯示運(yùn)算結(jié)果
        if (epoch+1) % display_step == 0:
            c = sess.run(cost, feed_dict={X: train_X, Y:train_Y})
            print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c),
                  "W=", sess.run(W), "b=", sess.run(b))

    print("Optimization Finished!")
    training_cost = sess.run(cost, feed_dict={X: train_X, Y: train_Y})
    print("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n')

    #數(shù)據(jù)可視化
    plt.plot(train_X, train_Y, 'ro', label='Original data')
    plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line')
    plt.legend()
  • 類邏輯斯蒂

softmax:


softmax.png

信息熵:


信息熵.png

交叉熵:
交叉熵.png

steps:

#導(dǎo)包
import tensorflow as tf

# Import MINST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("./", one_hot=True)
#聲明算法
# Parameters
learning_rate = 0.01
training_epochs = 25
batch_size = 100
display_step = 1

# tf Graph Input
x = tf.placeholder(tf.float32, shape = [None,784]) # mnist data image of shape 28*28=784
y = tf.placeholder(tf.float32, shape = [None,10]) # 0-9 digits recognition => 10 classes

# Set model weights
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))

# Construct model
pred = tf.nn.softmax(tf.matmul(x, W) + b) # Softmax

# Minimize error using cross entropy
cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred), reduction_indices=1))
# Gradient Descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

# Initialize the variables (i.e. assign their default value)
init = tf.global_variables_initializer()
#訓(xùn)練
# Start training
with tf.Session() as sess:
    sess.run(init)

    # Training cycle
    for epoch in range(training_epochs):
        avg_cost = 0.
        total_batch = int(mnist.train.num_examples/batch_size)
        # Loop over all batches
        for i in range(total_batch):
            batch_xs, batch_ys = mnist.train.next_batch(batch_size)
            # Fit training using batch data
            _, c = sess.run([optimizer, cost], feed_dict={x: batch_xs,
                                                          y: batch_ys})
            # Compute average loss
            avg_cost += c / total_batch
        # Display logs per epoch step
        if (epoch+1) % display_step == 0:
            print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost))

    print("Optimization Finished!")

    # Test model
    correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
    # Calculate accuracy for 3000 examples
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    print("Accuracy:", accuracy.eval({x: mnist.test.images[:3000], y: mnist.test.labels[:3000]}))
  • 了解KNN

距離

  • L1 Distance:曼哈頓距離
distance = tf.reduce_sum(tf.abs(tf.add(xtr, tf.negative(xte))), axis=1)
曼哈頓距離.png
  • L2 Distance:歐氏距離
distance = tf.sqrt(tf.reduce_sum(tf.pow((xtr-xte),2),axis = -1))
歐氏距離.png
#導(dǎo)包
import numpy as np
import tensorflow as tf

# Import MINST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("./", one_hot = True)
#算法
Xtr, Ytr = mnist.train.next_batch(5000) #5000 for training (nn candidates)
Xte, Yte = mnist.test.next_batch(200) #200 for testing

# tf Graph Input
xtr = tf.placeholder("float", [None, 784])
xte = tf.placeholder("float", [784])

# 使用 L1 Distance 算法計(jì)算距離
# Calculate L1 Distance
distance = tf.reduce_sum(tf.abs(tf.add(xtr, tf.negative(xte))), axis=1)
# distance = tf.sqrt(tf.reduce_sum(tf.pow((xtr-xte),2),axis = -1))
# Prediction: Get min distance index (Nearest neighbor)
pred = tf.argmin(distance, 0)

accuracy = 0.

# Initialize the variables (i.e. assign their default value)
init = tf.global_variables_initializer()
#訓(xùn)練
# Start training
with tf.Session() as sess:
    sess.run(init)

    # loop over test data
    for i in range(len(Xte)):
        # Get nearest neighbor
        nn_index = sess.run(pred, feed_dict={xtr: Xtr, xte: Xte[i, :]})
        # Get nearest neighbor class label and compare it to its true label
        print("Test", i, "Prediction:", np.argmax(Ytr[nn_index]), \
            "True Class:", np.argmax(Yte[i]))
        # Calculate accuracy
        if np.argmax(Ytr[nn_index]) == np.argmax(Yte[i]):
            accuracy += 1./len(Xte)
    print("Done!")
    print("Accuracy:", accuracy)

pip安裝指定源
conda install -i https://pypi.tuna.tsinghua.edu.cn/simple tensorflow

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容