____tz_zs
使用 np.eye 生成对角矩阵。
numpy.eye
numpy.eye(N, M=None, k=0, dtype=<class 'float'>, order='C')
https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.eye.html
生成一个对角线为1,其余位置为0的二维数组。
参数:
- N:int值,行数。
- M:int值,列数,如果没有则默认为N。
- dtype:返回的数据元素的格式,默认为float。
- order:1.14.0版本后,可选参数{'C', 'F'}
返回值:
- 一个对角线元素为1,其余位置为0的数组。
应用:ndarray转one-hot数组
import numpy as np
import pandas as pd
y = np.array([[1, 2, 3, 0, 2, 1]]) # [[1 2 3 0 2 1]],
print(y.shape) # (1, 6)
y2 = np.array([1, 2, 3, 0, 2, 1]) # [1 2 3 0 2 1]
print(y2.shape) # (6,)
y3 = y.reshape(-1) # [1 2 3 0 2 1]
print(y3.shape) # (6,)
n = np.eye(10, dtype=int)[y3]
print(n)
"""
[[0 1 0 0 0 0 0 0 0 0]
[0 0 1 0 0 0 0 0 0 0]
[0 0 0 1 0 0 0 0 0 0]
[1 0 0 0 0 0 0 0 0 0]
[0 0 1 0 0 0 0 0 0 0]
[0 1 0 0 0 0 0 0 0 0]]
"""
print(pd.DataFrame(n))
"""
0 1 2 3 4 5 6 7 8 9
0 0 1 0 0 0 0 0 0 0 0
1 0 0 1 0 0 0 0 0 0 0
2 0 0 0 1 0 0 0 0 0 0
3 1 0 0 0 0 0 0 0 0 0
4 0 0 1 0 0 0 0 0 0 0
5 0 1 0 0 0 0 0 0 0 0
"""