view()函数
view()函数是调整矩阵的形状
a1 = torch.arange(0,12).view(3,4)
print(a1)
# tensor([[ 0, 1, 2, 3],
# [ 4, 5, 6, 7],
# [ 8, 9, 10, 11]])
第一个参数是有多少行,第二个参数是每一行有多少个参数,但是必须保证range()函数与view()函数的数量是一致的,否则会报下图错误
import torch
a1 = torch.arange(0,12).view(3,2)
print(a1)
Traceback (most recent call last):
File "C:/Users/yiwan/Desktop/Hornet/test/__init__.py", line 3, in <module>
a1 = torch.arange(0,12).view(3,2)
RuntimeError: shape '[3, 2]' is invalid for input of size 12
view()函数变形的时候不修改里面的数据,只改变大小。
resize_函数
resize_函数也是修改矩阵的尺寸的,但是有一定区别,如果超过了矩阵的大小,会自动补全。补全的是矩阵的内存,resize_()第一个参数是有多少行,第二个参数是每行有多少个。
a2 =a1.resize_(3,5)
print(a2)
#tensor([[0,1,2, 3,4],
# [5, 6,7, 8,9],
# [10,1, 32651599815639144,25896191785697385, 27303570963497060]])
a3 = a1.resize_(5,3)
print(a3)
# tensor([[ 0, 1, 2],
# [ 3, 4, 5],
# [ 6, 7, 8],
# [ 9, 10, 11],
# [25896191785238631, 27866512327901300, 31525674138992744]])
该函数是截取某一个列或者某一行
a4 = a1 .resize_(1,4)
print(a3)
# tensor([[0, 1, 2, 3]])
a5 = a1.resize_(3,1)
print(a5)
# tensor([[0],
# [1],
# [2]])
a6 = a1.resize_(2,4)
print(a6)
#tensor([[0, 1, 2, 3],
# [4, 5, 6, 7]])
但是不能取负数,否则会报超出内存的错误
a7 = a1.resize_(3,-1)
print(a7)
# Traceback (most recent call last):
# File "C:/Users/yiwan/Desktop/Hornet/test/__init__.py", line 43, in <module>
# a7 = a1.resize_(3,-1)
# RuntimeError: [enforce fail at ..\c10\core\CPUAllocator.cpp:53] ((ptrdiff_t)nbytes) >= 0. alloc_cpu() seems to have been called with negative number: 18446744073709551592
#