tensorflow 动态数组 TensorArray

本文通过实例演示了如何使用TensorFlow中的动态数组进行数值运算,包括斐波那契数列生成及变量累加操作,展示了动态数组在处理不确定长度数据集时的优势。
tensorflow 动态数组随时可以读取

import tensorflow as tf
ta = tf.TensorArray(tf.float32, size=0, dynamic_size=True, clear_after_read=False)
ta = ta.write(0, 10)
ta = ta.write(1, 20)
ta = ta.write(2, 30)


print(ta.read(0))

print(ta.read(1))

print(ta.read(2))

print(ta.stack())
tf.Tensor(10.0, shape=(), dtype=float32)
tf.Tensor(20.0, shape=(), dtype=float32)
tf.Tensor(30.0, shape=(), dtype=float32)
tf.Tensor([10. 20. 30.], shape=(3,), dtype=float32)
@tf.function
def fibonacci(n):
  n=5
  ta = tf.TensorArray(tf.float32, size=0, dynamic_size=True)
  ta = ta.unstack([0., 1.])

  for i in range(2, n):
    ta = ta.write(i, ta.read(i - 1) + ta.read(i - 2))

  return ta.stack()

fibonacci(7)
<tf.Tensor: shape=(5,), dtype=float32, numpy=array([0., 1., 1., 2., 3.], dtype=float32)>
v = tf.Variable(1)
@tf.function
def f(x):
  ta = tf.TensorArray(tf.int32, size=0, dynamic_size=True)
  for i in tf.range(x):
    v.assign_add(i)
    ta = ta.write(i, v)
  return ta.stack()
f(5)

<tf.Tensor: shape=(5,), dtype=int32, numpy=array([ 1,  2,  4,  7, 11], dtype=int32)>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值