版權聲明:本文爲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.
下次遇到這種函數參數的問題,一定要查看這個函數是如何使用的,形參和返回值都是些什麼。
參考文章:
TensorFlow: generating a random constant
ipython筆記
————————————————
版權聲明:本文爲CSDN博主「alxe_made」的原創文章,遵循CC 4.0 by-sa版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/alxe_made/article/details/80506640