深度学习--浅谈torch和numpy的reshape()和view()方法的区别

结论:reshape不论是numpy.array还是torch.Tensor都是按照行的顺序将数据重新排列,reshape是可以对原来数据的维度进行修改的
但是需要注意的是,
Tensor.reshape(*shape);
array.reshape(shape, order=‘C’)
就是说使用的时候要注意的是
array.reshape(shape=(-1, 2, 3, 2));
Tensor.reshape(-1, 2, 3, 2)

多说一句:
torch的view()与reshape()方法都可以用来重塑tensor的shape(注意:numpy中的view()不是对数据重塑的方法而是将更改数据类型并返回一个副本的方法,别用错地方了)
view()与reshape()区别就是使用的条件不一样
view()方法只适用于满足连续性条件的tensor,并且该操作不会开辟新的内存空间,只是产生了对原存储空间的一个新别称和引用,返回值是视图。
而reshape()方法的返回值既可以是视图,也可以是副本,当满足连续性条件时返回view, 否则返回副本[ 此时等价于contiguous().view() 方法,但是不一样的是reshape会开辟一个新的内存空间来保存reshape后的数据]。
结论:
因此当不确能否使用view时,可以使用reshape。
如果只是想简单地重塑一个tensor的shape,那么就是用reshape,
但是如果需要考虑内存的开销而且要确保重塑后的tensor与之前的tensor共享存储空间,那就使用view()。

1、reshape(-1)

print("===================test reshape(-1)==============================")
test_arr = torch.Tensor([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print(test_arr)
print(test_arr.reshape(-1))
test_arr = torch.Tensor([[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]])
print(test_arr)
print(test_arr.reshape(-1))

结果:按照行的顺序将数据拉长

===================test reshape(-1)==============================
tensor([[ 1.,  2.,  3.,  4.],
        [ 5.,  6.,  7.,  8.],
        [ 9., 10., 11., 12.]])
tensor([[ 1.,  2.,  3.],
        [ 4.,  5.,  6.],
        [ 7.,  8.,  9.],
        [10., 11., 12.]])
[[ 1  4  7 10]
 [ 2  5  8 11]
 [ 3  6  9 12]]
[ 1  4  7 10  2  5  8 11  3  6  9 12]

2、reshape维度不变

print("===================test reshape==============================")
test_arr = torch.Tensor([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print(test_arr)
print(test_arr.reshape(-1, 3))
test_arr = np.array([[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]])
print(test_arr)
print(test_arr.reshape(-1, 3))

结果:按照行的顺序将数据重新排列

===================test reshape==============================
tensor([[ 1.,  2.,  3.,  4.],
        [ 5.,  6.,  7.,  8.],
        [ 9., 10., 11., 12.]])
tensor([[ 1.,  2.,  3.],
        [ 4.,  5.,  6.],
        [ 7.,  8.,  9.],
        [10., 11., 12.]])
[[ 1  4  7 10]
 [ 2  5  8 11]
 [ 3  6  9 12]]
[[ 1  4  7]
 [10  2  5]
 [ 8 11  3]
 [ 6  9 12]]

3、reshape增加一个维度

print("===================test reshape==============================")
test_arr = torch.Tensor([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print(test_arr)
print(test_arr.reshape(-1, 2, 3, 2))
test_arr = np.array([[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]])
print(test_arr)
print(test_arr.reshape((-1, 2, 3, 2)))

结果:按照行的顺序将数据重新排列

===================test reshape==============================
tensor([[ 1.,  2.,  3.,  4.],
        [ 5.,  6.,  7.,  8.],
        [ 9., 10., 11., 12.]])
tensor([[[[ 1.,  2.],
          [ 3.,  4.],
          [ 5.,  6.]],

         [[ 7.,  8.],
          [ 9., 10.],
          [11., 12.]]]])
[[ 1  4  7 10]
 [ 2  5  8 11]
 [ 3  6  9 12]]
[[[[ 1  4]
   [ 7 10]
   [ 2  5]]

  [[ 8 11]
   [ 3  6]
   [ 9 12]]]]

猜你喜欢

转载自blog.csdn.net/weixin_50727642/article/details/123000495
今日推荐