How to realize the knn algorithm of Machine Learning by pandas
This article mainly shows you "pandas how to achieve machine learning knn algorithm", the content is easy to understand, clear, hope to help you solve doubts, the following let Xiaobian lead you to study and learn "pandas how to achieve machine learning knn algorithm" this article.
The details are as follows
# coding: gbkimport pandas as pdimport numpy as npdef getdata (path): data = pd.read_csv (path, header=None, sep='\ t') character = data.iloc [:,:-1] label = data.iloc [:,-1] chara_max = character.max () chara_min = character.min () chara_range = chara_max-chara_min normal_chara = (character-chara_min) / chara_range return normal_chara, label # obtains normalized eigenvalues and tags def knn (inX, normal_chara Label, k): data_sub = normal_chara-inX data_square = data_sub.applymap (np.square) data_sum = data_square.sum (axis=1) data_sqrt = data_sum.map (np.sqrt) dis_sort = data_sqrt.argsort () k_label = label [dis _ sort [: K]] label_sort = k_label.value_counts () res_label = label_sort.index [0] return res_label # knn algorithm classification
Machine Learning-- the basic implementation of KNN
# _ * _ coding _ * _ import numpy as npimport mathimport operator def get_data (dataset): X = dataset [:,:-1] .astype (np.float) y = dataset [:,-1] return XMagi y # def cal_dis (aMague b): # x1Magna y1 = a [:] # x2Magi y2 = b [:] # dist = math.sqrt (math.pow (2Magnex2)-math.pow (2Query x1)) def knnclassifer (dataset,predict,k=3): X Y = get_data (dataset) dic = {} distince = np.sum ((predict-x) * * 2 countLabel axisym1) * * 0.5 sorted_dict = np.argsort (distince) # [2 034] countLabel = {} for i in range (k): label = y [sorted _ ordered [I]] # print (icountLabel sorted [I], label) countLabel [label] = countLabel.get (label,0) + 1 new_dic = sorted (countLabel,key=operator.itemgetter (0) Reverse=True) return new_dic [0] [0] if _ _ name__ ='_ _ main__': dataset = np.loadtxt ("dataset.txt", dtype=np.str,delimiter= ",") predict = [2Maine 2] label = knnclassifer (dataset,predict,3) print (label) these are all the contents of the article "how pandas implements the knn algorithm for Machine Learning" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!