one-hot encoder and classification accuracy in Python

we define an array “y”, and y1 is the one-hot encoder of y.
在这里插入图片描述
details about y and y1 can be seen in Spyder as follows(Note that if we do not use “.toarray()”, we will get a sparse matrix rather than a normal matrix):
在这里插入图片描述在这里插入图片描述
在这里插入图片描述在这里插入图片描述
when we compute the classification accuracy, we need to covert the one-hot vector to a column vector of labels and compares the predicted label vector and the actual vector.

y2= np.argmax(y1, axis=1) # y2 is the predicted label vector
a = (y2 == y.T) # y is the actual label vector, compare the predicted label vector and the actual vector. 
accuracy = float(a.sum()) /len(y) # compute accuracy

Details about y2 and a can be seen in Spyder.
在这里插入图片描述
the size of y2 is (3, ), which is a special size. the size of y is (3,1).
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
One important thing, we need to use a = (y2 == y.T) to compare the predicted label vector and the actual vector, namely we need to transpose the dimension of y. If we use a1 = (y2 == y), then:
在这里插入图片描述
在这里插入图片描述
this is obviously wrong, thus, i think that the size (3, ) is a little similar to a row vector, but strangely, it cannot be transposed.

Y5=y2. T

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

in summary, the correct coding is as follows:

import numpy as np
from sklearn.preprocessing import OneHotEncoder
enc = OneHotEncoder()  # one-hot encoder to convert the label to one-hot vector
y = np.array([[0],[1],[2]])
y1 = enc.fit_transform(y).toarray()
y2 = np.argmax(y1, axis=1)
a = (y2 == y.T)
accuracy = float(a.sum()) /len(y)

corresponding results are as follows:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值