基础学习--NumPy

本文记录了作者系统学习NumPy的过程,从安装Anaconda和Jupyter Notebook,到利用numpy_exercises和numpy-100资源进行实战练习。通过修改Jupyter配置和安装numpy,作者开始学习NumPy的基础知识,旨在提升在目标检测项目中的理解能力。
摘要由CSDN通过智能技术生成

我又来啦,抱歉啊,最近有点事情,opencv就先搁一搁吧,以后有空再补上吧,最近在做一个目标检测的工作,在看源码的时候发现了numpy的使用挺频繁的,之前一直没有系统的接触过,看源码的时候磕磕碰碰的,因此打算抽点时间系统的学习一下,现在记录一下。首先我在github上找来几个比较nice的练手的项目,链接如下

接下来便开始我们的正题把,首先,需要安装Anaconda软件,这个安装比较简单,不再赘述了

注:就是注意下载的时候尽量选择较新的版本,之前遇到一个学弟拿着旧的版本装上了但是使用不了,踩了一些坑。下载之后就是换国内源的操作,这个也比较简单,直接给比较靠谱的链接吧。

安装结束后,打开终端,输入下面指令安装Jupyter Notebook

指令输入:conda create -n Pynote jupyter=1.0.0
# 需要等待一段时间安装
指令输入:conda activate Pynote
# 激活虚拟环境
指令输入:jupyter notebook --generate-config --allow-root
窗口会弹出:Writing default config to: /home/xx/.jupyter/jupyter_notebook_config.py
# xx是你的服务器的名字
指令输入:sudo gedit /home/bobo/.jupyter/jupyter_notebook_config.py

在弹出的jupyter_notebook_config.py对文件进行更改,找到

## 是否允许notebook在root用户下运行.
#c.NotebookApp.allow_root = False

将其修改为c.NotebookApp.allow_root =True ,保存退出。
还需要安装numpy等

pip install mdutils==1.0.0  pandas==0.25.3 numpy==1.17.4 -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com

接着打开

python initialise.py

如果没有输出任何东西就可以了,接下来输入

jupyter notebook

在这里插入图片描述根据自己的路径找到numpy-100-master文件夹,打开100_Numpy_exercises.ipynb即可,画面如下
在这里插入图片描述接下来就可以学习啦,具体内容我还是记录一下吧,我以后自己也方便查找

1. Import the numpy package under the name np

>>import numpy as np

2. Print the numpy version and the configuration

>>print(np.__version__)
     np.show_config()

3. Create a null vector of size 10

>>np.zeros(10)
--array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])

4. How to find the memory size of any array

>>Z = np.zeros((10,10))
     print("%d bytes" % (Z.size * Z.itemsize))
--800 bytes

6. Create a null vector of size 10 but the fifth value which is 1

>>Z = np.zeros(10)
	Z[4] = 1
	print(Z)

7. Create a vector with values ranging from 10 to 49

>>np.arange(10,50)
 
8. Reverse a vector (first element becomes last) 
 >>Z = np.arange(50)
      Z = Z[::-1]
	  print(Z)

9. Create a 3x3 matrix with values ranging from 0 to 8?
>>Z = np.arange(9)
	 Z = Z.reshape(3,3)
	 print(Z)

10.  Find indices of non-zero elements from [1,2,0,0,4,0] ?

>>nz = np.nonzero([1,2,0,0,4,0])
	 print(nz)

11. Create a 3x3 identity matrix 
>>Z = np.eye(3)
    print(Z)

12. Create a 3x3x3 array with random values
>>Z = np.random.random((3,3,3))
print(Z)

13. Create a 10x10 array with random values and find the minimum and maximum values 

>>Z = np.random.random((10,10))
Zmin, Zmax = Z.min(), Z.max()
print(Zmin, Zmax)

14. Create a random vector of size 30 and find the mean value 

>>Z = np.random.random(30)
m = Z.mean()
print(m)

15. Create a 2d array with 1 on the border and 0 inside 

