转换数据集以进行多标签文本分类

Transforming a Dataset for Multi-Label Text Classification

我正在通过深度学习模型对多标签分类进行一些实验。 但是我遇到了数据集问题。

我使用 Keras,TensorFlow 2.0, numpy,pandas.

我有以下形式的数据集: Dataset in the form that I have it

要应用多标签分类(6 个标签),我需要我的数据集采用以下形式: Dataset in the form that I need it

如何实现这一点?是否有任何函数可以使这种转换更容易?

尝试:

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,但它与问题本身没有任何关系。

试试这个:

df = pd.get_dummies(data = df, columns = ['sentiment'])

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

"""
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])