统计机器学习-3-numpy100题

numpy 100道练习题

这100道练习题从numpy的mailing list、Stack Overflow和numpy官方文档收集而来,其目的是提供一个快速入门的参考文档为numpy学习者,也可以用作教学练习题。

如果你发现错误或者有更好的解法,欢迎在github上提交issue: https://github.com/rougier/numpy-100

1.如何导入numpy包?

import numpy as np

2.打印numpy版本和配置信息

print(np.__version__)
1.15.4
np.show_config()
blas_mkl_info:
  NOT AVAILABLE
blis_info:
  NOT AVAILABLE
openblas_info:
    libraries = ['openblas', 'openblas']
    library_dirs = ['/usr/local/lib']
    language = c
    define_macros = [('HAVE_CBLAS', None)]
blas_opt_info:
    libraries = ['openblas', 'openblas']
    library_dirs = ['/usr/local/lib']
    language = c
    define_macros = [('HAVE_CBLAS', None)]
lapack_mkl_info:
  NOT AVAILABLE
openblas_lapack_info:
    libraries = ['openblas', 'openblas']
    library_dirs = ['/usr/local/lib']
    language = c
    define_macros = [('HAVE_CBLAS', None)]
lapack_opt_info:
    libraries = ['openblas', 'openblas']
    library_dirs = ['/usr/local/lib']
    language = c
    define_macros = [('HAVE_CBLAS', None)]

3.创建一个10维的空向量

Z = np.zeros(10)
print(Z)
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]

4.查看一个矩阵占用内存大小

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

5.查看方法帮助信息

%run `python -c "import numpy; numpy.info(numpy.add)"`
ERROR:root:File `'`python.py'` not found.

6.创建一个10维的空向量,第5个元素值置1

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

7.创建一个向量,值为10到49

Z = np.arange(10,50)
print(Z)
[10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49]

8.反转一个向量

Z = np.arange(10)
Z = Z[::-1]
print(Z)
[9 8 7 6 5 4 3 2 1 0]

9.创建一个3*3的矩阵,值为0-8

Z = np.arange(0,9).reshape(3,3)
print(Z)
[[0 1 2]
 [3 4 5]
 [6 7 8]]

10.查找向量中的非负元素的位置

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

11.创建一个3*3的单位矩阵

Z = np.eye(3)
print(Z)
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]

12.创建一个3x3x3的随机数组

Z = np.random.random((3,3,3))
print(Z)
[[[0.13854955 0.99835168 0.14964813]
  [0.81025815 0.26882349 0.17608854]
  [0.50149982 0.30969241 0.79233029]]

 [[0.25014841 0.62259016 0.08474709]
  [0.41144453 0.07678162 0.4215841 ]
  [0.95705938 0.74772762 0.61415939]]

 [[0.10280342 0.5927821  0.67836604]
  [0.57329144 0.57727532 0.68117433]
  [0.7110556  0.38961554 0.8672104 ]]]

13.创建一个10*10的二维数组,找到其中的最大值和最小值

Z = np.random.random((10,10))
print(Z)
Zmin, Zmax = Z.min(), Z.max()
print(Zmin,Zmax)
[[0.25561564 0.34677381 0.37291065 0.36407523 0.57075556 0.74616685
  0.29275394 0.97174189 0.70312293 0.95137757]
 [0.32930664 0.76680212 0.03411341 0.6891707  0.07525525 0.63305991
  0.56937379 0.50935112 0.44551824 0.16113358]
 [0.38287982 0.43948445 0.45147072 0.45343676 0.84147744 0.84405623
  0.17612155 0.44853487 0.59365967 0.21382305]
 [0.57737686 0.76764731 0.52924878 0.43832771 0.43232812 0.27582494
  0.81809636 0.48204092 0.72446075 0.17121314]
 [0.78361539 0.3670213  0.43745526 0.79392565 0.94043517 0.98780196
  0.87732521 0.09725379 0.5779913  0.1794939 ]
 [0.47516542 0.14197428 0.81696136 0.28916184 0.35305486 0.26131989
  0.38968154 0.69896065 0.75537356 0.55963109]
 [0.26552027 0.55082818 0.32947654 0.04898929 0.2270137  0.25364827
  0.38164323 0.41891464 0.12324579 0.90304341]
 [0.2131408  0.22453357 0.37561031 0.16563801 0.03372727 0.46461429
  0.49478784 0.57528389 0.28509153 0.05824959]
 [0.22434699 0.62551763 0.76722029 0.22688218 0.91387016 0.70209686
  0.79776406 0.66136601 0.29725645 0.77543245]
 [0.27549283 0.37891796 0.26681741 0.07157089 0.89681116 0.05042483
  0.04756321 0.224474   0.44364862 0.44257503]]
