美文网首页
numpy练习100题(76-100)

numpy练习100题(76-100)

作者: 海盗船长_coco | 来源:发表于2019-12-26 12:49 被阅读0次

后面的题目基本都写不出来,平时遇到的也不多,为了文章的完整性,将答案贴出。

  1. 考虑一维数组Z,构建一个二维数组, 其第一行是(Z [0],Z [1],Z [2]),每个后续行移1(最后一行应该是( Z [-3],Z [-2],Z [-1])(提示: from numpy.lib import stride_tricks)
from numpy.lib import stride_tricks


def rolling(a, window):
    shape = (a.size - window + 1, window)
    strides = (a.itemsize, a.itemsize)
    return stride_tricks.as_strided(a, shape=shape, strides=strides)


Z = rolling(np.arange(10), 3)
print(Z)
  1. 如何对布尔值取反,或者原位(in-place)改变浮点数的符号(sign)?(提示: np.logical_not, np.negative)
# 方法一
Z = np.random.randint(0, 2, 100)
np.logical_not(Z, out=Z)
# 方法二
Z = np.random.uniform(-1.0, 1.0, 100)
np.negative(Z, out=Z)
  1. 考虑两组点集P0和P1去描述一组线(二维)和一个点p,如何计算点p到每一条线 i (P0[i],P1[i])的距离?
def distance(P0, P1, p):
    T = P1 - P0
    L = (T ** 2).sum(axis=1)
    U = -((P0[:, 0] - p[..., 0]) * T[:, 0] + (P0[:, 1] - p[..., 1]) * T[:, 1]) / L
    U = U.reshape(len(U), 1)
    D = P0 + U * T - p
    return np.sqrt((D ** 2).sum(axis=1))

P0 = np.random.uniform(-10, 10, (10, 2))
P1 = np.random.uniform(-10, 10, (10, 2))
p = np.random.uniform(-10, 10, (1, 2))
print(distance(P0, P1, p))

79.考虑两组点集P0和P1去描述一组线(二维)和一组点集P,如何计算每一个点j(P[j])到每一条线i(P0[i], P1[i])的距离?

# based on distance function from previous question
P0 = np.random.uniform(-10, 10, (10, 2))
P1 = np.random.uniform(-10, 10, (10, 2))
p = np.random.uniform(-10, 10, (10, 2))
print(np.array([distance(P0, P1, p_i) for p_i in p]))

80.考虑一个任意数组,写一个函数,提取一个固定形状的子部分,并以给定元素为中心(fill必要时填充一个值)(提示: minimum, maximum)

Z = np.random.randint(0, 10, (10, 10))
shape = (5, 5)
fill = 0
position = (1, 1)
R = np.ones(shape, dtype=Z.dtype) * fill
P = np.array(list(position)).astype(int)
Rs = np.array(list(R.shape)).astype(int)
Zs = np.array(list(Z.shape)).astype(int)
R_start = np.zeros((len(shape),)).astype(int)
R_stop = np.array(list(shape)).astype(int)
Z_start = (P - Rs // 2)
Z_stop = (P + Rs // 2) + Rs % 2
R_start = (R_start - np.minimum(Z_start, 0)).tolist()
Z_start = (np.maximum(Z_start, 0)).tolist()
R_stop = np.maximum(R_start, (R_stop - np.maximum(Z_stop - Zs, 0))).tolist()
Z_stop = (np.minimum(Z_stop, Zs)).tolist()
r = [slice(start, stop) for start, stop in zip(R_start, R_stop)]
z = [slice(start, stop) for start, stop in zip(Z_start, Z_stop)]
R[r] = Z[z]
print(Z)
print(R)

81.考虑一个数组Z = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],如何生成一个数组R = [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], ...,[11, 12, 13, 14]]?(提示: stride_tricks.as_strided)

Z = np.arange(1, 15, dtype=np.uint32)
R = stride_tricks.as_strided(Z, (11, 4), (4, 4))
print(R)

82.计算一个矩阵的秩(提示: np.linalg.svd)

Z = np.random.uniform(0, 1, (10, 10))
U, S, V = np.linalg.svd(Z)  # Singular Value Decomposition
rank = np.sum(S > 1e-10)
print(rank)

83.如何找到一个数组中出现频率最高的值?(提示: np.bincount, argmax)

Z = np.random.randint(0, 10, 50)
print(np.bincount(Z).argmax())

84.从一个10x10的矩阵中提取出连续的3x3区块(提示: stride_tricks.as_strided)

Z = np.random.randint(0, 5, (10, 10))
n = 3
i = 1 + (Z.shape[0] - 3)
j = 1 + (Z.shape[1] - 3)
C = stride_tricks.as_strided(Z, shape=(i, j, n, n), strides=Z.strides + Z.strides)
print(C)

85.创建一个满足Z[i, j] == Z[j, i]的子类(提示:class方法)

class Symetric(np.ndarray):

    def __setitem__(self, index, value):
        i, j = index
        super(Symetric, self).__setitem__((i, j), value)
        super(Symetric, self).__setitem__((j, i), value)

    def symetric(Z):
        return np.asarray(Z + Z.T - np.diag(Z.diagonal())).view(Symetric)

S = Symetric(np.random.randint(0, 10, (5, 5)))
S[2, 3] = 42
print(S)

86.考虑p个nxn矩阵和一组形状为(n, 1)的向量,如何直接计算p个矩阵的乘积(n, 1)?(提示: np.tensordot)

p, n = 10, 20
M = np.ones((p, n, n))
V = np.ones((p, n, 1))
S = np.tensordot(M, V, axes=[[0, 2], [0, 1]])
print(S)
# It works, because:M is (p,n,n),V is (p,n,1)
# Thus, summing over the paired axes 0 and 0 (of M and V independently),and 2 and 1, to remain with a (n,1) vector.

87.对于一个16x16的数组,如何得到一个区域(block - sum)的和(区域大小为4x4)?(提示: np.add.reduceat)

Z = np.ones((16, 16))
k = 4
S = np.add.reduceat(np.add.reduceat(Z, np.arange(0, Z.shape[0], k), axis=0),
                    np.arange(0, Z.shape[1], k), axis=1)
print(S)

88.如何利用numpy数组实现GameofLife?(提示: Game of Life)

def iterate(Z):
    # Count neighbours
    N = (Z[0:-2, 0:-2] + Z[0:-2, 1:-1] + Z[0:-2, 2:] +
         Z[1:-1, 0:-2] + Z[1:-1, 2:] +
         Z[2:, 0:-2] + Z[2:, 1:-1] + Z[2:, 2:])
    # Apply rules
    birth = (N == 3) & (Z[1:-1, 1:-1] == 0)
    survive = ((N == 2) | (N == 3)) & (Z[1:-1, 1:-1] == 1)
    Z[...] = 0
    Z[1:-1, 1:-1][birth | survive] = 1
    return Z

Z = np.random.randint(0, 2, (50, 50))
for i in range(100): Z = iterate(Z)
print(Z)

89.如何找到一个数组的第n个最大值?(提示: np.argsort | np.argpartition)

Z = np.arange(10000)
np.random.shuffle(Z)
n = 5
# 方法1
# Slow
print(Z[np.argsort(Z)[-n:]])
# 方法2
# Fast
print(Z[np.argpartition(-Z, n)[:n]])

90.给定任意个数向量,创建笛卡尔积(每一个元素的每一种组合)(提示: np.indices)

def cartesian(arrays):
    arrays = [np.asarray(a) for a in arrays]
    shape = (len(x) for x in arrays)
    ix = np.indices(shape, dtype=int)
    ix = ix.reshape(len(arrays), -1).T
    for n, arr in enumerate(arrays):
        ix[:, n] = arrays[n][ix[:, n]]
    return ix

print(cartesian(([1, 2, 3], [4, 5], [6, 7])))

91.如何从一个正常数组创建记录数组(recordarray)?(提示: np.core.records.fromarrays)

Z = np.array([("Hello", 2.5, 3),
              ("World", 3.6, 2)])
R = np.core.records.fromarrays(Z.T, names='col1, col2, col3', formats='S8, f8, i8')
print(R)

92.考虑一个大向量Z, 用三种不同的方法计算它的立方(提示: np.power, \ *, np.einsum)

# 方法1
x = np.random.rand()
np.power(x, 3)
# 方法2
x * x * x
# 方法3
np.einsum('i,i,i->i', x, x, x)

93.考虑两个形状分别为(8, 3)和(2, 2)的数组A和B.如何在数组A中找到满足包含B中元素的行?(不考虑B中每行元素顺序)?(提示: np.where)

A = np.random.randint(0, 5, (8, 3))
B = np.random.randint(0, 5, (2, 2))
C = (A[..., np.newaxis, np.newaxis] == B)
rows = np.where(C.any((3, 1)).all(1))[0]
print(rows)

94.考虑一个10x3的矩阵,分解出有不全相同值的行(如[2, 2, 3])

Z = np.random.randint(0, 5, (10, 3))
print(Z)
# 方法1
# solution for arrays of all dtypes (including string arrays and record arrays)
E = np.all(Z[:, 1:] == Z[:, :-1], axis=1)
U = Z[~E]
print(U)
# 方法2
# soluiton for numerical arrays only, will work for any number of columns in Z
U = Z[Z.max(axis=1) != Z.min(axis=1), :]
print(U)

95.将一个整数向量转换为matrixbinary的表现形式(提示: np.unpackbits)

I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128])
B = ((I.reshape(-1, 1) & (2 ** np.arange(8))) != 0).astype(int)
print(B[:, ::-1])
# 方法2
print(np.unpackbits(I[:, np.newaxis], axis=1))

