tensorflow入門

注:
tensorflow 1.3.0
python 3.6

入門學(xué)習(xí)

  • 建議下面的例子挨著敲一下,親測(cè)可用涉兽,注意看發(fā)表時(shí)間。最后一個(gè)例子下載失敗可以暫時(shí)忽略别厘。
    ps: 2018年3月6日23:45:29

  • hello tensorflow

import tensorflow as tf
'''
tensorflow 入門 hello tensorflow

簡(jiǎn)單的輸出一句話

tf constant
tf session
run

'''

hello = tf.constant('Hello, Tensorflow')
sess = tf.Session()
print(sess.run(hello))

輸出:

b'Hello, Tensorflow'
  • constant運(yùn)算 加 乘
import tensorflow as tf

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

with tf.Session() as sess:
    print("a=2,b=3")
    print("a+b=",sess.run(a+b))
    print("a*b=",sess.run(a*b))

輸出:

a=2,b=3
a+b= 5
a*b= 6

  • placeholder 運(yùn)算
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:
    print("add=",sess.run(add,feed_dict={a:1,b:2}))
    print("mul=",sess.run(mul,feed_dict={a:1,b:2}))

輸出:

add= 3
mul= 2
  • 矩陣相乘
import tensorflow as tf

a = tf.constant([[3.,3.]]) # 相當(dāng)于1*2矩陣
b = tf.constant([[2.],[2.]]) # 相當(dāng)于2*1矩陣
result = tf.matmul(a,b)

with tf.Session() as sess:
    print("result=",sess.run(result))



輸出:

result= [[12.]]
  • 線性回歸
import tensorflow as tf
import numpy
import matplotlib.pyplot as plt
rng = numpy.random

# Parameters
learning_rate = 0.01
training_epochs = 2000
display_step = 50

# Training Data
train_X = numpy.asarray([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])
train_Y = numpy.asarray([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])
n_samples = train_X.shape[0]

# tf Graph Input
X = tf.placeholder("float")
Y = tf.placeholder("float")

# Create Model

# Set model weights
W = tf.Variable(rng.randn(), name="weight")
b = tf.Variable(rng.randn(), name="bias")

# Construct a linear model
activation = tf.add(tf.multiply(X, W), b) # activation = x*W + b

# Minimize the squared errors
cost = tf.reduce_sum(tf.pow(activation-Y, 2))/(2*n_samples) #L2 loss
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) #Gradient descent

# Initializing the variables
init = tf.initialize_all_variables()

# Launch the graph
with tf.Session() as sess:
    sess.run(init)

    # Fit all training data
    for epoch in range(training_epochs):
        for (x, y) in zip(train_X, train_Y):
            sess.run(optimizer, feed_dict={X: x, Y: y})

        #Display logs per epoch step
        if epoch % display_step == 0:
            print("Epoch:", '%04d' % (epoch+1), "cost=", \
                "{:.9f}".format(sess.run(cost, feed_dict={X: train_X, Y:train_Y})), \
                "W=", sess.run(W), "b=", sess.run(b))

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

    #Graphic display
    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()
    plt.show()

  • 邏輯回歸
import tensorflow as tf
# Import MINST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)

'''
運(yùn)行失敗的 數(shù)據(jù)集網(wǎng)上無法下載的
提示如下:
urllib.error.URLError: <urlopen error [WinError 10060] 由于連接方在一段時(shí)間后沒有正確答復(fù)或連接的主機(jī)沒有反應(yīng),連接嘗試失敗仇祭。>
'''

# Parameters
learning_rate = 0.01
training_epochs = 25
batch_size = 100
display_step = 1

# tf Graph Input
x = tf.placeholder(tf.float32, [None, 784]) # mnist data image of shape 28*28=784
y = tf.placeholder(tf.float32, [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)

# Initializing the variables
init = tf.initialize_all_variables()

# Launch the graph
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)
            # Run optimization op (backprop) and cost op (to get loss value)
            _, 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
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    print("Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市华弓,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌寂屏,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,406評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異考廉,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)既绕,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門涮坐,熙熙樓的掌柜王于貴愁眉苦臉地迎上來凄贩,“玉大人,你說我怎么就攤上這事袱讹∑T” “怎么了?”我有些...
    開封第一講書人閱讀 163,711評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)椒丧。 經(jīng)常有香客問我壹甥,道長(zhǎng),這世上最難降的妖魔是什么瓜挽? 我笑而不...
    開封第一講書人閱讀 58,380評(píng)論 1 293
  • 正文 為了忘掉前任盹廷,我火速辦了婚禮,結(jié)果婚禮上久橙,老公的妹妹穿的比我還像新娘俄占。我一直安慰自己淆衷,他們只是感情好缸榄,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,432評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著祝拯,像睡著了一般甚带。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上佳头,一...
    開封第一講書人閱讀 51,301評(píng)論 1 301
  • 那天鹰贵,我揣著相機(jī)與錄音,去河邊找鬼康嘉。 笑死碉输,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的亭珍。 我是一名探鬼主播敷钾,決...
    沈念sama閱讀 40,145評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼肄梨!你這毒婦竟也來了阻荒?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,008評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤众羡,失蹤者是張志新(化名)和其女友劉穎侨赡,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體粱侣,經(jīng)...
    沈念sama閱讀 45,443評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡辆毡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,649評(píng)論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了甜害。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,795評(píng)論 1 347
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡球昨,死狀恐怖尔店,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤嚣州,帶...
    沈念sama閱讀 35,501評(píng)論 5 345
  • 正文 年R本政府宣布鲫售,位于F島的核電站,受9級(jí)特大地震影響该肴,放射性物質(zhì)發(fā)生泄漏情竹。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,119評(píng)論 3 328
  • 文/蒙蒙 一匀哄、第九天 我趴在偏房一處隱蔽的房頂上張望秦效。 院中可真熱鬧,春花似錦涎嚼、人聲如沸阱州。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,731評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽苔货。三九已至,卻和暖如春立哑,著一層夾襖步出監(jiān)牢的瞬間夜惭,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,865評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工铛绰, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留诈茧,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,899評(píng)論 2 370
  • 正文 我出身青樓至耻,卻偏偏與公主長(zhǎng)得像若皱,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子尘颓,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,724評(píng)論 2 354