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

Colab中Sklearn模型训练报错:无法将字符串转为浮点数

问题根源

Sklearn的机器学习模型无法直接处理字符串类型的特征,报错中的'delivered'属于文本分类值,必须先将其转换为数值格式,才能输入模型完成训练。

解决方法

1. 转换分类特征为数值格式

根据特征的类型选择对应的编码方式:

  • 标签编码(Label Encoding):适用于有序分类特征(如'low'/'medium'/'high')
from sklearn.preprocessing import LabelEncoder
import pandas as pd

# 替换为你数据集中的字符串列名
df['status'] = LabelEncoder().fit_transform(df['status'])
  • 独热编码(One-Hot Encoding):适用于无序分类特征(如'delivered'/'pending'/'cancelled')
    用Pandas快速实现:
# columns参数指定需要编码的字符串列
df = pd.get_dummies(df, columns=['status'])

结合Sklearn Pipeline实现完整流程(推荐用于交叉验证场景):

from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score

# 区分数值特征列和分类特征列,替换为你的实际列名
numeric_features = ['order_amount', 'delivery_time']
categorical_features = ['status']

# 构建预处理流程:数值列直接保留,分类列做独热编码
preprocessor = ColumnTransformer(
    transformers=[
        ('num', 'passthrough', numeric_features),
        ('cat', OneHotEncoder(handle_unknown='ignore'), categorical_features)
    ])

# 组装预处理+模型的Pipeline
clf = Pipeline(steps=[
    ('preprocessor', preprocessor),
    ('classifier', LogisticRegression())
])

# 执行交叉验证
scores = cross_val_score(clf, X, y, cv=10)

2. 清理字符串中的空格

如果怀疑数据存在空格干扰,先清洗字符串列:

# 去除字符串两端的空格
df['status'] = df['status'].str.strip()
# 可选:统一字符串大小写,避免大小写差异导致的分类错误
df['status'] = df['status'].str.lower()

3. 确认数据集特征类型

先排查数据类型和字符串列的唯一值,定位问题:

# 查看所有列的数据类型
print(df.dtypes)
# 查看目标字符串列的所有唯一值
print(df['status'].unique())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 19:21:06