SVM对sklearn自带手写数字数据集进行分类用Python做
时间: 2024-11-20 10:44:54 浏览: 26
使用Python和scikit-learn库对sklearn自带的Digits手写数字数据集进行分类的过程大致如下:
1. **导入所需库**:
```python
import numpy as np
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
```
2. **加载数据**:
```python
digits = datasets.load_digits()
X = digits.data # 特征数据
y = digits.target # 标签数据
```
3. **数据预处理**:
- 分割数据:将数据划分为训练集和测试集
- 归一化:对于SVM,标准化数据有利于提高模型性能
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
```
4. **模型创建和训练**:
```python
svm_model = SVC(kernel='linear') # 使用线性内核,也可以尝试其他核函数如'rbf'
svm_model.fit(X_train, y_train)
```
5. **模型预测**:
```python
y_pred = svm_model.predict(X_test)
```
6. **评估结果**:
```python
print("Classification Report:\n", classification_report(y_test, y_pred))
conf_mat = confusion_matrix(y_test, y_pred)
print("\nConfusion Matrix:\n", conf_mat)
```
阅读全文
相关推荐
![py](https://img-home.csdnimg.cn/images/20250102104920.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)