评估机器学习svm的accuracy,Precision,Recall,F1值的代码
时间: 2024-05-07 12:23:39 浏览: 266
下面是评估SVM机器学习模型的Accuracy、Precision、Recall和F1值的Python代码:
```python
from sklearn import datasets
from sklearn import svm
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
# 加载数据集
iris = datasets.load_iris()
X = iris.data
y = iris.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 建立SVM模型
clf = svm.SVC(kernel='linear', C=1)
clf.fit(X_train, y_train)
# 预测测试集结果
y_pred = clf.predict(X_test)
# 计算评估指标
acc = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred, average='macro')
recall = recall_score(y_test, y_pred, average='macro')
f1 = f1_score(y_test, y_pred, average='macro')
print("Accuracy:", acc)
print("Precision:", precision)
print("Recall:", recall)
print("F1 Score:", f1)
```
其中,我们使用了Iris数据集进行演示,使用SVM模型进行分类,然后使用`train_test_split`函数划分训练集和测试集,最后使用`accuracy_score`、`precision_score`、`recall_score`和`f1_score`函数计算评估指标。注意,在计算Precision、Recall和F1值时,我们使用了`average='macro'`参数,表示对每个类别的指标取平均值。如果需要对每个类别分别计算指标,可以设置`average=None`。
阅读全文