使用DNN进行多标签预测

时间:2018-01-22 15:47:17

标签: python tensorflow deep-learning tflearn

我试图预测给定文字的几个标签。它适用于单个标签,但我不知道如何实现多标签预测的置信度分数。

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

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

每个文本可以分配一个或多个主题。 到目前为止,我想出了这个。 首先,我准备我的数据 - tokenize,stem等。

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

正如您所看到的,我选择了prediction的最大值,这对于单个主题非常有用。为了选择多个主题,我需要一些信心分数或其他东西,这可以告诉我什么时候停止,因为我无法盲目地设置任意阈值。

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

您应该使用 sigmoid 激活,而不是在输出图层上使用softmax激活。您的损失函数应该仍然是交叉熵。这是多课程应该需要的关键变化。

softmax的问题​​在于它会在输出上创建概率分布。因此,如果A类和B类都被强烈表示,那么3类以上的softmax可能会给你一个类似[0.49,0.49,0.02]的结果,但你更喜欢[0.99,0.99,0.01]。

sigmoid激活就是这样,它将实值logits(应用转换之前的最后一层的值)压缩到[0,1]范围(这是使用交叉熵损失函数所必需的) )。并且它为每个输出独立完成。