Tensorflow中佔位符與Variable物件

2021-09-03 02:48:42 字數 2040 閱讀 7192

對於tensorflow中佔位符,可以把它看作乙個未知數,設矩陣a矩陣b矩陣c的乘積,

(1) b=

[123

4567

89

]b=\begin 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \end \tag

b=⎣⎡​1

47​2

58​3

69​⎦

⎤​(1

)那麼c矩陣只要滿足行數=3,列數不定就可以了,這時利用佔位符更容易表示,例子如下:

# -*- coding: utf-8 -*-

import tensorflow as tf

import numpy as np

# 佔位符

c = tf.placeholder(tf.float32, [3, none], name='c')

# 三行三列的矩陣

b = tf.constant(

[[1, 2, 3],

[4, 5, 6],

[7, 8, 9]

], tf.float32

)# 矩陣相乘

a = tf.matmul(b, c)

# 建立會話

session = tf.session()

# 令c為3行1列的矩陣

a1 = session.run(a, feed_dict=)

print(a1)

# 令c為3行2列的矩陣

a2 = session.run(a, feed_dict=)

print(a2)

[[ 68.]

[ 167.]

[ 266.]]

[[ 22. 28.]

[ 49. 64.]

[ 76. 100.]]

由此可以看出,通過會話的成員函式run中引數feed_dict佔位符賦值。

2.1 tensor物件的問題

tensor物件的值無法更改,tensor類中沒有任何成員函式改變其值,而且無法用同樣乙個tensor物件記錄乙個隨時變化的值,tensorflow中的variable類可以解決這個問題。

2.2 解決思路

1、建立乙個variable物件,對其初始化。

2、利用成員函式assign改變其值。

**如下:

# -*- coding: utf-8 -*-

import tensorflow as tf

# 建立variable物件

a = tf.variable(tf.constant([1, 2, 3]), tf.float32)

# 建立會話

session = tf.session()

# 初始化variable物件

session.run(tf.global_variables_initializer())

# 列印值

print("初始化的值為:")

print(session.run(a))

# 改變本身的值

session.run(a.assign([7, 8, 9]))

print("當前值為:")

print(session.run(a))

初始化的值為:

[1 2 3]

當前值為:

[7 8 9]

:在使用variable物件時,一定要初始化,否則會報錯。

tensorflow 如何使用佔位符與變數

refence tensorflow machine learning cookbook using placeholders and variables packt.tensorflow.machine.learning.cookbook.2017 筆記 如何使用佔位符與變數 申明變數 tf.va...

tensorflow中張量 常量 變數 佔位符

從例項出發 先導入tensorflow import tensorflow as tf create tensorflow object called hello constant hello constant tf.constant hello world with tf.session as s...

Mybatis佔位符 與佔位符 區別

速度快,能防止sql注入,是佔位符方式,先預編譯,然後填充引數,字串格式,使用者名稱 引數只是下劃線上的內容 是直接拼接到語句上,這種方式需要自己拼括號和引數,但是也可以拼接想執行的任何語句,也就是傳說中的sql注入 詳情如下 在mybatis中使用引數進行sql拼裝經常會使用到 和 兩種引數的設定...