python - 如何使用 sklearn 的 SGDClassifier 返回前 N 个预测的准确率?
问题描述
我正在尝试修改这篇文章中的结果(如何使用 sklearn 的 SGDClassifier 获得前 3 名或前 N 名预测)以获得返回的准确率,但是我得到的准确率为零,我不知道为什么。有什么想法吗?任何想法/编辑将不胜感激!谢谢你。
from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np
from sklearn import linear_model
arr=['dogs cats lions','apple pineapple orange','water fire earth air', 'sodium potassium calcium']
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(arr)
feature_names = vectorizer.get_feature_names()
Y = ['animals', 'fruits', 'elements','chemicals']
T=["eating apple roasted in fire and enjoying fresh air"]
test = vectorizer.transform(T)
clf = linear_model.SGDClassifier(loss='log')
clf.fit(X,Y)
x=clf.predict(test)
def top_n_accuracy(probs, test, n):
best_n = np.argsort(probs, axis=1)[:,-n:]
ts = np.argmax(test, axis=1)
successes = 0
for i in range(ts.shape[0]):
if ts[i] in best_n[i,:]:
successes += 1
return float(successes)/ts.shape[0]
n=2
probs = clf.predict_proba(test)
top_n_accuracy(probs, test, n)
解决方案
from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np
from sklearn import linear_model
arr=['dogs cats lions','apple pineapple orange','water fire earth air', 'sodium potassium calcium']
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(arr)
feature_names = vectorizer.get_feature_names()
Y = ['animals', 'fruits', 'elements','chemicals']
T=["eating apple roasted in fire and enjoying fresh air", "I love orange"]
test = vectorizer.transform(T)
clf = linear_model.SGDClassifier(loss='log')
clf.fit(X,Y)
x=clf.predict(test)
n=2
probs = clf.predict_proba(test)
topn = np.argsort(probs, axis = 1)[:,-n:]
在这里,我介绍了基本事实标签向量(这些是数字索引,您需要将 ["elements", etc] 映射到 [0,1,2 etc]。这里我假设您的测试示例属于元素。
y_true = np.array([2,1])
然后这应该计算您的准确性
np.mean(np.array([1 if y_true[k] in topn[k] else 0 for k in range(len(topn))]))
推荐阅读
- android - Play Protect 无法识别此应用的开发者
- java - EE Web 服务中的线程安全
- r - 从 selectInput 的动态数量访问值
- apache-kafka - Kafka Connect 添加 MySqlConnector 失败
- sql - 休眠:模式验证:缺少表
- python - Pandas:根据条件计数进行分组
- javascript - React Native 动态 - 来自 Api 的列表视图
- java - Java 9、Axis 2、TLS 1.2 握手失败
- cluster-computing - 设置 VerneMq 集群(VBox
- javascript - Angular 4 错误:应找到 1 个参数 0