>>Z = np.ones((10,10))
Z[1:-1,1:-1] = 0
print(Z)
[[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]]


16. How to add a border (filled with 0's) around an existing array? 

>>Z = np.ones((5,5))
Z = np.pad(Z, pad_width=1, mode='constant', constant_values=0)
print(Z)
[[0. 0. 0. 0. 0. 0. 0.]
 [0. 1. 1. 1. 1. 1. 0.]
 [0. 1. 1. 1. 1. 1. 0.]
 [0. 1. 1. 1. 1. 1. 0.]
 [0. 1. 1. 1. 1. 1. 0.]
 [0. 1. 1. 1. 1. 1. 0.]
 [0. 0. 0. 0. 0. 0. 0.]]

Z = np.pad(Z, pad_width=(2,1), mode='constant', constant_values=0)
[[0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 1. 1. 1. 1. 1. 0.]
 [0. 0. 1. 1. 1. 1. 1. 0.]
 [0. 0. 1. 1. 1. 1. 1. 0.]
 [0. 0. 1. 1. 1. 1. 1. 0.]
 [0. 0. 1. 1. 1. 1. 1. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0.]]

注:numpy.pad(array, pad_width, mode, **kwargs)   array为要填补的数组  pad_width是在各维度的各个方向上想要填补的长度,如((1,2),(2,2)),表示在第一个维度上水平方向上padding=1,垂直方向上padding=2,在第二个维度上水平方向上padding=2,垂直方向上padding=2。  mode为填补类型,即怎样去填补,有“constant”,“edge”等模式,如果为constant模式,就得指定填补的值,如果不指定,则默认填充0。 

18. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal 
>>Z = np.diag(1+np.arange(4),k=-1)
print(Z)
[[0 0 0 0 0]
 [1 0 0 0 0]
 [0 2 0 0 0]
 [0 0 3 0 0]
 [0 0 0 4 0]]

19. Create a 8x8 matrix and fill it with a checkerboard pattern
>>Z = np.zeros((8,8),dtype=int)
Z[1::2,::2] = 1
Z[::2,1::2] = 1
print(Z)
[[0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]]

20. Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element?

>>print(np.unravel_index(99,(6,7,8)))
(1, 5, 3)
注:numpy.unravel_index()函数的作用是获取一个/组int类型的索引值在一个多维数组中的位置。

21. Create a checkerboard 8x8 matrix using the tile function

>>Z = np.tile( np.array([[0,1],[1,0]]), (4,4))
print(Z)
[[0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]]
注:np.tile(a,(2,1))第一个参数为Y轴扩大倍数,第二个为X轴扩大倍数

22. Normalize a 5x5 random matrix

>>Z = np.random.random((5,5))
Z = (Z - np.mean (Z)) / (np.std (Z))
print(Z)
[[ 1.15972105 -0.46489348 -0.54634326 -0.54532322  0.43112979]
 [-0.74008296  0.651723   -0.24030448 -0.41589879 -0.01090501]
 [ 1.05512364 -0.28942058  1.69309926 -0.98126981  1.34581954]
 [-1.60600824 -1.02816557  0.6395796   1.46040082 -0.04551563]
 [-0.94638975 -1.80197518  1.07010047  1.3300596  -1.17426082]]

注:np.random.random(5,5)有错

24. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product)

>>Z = np.dot(np.ones((5,3)), np.ones((3,2)))
print(Z)

# Alternative solution, in Python 3.5 and above
Z = np.ones((5,3)) @ np.ones((3,2))
print(Z)
[[3. 3.]
 [3. 3.]
 [3. 3.]
 [3. 3.]
 [3. 3.]]
 
[[3. 3.]
 [3. 3.]
 [3. 3.]
 [3. 3.]
 [3. 3.]]
注:dot矩阵乘法

25. Given a 1D array, negate all elements which are between 3 and 8, in place

>>Z = np.arange(11)
Z[(3 < Z) & (Z < 8)] *= -1
print(Z)

