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

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.

下次遇到这种函数参数的问题,一定要查看这个函数是如何使用的,形参和返回值都是些什么。

参考文章:

  1. TensorFlow: generating a random constant
  2. ipython笔记
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值