tf.constant_initializer()
参数:
value: Python标量、值列表或元组,或n维Numpy数组。初始化变量的所有元素将在value参数中设置为对应的值。
dtype: 数据类型。
verify_shape: 布尔值,用于验证value的形状。如果为真,如果value的形状与初始化张量的形状不兼容,初始化器将抛出错误。
1. 大小正好的初始化
import numpy as np
import tensorflow as tf
value = [0, 1, 2, 3, 4, 5, 6, 7]
# value = np.array(value)
# value = value.reshape([2, 4]) 效果一样
init = tf.constant_initializer(value)
print('fitting shape:')
with tf.Session():
x = tf.get_variable('x', shape=[2, 4], initializer=init)
x.initializer.run()
print(x.eval())
结果为:
[[0. 1. 2. 3.]
[4. 5. 6. 7.]]
2. 初始的变量比init大,会用最后的值作为填充
import numpy as np
import tensorflow as tf
value = [0, 1, 2, 3, 4, 5, 6, 7]
init = tf.constant_initializer(value)
print('larger shape:')
with tf.Session():
x = tf.get_variable('x', shape=[3, 4], initializer=init)
x.initializer.run()
print(x.eval())
结果为:
[[0. 1. 2. 3.]
[4. 5. 6. 7.]
[7. 7. 7. 7.]]
3. 初始的变量比init小,会报错
import numpy as np
import tensorflow as tf
value = [0, 1, 2, 3, 4, 5, 6, 7]
init = tf.constant_initializer(value)
print('smaller shape:')
with tf.Session():
x = tf.get_variable('x', shape=[2, 3], initializer=init)
x.initializer.run()
print(x.eval())
报错为:
ValueError: Too many elements provided. Needed at most 6, but received 8
import numpy as np
import tensorflow as tf
value = [0, 1, 2, 3, 4, 5, 6, 7]
init = tf.constant_initializer(value)
print('shape verification:')
init_verify = tf.constant_initializer(value, verify_shape=True) # 当verify_shape=True时,如果value的形状与初始化张量的形状不兼容,初始化器将抛出错误。
with tf.Session():
x = tf.get_variable('x', shape=[3, 4], initializer=init_verify)
x.initializer.run()
print(x.eval())
报错为:
TypeError: Expected Tensor's shape: (3, 4), got (8,).
北木.
发布了289 篇原创文章 · 获赞 29 · 访问量 3万+
私信
关注