在Python中将整数转换为固定大小的分类向量
我有一组N个整数,取值范围为1-6。我想为每个整数生成大小为6的对应分类向量(因此是一个大小为Nx6的数组),这将是我的初始集的分类表示。如果我的整数为1,则结果应为:在Python中将整数转换为固定大小的分类向量,python,Python,我有一组N个整数,取值范围为1-6。我想为每个整数生成大小为6的对应分类向量(因此是一个大小为Nx6的数组),这将是我的初始集的分类表示。如果我的整数为1,则结果应为: [1, 0, 0, 0, 0, 0] 而对于6: [0, 0, 0, 0, 0, 1] 等等。您可以使用简单的列表理解: >>> x = 1 >>> [int(i+1 == x) for i in range(6)] [1, 0, 0, 0, 0, 0] >>> x =
[1, 0, 0, 0, 0, 0]
而对于6:
[0, 0, 0, 0, 0, 1]
等等。您可以使用简单的列表理解:
>>> x = 1
>>> [int(i+1 == x) for i in range(6)]
[1, 0, 0, 0, 0, 0]
>>> x = 6
>>> [int(i+1 == x) for i in range(6)]
[0, 0, 0, 0, 0, 1]
同样,对于Nx6
列表:
>>> X = [4,1,5]
>>> [[int(i+1 == x) for i in range(6)] for x in X]
[[0, 0, 0, 1, 0, 0],
[1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0]]
您可以使用一个简单的列表:
>>> x = 1
>>> [int(i+1 == x) for i in range(6)]
[1, 0, 0, 0, 0, 0]
>>> x = 6
>>> [int(i+1 == x) for i in range(6)]
[0, 0, 0, 0, 0, 1]
同样,对于Nx6
列表:
>>> X = [4,1,5]
>>> [[int(i+1 == x) for i in range(6)] for x in X]
[[0, 0, 0, 1, 0, 0],
[1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0]]
如果您愿意使用第三方库,可以通过NumPy高效地实现这一点:
import numpy as np
np.random.seed(0)
m, n = 6, 10
L = np.random.randint(1, m+1, n) # construct array of 10 numbers between 1 and 6
A = np.zeros((n, m)) # initialize array of zeros
A[np.arange(n), L-1] = 1 # use advanced indexing to assign values
结果是一个NumPy数组,您可以通过a[0]
,a[1]
等对其进行索引
print(A)
array([[ 0., 0., 0., 0., 1., 0.],
[ 0., 0., 0., 0., 0., 1.],
[ 1., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 1., 0., 0.],
[ 0., 0., 0., 1., 0., 0.],
[ 0., 0., 0., 1., 0., 0.],
[ 0., 1., 0., 0., 0., 0.],
[ 0., 0., 0., 1., 0., 0.],
[ 0., 0., 0., 0., 0., 1.],
[ 0., 0., 1., 0., 0., 0.]])
如果您愿意使用第三方库,可以通过NumPy高效地实现这一点:
import numpy as np
np.random.seed(0)
m, n = 6, 10
L = np.random.randint(1, m+1, n) # construct array of 10 numbers between 1 and 6
A = np.zeros((n, m)) # initialize array of zeros
A[np.arange(n), L-1] = 1 # use advanced indexing to assign values
结果是一个NumPy数组,您可以通过a[0]
,a[1]
等对其进行索引
print(A)
array([[ 0., 0., 0., 0., 1., 0.],
[ 0., 0., 0., 0., 0., 1.],
[ 1., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 1., 0., 0.],
[ 0., 0., 0., 1., 0., 0.],
[ 0., 0., 0., 1., 0., 0.],
[ 0., 1., 0., 0., 0., 0.],
[ 0., 0., 0., 1., 0., 0.],
[ 0., 0., 0., 0., 0., 1.],
[ 0., 0., 1., 0., 0., 0.]])
您可以使用
numpy.fill_diagonal
将您需要的值填入对角线:
import numpy as np
a = np.zeros((6, 6), int)
np.fill_diagonal(a, 1)
print(a)
输出:
[[1 0 0 0 0 0]
[0 1 0 0 0 0]
[0 0 1 0 0 0]
[0 0 0 1 0 0]
[0 0 0 0 1 0]
[0 0 0 0 0 1]]
现在,如果您的整数是1,请使用a[0]
,。。。对于6,使用a[5]
例如:
您可以使用
numpy.fill_diagonal
将您需要的值填入对角线:
import numpy as np
a = np.zeros((6, 6), int)
np.fill_diagonal(a, 1)
print(a)
输出:
[[1 0 0 0 0 0]
[0 1 0 0 0 0]
[0 0 1 0 0 0]
[0 0 0 1 0 0]
[0 0 0 0 1 0]
[0 0 0 0 0 1]]
现在,如果您的整数是1,请使用a[0]
,。。。对于6,使用a[5]
例如:
到目前为止你试过什么?请发布你所有的代码。你想要什么?您的问题中没有
集合
——只有两个列表
。请显示足够数量的输入数据和输出数据,以便我们可以得到您想要的数据。到目前为止,您尝试了哪些?请发布你所有的代码。你想要什么?您的问题中没有集合
——只有两个列表
。请显示足够数量的输入数据和输出数据,以便我们可以得到您想要做的事情