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

类型错误:int类型对象无len()方法,求逻辑回归代码报错解决

解决逻辑回归代码中的 TypeError: object of type 'int' has no len() 问题

让我们一步步拆解和修复这个问题:

报错根源分析

你遇到的错误是因为在使用OneHotEncoder时犯了两个关键错误:

  1. 列索引错误:你的X是从数据集中提取的第16列(iloc[:,16:17]),所以X只有1列,索引为0,但你却指定了categorical_features=1——这个索引根本不存在!当OneHotEncoder尝试访问不存在的第1列时,得到的是单个int值,而它需要的是可迭代的数组,自然就抛出了object of type 'int' has no len()的错误。
  2. 过时的参数用法:categorical_features这个参数在scikit-learn 0.20版本之后就被弃用了,官方推荐使用ColumnTransformer来更清晰地管理列预处理逻辑。

修正后的代码方案

下面是修复后的完整代码,同时采用了scikit-learn当前推荐的编码方式:

# Logistic Regression
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Loan.csv')
X = dataset.iloc[:, 16: 17 ].values
y = dataset.iloc[:, 20].values
# Encoding categorical data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.compose import ColumnTransformer

# 对分类特征进行标签编码(如果特征是字符串类型,这一步其实可以省略,新版OneHotEncoder支持直接处理)
labelencoder = LabelEncoder()
X[:, 0] = labelencoder.fit_transform(X[:, 0])

# 使用ColumnTransformer指定要编码的列(推荐用法)
column_transformer = ColumnTransformer(
    transformers=[('one_hot_encoder', OneHotEncoder(), [0])],  # 对第0列应用独热编码
    remainder='passthrough'  # 其他列保持原样(这里没有其他列,可省略,但保留更规范)
)
# 将转换结果转为numpy数组,确保后续模型可以正常使用
X = np.array(column_transformer.fit_transform(X))

额外说明

  • 如果你的原始特征(第16列)是字符串类型,其实可以跳过LabelEncoder这一步,新版的OneHotEncoder可以直接处理字符串形式的分类特征,简化代码。
  • 使用ColumnTransformer的好处是,当你后续需要对多列应用不同预处理(比如部分列独热编码,部分列标准化)时,逻辑会更清晰,也避免了手动处理数组维度的麻烦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:36:54