文章目录
1. numpy和torch在x.max(1)上的区别
import numpy as np
import torch
np_data = np.random.randint(1,10,(5,2))
np_max = np_data.max(1)
torch_data = torch.randint(1,10,(5,2))
torch_max = torch_data.max(1)
print('numpy:{}'.format(np_max))
print('torch:{}'.format(torch_max))
numpy:[7 8 4 6 5]
torch:(tensor([5, 9, 8, 9, 3]), tensor([1, 0, 1, 0, 1]))
如上,torch多一个tensor,记录最大值的位置。
2. 将二维数组转换为一维数组
(1)使用reshape()函数,这个方法是间接法,利用reshape()函数的属性,间接的把二维数组转换为一维数组
(2)使用flatten()函数, 推荐使用这个方法,这个方法是numpy自带的函数
# 把二维数组转换为一维数组
t1 = np.arange(12)
t2 = t1.reshape(3, 4)
print(t2)
t3 = t2.reshape(t2.shape[0]*t2.shape[1], )
print(t3)
t4 = t2.flatten()
print(t4)
运行效果如下图所示:
可以看到这两种方式都可以把二维数组转换为一维数组,但是推荐使用flatten()函数,该方法也可以将多维数组转换为一维数组
3. reshape 与 resize
3.1 reshape的参数
reshape的参数严格地说,应该是tuple类型(tuple of ints),似乎不是tuple也成(ints)。
>>> x = np.random.rand(2, 3)
>>> x.reshape((3, 2))
# 以tuple of ints
array([[ 0.19399632, 0.33569667],
[ 0.36343308, 0.7068406 ],
[ 0.89809989, 0.7316493 ]])
>>> x.reshape(3, 2)
array([[ 0.19399632, 0.33569667],
[ 0.36343308, 0.7068406 ],
[ 0.89809989, 0.7316493 ]])
3.2 reshape 实现维度的提升
(3, ) ≠ (3, 1):前者表示一维数组(无行和列的概念),后者则表示一个特殊的二维数组,也即是一个列向量;
>> x = np.ones(3)
>> x
array([ 1., 1., 1.])
>> x.reshape(3, 1)
array([[ 1.],
[ 1.],
[ 1.]])
>> x.reshape(1, 3)
array([[ 1., 1., 1.]])
3.3 reshape 与 resize
- reshape:有返回值,所谓有返回值,即不对原始多维数组进行修改;
- resize:无返回值,所谓有返回值,即会对原始多维数组进行修改;
>> X = np.random.randn(2, 3)
>> X
array([[ 1.23077478, -0.70550605, -0.37017735],
[-0.61543319, 1.1188644 , -1.05797142]])
>> X.reshape((3, 2))
array([[ 1.23077478, -0.70550605],
[-0.37017735, -0.61543319],
[ 1.1188644 , -1.05797142]])
>> X
array([[ 1.23077478, -0.70550605, -0.37017735],
[-0.61543319, 1.1188644 , -1.05797142]])
>> X.resize((3, 2))
>> X
array([[ 1.23077478, -0.70550605],
[-0.37017735, -0.61543319],
[ 1.1188644 , -1.05797142]])