[Numpy][学习笔记] Numpy 中向量使用技巧_避免秩为1的形式

在使用矩阵或向量时,需要尽量避免使用秩为1的形式以避免未可知的错误

a = np.random.randn(5) # rank 1 array, 尽量不使用
# 使用:
a = np.random.randn(5,1)
a = np.random.randn(1,5)

如果得到秩为1的向量,可以通过 a.reshape(5, 1) or a.reshape(1, 5) 来改变

在程序编写过程中,可以使用 assert() 来判断向量是否符合要求,例如:


  • Demo 1
import numpy as np

a = np.random.randn(5)

print(a)
assert(a.shape == (5, 1))
  • Demo 1 输出结果:
[ 1.21639459 -0.28145761 -0.52131199  0.07465154 -1.34308672]
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-3-978fe4e79b86> in <module>
      4 
      5 print(a)
----> 6 assert(a.shape == (5, 1))

AssertionError: 

  • Demo 2
import numpy as np

a = np.random.randn(5, 1)

print(a)
assert(a.shape == (5, 1))
  • Demo 2 输出结果:
[[-0.75186333]
 [-1.18857409]
 [-0.55769239]
 [ 1.27631033]
 [ 1.09097972]]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值