96.给定一个二维数组,如何提取出唯一的(unique)行?(提示: np.ascontiguousarray)

Z = np.random.randint(0, 2, (6, 3))
T = np.ascontiguousarray(Z).view(np.dtype((np.void, Z.dtype.itemsize * Z.shape[1])))
_, idx = np.unique(T, return_index=True)
uZ = Z[idx]
print(uZ)

97.考虑两个向量A和B,写出用einsum等式对应的inner, outer, sum, mul函数(提示: np.einsum)

A = np.random.uniform(0, 1, 10)
B = np.random.uniform(0, 1, 10)
print('sum')
print(np.einsum('i->', A))  # np.sum(A)
print('A * B')
print(np.einsum('i,i->i', A, B))  # A * B
print('inner')
print(np.einsum('i,i', A, B))  # np.inner(A, B)
print('outer')
print(np.einsum('i,j->ij', A, B))  # np.outer(A, B)

98.考虑一个由两个向量描述的路径(X, Y),如何用等距样例(equidistantsamples)对其进行采样(sample)?(提示: np.cumsum, np.interp)

phi = np.arange(0, 10 * np.pi, 0.1)
a = 1
x = a * phi * np.cos(phi)
y = a * phi * np.sin(phi)
dr = (np.diff(x) ** 2 + np.diff(y) ** 2) ** .5  # segment lengths
r = np.zeros_like(x)
r[1:] = np.cumsum(dr)  # integrate path
r_int = np.linspace(0, r.max(), 200)  # regular spaced path
x_int = np.interp(r_int, r, x)  # integrate path
y_int = np.interp(r_int, r, y)