0.03372726599172826 0.9878019616433998

14.创建一个30维的随机向量,找到其中的平均值

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

15.创建一个二维数组,内部为0边为1

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

16.给一个矩阵加边(全为0)

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

17.计算下列表达式的结果

print(0 * np.nan)
print(np.nan == np.nan)
print(np.inf > np.nan)
print(np.nan - np.nan)
print(np.nan in set([np.nan]))
print(0.3 == 3*0.1)
nan
False
False
nan
True
False

18.创建一个5x5的矩阵,对角线下面的一行为[1,2,3,4]

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.创建一个8x8的矩阵,用棋盘格模式填充

Z = np.zeros((8,8))
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.创建一个6x7x8的数组,第100个元素的坐标是什么?

print(np.unravel_index(100,(6,7,8)))
(1, 5, 4)

21.使用tile函数创建一个8x8的棋盘矩阵

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

22.标准化一个5x5的随机矩阵

Z = np.random.random((5,5))
print(Z)
print(np.mean(Z))
print(Z - np.mean(Z))
print(np.std(Z))
Z = (Z - np.mean(Z))/(np.std(Z))
print(Z)
[[0.30044185 0.71441592 0.60760487 0.36140299 0.70529362]
 [0.95490502 0.68696356 0.87501537 0.11260691 0.63311754]
 [0.4172747  0.12554581 0.06697218 0.59951544 0.63208388]
 [0.29634218 0.59950745 0.26741324 0.55475958 0.53740619]
 [0.77365458 0.3582571  0.04332674 0.65957491 0.8489008 ]]
0.5092920976751807
[[-0.20885025  0.20512382  0.09831277 -0.1478891   0.19600152]
 [ 0.44561292  0.17767147  0.36572328 -0.39668518  0.12382544]
 [-0.0920174  -0.38374629 -0.44231992  0.09022335  0.12279178]
 [-0.21294992  0.09021535 -0.24187886  0.04546748  0.02811409]
 [ 0.26436248 -0.15103499 -0.46596535  0.15028281  0.3396087 ]]
0.25529712546277883
[[-0.81806736  0.80347093  0.38509159 -0.57928229  0.76773885]
 [ 1.74546782  0.69593994  1.43253973 -1.55381767  0.48502482]
 [-0.36043255 -1.50313597 -1.73256914  0.35340526  0.48097596]
 [-0.83412579  0.35337394 -0.9474406   0.17809633  0.11012304]
 [ 1.03550903 -0.59160476 -1.82518841  0.58865846  1.33024883]]

23.创建一个描述颜色的自定义数据类型

color = np.dtype([("r", np.ubyte, 1),
                  ("g", np.ubyte, 1),
                  ("b", np.ubyte, 1),
                  ("a", np.ubyte, 1)])
print(color)
[('r', 'u1'), ('g', 'u1'), ('b', 'u1'), ('a', 'u1')]

24.矩阵相乘:一个5x3的矩阵乘上3x2的矩阵

Z = np.dot(np.ones((5,3)), np.ones((3,2)))
print(Z)
# python 3.5以上可以用另外一种方式
Z = np.ones((5,3)) @ np.ones((3,2))
[[3. 3.]
 [3. 3.]
 [3. 3.]
 [3. 3.]
 [3. 3.]]

25.给定一个1维数组,把3-8之间的数取反

Z = np.arange(11)
Z[(3<Z)&(Z<=8)] *=-1
print(Z)
[ 0  1  2  3 -4 -5 -6 -7 -8  9 10]

26.下列脚本的输出是什么?

print(sum(range(5),-1))
from numpy import *
print(sum(range(5),-1))

# https://stackoverflow.com/questions/39552458/python-sum-has-a-different-result-after-importing-numpy
9
10

27.Z是零向量,下列哪些表达式是合法的?

Z = zeros(5)
print(Z)
print(Z**Z)
# 2<<Z>>2
print(Z<-Z)
print(1j*Z)
print(Z/1/1)
#print(Z<Z>Z)
[0. 0. 0. 0. 0.]
[1. 1. 1. 1. 1.]
[False False False False False]
[0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]
[0. 0. 0. 0. 0.]

