Найти лучшие n терминов с наибольшим количеством баллов TF-IDF в классе - PullRequest
1 голос
/ 21 июня 2019

Предположим, у меня есть кадр данных с двумя столбцами в pandas, который похож на следующий:

    text                                label
0   This restaurant was amazing         Positive
1   The food was served cold            Negative
2   The waiter was a bit rude           Negative
3   I love the view from its balcony    Positive

и затем я использую TfidfVectorizer из sklearn для этого набора данных.

Какой самый эффективный способ найти лучшие n с точки зрения словарного запаса TF-IDF на класс?

По-видимому, мой фактический фрейм данных состоит из гораздо большего количества строк данных, чем приведенные выше 4.

Суть моего поста в том, чтобы найти код, который работает для любого фрейма данных, похожего на приведенный выше; 4-рядный или 1-рядный.

Я думаю, что мой пост довольно сильно связан со следующими постами:

1 Ответ

1 голос
/ 21 июня 2019

Далее вы можете найти фрагмент кода, который я написал более трех лет назад для аналогичной цели.Я не уверен, что это самый эффективный способ делать то, что ты собираешься делать, но, насколько я помню, это сработало для меня.

# X: data points
# y: targets (data points` label)
# vectorizer: TFIDF vectorizer created by sklearn
# n: number of features that we want to list for each class
# target_list: the list of all unique labels (for example, in my case I have two labels: 1 and -1 and target_list = [1, -1])
# --------------------------------------------
# splitting X vectors based on target classes
for label in target_list:
    # listing the most important words in each class
    indices = []
    current_dict = {}

    # finding indices the of rows (data points) for the current class
    for i in range(0, len(X.toarray())):
        if y[i] == label:
            indices.append(i)

    # get rows of the current class from tf-idf vectors matrix and calculating the mean of features values
    vectors = np.mean(X[indices, :], axis=0)

    # creating a dictionary of features with their corresponding values
    for i in range(0, X.shape[1]):
        current_dict[X.indices[i]] = vectors.item((0, i))

    # sorting the dictionary based on values
    sorted_dict = sorted(current_dict.items(), key=operator.itemgetter(1), reverse=True)

    # printing the features textual and numeric values
    index = 1
    for element in sorted_dict:
        for key_, value_ in vectorizer.vocabulary_.items():
            if element[0] == value_:
                print(str(index) + "\t" + str(key_) + "\t" + str(element[1]))
                index += 1
                if index == n:
                    break
        else:
            continue
        break
...