本节使用路透社数据集,它包含许多新闻及其对应的主题,由路透社在1986年发布。它是一个简单的、广泛使用的文本分类数据集。包括46个主题:某些主题的样本更多,但训练集中每个主题都至少10个样本。
因为有多个类别,所以这是多分类问题。因为每个数据点只能划分到一个类别,所以这又是单标签、多分类问题。
完整代码实现:
from keras.datasets import reuters import numpy as np # 第一步:加载数据 (train_data, train_labels), (test_data, test_labels) = reuters.load_data(num_words=10000) # 第二步:编码数据,输入数据 def vectorize_sequences(sequences, dimension=10000): # 定义一个向量化序列函数,将所有评论都向量化成一样的维度 results = np.zeros((len(sequences), dimension)) # 创建一个零矩阵,二维张量 for i, sequence in enumerate(sequences): # 将一个可遍历的数据对象组合成一个索引序列。 results[i, sequence] = 1. return results # 例如,序列[3,5,6]将被转化为1000维向量,只有索引为3,5,6的元素才为1,其他都为0. # 数据向量化 x_train = vectorize_sequences(train_data) x_test = vectorize_sequences(test_data) def to_one_hot(labels, dimension=46): # 标签有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) 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() """ Q: 为什么此处输入单元数要使用64,为什么不使用电影评论分类时使用的16? A:16维空间对于这个例子来说太小了,无法学会区分46个不同的类别。 这种维度较小的层可能成为信息瓶颈,永久地丢失相关信息。 如果是三分类,四分类问题你依然可以使用16个隐藏单元 Q:我能不能设置为640个单元? A:单元数不是越大越好,网络容量越大,网络就越容易记住训练过的数据。 网络会在训练过的数据上表现优异,但是在没有见过的数据上的表现则不容乐观。 因此单元数不是越大越好,需要在欠拟合与过拟合之间找到一个平衡点。 """ model.add(layers.Dense(64, activation='relu', input_shape=(10000, ))) model.add(layers.Dense(4, 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=20, 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() # 重新训练模型 model = models.Sequential() model.add(layers.Dense(64, activation='relu', input_shape=(10000, ))) model.add(layers.Dense(4, activation='relu')) model.add(layers.Dense(46, activation='softmax')) model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) history = 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) print(results) # [0.9868815943054715, 0.7862867116928101] # 80%左右的精度 # 采取随机预测的方式 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) print(float(np.sum(hits_array)) / len(test_labels)) # 0.18788958147818344 # 20%的精度,可以看出模型的预测效果好得多
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)