[ 0  1  2  3 -4 -5 -6 -7  8  9 10]

29. How to round away from zero a float array ? 

>>Z = np.random.uniform(-10,+10,10)
print (np.copysign(np.ceil(np.abs(Z)), Z))

[  4.   8.  -8.  -4. -10.   4.   3.  -4.   4.   1.]

注: numpy.random.uniform(low,high,size) 功能:从一个均匀分布[low,high)中随机采样,注意定义域是左闭右开,即包含low,不包含high.
np.ceil(ndarray)  计算大于等于该值的最小整数
np.abs(x)、np.fabs(x) : 计算数组各元素的绝对值
np.sqrt(x) : 计算数组各元素的平方根
np.square(x) : 计算数组各元素的平方
np.log(x) 、np.log10(x)、np.log2(x) : 计算数组各元素的自然对数、10底对数和2底对数
np.copysign(x,y)将数组y中各元素的符号赋值给数组x对应元素

30. How to find common values between two arrays?
>>Z1 = np.random.randint(0,10,10)
Z2 = np.random.randint(0,10,10)
print(np.intersect1d(Z1,Z2))

35. How to compute ((A+B)*(-A/2)) in place (without copy)?
>>A = np.ones(3)*1
B = np.ones(3)*2
C = np.ones(3)*3
np.add(A,B,out=B)
np.divide(A,2,out=A)
np.negative(A,out=A)
np.multiply(A,B,out=A)

36. Extract the integer part of a random array using 5 different methods 

>>Z = np.random.uniform(0,10,10)
print (Z - Z%1)
print (np.floor(Z))
print (np.ceil(Z)-1)
print (Z.astype(int))
print (np.trunc(Z))

37. Create a 5x5 matrix with row values ranging from 0 to 4 

>>Z = np.zeros((5,5))
Z += np.arange(5)
print(Z)
[[0. 1. 2. 3. 4.]
 [0. 1. 2. 3. 4.]
 [0. 1. 2. 3. 4.]
 [0. 1. 2. 3. 4.]
 [0. 1. 2. 3. 4.]]

38. Consider a generator function that generates 10 integers and use it to build an array 

>>def generate():
       for x in range(10):
           yield x
Z = np.fromiter(generate(),dtype=float,count=-1)
print(Z)
[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
注:np.fromiter从可迭代对象创建新的1维数组

39. Create a vector of size 10 with values ranging from 0 to 1, both excluded 

>>Z = np.linspace(0,1,11,endpoint=False)[1:]
print(Z)
[0.09090909 0.18181818 0.27272727 0.36363636 0.45454545 0.54545455
 0.63636364 0.72727273 0.81818182 0.90909091]
注:np.linspace主要用来创建等差数列
numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)
start:返回样本数据开始点
stop:返回样本数据结束点
num:生成的样本数据量,默认为50
endpoint:True则包含stop;False则不包含stop
retstep:If True, return (samples, step), where step is the spacing between samples.(即如果为True则结果会给出数据间隔)
dtype:输出数组类型
axis:0(默认)或-1

40. Create a random vector of size 10 and sort it 

>>Z = np.random.random(10)
Z.sort()
print(Z)
[0.0119475  0.12451302 0.19165422 0.22138576 0.2827767  0.32220576
 0.49167575 0.59730205 0.61813293 0.69876549]

41. How to sum a small array faster than np.sum? 

>>Z = np.arange(10)
np.add.reduce(Z)
45

42. Consider two random array A and B, check if they are equal

>>A = np.random.randint(0,2,5)
B = np.random.randint(0,2,5)

# Assuming identical shape of the arrays and a tolerance for the comparison of values
equal = np.allclose(A,B)
print(equal)

# Checking both the shape and the element values, no tolerance (values have to be exactly equal)
equal = np.array_equal(A,B)
print(equal)

43. Make an array immutable (read-only) 

>>Z = np.zeros(10)
Z.flags.writeable = False
Z[0] = 1

46. Create a structured array with x and y coordinates covering the [0,1]x[0,1] area

