問(wèn)題1: 選取二維數(shù)組中的若干行與列的交叉點(diǎn)
例如:
import numpy as np
a = np.arange(20).reshape((5,4))
# array([[ 0, 1, 2, 3],
# [ 4, 5, 6, 7],
# [ 8, 9, 10, 11],
# [12, 13, 14, 15],
# [16, 17, 18, 19]])
# select certain rows(0, 1, 3) AND certain columns(0, 2)
解答見(jiàn) https://stackoverflow.com/questions/22927181/selecting-specific-rows-and-columns-from-numpy-array
Using ix_ one can quickly construct index arrays that will index the cross product. a[np.ix_([1,3],[2,5])] returns the array [[a[1,2] a[1,5]], [a[3,2] a[3,5]]].
>>> a = np.arange(20).reshape((5,4))
>>> a[np.ix_([0,1,3], [0,2])]
array([[ 0, 2],
[ 4, 6],
[12, 14]])
問(wèn)題2: One Hot encodings
所謂'One Hot encodings', 是將多類(lèi)問(wèn)題的向量變化為0-1矩陣:

image.png
定義以下函數(shù)即可:
import numpy as np
def convert_to_one_hot(Y, C):
"""
Y是一個(gè)numpy.array, C是分類(lèi)的種數(shù)
"""
Y = np.eye(C)[Y.reshape(-1)].T
return Y
y = np.array([[1, 2, 3, 0, 2, 1]])
print(y.shape)
print(y.reshape(-1).shape)
C = 4
print(convert_to_one_hot(y, C))
np.eye(C)是構(gòu)造一個(gè)對(duì)角線為1的對(duì)角矩陣, Y.reshape(-1)把Y壓縮成向量[numpy中向量shape是(n,), 矩陣shape是(1, n)],np.eye(C)[Y.reshape(-1)]的意思是取對(duì)角矩陣的相應(yīng)行, 最后.T做轉(zhuǎn)置, 就獲得了下面的結(jié)果:
(1, 6)
(6,)
[[ 0. 0. 0. 1. 0. 0.]
[ 1. 0. 0. 0. 0. 1.]
[ 0. 1. 0. 0. 1. 0.]
[ 0. 0. 1. 0. 0. 0.]]
參考文獻(xiàn)
[1] https://stackoverflow.com/questions/22927181/selecting-specific-rows-and-columns-from-numpy-array
[2] https://docs.scipy.org/doc/numpy-1.13.0/user/basics.indexing.html