【发布时间】:2018-11-07 17:32:18
【问题描述】:
我有一个二元分类问题,第二类的 f1 score 较低。
我需要两个f1 scores 都很好,因为我试图预测一件商品被售出的概率。
如果有帮助,我的数据集也是不平衡的。
我认为我的模型是泛化而不是做出正确的预测。
【问题讨论】:
标签: python scikit-learn cross-validation
我有一个二元分类问题,第二类的 f1 score 较低。
我需要两个f1 scores 都很好,因为我试图预测一件商品被售出的概率。
如果有帮助,我的数据集也是不平衡的。
我认为我的模型是泛化而不是做出正确的预测。
【问题讨论】:
标签: python scikit-learn cross-validation
我参加聚会迟到了,但是对于任何从 ✨未来✨ 中发现这个的人,试试这个:
from sklearn.metrics import f1_score
y_true = [1, 0, 1, 0, 0]
y_pred = [1, 1, 1, 0, 1]
f1_score(y_true, y_pred, average='binary')
它将返回正类的分数 (True/1)。您可以通过打印上述分类报告来确认这一点。
【讨论】:
iris 数据集和train-test spliting 的完整示例。import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm, datasets
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
# import data
iris = datasets.load_iris()
X = iris.data
y = iris.target
class_names = iris.target_names
#keep only 2 classes to make the problem binary
X = X[y!=2]
y = y[y!=2]
# Split the data into a training set and a test set
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
# Fit the classifier using the training data
classifier = svm.SVC(kernel='linear', C=0.01)
classifier.fit(X_train, y_train)
# Predict using the trained classifier and the test data
y_pred = classifier.predict(X_test)
print(classification_report(y_test, y_pred, target_names=class_names))
precision recall f1-score support
setosa 1.00 1.00 1.00 13
versicolor 1.00 1.00 1.00 12
avg / total 1.00 1.00 1.00 25
iris 数据集和KFold cross-validation 的完整示例。import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm, datasets
from sklearn.metrics import classification_report
from sklearn.model_selection import cross_val_predict
from sklearn.model_selection import KFold
# import data
iris = datasets.load_iris()
X = iris.data
y = iris.target
class_names = iris.target_names
# keep only 2 classes to make the problem binary
X = X[y!=2]
y = y[y!=2]
# Define the classifier
classifier = svm.SVC(kernel='linear', C=0.01)
# KFold cross validation
cv = KFold(n_splits=3)
y_pred = cross_val_predict(classifier, X, y, cv = cv)
print(classification_report(y, y_pred, target_names=class_names))
precision recall f1-score support
setosa 0.98 1.00 0.99 50
versicolor 1.00 0.98 0.99 50
avg / total 0.99 0.99 0.99 100
【讨论】:
尝试使用metrics.classification_report()
Eg) print metrics.classification_report(y_test, y_pred)
precision recall f1-score support
0 0.11 0.21 0.14 24
1 0.18 0.21 0.20 42
2 0.14 0.15 0.15 39
3 0.12 0.12 0.12 48
4 0.19 0.13 0.16 52
5 0.20 0.04 0.07 23
avg / total 0.16 0.15 0.15 228
【讨论】: