svm分类器进行模型评估代码
时间: 2024-09-24 12:05:43 浏览: 44
SVM (支持向量机) 分类器的模型评估通常涉及以下几个步骤,这里以Python的Scikit-Learn库为例:
1. **数据预处理**:首先需要对数据进行清洗、编码(如One-Hot Encoding)、标准化或归一化等。
```python
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
2. **训练模型**:
```python
from sklearn.svm import SVC
classifier = SVC(kernel='linear') # 或 'rbf', 'poly'等其他内核
classifier.fit(X_train, y_train)
```
3. **预测结果**:
```python
predictions = classifier.predict(X_test)
```
4. **评估指标**:
- **准确率**:`accuracy_score(y_test, predictions)`
- **精确度(Precision)**:`precision_score(y_test, predictions)`
- **召回率(Recall)**:`recall_score(y_test, predictions)`
- **F1分数(F1 Score)**:`f1_score(y_test, predictions)`
- **混淆矩阵 Confusion Matrix**:`confusion_matrix(y_test, predictions)`
5. **交叉验证**:
如果想要更稳定地评估模型性能,可以使用交叉验证,例如 `cross_val_score` 函数:
```python
from sklearn.model_selection import cross_val_score
scores = cross_val_score(classifier, X, y, cv=5)
```
6. **保存和加载模型**:
```python
joblib.dump(classifier, 'svm_model.pkl')
loaded_classifier = joblib.load('svm_model.pkl')
```
阅读全文