svm图像识别代码python
时间: 2024-06-23 14:00:58 浏览: 8
Support Vector Machines (SVM) 是一种常用的监督学习算法,常用于分类和回归问题。在Python中,我们可以使用Scikit-learn库来实现图像识别中的SVM。以下是一个简单的示例,展示如何使用SVM对图像数据进行分类:
```python
# 导入所需库
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.metrics import classification_report, confusion_matrix
import matplotlib.pyplot as plt
import numpy as np
# 加载数据集(例如MNIST手写数字数据)
digits = datasets.load_digits()
X = digits.data
y = digits.target
# 数据预处理(归一化)
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)
# 创建SVM分类器
svm_classifier = SVC(kernel='linear') # 使用线性核函数
# 训练模型
svm_classifier.fit(X_train, y_train)
# 预测
y_pred = svm_classifier.predict(X_test)
# 评估性能
print("Classification Report:")
print(classification_report(y_test, y_pred))
conf_mat = confusion_matrix(y_test, y_pred)
print("Confusion Matrix:")
print(conf_mat)
# 可视化决策边界(仅适用于二维数据)
if digits.images.shape == 2: # 假设我们正在处理二维图像
plt.imshow(scaler.inverse_transform(X_scaled[::50, ::50]).reshape(8, 8), cmap='gray')
plt.scatter(X_scaled[y_train==0, 0], X_scaled[y_train==0, 1], color='red', marker='o', label='Class 0')
plt.scatter(X_scaled[y_train==1, 0], X_scaled[y_train==1, 1], color='blue', marker='x', label='Class 1')
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.legend()
plt.title('SVM Decision Boundaries')
plt.show()
#