欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python利用scikit-learn實現近鄰算法分類的示例詳解

 更新時間:2023年02月28日 09:21:54   作者:吃肉的小饅頭  
scikit-learn已經封裝好很多數據挖掘的算法,這篇文章就來用scikit-learn實現近鄰算法分類,文中的示例代碼講解詳細,感興趣的小伙伴可以了解一下

scikit-learn庫

scikit-learn已經封裝好很多數據挖掘的算法

現介紹數據挖掘框架的搭建方法

1.轉換器(Transformer)用于數據預處理,數據轉換

2.流水線(Pipeline)組合數據挖掘流程,方便再次使用(封裝)

3.估計器(Estimator)用于分類,聚類,回歸分析(各種算法對象)

所有的估計器都有下面2個函數

fit() 訓練

用法:estimator.fit(X_train, y_train)

estimator = KNeighborsClassifier() 是scikit-learn算法對象

X_train = dataset.data 是numpy數組

y_train = dataset.target 是numpy數組

predict() 預測

用法:estimator.predict(X_test)

estimator = KNeighborsClassifier() 是scikit-learn算法對象

X_test = dataset.data 是numpy數組

示例

%matplotlib inline
# Ionosphere數據集
# https://archive.ics.uci.edu/ml/machine-learning-databases/ionosphere/
# 下載ionosphere.data和ionosphere.names文件,放在 ./data/Ionosphere/ 目錄下
import os
home_folder = os.path.expanduser("~")
print(home_folder) # home目錄
# Change this to the location of your dataset
home_folder = "." # 改為當前目錄
data_folder = os.path.join(home_folder, "data")
print(data_folder)
data_filename = os.path.join(data_folder, "ionosphere.data")
print(data_filename)
import csv
import numpy as np
# Size taken from the dataset and is known已知數據集形狀
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)
    for i, row in enumerate(reader):
        # Get the data, converting each item to a float
        data = [float(datum) for datum in row[:-1]]
        # Set the appropriate row in our dataset用真實數據覆蓋掉初始化的0
        X[i] = data
        # 1 if the class is 'g', 0 otherwise
        y[i] = row[-1] == 'g' # 相當于if row[-1]=='g': y[i]=1 else: y[i]=0
# 數據預處理
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=14)
print("訓練集數據有 {} 條".format(X_train.shape[0]))
print("測試集數據有 {} 條".format(X_test.shape[0]))
print("每條數據有 {} 個features".format(X_train.shape[1]))

輸出:

訓練集數據有 263 條
測試集數據有 88 條
每條數據有 34 個features

# 實例化算法對象->訓練->預測->評價
from sklearn.neighbors import KNeighborsClassifier

estimator = KNeighborsClassifier()
estimator.fit(X_train, y_train)
y_predicted = estimator.predict(X_test)
accuracy = np.mean(y_test == y_predicted) * 100
print("準確率 {0:.1f}%".format(accuracy))

# 其他評價方式
from sklearn.cross_validation import cross_val_score
scores = cross_val_score(estimator, X, y, scoring='accuracy')
average_accuracy = np.mean(scores) * 100
print("平均準確率 {0:.1f}%".format(average_accuracy))

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)

輸出:

準確率 86.4%
平均準確率 82.3%

from matplotlib import pyplot as plt
plt.figure(figsize=(32,20))
plt.plot(parameter_values, avg_scores, '-o', linewidth=5, markersize=24)
#plt.axis([0, max(parameter_values), 0, 1.0])

for parameter, scores in zip(parameter_values, all_scores):
    n_scores = len(scores)
    plt.plot([parameter] * n_scores, scores, '-o')

plt.plot(parameter_values, all_scores, 'bx')

from collections import defaultdict
all_scores = defaultdict(list)
parameter_values = list(range(1, 21))  # Including 20
for n_neighbors in parameter_values:
    for i in range(100):
        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')

以上就是Python利用scikit-learn實現近鄰算法分類的示例詳解的詳細內容,更多關于Python scikit-learn近鄰算法分類的資料請關注腳本之家其它相關文章!

相關文章

  • Python使用QQ郵箱發(fā)送郵件實例與QQ郵箱設置詳解

    Python使用QQ郵箱發(fā)送郵件實例與QQ郵箱設置詳解

    這篇文章主要介紹了Python發(fā)送QQ郵件實例與QQ郵箱設置詳解,需要的朋友可以參考下
    2020-02-02
  • Python實現爬取某站視頻彈幕并繪制詞云圖

    Python實現爬取某站視頻彈幕并繪制詞云圖

    這篇文章主要介紹了利用Python爬取某站的視頻彈幕,并將其繪制成詞云圖,文中的示例代碼講解詳細,對我學習Python爬蟲有一定的幫助,需要的朋友可以參考一下
    2021-12-12
  • Python argparse命令參數與config配置參數示例深入詳解

    Python argparse命令參數與config配置參數示例深入詳解

    這篇文章主要介紹了Python argparse命令參數與config配置參數,argparse是Python內置的一個用于命令項選項與參數解析的模塊,通過在程序中定義好我們需要的參數,然后在程序啟動命令行傳遞我們想要改變的參數
    2023-03-03
  • 如何在python?中導入?package

    如何在python?中導入?package

    這篇文章主要介紹了?如何在python中導入,package,package?在python中是一種有效組織代碼,module可以是一個文件,可以通過import來導入一個module?單個文件,而,package,則是作為一個目錄來導入,下文操作流程需要的朋友可以參考一下
    2022-04-04
  • python爬蟲增加訪問量的方法

    python爬蟲增加訪問量的方法

    這篇文章主要介紹了python爬蟲增加訪問量的方法,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-08-08
  • Python計算雙重差分模型DID及其對應P值使用詳解

    Python計算雙重差分模型DID及其對應P值使用詳解

    這篇文章主要介紹了Python計算DID及其對應P值的使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步早日升職加薪
    2021-09-09
  • Python計算程序運行時間的方法

    Python計算程序運行時間的方法

    這篇文章主要介紹了Python計算程序運行時間的方法,分別記錄起始時間與結束時間,計算兩者之間的差值來獲得程序的運行時間,需要的朋友可以參考下
    2014-12-12
  • Python使用裝飾器模擬用戶登陸驗證功能示例

    Python使用裝飾器模擬用戶登陸驗證功能示例

    這篇文章主要介紹了Python使用裝飾器模擬用戶登陸驗證功能,結合登錄驗證實例形式分析了裝飾器的簡單使用技巧,需要的朋友可以參考下
    2018-08-08
  • Django框架實現逆向解析url的方法

    Django框架實現逆向解析url的方法

    這篇文章主要介紹了Django框架實現逆向解析url的方法,結合實例形式分析了Django逆向解析URL的原理、步驟、相關實現技巧與注意事項,需要的朋友可以參考下
    2018-07-07
  • 樸素貝葉斯Python實例及解析

    樸素貝葉斯Python實例及解析

    這篇文章主要為大家詳細介紹了樸素貝葉斯Python算法實現,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-11-11

最新評論