sklearn knn预测错误:float()参数必须是字符串或数字,而不是' dict'

时间:2015-03-17 15:50:20

标签: python-3.x scikit-learn knn

我尝试将记录输入knn.predict()以使用以下代码进行预测:

person_features = {
 'cma': 462, # Metropolitan area
 'agegrp': 9, # Age Group
 'sex': 1, 
 'ageimm': 6, # Age group at immigration
 'immstat': 1, # Immigrant status
 'pob': 21, # Other Eastern Asia
 'nol': 4, # First languages
 'cip2011': 7, # Major field of study: Mathematics, computer and information     sciences
 'hdgree': 12, # Hightest Education
}

prediction = knn.predict(person_features)
labels={True: '>50K', False: '<=50K'}
print(labels[prediction])

但它显示了

  

TypeError:float()参数必须是字符串或数字,而不是&#39; dict&#39;

我尝试将它变成元组列表,如:

person_features= [('cma',462), ('agegrp',9), ('sex',1), ('ageimm',6), ('immstat',1), ('pob',21), ('nol',4), ('cip2011',7), ('hdgree',12)])

但也没有工作。

我该怎么做才能解决这种类型错误?我觉得这个解决方案很简单,但不知怎的,我只能把它包裹起来。

1 个答案:

答案 0 :(得分:3)

编程新手,刚开始学习Python不到三个月。所以请耐心等待我的业余问题和答案!

# I looked up the numbers from the coding book
cma = 462
agegrp = 9
sex = 1
ageimm = 6 
immstat = 1 
pob = 21
nol = 4
cip2011 =7  
hdgree = 12
MoreThan50K = 1 # what I am going to predict, 1 for >50K, 0 for <50K 

person_features = [cma, agegrp, sex, ageimm, immstat, pob, nol, cip2011, hdgree, MoreThan50K]
prediction = knn.predict(person_features)

所以这毕竟非常简单。