tf.reshape 改变形状

介绍

改变形状

用法与np.reshape()类似

语法

tf.reshape(
    tensor,
    shape,
    name=None
)
参数
  • tensor:要调整的张量
  • shape:要改变的形状,int32 或 int64 类型

例子

3行4列转2行6列

import numpy as np
import tensorflow as tf

arr=np.arange(12).reshape(3,4)

tens=tf.Variable(arr)

tens2=tf.reshape(tens,[2,6])

print(tens)
print('-'*50)
print(tens2)

执行结果:

<tf.Variable 'Variable:0' shape=(3, 4) dtype=int64, numpy=
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])>
--------------------------------------------------
tf.Tensor(
[[ 0  1  2  3  4  5]
 [ 6  7  8  9 10 11]], shape=(2, 6), dtype=int64)

2行3列转1行x列

改变形状时,将不确定的x设置为-1,tensorflow会自行计算

import numpy as np
import tensorflow as tf

arr=np.array([[1,2,3],[3,4,5]])
tens=tf.Variable(arr)

# 将不确定的设置为-1
tens2=tf.reshape(tens,(1,-1))

print(tens)
print(tens2)

执行结果:

<tf.Variable 'Variable:0' shape=(2, 3) dtype=int64, numpy=
array([[1, 2, 3],
       [3, 4, 5]])>
tf.Tensor([[1 2 3 3 4 5]], shape=(1, 6), dtype=int64)

2行3列转一维

import numpy as np
import tensorflow as tf

arr=np.array([[1,2,3],[3,4,5]])
tens=tf.Variable(arr)

tens2=tf.reshape(tens,[-1])

print(tens)
print('-'*50)
print(tens2)

执行结果:

<tf.Variable 'Variable:0' shape=(2, 3) dtype=int64, numpy=
array([[1, 2, 3],
       [3, 4, 5]])>
--------------------------------------------------
tf.Tensor([1 2 3 3 4 5], shape=(6,), dtype=int64)

将1行1列转成数字张量

import numpy as np
import tensorflow as tf

arr=np.array([19])
tens=tf.Variable(arr)

tens2=tf.reshape(tens,[])

print(tens)
print('-'*50)
print(tens2)

执行结果:

<tf.Variable 'Variable:0' shape=(1,) dtype=int64, numpy=array([19])>
--------------------------------------------------
tf.Tensor(19, shape=(), dtype=int64)

原文出处:/show_1EF5a6BOETEz.html