sklearn-LinearRegression: 无法将字符串'--'转换为浮点数。

9

我正在尝试使用来自sklearn的LinearRegression,但出现了“无法将字符串转换为浮点数”的错误。数据框的所有列都是浮点数,输出y也是浮点数。我已经查看了其他帖子,并建议将其转换为浮点数,我已经这样做了。

<class 'pandas.core.frame.DataFrame'>
Int64Index: 789 entries, 158 to 684
Data columns (total 8 columns):
f1     789 non-null float64
f2     789 non-null float64
f3     789 non-null float64
f4     789 non-null float64
f5     789 non-null float64
f6     789 non-null float64
OFF    789 non-null uint8
ON     789 non-null uint8
dtypes: float64(6), uint8(2)
memory usage: 44.7 KB

type(y_train)
pandas.core.series.Series
type(y_train[0])
float

from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(X,Y,random_state=0)
X_train.head()
from sklearn.linear_model import LinearRegression
linreg = LinearRegression().fit(X_train, y_train)

我收到的错误是:a
ValueError                                Traceback (most recent call last)
<ipython-input-282-c019320f8214> in <module>()
      6 X_train.head()
      7 from sklearn.linear_model import LinearRegression
----> 8 linreg = LinearRegression().fit(X_train, y_train)
510         n_jobs_ = self.n_jobs
    511         X, y = check_X_y(X, y, accept_sparse=['csr', 'csc', 'coo'],
--> 512                          y_numeric=True, multi_output=True)
    513 
    514         if sample_weight is not None and np.atleast_1d(sample_weight).ndim > 1:

 527         _assert_all_finite(y)
    528     if y_numeric and y.dtype.kind == 'O':
--> 529         y = y.astype(np.float64)
    530 
    531     check_consistent_length(X, y)

ValueError: could not convert string to float: '--'

请帮忙。


XY是什么? - Quickbeam2k1
3个回答

10

一个快速的解决方案是使用pd.to_numeric将您的数据中可能包含的任何字符串转换为数值。如果它们不兼容转换,它们将被减少为NaN

from sklearn.linear_model import LinearRegression

X = X.apply(pd.to_numeric, errors='coerce')
Y = Y.apply(pd.to_numeric, errors='coerce')

另外,您可以选择使用一些默认值来填充这些值:

X.fillna(0, inplace=True)
Y.fillna(0, inplace=True)

用与问题相关的值替换填充值。我不建议删除这些行,因为您可能会删除与XY不同的行,从而导致数据标签不匹配。

最后,拆分并调用分类器:

X_train, X_test, y_train, y_test = train_test_split(X, Y, random_state=0)
clf = LinearRegression().fit(X_train, y_train)

但如果它们变成了“Nan”,LinearRegression.fit()仍然会抛出一个错误。 - Vivek Kumar
@VivekKumar 我不知道 OP 想要对那些 NaN 做什么...也许是删除它们?填充它们?我会在进一步澄清后进行编辑。 - cs95
啊,好的。这将验证 OP 所拥有的数据是否真正有效。谢谢。 - Vivek Kumar
1
@ColdSpeed 谢谢!那很有帮助! - Tinniam V. Ganesh

3

我认为最好将所有的字符串列使用标签编码或独热编码转换为二进制(0,1),然后我们的线性回归模型表现会更好。!!


0

这是因为您的某一列包含字符串值。我曾经遇到过同样的问题,因为我被要求删除一列,但实际上这些列已经被删除了。

然而,在执行以下代码后:

model = LogisticRegressionCV(solver='lbfgs', cv=5, max_iter=1000, random_state=42)
model.fit(X_train, y_train)

我遇到了这个错误:

could not convert string to float: 'product_mng'

原因是X_train仍然有字符串列,我以为已经删除了。总之,请再次检查所有列是否都不是字符串。如果有一个是字符串,请使用pd.drop删除它,或对该字符串列进行标签编码(或1-hot编码)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接