-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMachine Learning.py
More file actions
39 lines (30 loc) · 1.25 KB
/
Machine Learning.py
File metadata and controls
39 lines (30 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
# 加载鸢尾花数据集
iris = load_iris()
# 将数据转化为 pandas DataFrame
X = pd.DataFrame(iris.data, columns=iris.feature_names) # 特征数据
y = pd.Series(iris.target) # 标签数据
# 显示前五行数据
print(X.head())
# 划分训练集和测试集(80% 训练集,20% 测试集)
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) #fit():计算训练数据的均值和标准差transform():用计算出的均值和标准差来转换数据
X_test = scaler.transform(X_test) #未来数据计算不出来均值和标准差
# 创建 KNN 分类器o
knn = KNeighborsClassifier(n_neighbors=3)
# 训练模型
knn.fit(X_train, y_train)
# 预测测试集
y_pred = knn.predict(X_test)
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print(f'模型准确率: {accuracy:.2f}')