У меня есть набор данных сотрудника. Я пытаюсь применить K ближайшего соседа. Набор данных имеет 34 атрибута и 1029 строк. Среди 34 атрибутов 7 атрибутов относятся к типу объектов. Я получаю эту ошибку «Не удалось преобразовать строку в число с плавающей точкой:« Travel_Frequently ».» Как я могу решить это. Иногда, это также показывает, что «список вне индекса». Как я могу решить это?
import random
import operator
import math
def getdata(filename):
with open(filename,'rb') as f:
reader = unicodecsv.reader(f)
return list(reader)
with open('employee.csv','rb') as f:
reader = unicodecsv.reader(f)
taposh = list(reader)
len(taposh)
def shuffle(taposh):
random.shuffle(taposh)
train_data = taposh[:int(0.7*11)]
test_data = taposh[int(0.7*11):]
return train_data, test_data
def euclideanDist(x, xi):
d = 0.0
for i in range(len(x)-1):
d += pow((float(x[i])-float(xi[i])),2)
d = math.sqrt(d)
return d
def knn_predict(test_data, train_data, k_value):
for i in test_data:
eu_Distance =[]
knn = []
good = 0
bad = 0
for j in train_data:
eu_dist = euclideanDist(i, j)
eu_Distance.append((j[5], eu_dist))
eu_Distance.sort(key = operator.itemgetter(1))
knn = eu_Distance[:k_value]
for k in knn:
if k[0] =='g':
good += 1
else:
bad +=1
if good > bad:
i.append('g')
elif good < bad:
i.append('b')
else:
i.append('NaN')
def accuracy(test_data):
correct = 0
for i in test_data:
if i[1] == i[2]:
correct += 1
accuracy = float(correct)/len(test_data) *100
return accuracy
dataset = getdata('employee.csv')
train_dataset, test_dataset = shuffle(dataset)
K = 3
knn_predict(test_dataset, train_dataset, K)
print (test_dataset)
print ("Accuracy : ",accuracy(test_dataset))```