赞
踩
- from sklearn.datasets import load_iris
- from sklearn.model_selection import train_test_split
- from sklearn.preprocessing import StandardScaler
- from sklearn.neighbors import KNeighborsClassifier
-
- def knn_selector():
-
- iris = load_iris()
-
- x_train,x_test,y_train,y_test = train_test_split(iris.data, iris.target, test_size=0.3)
-
- transfer = StandardScaler()
- x_train = transfer.fit_transform(x_train)
- x_test = transfer.transform(x_test)
-
- estimator = KNeighborsClassifier(n_neighbors = 3)
- estimator.fit(x_train, y_train)
-
- # estimator.predict(x_test)
- score = estimator.score(x_test, y_test)
-
- print("score: ", score)
-
-
- if __name__ == "__main__":
-
- knn_selector()
- import matplotlib.pyplot as plt
- from sklearn.datasets import load_iris
- from sklearn.model_selection import train_test_split
- from sklearn.neighbors import KNeighborsClassifier
- from sklearn.preprocessing import StandardScaler
-
- # 获取数据集
- # 划分数据集
- # 标准化
- # 创建模型
- # 模型训练
- # 模型预测与评估
-
- def knn_selector():
-
- iris = load_iris()
-
- X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size= 0.3)
-
- # print(X_train)
- # plt.plot(X_train[:,0])
- # plt.show()
-
- transfer = StandardScaler()
- X_train = transfer.fit_transform(X_train)
- X_test = transfer.transform(X_test)
-
- # print(X_train[:,0])
- # plt.plot(X_train[:,0])
- # plt.show()
-
- estimator = KNeighborsClassifier(n_neighbors = 3)
- estimator.fit(X_train, y_train)
-
- score = estimator.score(X_test, y_test)
-
- print("准确率: ", score)
-
- if __name__ == "__main__":
-
- knn_selector()
- from sklearn import datasets
- from sklearn.model_selection import train_test_split
- from sklearn.neighbors import KNeighborsClassifier
-
- #------------------------------引入数据------------------------------
-
- iris = datasets.load_iris() # 引入 iris 鸢尾花数据集
- # 鸢尾花数据集 包含 4个 特征变量
-
- iris_X = iris.data # 特征变量
- iris_y = iris.target # 目标值
-
- # iris['data']
- # iris['target']
-
- X_train, X_test, y_train, y_test = train_test_split(iris_X, iris_y, test_size=0.3)
-
- #---------------------------训练数据
- knn = KNeighborsClassifier() # 引入训练方法
- knn.fit(X_train,y_train) # 进行填充测试数据进行训练
-
- knn.predict(X_test) # 预测 特征值
-
- '''
- array([2, 1, 2, 0, 0, 1, 1, 2, 0, 1, 0, 2, 0, 1, 0, 2, 1, 2, 2, 2, 2, 2, 1,
- 1, 1, 1, 0, 2, 1, 2, 0, 1, 1, 0, 0, 2, 0, 0, 1, 0, 2, 1, 1, 2, 2])
- '''
-
- y_test # 真实的 特征值
- '''
- array([2, 1, 2, 0, 0, 1, 2, 2, 0, 1, 0, 2, 0, 1, 0, 2, 1, 2, 2, 2, 2, 2, 1,
- 1, 1, 2, 0, 2, 2, 2, 0, 1, 1, 0, 0, 2, 0, 0, 1, 0, 1, 1, 1, 2, 2])
- '''
-
- print(test_y)
-
- print(pre)
-
- print( sum(abs(pre - test_y)) / len(pre) )
-
- knn.score(test_X, test_y)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。