将概率向量转换为python中的目标vecor?

jia*_* wu 4 python numpy machine-learning

我正在对来自sklearn的虹膜数据集进行逻辑回归,我知道数学并尝试实现它.在最后一步,我得到一个预测向量,这个预测向量表示该数据点进入1类或2类(二进制分类)的概率.

现在我想将这个预测向量转换为目标向量.假设概率大于50%,则相应的数据点将属于类1,否则为类2.使用0表示类1,类1表示1.

我知道它有一个for循环版本,只是循环遍历整个向量.但是当大小变大时,for循环非常昂贵,所以我想更高效地完成它,比如numpy的矩阵运算,它比for循环中的矩阵运算更快.

有关更快方法的任何建议吗?

Shi*_*eng 8

import numpy as np

a = np.matrix('0.1 0.82')
print(a)

a[a > 0.5] = 1
a[a <= 0.5] = 0
print(a)
Run Code Online (Sandbox Code Playgroud)

输出:

[[ 0.1   0.82]]
[[ 0.  1.]]
Run Code Online (Sandbox Code Playgroud)

更新:

import numpy as np

a = np.matrix('0.1 0.82')
print(a)

a = np.where(a > 0.5, 1, 0)
print(a)
Run Code Online (Sandbox Code Playgroud)


小智 5

二维数组的更通用的解决方案具有许多类别的许多向量:

import numpy as np
a = np.array( [ [.5, .3, .2], 
                [.1, .2, .7], 
                [ 1,  0,  0] ] )

idx = np.argmax(a, axis=-1)
a = np.zeros( a.shape )
a[ np.arange(a.shape[0]), idx] = 1

print(a)
Run Code Online (Sandbox Code Playgroud)

输出:

[[1. 0. 0.]
 [0. 0. 1.]
 [1. 0. 0.]]    
Run Code Online (Sandbox Code Playgroud)


Ara*_*ray 5

选项 1:如果您进行二元分类并具有 1d 预测向量,那么您的解决方案是numpy.round

prob = model.predict(X_test)
Y = np.round(prob)
Run Code Online (Sandbox Code Playgroud)

选项 2:如果您有一个 n 维单热预测矩阵,但想要有标签,那么您可以使用numpy.argmax。这将返回带有标签的一维向量:

prob = model.predict(X_test)
y = np.argmax(prob, axis=1)
Run Code Online (Sandbox Code Playgroud)