如何使用线性回归将字符串作为 Y 输出 Python

How to get string as Y output using Linear regression Python

我有这个使用线性回归的评分预测模型

status = pd.DataFrame({'rating': [10.5,20.30,30.12,40.24,50.55,60.6,70.2], 'B': ['Bad','Not bad','Good','I like it','Very good','The best','Deserve an oscar']})

x = status.iloc[:,:-1].values
y = status.iloc[:,-1].values

from sklearn.model_selection import train_test_split

x_train,x_test,y_train,y_test = train_test_split(x,y,train_size=0.4,random_state=0)

from sklearn.linear_model import LinearRegression

lr = LinearRegression()
lr.fit(x,y)

input = 40.24
lr.predict([[input]])

所以我有 40.24 作为 X 值的输入,我期望 'I like it' 作为输出,但它抛出错误,因为预期的输出是一个字符串,这里是错误:ValueError: could not convert string to float: 'Bad'。我如何让它能够将字符串作为输出?

你好,因为 sckitlearn 或机器学习标签需要数字作为输入,我不确定在这种情况下 类 是什么,但你可以使用 sckitlearn[=12] 中的 onehotencoder =]

也请将其更改为逻辑回归

from sklearn.preprocessing import OneHotEncoder
from sklearn.linear_model import LogisticRegression

# 1. INSTANTIATE
enc = OneHotEncoder()

# 2. FIT
enc.fit(y)

# 3. Transform
onehotlabels = enc.transform(y).toarray()
onehotlabels.shape

clf = LogisticRegression(random_state=0).fit(x, onehotlabels)

或者您可以手动将其绘制成您喜欢的方式 (例如差 -> 0,好 -> 1)

如果您有 Target feature as a Categorical D-Type,则无法执行 Linear Regression。 这是执行线性回归的第一条规则,您应该具有连续目标特征,因为 y=mx+c 函数仅将数字作为输入并针对数字项目测试函数并预测数字项目。

That is why it gets trained but fails to predict.

您需要对目标特征进行编码。 请self-study这些概念。

希望对您有所帮助。

你的标签是分类的,其中回归标签应该是连续的数字。 您可以考虑将其视为分类问题而不是回归问题。