新闻分类:多分类问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Einstellung/article/details/82695194

本文使用的数据集是路透社数据集,包含许多短新闻以及对应的主题。路透社将新闻划分为46个互斥的主题。因为有多个类别,且每个数据点只能划分到一个类别,所以是单标签、多分类问题

准备数据

首先,加载数据

from keras.datasets import reuters

(train_data, train_labels), (test_data, test_labels) = reuters.load_data(num_words=10000)
len(train_data)

8982

len(test_data)

2246

毓IMDB数据集一样,每个样本都是一个整数列表

train_data[10]

[1,
245,
273,
207,
156,
53,
74,
160,
26,
14,
46,…

所以,我们也需要用one-hot编码处理一下:

import numpy as np

def vectorize_sequences(sequences, dimension=10000):
    results = np.zeros((len(sequences), dimension))
    for i, sequence in enumerate(sequences):
        results[i, sequence] = 1.
    return results

# Our vectorized training data
x_train = vectorize_sequences(train_data)
# Our vectorized test data
x_test = vectorize_sequences(test_data)

因为这个是多分类问题,所以我们对labels也要进行独热编码处理

def to_one_hot(labels, dimension=46):
    results = np.zeros((len(labels), dimension))
    for i, label in enumerate(labels):
        results[i, label] = 1.
    return results

# Our vectorized training labels
one_hot_train_labels = to_one_hot(train_labels)
# Our vectorized test labels
one_hot_test_labels = to_one_hot(test_labels)

内置方法

Keras的内置方法也可以实现one-hot编码操作:

from keras.utils.np_utils import to_categorical

one_hot_train_labels = to_categorical(train_labels)
one_hot_test_labels = to_categorical(test_labels)

构建网络

相比于之前的二分类问题,我们现在有了一个新的约束条件:输出类别数量从2个变成了46个,输出空间的维度变得大得多。

对于前面用过的Dense层的堆叠,每层只能访问上一层的输出信息。如果某一层丢失了毓分类问题相关的一些信息,那么这些信息无法被后面的层找回,也就是说,每一层都可能成为信息瓶颈。对于二分类问题,我们使用了16维的中间层,但对于这个例子来说16维的空间可能太小了,无法学会区分46个不同的类别。这种维度较小的层可能成为信息瓶颈,永久的丢失相关信息。
如果你把中间层设置为4个神经元,效果要比中间层为64个神经元效果差8%

from keras import models
from keras import layers

model = models.Sequential()
model.add(layers.Dense(64, activation='relu', input_shape=(10000,)))
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(46, activation='softmax'))
model.compile(optimizer='rmsprop',
              loss='categorical_crossentropy',
              metrics=['accuracy'])

对于这个例子,最好的损失函数是categorical_crossentropy(分类交叉熵),它用于衡量两个概率分布之间的距离,这里两个概率分布分别是网络输出的概率分布和标签的真实分布。


训练

x_val = x_train[:1000]
partial_x_train = x_train[1000:]

y_val = one_hot_train_labels[:1000]
partial_y_train = one_hot_train_labels[1000:]
history = model.fit(partial_x_train,
                    partial_y_train,
                    epochs=20,
                    batch_size=512,
                    validation_data=(x_val, y_val))

我们在训练数据中留出1000个样本作为验证集,之后开始训练,训练20次。


画图

import matplotlib.pyplot as plt

loss = history.history['loss']
val_loss = history.history['val_loss']

epochs = range(1, len(loss) + 1)

plt.plot(epochs, loss, 'bo', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()

plt.show()

这里写图片描述

plt.clf()   # clear figure

acc = history.history['acc']
val_acc = history.history['val_acc']

plt.plot(epochs, acc, 'bo', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()

plt.show()

这里写图片描述


测试

从图中可以看出,大致网络在训练9轮之后开始出现过拟合,下面我们从新训练一个新的网络,共训练9个轮次,然后在测试集上进行评估。

model = models.Sequential()
model.add(layers.Dense(64, activation='relu', input_shape=(10000,)))
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(46, activation='softmax'))

model.compile(optimizer='rmsprop',
              loss='categorical_crossentropy',
              metrics=['accuracy'])
model.fit(partial_x_train,
          partial_y_train,
          epochs=8,
          batch_size=512,
          validation_data=(x_val, y_val))
results = model.evaluate(x_test, one_hot_test_labels)
results

得出结果是:
[0.98764628548762257, 0.77693677651807869]

这个结果,我们差不多可以得到80%的精度。


生成预测结果

predictions = model.predict(x_test)

predictions[0].shape

(46,)
predictions中的每个元素都是长度为46的向量

np.sum(predictions[0])

0.99999994
这个向量的所有元素总和为1

np.argmax(predictions[0])

3
最大的元素就是预测类别,即概率最大的类别。


注意

在模型构建的过程中,如果最后输出的层是46个输出可能,中间层的神经元最好要比46个多。否则,如果试图将大量信息压缩到一个很小的中间空间中去,可能会导致一些信息丢失。

更多精彩内容,欢迎关注我的微信公众号:数据瞎分析
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Einstellung/article/details/82695194