TensorFlow之常量tf.constant和变量tf.Variable

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.]]
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值