wordpress快速仿站,用织梦做网站能练技术吗,广州网站设计智能 乐云践新专家,金阊公司网站建设电话题目#xff1a; 思路#xff1a;
1、处理数据集#xff0c;这里用的是题目已知的数据集#xff0c;所以说需要提前将写好的数据放到excel表格里#xff0c;再进行读取。
2、将数据集划分为训练集和测试集
3、定义K-NN模型。
4、训练模型
5、预测模型
6、计算分类精…题目 思路
1、处理数据集这里用的是题目已知的数据集所以说需要提前将写好的数据放到excel表格里再进行读取。
2、将数据集划分为训练集和测试集
3、定义K-NN模型。
4、训练模型
5、预测模型
6、计算分类精度
7、使用网格搜索法
8、训练模型
9、可视化
结果: 大致就是这样代码如下
#加载数据集
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.neighbors import KNeighborsClassifier
import warnings
warnings.filterwarnings(ignore)import matplotlib
print(matplotlib.matplotlib_fname())# 加载数据集
def read():filename r水仙花.xlsxdata pd.read_excel(filename, headerNone)x1 data.iloc[1:, [0, 1]].valuesx2 data.iloc[1:, [3, 4]].values# print(x2)y1 data.iloc[1:, 2].valuesy2 data.iloc[1:, 5].valuesX np.vstack((x1, x2)) # 竖向合并y np.hstack((y1, y2)) # 横向合并y y.astype(int)return X, y
# 划分训练集和测试集
X,yread()
X_train, X_test, y_train, y_test train_test_split(X, y, test_size0.3, random_state42)
# 定义K-NN模型
knn KNeighborsClassifier(n_neighbors3) # 设置k3
#训练模型
knn.fit(X_train, y_train)
#预测测试集
y_pred knn.predict(X_test)
#计算分类精度
accuracy accuracy_score(y_test, y_pred)
print(分类精度, accuracy)# 使用网格搜索找到最佳参数
param_grid {n_neighbors: [1,3, 5, 7, 9]} # 尝试不同的k值
grid_search GridSearchCV(knn, param_grid, cv5)
#训练模型
grid_search.fit(X_train, y_train)
print(最佳参数, grid_search.best_params_)
print(最佳分类精度, grid_search.best_score_)
#可视化
#绘制散点图
cmap_light ListedColormap([#FFAAAA, #AAFFAA, #AAAAFF])
cmap_bold ListedColormap([#FF0000, #00FF00, #0000FF])x_min, x_max X[:, 0].min() - 0.1, X[:, 0].max() 0.1
y_min, y_max X[:, 1].min() - 0.1, X[:, 1].max() 0.1
xx, yy np.meshgrid(np.arange(x_min, x_max, 0.02), np.arange(y_min, y_max, 0.02))
Z knn.predict(np.c_[xx.ravel(), yy.ravel()])
Z Z.reshape(xx.shape)plt.figure()
plt.pcolormesh(xx, yy, Z, cmapcmap_light)
# 绘制训练样本和测试样本
plt.scatter(X_train[:, 0], X_train[:, 1], cy_train, cmapcmap_bold, edgecolork)
plt.scatter(X_test[:, 0], X_test[:, 1], cy_test, cmapcmap_bold, markerx, edgecolork)plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.title(K-NN分类k3)
plt.show()可能出现的问题 图片中中文无法显现原因是配置文件中没有配置中文库解决办法
首先打印出配置文件所在的目录 代码如下
import matplotlib
print(matplotlib.matplotlib_fname())然后根据地址找到相应文件ctrf搜索font.family,找到下面图片中的两行 然后将其注释符号全部删掉并在font.sans-serif中添加中文字体名称 这样再重新运行程序代码即可。