I was trying to write a classifier algorithm for a machine learning model but it comes with an error. Could anyone help? thanks in advance
import pandas as pd
from sklearn.metrics import accuracy_score
from scipy.spatial import distance
def euc(a, b):
return distance.euclidean(a,b)
class classifierKN():
def fit(self, X_train, Y_train):
self.X_train = X_train
self.Y_train = Y_train
def predict(self, X_test):
predictions = []
for row in X_test:
label = self.closest(row)
predictions.append(label)
return predictions
def closest(self, row):
best_dist = euc(row, self.X_train[0])
best_index = 0
for i in range(1, len(self.X_train)):
dist = euc(row, self.X_train[i])
if dist < best_dist:
best_dist = dist
best_index = i
return self.Y_train[best_index]
#Load the dataset
diabetdata = pd.read_csv("diabetes.csv")
#set features and target
features = ["PlasmaGlucose", "DiastolicBloodPressure", "TricepsThickness", "SerumInsulin"]
X = diabetdata[features]
print("FEATURES: " , X.head())
Y = diabetdata.Diabetic
print("TARGET: " , Y.head())
print("")
from sklearn.model_selection import train_test_split #No module named 'sklearn.cross_validation' so I replace it with model_selection
X_train, X_test, Y_train, Y_test = train_test_split(X,Y, test_size=0.3, random_state=0)
#predict
model= classifierKN()
model.fit(X_train,Y_train)
predictKN = model.predict(X)
print ("Predict result with KNeighborsClassifier")
print(predictKN)
#accuracy
print("Accuracy")
print (accuracy_score(Y, predictKN))
Outcome
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Vlad\Desktop\Machine learning\Machine Learning\coursework\test2.py", line 63, in <module>
predictKN = model.predict(X)
File "C:\Users\Vlad\Desktop\Machine learning\Machine Learning\coursework\test2.py", line 26, in predict
label = self.closest(row)
File "C:\Users\Vlad\Desktop\Machine learning\Machine Learning\coursework\test2.py", line 30, in closest
best_dist = euc(row, self.X_train[0])
File "E:\Anaconda\lib\site-packages\pandas\core\frame.py", line 2800, in __getitem__
indexer = self.columns.get_loc(key)
File "E:\Anaconda\lib\site-packages\pandas\core\indexes\base.py", line 2648, in get_loc
return self._engine.get_loc(self._maybe_cast_indexer(key))
File "pandas\_libs\index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\hashtable_class_helper.pxi", line 1619, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas\_libs\hashtable_class_helper.pxi", line 1627, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 0