文章目錄
- 摘要
- 1.資料獲取
- 2.資料集分割與初步訓練表現
- 3.測驗不同近鄰值
- 4.交叉檢驗
- 5. 十折交叉檢驗
- 6.輸出預測結果
摘要
本文使用python機器學習庫Scikit-learn中的工具,以某網站電離層資料為案例,使用近鄰演算法進行分類預測,并在訓練后使用K折交叉檢驗進行檢驗,最后輸出預測結果及準確率,程序產生一系列直觀的可視化影像,希望文章能夠對大家有所幫助,祝大家學習順利!

1.資料獲取
1.點擊鏈接獲取資料
資料獲取鏈接
http://archive.ics.uci.edu/ml/datasets/Ionosphere
2.點擊Data Floder

3.選擇ionosphere.data和ionosphere.name這兩個檔案并下載

4.下載后放在指定目錄下,可以直接通過pycharm查看資料的基本資訊
ionosphere.data是我們需要用到的資料,

ionosphere.name是對該資料的介紹,
從ionosphere.name中可以看到,ionosphere.data共有351個樣本,34個特征,且第35個表示類別,有g和b兩個取值,分別表示“good”和“bad”,

2.資料集分割與初步訓練表現
import os
import csv
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import cross_val_score
from matplotlib import pyplot as plt
from collections import defaultdict
data_filename = "ionosphere.data"
X = np.zeros((351, 34), dtype='float')
y = np.zeros((351,), dtype='bool')
with open(data_filename, 'r') as input_file:
reader = csv.reader(input_file)
# print(reader) # csv.reader型別
for i, row in enumerate(reader):
data = [float(datum) for datum in row[:-1]]
# Set the appropriate row in our dataset
X[i] = data
# 將“g”記為1,將“b”記為0,
y[i] = row[-1] == 'g'
# 劃分訓練集、測驗集
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=14)
# 即創建估計器(K近鄰分類器實體) 默認選擇5個近鄰作為分類依據
estimator = KNeighborsClassifier()
# 進行訓練,
estimator.fit(X_train, y_train)
# 評估在測驗集上的表現
y_predicted = estimator.predict(X_test)
# 計算準確率
accuracy = np.mean(y_test == y_predicted) * 100
print("The accuracy is {0:.1f}%".format(accuracy))
# 進行交叉檢驗,計算平均準確率
scores = cross_val_score(estimator, X, y, scoring='accuracy')
average_accuracy = np.mean(scores) * 100
print("The average accuracy is {0:.1f}%".format(average_accuracy))
如圖,該分類演算法準確率可達86.4%,交叉檢驗后的平均準確率可達82.6%,屬于是比較優秀的演算法,

3.測驗不同近鄰值
測驗不同的 近鄰數 n_neighbors的值(上邊默認為5)下的分類準確率,
選擇近鄰值從1到20的二十個數字,
并繪圖展示
avg_scores = []
all_scores = []
parameter_values = list(range(1, 21)) # Including 20
for n_neighbors in parameter_values:
estimator = KNeighborsClassifier(n_neighbors=n_neighbors)
scores = cross_val_score(estimator, X, y, scoring='accuracy')
avg_scores.append(np.mean(scores))
all_scores.append(scores)
# 繪制n_neighbors的不同取值與分類正確率之間的關系
plt.figure(figsize=(32, 20))
plt.plot(parameter_values, avg_scores, '-o', linewidth=5, markersize=24)
plt.show()

可以看出,準確率整體趨勢隨著近鄰數的增加而減小,近鄰值為2時準確率最高,
4.交叉檢驗
把交叉檢驗每次驗證的準確率也繪制出來
(20個近鄰值每個對應5個訓練集,對應5次檢驗)
for parameter, scores in zip(parameter_values, all_scores):
n_scores = len(scores)
plt.plot([parameter] * n_scores, scores, '-o')
plt.show()
各次檢驗準確率圖示如下:

繪制出散點圖
plt.plot(parameter_values, all_scores, 'bx')
plt.show()

5. 十折交叉檢驗
all_scores = defaultdict(list)
parameter_values = list(range(1, 21)) # Including 20
for n_neighbors in parameter_values:
estimator = KNeighborsClassifier(n_neighbors=n_neighbors)
scores = cross_val_score(estimator, X, y, scoring='accuracy', cv=10)
all_scores[n_neighbors].append(scores)
for parameter in parameter_values:
scores = all_scores[parameter]
n_scores = len(scores)
plt.plot([parameter] * n_scores, scores, '-o')
plt.plot(parameter_values, avg_scores, '-o')
plt.show()
檢驗結果如下圖所示:

因為每個近鄰值下,10次檢驗中的準確率可能會有重復值,所以在影像中每個近鄰值上的準確率個數會有差異,
6.輸出預測結果
這里用測驗集作為待測資料,使用上述演算法進行預測,并輸出預測結果,
且令n_neighbors=2
Estimator = KNeighborsClassifier(n_neighbors=2)
Estimator.fit(X_train, y_train)
Y_predicted = Estimator.predict(X_test)
accuracy = np.mean(y_test == Y_predicted) * 100
pre_result = np.zeros_like(Y_predicted, dtype=str)
pre_result[Y_predicted == 1] = 'g'
pre_result[Y_predicted == 0] = 'b'
print(pre_result)
print("The accuracy is {0:.1f}%".format(accuracy))
程式運行結果如下:

如圖,預測準確率達92.0%,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/423751.html
標籤:AI
上一篇:基于face_recognition進行人臉關鍵點檢測(1)
下一篇:Nginx匯總
