构建一个网络,将路透社新闻划分为 46 个互斥的主题。因为有多个类别,所以这是多分类。
加载路透社数据集
from keras.datasets import reuters
(train_data, train_labels), (test_data, test_labels) = reuters.load_data(num_words=10000)
我们有 8982 个训练样本和 2246 个测试样本
编码数据
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
x_train = vectorize_sequences(train_data) 将训练数据向量化
x_test = vectorize_sequences(test_data) 将测试数据向量化
将标签向量化,使用 one-hot 编码。标签的 one-hot 编码就是将每个标签表示为全零向量,只有标签索引对应的元素为 1。
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
one_hot_train_labels = to_one_hot(train_labels) 将训练标签向量化
one_hot_test_labels = to_one_hot(test_labels) 将测试标签向量化
注意,Keras 内置方法可以实现这个操作
from keras.utils.np_utils import to_categorical
one_hot_train_labels = to_categorical(train_labels)
one_hot_test_labels = to_categorical(test_labels)
模型定义
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'))
网络的最后一层是大小为 46 的 Dense 层。这意味着,对于每个输入样本,网络都会输出一个 46 维向量。这个向量的每个元素(即每个维度)代表不同的输出类别。
最后一层使用了 softmax 激活。网络将输出在 46个不同输出类别上的概率分布——对于每一个输入样本,网络都会输出一个 46 维向量,其中 output[i] 是样本属于第 i 个类别的概率。46 个概率的总和为 1。
编译模型
最好的损失函数是 categorical_crossentropy(分类交叉熵)。
model.compile(optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['accuracy'])
留出验证集
我们在训练数据中留出 1000 个样本作为验证集。
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))
绘制损失曲线和精度曲线
在新数据上生成预测结果
predictions = model.predict(x_test)
predictions 中的每个元素都是长度为 46 的向量。
>>> predictions[0].shape
(46,)
这个向量的所有元素总和为 1。
>>> np.sum(predictions[0])
1.0
最大的元素就是预测类别,即概率最大的类别。
>>> np.argmax(predictions[0])
4
处理标签和损失的另一种方法
将其转换为整数张量
y_train = np.array(train_labels)
y_test = np.array(test_labels)
对于这种编码方法,唯一需要改变的是损失函数的选择。
one-hot 编码,使用的损失函数 categorical_crossentropy,标签应该遵循分类编码。
整数标签,你应该使用sparse_categorical_crossentropy。
model.compile(optimizer='rmsprop',
loss='sparse_categorical_crossentropy',
metrics=['acc'])