>>Z = np.zeros((5,5), [('x',float),('y',float)])
Z['x'], Z['y'] = np.meshgrid(np.linspace(0,1,5),
                             np.linspace(0,1,5))
print(Z)

47. Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj))

>>X = np.arange(8)
Y = X + 0.5
C = 1.0 / np.subtract.outer(X, Y)
print(np.linalg.det(C))
3638.163637117973

注:np.subtract.outer()的例子
a = np.array([5,6,7])
b = np.array([9,12,10])
np.subtract.outer(b,a)
array([[4, 3, 2],
       [7, 6, 5],
       [5, 4, 3]])
9 - 5 = 4  12 - 5 = 7  10 - 5 = 5
9 - 6 = 3  12 - 6 = 6  10 - 6= 4
9 - 7 = 2  12 - 7 = 5  10 - 7= 3
np.linalg.det():矩阵求行列式
np.linalg.inv():矩阵求逆
np.linalg.norm():求范数

53. How to convert a float (32 bits) array into an integer (32 bits) in place?

>>Z = (np.random.rand(10)*100).astype(np.float32)
Y = Z.view(np.int32)
Y[:] = Z
print(Y)
[24 24 48 80 19 42 59 25 20 53]

55. What is the equivalent of enumerate for numpy arrays?

>>Z = np.arange(9).reshape(3,3)
for index, value in np.ndenumerate(Z):
    print(index, value)
for index in np.ndindex(Z.shape):
    print(index, Z[index])
(0, 0) 0
(0, 1) 1
(0, 2) 2
(1, 0) 3
(1, 1) 4
(1, 2) 5
(2, 0) 6
(2, 1) 7
(2, 2) 8
(0, 0) 0
(0, 1) 1
(0, 2) 2
(1, 0) 3
(1, 1) 4
(1, 2) 5
(2, 0) 6
(2, 1) 7
(2, 2) 8

57. How to randomly place p elements in a 2D array?

>>n = 10
p = 3
Z = np.zeros((n,n))
np.put(Z, np.random.choice(range(n*n), p, replace=False),1)
print(Z)
[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 1. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]]
 
 注:
choice(a, size=None, replace=True, p=None)
a为一个一维数据或者int的对象
size为随机选取出后的数据的类型,可以是一维,也可以是二维
replace=True 代表选取后可以放回,也就是说有可能会出现重复选取的数据
replace=False 代表选取后不放回,不会出现重复数据
p为选取的概率

59. How to sort an array by the nth column?

>>Z = np.random.randint(0,10,(3,3))
print(Z)
print(Z[Z[:,1].argsort()])
[[2 3 5]
 [4 9 4]
 [1 1 8]]
[[1 1 8]
 [2 3 5]
 [4 9 4]]
 注:
 np.argsort()函数将数组的值从小到大排序后,并按照其相对应的索引值输出
b = array([[10,3,5],[4,6,1]])
print(np.argsort(b,axis=1))	 # 按行排序
print(np.argsort(b,axis=0))
[[1 2 0]
 [2 0 1]]
[[1 0 1]
 [0 1 0]]
 
 61. Find the nearest value from a given value in an array
 
 >>Z = np.random.uniform(0,1,10)
z = 0.5
m = Z.flat[np.abs(Z - z).argmin()]
print(m)
0.3934212956276276
注:flat返回的是一个迭代器,可以用for访问数组每一个元素
 
 62. Considering two arrays with shape (1,3) and (3,1), how to compute their sum using an iterator? 
 
 >>A = np.arange(3).reshape(3,1)
B = np.arange(3).reshape(1,3)
it = np.nditer([A,B,None])
for x,y,z in it: z[...] = x + y
print(it.operands[2])
 [[0 1 2]
 [1 2 3]
 [2 3 4]]

三星的和另外一个学习资料未详细的记录,感兴趣的自己去看吧,在这里感谢那些开源的同学!!!分享到此结束吧,不早了,洗洗睡觉了吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值