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

时间:2018-11-03 13:01:39

标签: python machine-learning scikit-learn linear-regression data-mining

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

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]

因此,我该如何使用multiple independent variables作为单词列表进行线性回归(或代表相应术语列表中任何单词存在的变量,因为列表中的每个术语都是唯一的 )和dependent variable as a rating。换句话说

  

我如何评估sklearn对术语表的影响

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

1 个答案:

答案 0 :(得分:1)

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

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)来说就是这样。

相关问题