Python 逻辑回归 Y 值问题

Python Logistic Regression Y Value Issues

我目前遇到以下混合错误:

当我搜索遇到同样问题的其他人时,答案通常会将我从上述错误之一引向另一个错误。下面是我的代码的屏幕截图。第 7-9 行是我为我的错误找到的解决方案,这些错误只会导致不同的错误。注释掉第 8 行或第 9 行或两者,它会给你错误的形状错误。注释掉所有三个,您会收到标签类型未知错误。

对于第 7 行,我尝试了 bool、int 和 float。

df.loc[df['ReAdmis'] == 'No', 'ReAdmis'] = "False"
df.loc[df['ReAdmis'] == 'Yes', 'ReAdmis'] = "True"

log_ra = df['ReAdmis']

print(log_ra.head)
log_ra=log_ra.astype('bool')
# log_ra=log_ra.to_numpy()
log_ra=log_ra.reshape(-1,1)


model = LogisticRegression(solver='liblinear')
logistic_regression = model.fit(df1,log_ra)
model.score(log_ra, df1)

我正在使用掩码将 Y 值的 Yes/No 转换为 1/0,这是导致此问题的原因吗?当我在研究这个的多元回归版本时,我发现了很多很棒的文章,但逻辑回归似乎很少被使用,而且我没有找到那么多有用的文章。

第 9 行:请注意,在您的代码中,shape 是元组和 DataFrame 对象的 属性,即您不能 调用 它但只能访问它;见 https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.shape.html

也许您想在那里使用 reshape

第 7 行:astype(float) 将列的类型更改为 float(参见 https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.astype.html);如果你想分别用 TrueFalse 替换 YesNo,你可以在第 1 行和第 2 行这样设置。之后,你可以使用 df = df.astype(bool) 将类型设置为 bool.

示例:

>>> df = pd.DataFrame([{"ReAdmis": "No"}, {"ReAdmis": "Yes"}])
>>> df[df["ReAdmis"] == "Yes"] = True
>>> df[df["ReAdmis"] == "No"] = False
>>> # The dtype of the ReAdmins column is object; need to explicitly convert it to bool
>>> df = df.astype(bool)
>>> print(df)
  ReAdmis
0    False
1    True
>>> print(df.dtypes)
ReAdmis    bool
dtype: object