Numpy笔记


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]])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值