《Python深度学习》第三章-3(路透社数据—多分类问题)读书笔记

新闻分类:多分类问题

前两个例子介绍了如何用密集连接的神经网络将向量输入划分为两个互斥的类别。本节将路透社新闻划分为 46 个互斥的主题,这是 多 分 类 ( m u l t i c l a s s c l a s s i f i c a t i o n ) 问 题 \color{red}多分类(multiclass classification)问题 multiclassclassification

  • 每个数据点只能划分到一个类别,这是 单 标 签 、 多 分 类 ( s i n g l e − l a b e l , m u l t i c l a s s    c l a s s i f i c a t i o n ) \color{red}单标签、多分类(single-label, multiclass\;classification) singlelabel,multiclassclassification;
  • 每个数据点可以划分到多个类别,这是 多 标 签 、 多 分 类 ( m u l t i l a b e l , m u l t i c l a s s    c l a s s i f i c a t i o n ) \color{red}多标签、多分类(multilabel,multiclass\;classification) multilabel,multiclassclassification

本例是单标签、多分类问题。使用路透社数据集,它包含许多短新闻及其对应的主题,由路透社在 1986 年发布。它是一个简单的、广泛使用的文本分类数据集。它包括 46 个不同的主题:某些主题的样本更多,但训练集中每个主题都有至少 10 个样本。

1. 准备数据

1.1 加载数据

from keras.datasets import reuters
(train_data, train_labels), (test_data, test_labels) = reuters.load_data(num_words=10000)

参数 num_words=10000 将数据限定为前 10 000 个最常出现的单词。有 8982 个训练样本和 2246 个测试样本。每个样本都是一个整数列表(表示单词索引)。

>>> len(train_data)
8982
>>> len(test_data)
2246

1.2 将索引解码为新闻文本

word_index = reuters.get_word_index()
reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])
decoded_newswire = ' '.join([reverse_word_index.get(i - 3, '?') for i in train_data[0]])
# 索引减去了 3,因为 0、1、2 是为“padding”(填充)、“start of 
# sequence”(序列开始)、“unknown”(未知词)分别保留的索引

样本对应的标签是一个 0~45 范围内的整数,即话题索引编号。

>>> train_labels[10]
3

1.3 编码数据

  1. 向量化
    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) #将测试数据向量化
    

1.4 标签处理

将标签向量化有两种方法:
- 将标签列表转换为整数张量;
- 使用 one-hot 编码。将每个标签表示为全零向量,只有标签索引对应的元素为 1。
1.4.1 one-hot

此处用one-hot,one-hot 编码是分类数据广泛使用的一种格式,也叫分类编码(categorical encoding)。

  1. one-hot
    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) # 将测试标签向量化
    
  2. 上面2步可以用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)
    
1.4.2 整数张量化
y_train = np.array(train_labels)
y_test = np.array(test_labels)

对于这种编码方法,唯一需要改变的是损失函数的选择。对于整数标签,你应该使用sparse_categorical_crossentropy

model.compile(optimizer='rmsprop',
			  loss='sparse_categorical_crossentropy',
			  metrics=['acc'])

这个新的损失函数在数学上与 categorical_crossentropy 完全相同,二者只是接口不同。


2. 构建网络

  1. 模型定义
    有一个新的约束条件:输出类别的数量从 2 个变为 46 个。输出空间的维度要大得多。

    Dense 层的堆叠,每层只能访问上一层输出的信息。如果某一层丢失了与分类问题相关的一些信息,那么这些信息无法被后面的层找回,也就是说,每一层都可能成为信息瓶颈。 使 用 维 度 更 大 的 层 , 包 含 64 个 单 元 。 \color{red}使用维度更大的层,包含 64 个单元。 使64

    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'))
    
  2. 编译模型
    最好的损失函数是 categorical_crossentropy (分类交叉熵)。它用于衡量两个概率分布之间的距离,这里两个概率分布分别是 网 络 输 出 的 概 率 分 布 \color{red}网络输出的概率分布 标 签 的 真 实 分 布 \color{red}标签的真实分布 。通过将这两个分布的距离最小化,训练网络可使输出结果尽可能接近真实标签。

