Tensorflow中占位符与Variable对象

一、占位符

对于Tensorflow中占位符,可以把它看作一个未知数,设矩阵a矩阵b矩阵c的乘积,
(1) b = [ 1 2 3 4 5 6 7 8 9 ] b=\begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \end{bmatrix} \tag{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={c: np.array([[10], [11], [12]], np.float32)})
print(a1)
# 令c为3行2列的矩阵
a2 = session.run(a, feed_dict={c: np.array([[1, 2], [3, 4], [5, 6]], np.float32)})
print(a2)

[[  68.]
 [ 167.]
 [ 266.]]
 
[[  22.   28.]
 [  49.   64.]
 [  76.  100.]]

由此可以看出,通过 会话 的成员函数 run 中参数feed_dict占位符 赋值。

二、Variable对象

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对象时,一定要初始化,否则会报错。

猜你喜欢

转载自blog.csdn.net/a1786742005/article/details/85009044