首页 > 解决方案 > 为多标签文本分类转换数据集

问题描述

我正在通过深度学习模型进行一些关于多标签分类的实验。但我面临数据集的问题。

我使用 Keras、TensorFlow 2.0、numpy、pandas。

我有一个表单中的 数据集:我拥有的表单中的数据集

要应用多标签分类(6 个标签),我需要我的数据集采用这种形式: 数据集采用我需要的形式

怎么可能做到这一点?是否有任何功能使这种转换更容易?

尝试:

comments_df[['abusive','hateful','offensive','disrespectful','fearful','normal']] = comments_df['sentiment'].str.split('_', -1, expand=True)

这给了我一个错误:

ValueError: Columns must be same length as key

关于我将使用的 DL 模型,它是 bi-LSTM,但它与问题本身没有任何关系。

标签: deep-learningdatasetclassificationdata-sciencedata-transform

解决方案


我发现这可行(不是最佳解决方案):

"""
Creating a column for each of the target labels with sentiment's column data.
"""


def split_sentiment_outputs(output_label, sentiment_col="sentiment"):
    comments_df[output_label] = comments_df[sentiment_col].str.split('_')


"""
Transform column's data to categorical.
"""


def transform_data_for_multilabel(output_label):
    row = comments_df[output_label]
    for index, row in row.items():
        # print("Index:", index)
        # print("length:", len(row))
        # print("content:", row)
        # print("--------------")
        z = 0
        while z < len(row):
            if row[z] == output_label:
                comments_df.at[index, output_label] = 1
                break
            else:
                comments_df.at[index, output_label] = 0
            z = z + 1

# Applying Data Transformation
output_labels = ["abusive", "hateful", "offensive", "disrespectful", "fearful", "normal"]
for i in range(MAX_OUT):
    split_sentiment_outputs(output_labels[i])

for i in range(MAX_OUT):
    transform_data_for_multilabel(output_labels[i])

推荐阅读