28.下列表达式的结果是什么?

print(np.array(0) / np.array(0))
print(np.array(0) // np.array(0))
print(np.array([np.nan]).astype(int).astype(float))
nan
0
[-9.22337204e+18]


/usr/local/lib/python3.7/site-packages/ipykernel_launcher.py:1: RuntimeWarning: invalid value encountered in true_divide
  """Entry point for launching an IPython kernel.
/usr/local/lib/python3.7/site-packages/ipykernel_launcher.py:2: RuntimeWarning: divide by zero encountered in floor_divide

29. 数组向上取整

Z = np.random.uniform(-10,+10,10)
print(Z)
print(np.ceil(np.abs(Z)))
print (np.copysign(np.ceil(np.abs(Z)), Z))
[ 7.91394163 -9.96084271 -1.9621627   3.78892767 -7.99546695 -3.27477486
  5.69418011 -0.97745194  7.17444217  5.91949544]
[ 8. 10.  2.  4.  8.  4.  6.  1.  8.  6.]
[  8. -10.  -2.   4.  -8.  -4.   6.  -1.   8.   6.]

30.找到两个数组的公共元素

Z1 = np.random.randint(0,10,10)
print(Z1)
print(Z2)
Z2 = np.random.randint(0,10,10)
print(np.intersect1d(Z1,Z2))
[2 7 1 7 3 8 8 8 1 8]



---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

<ipython-input-36-a190b35a16f9> in <module>
      1 Z1 = np.random.randint(0,10,10)
      2 print(Z1)
----> 3 print(Z2)
      4 Z2 = np.random.randint(0,10,10)
      5 print(np.intersect1d(Z1,Z2))


NameError: name 'Z2' is not defined

31.如何忽略numpy提醒

# Suicide mode on
defaults = np.seterr(all='ignore')
Z = np.ones(1)/0
print(Z)

# Back to sanity
_ = np.seterr(**defaults)

#An equivalent way, with a context manager:

with np.errstate(divide='ignore'):
    Z = np.ones(1) / 0
    

32.下列表达式是否正确

print(np.sqrt(-1))
print(np.emath.sqrt(-1))
np.sqrt(-1) == np.emath.sqrt(-1)

33. 取得昨天、今天、明天的日期

yesterday = np.datetime64('today', 'D') - np.timedelta64(1, 'D')
today     = np.datetime64('today', 'D')
tomorrow  = np.datetime64('today', 'D') + np.timedelta64(1, 'D')
print(yesterday,today,tomorrow)

34.计算( (A+B)*-(A/2)),不使用复制

A = np.ones(3)*1
B = np.ones(3)*2
C = np.ones(3)*3
print(A)
print(B)
print(C)
np.add(A,B,out=A)
print(A)
np.divide(A,2,out=A)
print(A)
np.negative(A,out=A)
print(A)
np.multiply(A,B,out=A)
print(A)

36.五种方法提取一个数组的整数部分

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

37.创建一个5*5的矩阵,每一行的值为0到4

Z = np.zeros((5,5))
Z += np.arange(5)
print(Z)

38.创建一个函数生成器生成10个整数,用这个函数生成一个数组

def generate():
    for x in range(10):
        yield x
Z = np.fromiter(generate(),dtype=float,count=-1)
print(Z)

39. 创建一个10维的向量,取值在0到1之间,不包含0和1

Z = np.linspace(0,1,11,endpoint=False)[1:]
print(Z)

40.创建一个10维的随机向量并排序

Z = np.random.random(10)
Z.sort()
print(Z)

41.怎样对数组求和比np.sum()更快?

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

42.检查随机数组A和B是否相等

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

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.令一个数组不可变

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

44.将笛卡尔坐标转换为极坐标

Z = np.random.random((10,2))
print(Z)
X,Y = Z[:,0], Z[:,1]
print(X)
print(Y)
R = np.sqrt(X**2+Y**2)
T = np.arctan2(Y,X)
print(R)
print(T)

45.创建一个10维的随机向量,并用0取代最大值

Z = np.random.random(10)
Z[Z.argmax()] = 0
print(Z)

46.创建一个结构化数组,其x和y坐标覆盖[0,1] x [0,1]区域

Z = np.zeros((5,5), [('x',float),('y',float)])
print(Z)
Z['x'], Z['y'] = np.meshgrid(np.linspace(0,1,5),
                             np.linspace(0,1,5))
print(Z)
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页