【问题标题】:sklearn knn prediction error: float() argument must be a string or a number, not 'dict'sklearn knn 预测错误:float() 参数必须是字符串或数字,而不是 'dict'
【发布时间】:2015-05-20 03:40:06
【问题描述】:

我正在尝试将记录提供给 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() 参数必须是字符串或数字,而不是 'dict'

我尝试将其放入元组列表中,例如:

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

但也没有用。

我应该怎么做才能解决这个类型错误?我觉得解决方案很简单,但不知何故我只能绕着它转。

【问题讨论】:

  • 它需要一个浮点数的 numpy 数组,您正在传递一个 dict,您需要将输入数据转换为仅包含值的 numpy 数组,请参见此处的示例:scikit-learn.org/stable/tutorial/statistical_inference/…
  • 非常感谢您的回复。然后我尝试了 inputData = np.ndarray(shape=(1,10)) inputData=[462,12,1,6,1,21,4,7,12,1] 它有效:)虽然我不是对预测感到满意,因为它说我的收入将少于
  • 你可以发帖作为答案并记得接受它,答案左上角会有一个空的勾号

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


【解决方案1】:

刚开始学习 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)

所以这毕竟是相当简单的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-24
    • 2023-04-09
    • 2018-02-26
    • 2020-10-04
    • 1970-01-01
    • 1970-01-01
    • 2019-11-16
    • 2022-06-14
    相关资源
    最近更新 更多