【numpy】 之 np.eye

____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
"""

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值