最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python利用scikit-learn實現(xiàn)近鄰算法分類的示例詳解

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

scikit-learn庫

scikit-learn已經(jīng)封裝好很多數(shù)據(jù)挖掘的算法

現(xiàn)介紹數(shù)據(jù)挖掘框架的搭建方法

1.轉(zhuǎn)換器(Transformer)用于數(shù)據(jù)預(yù)處理,數(shù)據(jù)轉(zhuǎn)換

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

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

所有的估計器都有下面2個函數(shù)

fit() 訓(xùn)練

用法:estimator.fit(X_train, y_train)

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

X_train = dataset.data 是numpy數(shù)組

y_train = dataset.target 是numpy數(shù)組

predict() 預(yù)測

用法:estimator.predict(X_test)

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

X_test = dataset.data 是numpy數(shù)組

示例

%matplotlib inline
# Ionosphere數(shù)據(jù)集
# 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 = "." # 改為當(dāng)前目錄
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已知數(shù)據(jù)集形狀
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用真實數(shù)據(jù)覆蓋掉初始化的0
        X[i] = data
        # 1 if the class is 'g', 0 otherwise
        y[i] = row[-1] == 'g' # 相當(dāng)于if row[-1]=='g': y[i]=1 else: y[i]=0
# 數(shù)據(jù)預(yù)處理
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("訓(xùn)練集數(shù)據(jù)有 {} 條".format(X_train.shape[0]))
print("測試集數(shù)據(jù)有 {} 條".format(X_test.shape[0]))
print("每條數(shù)據(jù)有 {} 個features".format(X_train.shape[1]))

輸出:

訓(xùn)練集數(shù)據(jù)有 263 條
測試集數(shù)據(jù)有 88 條
每條數(shù)據(jù)有 34 個features

# 實例化算法對象->訓(xùn)練->預(yù)測->評價
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("準(zhǔn)確率 {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("平均準(zhǔn)確率 {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)

輸出:

準(zhǔn)確率 86.4%
平均準(zhǔn)確率 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實現(xiàn)近鄰算法分類的示例詳解的詳細(xì)內(nèi)容,更多關(guān)于Python scikit-learn近鄰算法分類的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Python?pycharm讀取文件相對路徑與絕對路徑的方法

    Python?pycharm讀取文件相對路徑與絕對路徑的方法

    這篇文章主要給大家介紹了關(guān)于Python?pycharm讀取文件相對路徑與絕對路徑的方法,絕對路徑就是文件的真正存在的路徑,是指從硬盤的根目錄(盤符)開始,進(jìn)行一級級目錄指向文件,相對路徑就是以當(dāng)前文件為基準(zhǔn)進(jìn)行一級級目錄指向被引用的資源文件,需要的朋友可以參考下
    2023-12-12
  • matplotlib legend()里字體如何修改

    matplotlib legend()里字體如何修改

    這篇文章主要介紹了matplotlib legend()里字體如何修改問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • Python實現(xiàn)更改圖片尺寸大小的方法(基于Pillow包)

    Python實現(xiàn)更改圖片尺寸大小的方法(基于Pillow包)

    這篇文章主要介紹了Python實現(xiàn)更改圖片尺寸大小的方法,結(jié)合實例形式分析了Python基于Pillow包更改圖片屬性的相關(guān)技巧,需要的朋友可以參考下
    2016-09-09
  • Python正則表達(dá)式指南 推薦

    Python正則表達(dá)式指南 推薦

    本文介紹了Python對于正則表達(dá)式的支持,包括正則表達(dá)式基礎(chǔ)以及Python正則表達(dá)式標(biāo)準(zhǔn)庫的完整介紹及使用示例。本文的內(nèi)容不包括如何編寫高效的正則表達(dá)式、如何優(yōu)化正則表達(dá)式,這些主題請查看其他教程。
    2018-10-10
  • python實現(xiàn)用戶答題功能

    python實現(xiàn)用戶答題功能

    這篇文章主要為大家詳細(xì)介紹了python實現(xiàn)用戶答題功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-01-01
  • Python基礎(chǔ)之numpy庫的使用

    Python基礎(chǔ)之numpy庫的使用

    這篇文章主要介紹了Python基礎(chǔ)之numpy庫的使用,文中有非常詳細(xì)的代碼示例,對正在學(xué)習(xí)python基礎(chǔ)的小伙伴們有非常好的幫助,需要的朋友可以參考下
    2021-04-04
  • Python中如何快速解析JSON對象數(shù)組

    Python中如何快速解析JSON對象數(shù)組

    由于瀏覽器可以迅速地解析JSON對象,它們有助于在客戶端和服務(wù)器之間傳輸數(shù)據(jù),本文將描述如何使用Python的JSON模塊來傳輸和接收J(rèn)SON數(shù)據(jù)
    2023-09-09
  • python+selenium+chrome批量文件下載并自動創(chuàng)建文件夾實例

    python+selenium+chrome批量文件下載并自動創(chuàng)建文件夾實例

    這篇文章主要介紹了python+selenium+chrome批量文件下載并自動創(chuàng)建文件夾實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-04-04
  • 詳解PyCharm安裝MicroPython插件的教程

    詳解PyCharm安裝MicroPython插件的教程

    PyCharm可以說是當(dāng)今最流行的一款Python IDE了,大部分購買TPYBoard的小伙伴都會使用PyCharm編寫MicroPython的程序。這篇文章給大家介紹了PyCharm安裝MicroPython插件的教程,需要的朋友參考下吧
    2019-06-06
  • python獲取指定時間差的時間實例詳解

    python獲取指定時間差的時間實例詳解

    這篇文章主要介紹了python獲取指定時間差的時間實例詳解的相關(guān)資料,需要的朋友可以參考下
    2017-04-04

最新評論

绥棱县| 图木舒克市| 新乡市| 新闻| 方城县| 两当县| 上杭县| 仁化县| 潮安县| 博野县| 昌黎县| 新巴尔虎右旗| 桑植县| 武陟县| 北宁市| 肇东市| 太谷县| 宁晋县| 贵定县| 湘潭市| 尚志市| 旬邑县| 津市市| 沧州市| 靖边县| 自贡市| 安溪县| 九龙城区| 康定县| 武城县| 铜陵市| 九江县| 依安县| 黄陵县| 建瓯市| 都匀市| 清河县| 新干县| 兴山县| 聂拉木县| 根河市|