gpt4 book ai didi

python - 使用 sklearn - python 具有分类特征的多元线性回归

转载 作者:行者123 更新时间:2023-11-30 08:53:18 24 4
gpt4 key购买 nike

我有一个数据集,其中每个文档都有相应的分数/评级

dataset = [
{"text":"I don't like this small device", "rating":"2"},
{"text":"Really love this large device", "rating":"5"},
....
]

此外,我还有一个从同一数据集中的 text 变量中提取的术语列表类别(变量)

x1 = [short, slim, small, shrink]
x2 = [big,huge,large]

那么,如何使用多个自变量作为单词列表(或代表相应术语列表中任何单词存在的变量,因为列表中的每个术语都是unique )和因变量作为评级。换句话说

how could I evaluate term lists impact on the rating with sklearn

我使用 TfidfVectorizer 来导出文档术语矩阵。如果可能,请提供简单的代码片段或示例。

最佳答案

鉴于评论中的讨论,似乎解释应该是每个列表定义一个二进制变量,其值取决于列表中的任何单词是否出现在相关文本中。因此,让我们首先更改文本,以便单词实际出现:

dataset = [
{"text": "I don't like this large device", "rating": "2"},
{"text": "Really love this small device", "rating": "5"},
{"text": "Some other text", "rating": "3"}
]

为了简化我们的工作,我们将这些数据加载到数据框中,将评级更改为整数,并创建相关变量:

df = pd.DataFrame(dataset)
df['rating'] = df['rating'].astype(int)
df['text'] = df['text'].str.split().apply(set)
x1 = ['short', 'slim', 'small', 'shrink']
x2 = ['big', 'huge', 'large']
df['x1'] = df.text.apply(lambda x: x.intersection(x1)).astype(bool)
df['x2'] = df.text.apply(lambda x: x.intersection(x2)).astype(bool)

也就是说,此时df就是下面的数据框:

   rating                                   text     x1     x2
0 2 {this, large, don't, like, device, I} False True
1 5 {this, small, love, Really, device} True False
2 3 {other, Some, text} False False

这样,我们就可以创建相关模型,并检查系数最终是多少:

model = LinearRegression()
model.fit(df[['x1', 'x2']], df.rating)
print(model.coef_) # array([ 2., -1.])
print(model.intercept_) # 3.0

正如评论中提到的,这个东西最多会产生四个评级,每个 x1x2 的组合为 TrueFalse。在这种情况下,所有可能的输出都是整数,但一般来说,它们不需要,也不需要被限制在感兴趣的区间内。考虑到评级的顺序性质,这确实是某种 ordinal regression 的情况。 (例如 mord )。

关于python - 使用 sklearn - python 具有分类特征的多元线性回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53131575/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com