使用 sklearn.metrics 中的 accuracy_score 计算准确率分数
在此步骤中,我们将计算模型预测的准确率。准确率是最直观的分类指标之一。它衡量了正确预测的实例数占总实例数的比例。
sklearn.metrics 中的 accuracy_score 函数用于计算此值。它将真实标签和预测标签作为参数。
首先,打开左侧文件浏览器中的 evaluate.py 文件。该文件已包含 y_true 和 y_pred 列表。现在,在文件末尾添加以下代码,以导入 accuracy_score 函数,计算准确率,并打印结果。
from sklearn.metrics import accuracy_score
## Calculate accuracy
accuracy = accuracy_score(y_true, y_pred)
print(f"Accuracy: {accuracy}")
现在,你的完整 evaluate.py 文件应如下所示:
## In this lab, we will use a predefined set of true labels and predicted labels
## to understand different evaluation metrics.
## y_true represents the actual, ground truth labels for our data points.
## For a binary classification, 0 could mean 'negative' and 1 could mean 'positive'.
y_true = [0, 1, 1, 0, 1, 0, 0, 1, 0, 1]
## y_pred represents the labels predicted by our hypothetical classification model.
y_pred = [0, 1, 0, 0, 1, 1, 0, 1, 0, 1]
print("Setup complete. True and predicted labels are defined in evaluate.py.")
print(f"True labels: {y_true}")
print(f"Predicted labels: {y_pred}")
from sklearn.metrics import accuracy_score
## Calculate accuracy
accuracy = accuracy_score(y_true, y_pred)
print(f"Accuracy: {accuracy}")
现在,让我们运行脚本。在你的 IDE 中打开终端,并执行以下命令:
python3 evaluate.py
你应该会看到以下输出,其中包含准确率得分。准确率为 0.8 意味着 80% 的预测是正确的。
Setup complete. True and predicted labels are defined in evaluate.py.
True labels: [0, 1, 1, 0, 1, 0, 0, 1, 0, 1]
Predicted labels: [0, 1, 0, 0, 1, 1, 0, 1, 0, 1]
Accuracy: 0.8