14-TensorFlow入門(mén)和基本模型

一.什么是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襟诸,寫(xiě)的很快并且具有可讀性瓦堵。
第二,在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)練開(kāi)始
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()
  • 類(lèi)邏輯斯蒂

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)系作者
  • 序言:七十年代末八堡,一起剝皮案震驚了整個(gè)濱河市樟凄,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌兄渺,老刑警劉巖缝龄,帶你破解...
    沈念sama閱讀 218,682評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異挂谍,居然都是意外死亡叔壤,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,277評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)口叙,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)炼绘,“玉大人,你說(shuō)我怎么就攤上這事妄田“沉粒” “怎么了仗哨?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,083評(píng)論 0 355
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)铅辞。 經(jīng)常有香客問(wèn)我,道長(zhǎng)萨醒,這世上最難降的妖魔是什么斟珊? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,763評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮富纸,結(jié)果婚禮上囤踩,老公的妹妹穿的比我還像新娘。我一直安慰自己晓褪,他們只是感情好堵漱,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,785評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著涣仿,像睡著了一般勤庐。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上好港,一...
    開(kāi)封第一講書(shū)人閱讀 51,624評(píng)論 1 305
  • 那天愉镰,我揣著相機(jī)與錄音,去河邊找鬼钧汹。 笑死丈探,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的拔莱。 我是一名探鬼主播碗降,決...
    沈念sama閱讀 40,358評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼塘秦!你這毒婦竟也來(lái)了讼渊?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,261評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤嗤形,失蹤者是張志新(化名)和其女友劉穎精偿,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體赋兵,經(jīng)...
    沈念sama閱讀 45,722評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡笔咽,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,900評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了霹期。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片叶组。...
    茶點(diǎn)故事閱讀 40,030評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖历造,靈堂內(nèi)的尸體忽然破棺而出甩十,到底是詐尸還是另有隱情船庇,我是刑警寧澤,帶...
    沈念sama閱讀 35,737評(píng)論 5 346
  • 正文 年R本政府宣布侣监,位于F島的核電站鸭轮,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏橄霉。R本人自食惡果不足惜窃爷,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,360評(píng)論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望姓蜂。 院中可真熱鬧按厘,春花似錦、人聲如沸钱慢。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,941評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)束莫。三九已至懒棉,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間麦箍,已是汗流浹背漓藕。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,057評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留挟裂,地道東北人享钞。 一個(gè)月前我還...
    沈念sama閱讀 48,237評(píng)論 3 371
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像诀蓉,于是被迫代替她去往敵國(guó)和親栗竖。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,976評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容