方法tf.reshape()快速理解

本文通过具体示例介绍了 TensorFlow 中 reshape 函数的使用方法,包括如何改变张量形状及参数为-1时的自动计算功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法:tf.reshape(tensor, shape, name=None)

看个例子:

import tensorflow as tf
#首先我们定义一个二维数组(一共有num = 40 个参数):
arraylist= [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
            [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
            [3, 3, 3, 3, 3, 3, 3, 3, 3, 3],
            [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]

input = tf.constant(arraylist)

#reshape里面的参数的乘积必须是等于上面数组所有参数的总和 
#即 x * y * z = num     4 * 2 * 5 = 40
#结果为一个三维数组
output_1 = tf.reshape(input, [4, 2, 5])

#为-1时, 要注意的是reshape里面最多有一个维度的值可以填写为-1,表示自动计算(自动计算出来的值为:4 )。
output_2 = tf.reshape(input, [-1,2, 5])

arrays = []
arrays.append(output_1)
arrays.append(output_2)
#运行
with tf.Session() as sess:
    print('-----output_1    reshape(4, 2, 5):  ----')
    print(output_1)
    print(sess.run(arrays[0]))
    print('-----output_2    reshape(-1, 2, 5):  ----')
    print(output_2)
    print(sess.run(arrays[1]))

运行结果可以知道output_1 = output_2
-----output_1    reshape(4, 2, 5):  ----
Tensor("Reshape:0", shape=(4, 2, 5), dtype=int32)
[[[0 1 2 3 4]
  [5 6 7 8 9]]
 [[1 1 1 1 1]
  [1 1 1 1 1]]
 [[3 3 3 3 3]
  [3 3 3 3 3]]
 [[1 1 1 1 1]
  [1 1 1 1 1]]]
-----output_2    reshape(-1, 2, 5):  ----
Tensor("Reshape_1:0", shape=(4, 2, 5), dtype=int32)
[[[0 1 2 3 4]
  [5 6 7 8 9]]
 [[1 1 1 1 1]
  [1 1 1 1 1]]
 [[3 3 3 3 3]
  [3 3 3 3 3]]
 [[1 1 1 1 1]
  [1 1 1 1 1]]]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值