model.compile(optimizer='rmsprop',
			  loss='categorical_crossentropy',
			  metrics=['accuracy'])

3. 训练模型

  1. 留出验证集
    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:]
    
  2. 训练模型
history = model.fit(partial_x_train,
					partial_y_train,
					epochs=20,
					batch_size=512,
					validation_data=(x_val, y_val))
  1. 绘制训练损失和验证损失

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

在这里插入图片描述

  1. 绘制训练精度和验证精度
plt.clf()#清空图像
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']

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('Accuracy')
plt.legend()
plt.show()

在这里插入图片描述
网络在训练 9 轮后开始过拟合。我们从头开始训练一个新网络,共 9 个轮次,然后在测试集上评估模型。

4. 重新训练一个模型

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=9,
		  batch_size=512,
		  validation_data=(x_val, y_val))
# 只进行了9次epochs
results = model.evaluate(x_test, one_hot_test_labels)

最终结果:

>>> results
[0.9798413515090942, 0.790739119052887]
  • 对于平衡的二分类问题,完全随机的分类器能够得到50% 的精度。
  • 这个例子中,完全随机的精度约为 19%,79.7%的精度和随机的基准比起来还不错。
>>> import copy
>>> test_labels_copy = copy.copy(test_labels)
>>> np.random.shuffle(test_labels_copy)
>>> hits_array = np.array(test_labels) == np.array(test_labels_copy)
>>> float(np.sum(hits_array)) / len(test_labels)
0.18210151380231523

5. 新数据上生成预测结果

predictions = model.predict(x_test)
#predictions 中的每个元素都是长度为 46 的向量。
>>> predictions[0].shape
(46,)
#这个向量的所有元素总和为 1。
>>> np.sum(predictions[0])
1.0
#最大的元素就是预测类别,即概率最大的类别。
>>> np.argmax(predictions[0])
3

6. 小结

  • 最 后 一 层 D e n s e 中 输 出 N \color{red}最后一层Dense中输出N DenseN。如果要对 N 个类别的数据点进行分类,网络的最后一层应该是大小为 N 的 Dense 层。
  • 最 后 一 层 D e n s e 用 s o f t m a x \color{red}最后一层Dense用softmax Densesoftmax。对于单标签、多分类问题,网络的最后一层应该使用 softmax 激活,这样可以输出在 N个输出类别上的概率分布。
  • 损 失 函 数 使 用 分 类 交 叉 熵 \color{red}损失函数使用分类交叉熵 使。它将网络输出的概率分布与目标的真实分布之间的距离最小化。
  • 处理多分类问题的标签有两种方法。
    • 通过分类编码(也叫 o n e − h o t 编 码 \color{red}one-hot 编码 onehot)对标签进行编码,然后使用 categorical_crossentropy 作为损失函数。
    • 标 签 编 码 为 整 数 \color{red}标签编码为整数 ,然后使用 sparse_categorical_crossentropy 损失函数。
  • 中 间 层 不 要 太 小 \color{red}中间层不要太小 。如果你需要将数据划分到许多类别中,应该避免使用太小的中间层,以免在网络中造成信息瓶颈。

7. 整体代码

from keras.datasets import reuters
from keras.utils.np_utils import to_categorical
from keras import models
from keras import layers
import numpy as np
import matplotlib.pyplot as plt

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

# 将索引解码为新闻文本
word_index = reuters.get_word_index()
reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])
decoded_newswire = ' '.join([reverse_word_index.get(i - 3, '?') for i in train_data[0]])
# 索引减去了 3,因为 0、1、2 是为“padding”(填充)、“start of 
# sequence”(序列开始)、“unknown”(未知词)分别保留的索引

# 向量化data
# 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化标签
# 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(128, activation='relu'))
model.add(layers.Dense(46, activation='softmax'))

model.compile(optimizer='rmsprop',
			  loss='categorical_crossentropy',
			  metrics=['accuracy'])
# 训练模型
# 留出验证数据
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=10,
					batch_size=512,
					validation_data=(x_val, y_val))
# 绘制训练损失和验证损失
# 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()#清空图像
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']

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('Accuracy')
plt.legend()
plt.show()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值