numpy100题(48-74)
- Print the minimum and maximum representable value for each numpy scalar type (★★☆)
for dtype in [np.int8,np.int32,np.int64]:
print(np.iinfo(dtype).min)
print(np.iinfo(dtype).max)
for dtype in [np.float32,np.float64]:
print(np.finfo(dtype).min)
print(np.finfo(dtype).max)
print(np.finfo(dtype).eps)
- How to print all the values of an array? (★★☆)
import sys
np.set_printoptions(threshold=sys.maxsize)#default 1000
#该函数还有参数precision:打印小数的精确度
suppress:True,接近0的小数表示为0,False,小数用科学计数法表示
Z=np.zeros((16,16))
print(Z)
- How to find the closest value (to a given scalar) in a vector? (★★☆)
array_50=np.arange(100)
v=np.random.uniform(0,100) #随机采样函数
index=np.abs(array_50-v).argmin()
print(v,index)
- Create a structured array representing a position (x,y) and a color (r,g,b) (★★☆)
array_51=np.zeros(5,dtype=[('position',[('x','f8',1),
('y','f8',1)]),
('color',[('r','i4',1),
('g','i4',1),
('b','i4',1)])])
print(array_51.dtype)
- Consider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆)
vector_52=np.random.random((10,2))
# print(vector_52)
X,Y=np.atleast_2d(vector_52[:,0],vector_52[:,1]) #产生一个2d矩阵
distance=np.sqrt((X-X.T)**2+(Y-Y.T)**2)
print(distance)
- How to convert a float (32 bits) array into an integer (32 bits) in place?
解法1
array_53_1=np.arange(5,dtype=np.float32)
print(array_53_1.dtype)
array_53_1=array_53_1.astype(np.int32)
print(array_53_1.dtype)
解法2
array_53_2 = (np.random.rand(10)*100).astype(np.float32)
array_v = array_53_2.view(np.int32) #以int32的模式读取array_53_2
array_v[:]=array_53_2 #array_v.dtype=int32
print(array_v)
- How to read the following file? (★★☆)
array_54=np.genfromtxt('54.txt',delimiter=',',dtype=np.int) #delimiter:以逗号为符号分隔txt,组成数组
print(array_54)
- What is the equivalent of enumerate for numpy arrays? (★★☆)
array_55=np.arange(9).reshape(3,3)
# for i in np.ndenumerate(array_55): #返回索引和编号
print(i)
# for i in np.ndindex(array_55.shape): #只返回索引
print(i)#55.
- Generate a generic 2D Gaussian-like array (★★☆)
看不懂题目,照抄答案...
X, Y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10))
D = np.sqrt(X*X+Y*Y)
sigma, mu = 1.0, 0.0
G = np.exp(-( (D-mu)**2 / ( 2.0 * sigma**2 ) ) )
print(G)
- How to randomly place p elements in a 2D array? (★★☆)
解法1
array_57=np.arange(9).reshape(3,3)*10
p_57=[6,6,6]
array_57_v=array_57.view()
array_57_v=np.reshape(array_57_v,9)
rd=np.random.choice(np.arange(9),3)
np.put(array_57_v,rd,p_57)
print(array_57)
解法2
n = 10
p = 3
array_57 = np.zeros((n,n))
np.put(array_57, np.random.choice(range(n*n), p, replace=False),1)#replace=False不允许出现重复
print(Z)
np.put()函数:
np.put(目标数组,索引,替换值)
- Subtract the mean of each row of a matrix (★★☆)
解法1
mat_58=np.arange(9).reshape(3,3)
mat_58_mean=np.mean(mat_58,axis=1)
mat_58_mean=mat_58_mean.reshape(3,1)
res_58=mat_58-mat_58_mean
print(res_58)
解法2
mat_58 = np.random.rand(5, 10)
res_mat_58 = mat_58 - mat_58.mean(axis=1, keepdims=True)#keepdims保持原维度
print(res_58)
- How to sort an array by the nth column? (★★☆)
array_59=np.random.random((3,3))*10
array_59[:,2]=np.sort(array_59[:,2])
print(array_59)
- How to tell if a given 2D array has null columns? (★★☆)
array_60=np.array([[0,2,3],
[0,1,2]])
print(np.any(array_60,axis=0))
print((~np.any(array_60,axis=0)).any())
# ~ bool取反运算符,np.any()或运算
- Find the nearest value from a given value in an array (★★☆)
value_61=5.123
array_61=np.arange(9).reshape(3,3))
print(array_61.flat[abs(array_61-value_61).argmin()])
- 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])
- Create an array class that has a name attribute (★★☆)
class NamedArray(np.ndarray):
def __new__(cls, array, name="no name"):
obj = np.asarray(array).view(cls)
obj.name = name
return obj
def __array_finalize__(self, obj):
if obj is None: return
self.info = getattr(obj, 'name', "no name")
- Consider a given vector, how to add 1 to each element indexed by a second vector (be careful with repeated indices)? (★★★)
解法1
array_64=np.zeros(10)
rd_64=np.random.randint(0,len(array_64),15)
array_64+=np.bincount(rd_64,minlength=len(array_64))
print(array_64)
np.bincount()函数
#numpy.bincount(x, weights=None, minlength=0)
#x为1维目标数组,weights为权值,minlength为最小长度(不得小于原长度)。
#该函数返回一个索引,长度为数组中最大值+1
a=array([9, 3, 3, 4, 4])
print(np.bincount(a))
#array([0, 0, 0, 2, 2, 0, 0, 0, 0, 1], dtype=int64)
w=np.array([0.1,0.2,0.3,0.4,0.5])
print(np.bincount(a,weights=w))
#array([0. , 0. , 0. , 0.5, 0.9, 0. , 0. , 0. , 0. , 0.1])
print(np.bincount(a,weights=w,minlength=15))
#array([0. , 0. , 0. , 0.5, 0.9, 0. , 0. , 0. , 0. , 0.1, 0. , 0. , 0. ,0. , 0. ])
解法2
array_64=np.zeros(10)
rd_64=np.random.randint(0,len(array_64),15)
np.add.at(array_64,rd_64,1)
print(array_64)
np.add.at(x,y,value)函数
#x:目标数组,y:索引数组,value:add的值
a=np.arange(5)
b=np.array([0,1,2,3,4])
np.add.at(a,b,1)
print(a)
#array([1, 2, 3, 4, 5])
- How to accumulate elements of a vector (X) to an array (F) based on an index list (I)? (★★★)
vector_X = np.arange(5)
list_I = np.array([1,1,2,2,3])
array_F = np.bincount(list_I,vector_X)#X为权值
print(array_F)
- Considering a (w,h,3) image of (dtype=ubyte), compute the number of unique colors (★★★)
没看懂题目要干嘛。。。
w, h = 16, 16
I = np.random.randint(0, 2, (h, w, 3)).astype(np.ubyte)
F = I[..., 0] * 256 * 256 + I[..., 1] * 256 + I[..., 2]
n = len(np.unique(F)) #返回一个排序过的数组,打印原数组中出现过的元素各一次
print(np.unique(I))
- Considering a four dimensions array, how to get sum over the last two axis at once? (★★★)
array_67 = np.arange(16).reshape((2, 2, 2, 2))
sum_1 = np.sum(array_67, axis=-1)
sum_2 = np.sum(array_67, axis=-2)
sum_1_2 = np.sum(array_67, axis=(-1, -2))
print(sum_1,"\n",sum_2,"\n",sum_1_2)
- Considering a one-dimensional vector D, how to compute means of subsets of D using a vector S of same size describing subset indices? (★★★)
又是一题没看懂题干的题目,不知道到底要我干什么
vector_68 = np.random.uniform(0, 1, 100)
vector_S = np.random.randint(0, 10, 100)
sum_68 = np.bincount(vector_S, weights=vector_68)
counts_68 = np.bincount(vector_S)
print(sum_68/counts_68)
- How to get the diagonal of a dot product? (★★★)
vector_69_1 = np.arange(9).reshape(3, 3)
vector_69_2 = np.ones((3, 3))
value_69 = vector_69_1 @ vector_69_2
print(np.diag(value_69))#慢
print(np.sum(vector_69_1 * vector_69_2.T, axis=1))#中
print(np.einsum('ij,ji->i',vector_69_1,vector_69_2)) #快
关于np.einsum()函数,详见该博客
(https://cloud.tencent.com/developer/article/1369762)
- Consider the vector [1, 2, 3, 4, 5], how to build a new vector with 3 consecutive zeros interleaved between each value? (★★★)
step = 3
vector_70 = np.array([1, 2, 3, 4, 5])
zeros_70 = np.zeros((len(vector_70) - 1) * step + len(vector_70))
zeros_70[::step + 1] = vector_70
print(zeros_70)
#很机智的解法!
- Consider an array of dimension (5,5,3), how to mulitply it by an array with dimensions (5,5)? (★★★)
array_71 = np.arange(75).reshape(5, 5, 3)
array_71_55 = np.ones((5, 5))
array_71_55 = array_71_55[..., None]
print(array_71*array_71_55)
- How to swap two rows of an array? (★★★)
解法1
array_72 = np.arange(9).reshape(3, 3)
row_temp = array_72[0, :].copy()
array_72[0, :] = array_72[1, :]
array_72[1, :] = row_temp
# print(array_72)
解法2
array_72 = np.arange(25).reshape(5, 5)
array_72[[0, 1]] = array_72[[1, 0]] #表示直接交换标记的两行
print(array_72)
- Consider a set of 10 triplets describing 10 triangles (with shared vertices), find the set of unique line segments composing all the triangles (★★★)
看完答案也不知道这道题在干嘛...弃了
faces = np.random.randint(0,100,(10,3))
F = np.roll(faces.repeat(2,axis=1),-1,axis=1)
F = F.reshape(len(F)*3,2)
F = np.sort(F,axis=1)
G = F.view( dtype=[('p0',F.dtype),('p1',F.dtype)] )
G = np.unique(G)
print(G)
- Given an array C that is a bincount, how to produce an array A such that np.bincount(A) == C? (★★★)
array_74 = np.bincount([1, 1, 2, 3, 4, 4, 6])
A_74 = np.repeat(np.arange(len(array_74)), array_74)
print(A_74)
numpy100题刷到★★★的题目时明显感觉力不从心,大部分题目都难以理解出题意图,用到的函数也越来越复杂,导致我抄答案越来越频繁。学习效率也越来越低...因此我打算不再往下死磕,numpy学到如今也算有所了解,能应付机器学习中的日常使用,如果以后在实践中遇到不懂的再进行学习。
概率论部分
1.多维随机变量函数的分布,,,真难,听说是概率论里最难的
2.数学期望,方差,标准差,,,简单多了









网友评论