python进行Digits数据进行KNN分类和逻辑回归代码
时间: 2023-03-21 17:03:05 浏览: 135
逻辑回归python代码
当使用Python进行Digits数据的KNN分类和逻辑回归时,你可以按照以下步骤操作:
1. 加载Digits数据集:
```python
from sklearn.datasets import load_digits
digits = load_digits()
```
2. 数据预处理:将数据集分为训练集和测试集,并将数据进行标准化处理。
```python
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target, test_size=0.3, random_state=42)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
```
3. 进行KNN分类:
```python
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(X_train, y_train)
print("KNN分类器的准确率:{:.2f}%".format(knn.score(X_test, y_test)*100))
```
4. 进行逻辑回归:
```python
from sklearn.linear_model import LogisticRegression
logreg = LogisticRegression()
logreg.fit(X_train, y_train)
print("逻辑回归分类器的准确率:{:.2f}%".format(logreg.score(X_test, y_test)*100))
```
通过这些步骤,你就可以对Digits数据集进行KNN分类和逻辑回归了。
阅读全文