python - 使用 DNN 进行多标签预测

标签 python tensorflow deep-learning tflearn

我正在尝试预测给定文本的多个标签。它对于单个标签效果很好,但我不知道如何实现多标签预测的置信度得分。

我有以下非规范化格式的数据:

┌────┬──────────┬────────┐
│ id │  Topic   │  Text  │
├────┼──────────┼────────┤
│  1 │ Apples   │ FooBar │
│  1 │ Oranges  │ FooBar │
│  1 │ Kiwis    │ FooBar │
│  2 │ Potatoes │ BazBak │
│  3 │ Carrot   │ BalBan │
└────┴──────────┴────────┘

每篇文本可以指定一个或多个主题。 到目前为止我想出了这个。 首先,我准备数据 - 标记化、词干等。

df = #read data from csv
categories = [ "Apples", "Oranges", "Kiwis", "Potatoes", "Carrot"]
words = []
docs = []

for index, row in df.iterrows():
    stems = tokenize_and_stem(row, stemmer)
    words.extend(stems)
    docs.append((stems, row[1]))

# remove duplicates
words = sorted(list(set(words)))

# create training data
training = []
output = []
# create an empty array for our output
output_empty = [0] * len(categories)


for doc in docs:
    # initialize our bag of words(bow) for each document in the list
    bow = []
    # list of tokenized words for the pattern
    token_words = doc[0]

    # create our bag of words array
    for w in words:
        bow.append(1) if w in token_words else bow.append(0)

    output_row = list(output_empty)
    output_row[categories.index(doc[1])] = 1

    # our training set will contain a the bag of words model and the output row that tells which catefory that bow belongs to.
    training.append([bow, output_row])

# shuffle our features and turn into np.array as tensorflow  takes in numpy array
random.shuffle(training)
training = np.array(training)

# trainX contains the Bag of words and train_y contains the label/ category
train_x = list(training[:, 0])
train_y = list(training[:, 1])

接下来,我创建我的训练模型

# reset underlying graph data
tf.reset_default_graph()
# Build neural network
net = tflearn.input_data(shape=[None, len(train_x[0])])
net = tflearn.fully_connected(net, 8)
net = tflearn.fully_connected(net, 8)
net = tflearn.fully_connected(net, len(train_y[0]), activation='softmax')
net = tflearn.regression(net)

# Define model and setup tensorboard
model = tflearn.DNN(net, tensorboard_dir='tflearn_logs')
# Start training (apply gradient descent algorithm)
model.fit(train_x, train_y, n_epoch=1000, batch_size=8, show_metric=True)
model.save('model.tflearn')

之后我尝试预测我的主题:

df = # read data from excel

for index, row in df.iterrows():
    prediction = model.predict([get_bag_of_words(row[2])])
    return categories[np.argmax(prediction)]

如您所见,我选择了最大的预测,这对于单个主题效果很好。为了选择多个主题,我需要一些置信度分数或其他东西,它可以告诉我何时停止,因为我不能盲目地设置任意阈值。

有什么建议吗?

最佳答案

您应该使用sigmoid激活,而不是在输出层上使用softmax激活。你的损失函数应该仍然是交叉熵。这是多类应该需要的关键更改。

softmax 的问题在于它会在输出上创建概率分布。因此,如果 A 类和 B 类都具有很强的代表性,则超过 3 个类的 softmax 可能会给出类似 [0.49, 0.49, 0.02] 的结果,但你会更喜欢类似 [0.99, 0.99, 0.01] 的结果。

sigmoid 激活正是这样做的,它将实值 logits(应用变换之前最后一层的值)压缩到 [0, 1] 范围(这是使用交叉熵损失函数所必需的) )。它独立地为每个输出执行此操作。

关于python - 使用 DNN 进行多标签预测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48385376/

相关文章:

tensorflow - 如何在 Keras 中的两个 LSTM 层之间添加注意层

python - 为什么在推理中使用 Variable() ?

tensorflow - 何时在 tensorflow 中使用 model.predict(x) 与 model(x)

python - 批处理划分时 TensorFlow CNN 的行为有所不同

python - 添加和减去纪元时间的最佳方法?

python - 如何使用 Superfeedr 订阅实时 XMPP RSS 提要

python - tensorflow 错误 : Invalid argument: shape must be a vector

machine-learning - LSTM 后接均值池化

keras - 内核大小应该与一维卷积中的字长相同吗?

python - 为什么当我使用 .astype(str) 时 numpy/pandas 仅返回第一个字符