0
0

More than 1 year has passed since last update.

k近傍法をsklearnなしで実行する方法について!!

Posted at

こんにちは!初投稿させていただきます.

今回はk近傍法をsklearnを使わず行う方法を解説します.

使うデータとしてはsklearnに内蔵されているdigitデータです.

k.py
import numpy as np
import pandas as pd
import collections
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, accuracy_score, confusion_matrix

# データのロード
digits = datasets.load_digits()

# 特徴量
image = digits.images
total , x , y = image.shape 
image = np.reshape( image , [total,x*y] )

# 目的変数
label = digits.target

# 学習データ,テストデータ
train_data, test_data, train_label, test_label = train_test_split(image, label, test_size=0.5, random_state=None)

# テストデータ数
testcount = test_label.shape[0]

# 予測結果を格納する配列
all_label=[]
#k近傍法のkの指定
mk=int(input())


#テストデータの繰り返しの準備
for i in range(len(test_data)):
    #あるテストデータにおける最近傍を求めるためのデータフレームの準備
    output=pd.DataFrame(columns=['index','ans'])
    #学習データの繰り返しの準備
    for j in range(len(train_data)):
        #あるテストデータと学習データの距離を格納するための変数ans
        ans=0
        #あるテストデータと学習データの距離を調べるfor文
        for k in range(len(train_data[0,:])):
            ans+=(train_data[j,k]-test_data[i,k])**2
        #outputに各学習データのindexとあるテストデータとの距離を格納
        number = pd.Series([int(j),ans],index=output.columns)
        output = output.append(number, ignore_index=True)
    #outputを距離で昇順に並べる
    output = output.sort_values('ans')
    #距離で昇順に並べたあとのindexを格納するリストkkk
    kkk=[]
    #距離で昇順に並べたあとのindexから学習データの中のラベルを調べるfor文
    for l in range(mk):
        kkk.append(train_label[int(output.iat[l,0])])
    #ラベルを調べた後にその中にどの値が最も多いのか(最頻値)を調べてkkkに格納
    kk = collections.Counter(kkk).most_common()[0][0]
    #ラベルを結果に格納する
    all_label.append(kk)






#念の為の正解率や混合行列の結果

#予測結果
print( classification_report(test_label, all_label) )

#正解率
print( accuracy_score(test_label, all_label) )

#混同行列
print( confusion_matrix(test_label, all_label) )

ぜひ,ご自分でも加工して作ってみてください!!
これを学ぶだけでもpythonの中身がわかっていい勉強になると思います.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0