Tensorflow使用变量出现错误: List of Tensors when single Tensor expected

版权声明:本文为CSDN博主「alxe_made」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/alxe_made/article/details/80506640

1.背景:
import tensorflow as tf
a = tf.constant(tf.random_normal([2, 2]))    # 运行该代码出现错误
print(a)

将tf.random_normal传入给tf.constant发生错误: 
TypeError: List of Tensors when single Tensor expected

2. 问题出现原因:
查看tf.constant()和tf.random_normal()是如何使用的

2.1 tf.random_normal函数定义:
def random_normal(shape,
                  mean=0.0,
                  stddev=1.0,
                  dtype=dtypes.float32,
                  seed=None,
                  name=None):

Returns: A tensor of the specified shape filled with random normal values.


2.2 tf.constant函数定义:
def constant(value, dtype=None, shape=None, name="Const", verify_shape=False)

value: A constant value (or list) of output type dtype.
Returns: A Constant Tensor.
2.3 问题的原因:
结论: 因为tf.random_normal返回值是一个Tensor,但是tf.constat传入的形参是list二者类型是不匹配的,所以出现错误。

3. 如何解决:
3.1 方法1:
Use NumPy to generate the random value and put it in a tf.constant()

some_test = tf.constant(
    np.random.normal(loc=0.0, scale=1.0, size=(2, 2)).astype(np.float32))


3.2 方法2:
Potentially faster, as it can use the GPU to generate the random numbers,Use TensorFlow to generate the random value and put it in a tf.Variable

some_test = tf.Variable(
    tf.random_normal([2, 2], mean=0.0, stddev=1.0, dtype=tf.float32)
sess.run(some_test.initializer)

查看tf.Variable函数定义:

def __init__(self,
               initial_value=None,
               trainable=True,
               collections=None,
               validate_shape=True,
               caching_device=None,
               name=None,
               variable_def=None,
               dtype=None,
               expected_shape=None,
               import_scope=None,
               constraint=None):
               ...
               )

args: initial_value: A Tensor, or Python object convertible to a Tensor,which is the initial value for the Variable.
下次遇到这种函数参数的问题,一定要查看这个函数是如何使用的,形参和返回值都是些什么。

关注【OpenCV与AI深度学习】获得更多学习资讯

扫描下面二维码即可关注

参考文章:
TensorFlow: generating a random constant
ipython笔记
 ———————————————— 
版权声明:本文为CSDN博主「alxe_made」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/alxe_made/article/details/80506640

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值