重新整理tensorflow 1.x基本概念(2)

Variable
在tensorflow中,用variable表示可以改变其值的特殊tensor,是用于表示程序处理的共享持久状态的推荐方法。许多高级的库(如 tf.keras)使用 tf.Variable 来存储模型参数。

1.创建变量

要创建变量,请提供一个初始值。tf.Variable 与初始值的 dtype 相同

my_tensor = tf.constant([[1.0, 2.0], [3.0, 4.0]])
my_variable = tf.Variable(my_tensor)

# Variables can be all kinds of types, just like tensors
bool_variable = tf.Variable([False, False, False, True])
complex_variable = tf.Variable([5 + 4j, 6 + 1j])

变量与张量的定义方式和操作行为都十分相似,实际上,它们都是 tf.Tensor 支持的一种数据结构。与张量类似,变量也有 dtype 和形状,并且可以导出至 NumPy。
大部分张量运算在变量上也可以按预期运行,不过变量无法重构形状。

2.运算和赋值

变量由张量提供支持。您可以使用 tf.Variable.assign 重新分配张量。调用 assign是现有张量的内存进行重新赋值的操作。

a = tf.Variable([2.0, 3.0])
# This will keep the same dtype, float32
a.assign([1, 2]) 
# Not allowed as it resizes the variable: 
try:
  a.assign([1.0, 2.0, 3.0])
except Exception as e:
  print(f"{type(e).__name__}: {e}")

以上会输出error,因为变量的shape不能改变

从现有变量创建新变量会复制支持张量。两个变量不能共享同一内存空间。

a = tf.Variable([2.0, 3.0])
# Create b based on the value of a
b = tf.Variable(a)
a.assign([5, 6])
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值