1简介tf.constant()
在TensorFlow API中创建常量的函数原型如下所示:
tf.constant(
value,
dtype=None,
shape=None,
name='Const',
verify_shape=False
)
value: 要创建的常量(可以为字符、数字矩阵等)
dtype: 常量的类型(tf.float16/32/64 tf.int8/16/32/64)
shape: 生成常量的形状(如矩阵)
name: 为常量命名
verify_shape: 默认为False,如果修改为True的话表示检查value的形状与shape是否相符,如果不符会报错。
1.1测试
import tensorflow as tf
constant=tf.constant(1) #-->1.0
constant1 = tf.constant('hello world') #-->b'hello world'
constant2 = tf.constant([[1, 2],
[3, 4]])
with tf.Session() as sess:
result = sess.run(constant)
print(result)
这里简单列出几个,读者们可以自己编写试试加深理解。
类似还有tf.zeros() ,tf.ones()分别生成全0 全1 常量。
2简介tf.Variable()
在TensorFlow中,变量(tf.Variable)用于保存,更新神经网络的参数张量。
import tensorflow as tf
v1=tf.Variable(tf.random_normal(shape=[4,3],mean=0,stddev=1),name='v1')
v2=tf.Variable(tf.constant(2),name='v2')
v3=tf.Variable(tf.ones([4,3]),name='v3')
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(sess.run(v1))
print(sess.run(v2))
print(sess.run(v3))
结果如下
[[-1.2115501 1.0484737 0.55210656]
[-1.5301195 0.9060654 -2.6766613 ]
[ 0.27101386 -0.32336152 0.44544214]
[-0.0120788 -0.3409422 -0.48505628]]
2
[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]]