pandas frame中存储了文本数据,如何用sklearn实现简单的分类

Having text data stored in pandas frame, how to implement simple classification with sklearn

我有一个框架,它在 A 列中存储文本评论,在 B 列中存储评分(1 到 5)。

id .....review ..............rating          
1  .....That was awful ......1...

我需要创建一个简单的(任何基于算法的)分类器,例如,基于 word:occurrances 词汇表等特征,它可以预测评分是 > 3 还是 < 3(假设我们要添加如果评分> 3 则为 1,如果 <)

则为 0

我不擅长 Python 和机器学习,所以我在搜索过的所有样本上都卡住了。

请解释一下如何在该示例案例中提取特征,如何训练模型等等,或者为该案例提供一个好的导师(我无法将 sklearn 导师翻译成我的案例)。

大约有两个一般步骤,可以详细解释一下。

特征提取

首先,您需要确定要使用的功能。这是主要任务之一,由您决定。标准方法是 bag-of-words model. This counts the occurrence of each word in each text. It is

quite simplistic but surprisingly useful in practice

还有一些专门的工具可以为您进行 tf-idf 分析,例如 Sally

假设您想在 Python 中使用 scikit-learn 执行此操作。数据已经作为具有 textrating 属性的 class Review(object) 提供。您需要从 text 中提取特征。

示例:

def extract(review):
    '''extracts features from review'''
    result = {}
    for word in review.text.split():
        if result[word] is not None:
            result[word] += 1
        else:
            result[word] = 1
    return result

会给你一个文本中所有单词的计数(还有一个库 class Counter,它可能会为你做这个)。这些,你可以结合起来形成一个特征矩阵X。 (此代码可以进行大量优化)

X = []
y = []
words = []
# build an index of all occurring words
for review in reviews:
    for word in extract(review):
        if word not in words:
            words.append(word)
# creates the feature vectors for classification
for review in reviews:
    feature_vector = [0] * len(words)
    y.append(review.rating)
    for word, count in extract(review):
        feature_vector[words.index(word)] = count
    X.append(feature_vector)

分类

现在您已经获得了特征向量,您需要决定使用哪个 classifier。其中最简单的是 k-nearest-neighbors.

from sklearn import neighbors, cross_validation
X_train, X_test, y_train, y_test = cross_validation.train_test_split(
    X, y, test_size=0.33, random_state=42)
knn = neighbors.KNeighborsClassifier()
knn.fit(X_train, y_train)
knn.predict(X_test)

将此与 y_test 进行比较。

来自评论的示例(略有编辑)

Let's consider an example of two reviews:

  1. that was awful | rating 1;
  2. that was great | rating 5.

Two dicts are created: {'that': 1, 'was': 1, 'awful': 1 } and {'that': 1, 'was': 1, 'great': 1}. And what X and y vectors should look like in that case?

首先,您的 words 可能是 ['that', 'was', 'awful', 'great']

那么,你可能会得到

X = [[1, 1, 1, 0],
     [1, 1, 0, 1]]
y = [1, 5]

您可以在 scikit 中非常轻松地做到这一点。

假设您有 X 和 y 数据:

X = ['the food was really delicious', 'the food was really terrible']
y = [5,2]

使用 CountVectorizer 你可以用两行代码将数据转换成数字:

from sklearn.feature_extraction.text import CountVectorizer
x_data = CountVectorizer().fit_transform(X)    

这会将您的数据完全转换为计数,然后可以输入您想要的任何算法:

from sklearn.neighbors import KNeighbors
clf = KNeighbors().fit(x_data, y)