Find top n terms with highest TF-IDF score per class

前端 未结 3 1528
南笙
南笙 2021-01-23 05:59

Let\'s suppose that I have a dataframe with two columns in pandas which resembles the following one:

    text                                label
0         


        
3条回答
  •  日久生厌
    2021-01-23 06:19

    In the following, you can find a piece of code I wrote more than three years ago for a similar purpose. I'm not sure if this is the most efficient way of doing what you're going to do, but as far as I remember, it worked for me.

    # 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
    

提交回复
热议问题