You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

sklearn训练模型报错ValueError: could not convert string to float求助

报错原因

你的代码出现该错误是因为从cars表查询到的字段包含字符串类型数据,scikit-learn的决策树模型不支持直接输入字符串格式的特征或标签,要求输入必须为数值类型。

修复代码(使用LabelEncoder处理字符串)
import sqlite3
from sklearn import tree
from sklearn.preprocessing import LabelEncoder
import numpy as np

database = sqlite3.connect("database.db")
c = database.cursor()

x = []
y = []

for row in c.execute('SELECT * FROM cars'):
    x.append(row[0])
    y.append(row[1])

# 初始化编码器
x_encoder = LabelEncoder()
y_encoder = LabelEncoder()
# 对字符串类型的特征和标签做数值编码
x_encoded = x_encoder.fit_transform(x)
y_encoded = y_encoder.fit_transform(y)
# 把特征转成二维数组格式,符合sklearn输入要求
x_encoded = x_encoded.reshape(-1, 1)

clf = tree.DecisionTreeClassifier()
ml = clf.fit(x_encoded, y_encoded)
补充说明
  • 如果后续需要把预测得到的数值标签转回原始字符串,可以调用y_encoder.inverse_transform(预测结果数组)实现
  • 如果你的x包含多个特征列,建议逐列对字符串类型的特征单独做LabelEncoder编码,再合并为特征矩阵使用

内容的提问来源于stack exchange,提问作者Abbott Taft

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 01:15:10