99.给定整数n和2D数组X,从X中选择可以解释为具有n度的多项分布的绘制的行,即,仅包含整数并且总和为n的行。(提示: np.logical_and.reduce, np.mod)

X = np.asarray([[1.0, 0.0, 3.0, 8.0],
                [2.0, 0.0, 1.0, 1.0],
                [1.5, 2.5, 1.0, 0.0]])
n = 4
M = np.logical_and.reduce(np.mod(X, 1) == 0, axis=-1)
M &= (X.sum(axis=-1) == n)
print(X[M])

100.计算1D阵列X的平均值的自举95%置信区间(即,对替换N次的阵列的元素进行重新采样,计算每个样本的平均值,然后计算均值上的百分位数)。

X = np.random.randn(100)  # random 1D array
N = 1000  # number of bootstrap samples
idx = np.random.randint(0, X.size, (N, X.size))
means = X[idx].mean(axis=1)
confint = np.percentile(means, [2.5, 97.5])
print(confint)

相关文章

  • numpy练习100题(76-100)

    后面的题目基本都写不出来,平时遇到的也不多,为了文章的完整性,将答案贴出。 考虑一维数组Z,构建一个二维数组, 其...

  • numpy练习100题(26-50)

    下面脚本运行后的结果是什么?(提示: np.sum) 考虑一个整数向量Z,下列表达合法的是哪个? 下列表达式的结果...

  • numpy练习100题(1-25)

    导入numpy库并简写为 np 打印numpy的版本和配置说明 创建一个长度为10的空向量 如何找到任何一个数组的...

  • numpy练习100题(51-75)

    创建一个表示位置(x,y)和颜色(r,g,b)的结构化数组(提示: dtype) 对一个表示坐标形状为(100,2...

  • 50道练习带你玩转Pandas

    受到numpy100题的启发,我们制作了pandas50题。 Pandas 是基于 NumPy 的一种数据处理工具...

  • 口算2

    口算练习2,共100题用时8分钟,对99题

  • 感受日记76-100

    今日意图,工作,陪她聊天,逗她开心 今天工作好累啊,可能是因为周末吧,人比较多,而我准备的又比较少,结果加餐加到想...

  • Rust语言编程实例100题-044

    Rust语言编程实例100题-044 题目:在第41题和43题已经练习过static修饰变量的用法。今天再来练习下...

  • Rust语言编程实例100题-045

    Rust语言编程实例100题-045 题目:在第39题和42题已经练习过选择排序,插入排序,冒泡排序。今天再来练习...

  • numpy 100道通关题(二)

    34. How to get all the dates corresponding to the month o...

网友评论

      本文标题:numpy练习100题(76-100)

      本文链接:https://www.haomeiwen.com/subject/itbkoctx.html