iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 19
0
自我挑戰組

Machine Learning 學習筆記系列 第 19

[第19天] Tensorflow 練習2

參考網站1 參考網站2

今天要來練習Session(會話控制)這個執行指令與Variable(變量)的用法~

Session

首先來建立矩陣相乘

import tensorflow as tf

# create two matrixes

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

以上只是把結構畫出來,接下來要用session來執行

# method 1
sess = tf.Session()
result = sess.run(product)
print(result)
sess.close()
# [[12]]

# method 2
with tf.Session() as sess:     # 就不用再關sess了
    result2 = sess.run(product)
    print(result2)
# [[12]]

Variable

接下來練習一個反復加1的計數器來熟悉變量

import tensorflow as tf

state = tf.Variable(0, name='counter')  #定義一個初始狀態0

# 定義常量
one = tf.constant(1) #定義一個常數1

# 定義加法 
new_value = tf.add(state, one) 

# 將 State 更新成 new_value
update = tf.assign(state, new_value)

一定要定義初始化

init = tf.global_variables_initializer()

最後使用Session來執行

# 使用 Session
with tf.Session() as sess:
    sess.run(init)
    for _ in range(3):
        sess.run(update)
        print(sess.run(state))     # 一定要將sess指向state才行

最後輸出結果
https://ithelp.ithome.com.tw/upload/images/20181102/20112303y5fyUnPneM.png

今天熟悉Session與Variable的用法,明天來了解一下Placeholder這個功能。最近真的太操了年終將近一堆雜事/images/emoticon/emoticon06.gif


上一篇
[第十八天] Tensorflow 練習1
下一篇
[第二十天]Tensorflow 練習3
系列文
Machine Learning 學習筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言