AI-040: Python深度学习3 - 三个Karas实例-2

实例2:

通过路透社数据集来将文本区分46个不同主题

这里与上一个实例不同的地方:这是个多元分类问题,因此最终输出是46维向量

加载数据

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

预处理数据:

将样本映射到单词词典,转化为相同长度的向量

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)

将标签转换为one-hot编码,就是这样的向量[0,0,0,1,0,0,...],这个例子表示样本属于第四类主题。

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)

构建网络:

这里因为输出是46维,为了防止信息瓶颈,每层的元素要多一些,这里先选取为64

输出层的激活函数选取softmax,这样可以求取每个取值的概率,这里一共46个概率且和为1。

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

训练模型

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=15,
                    epochs=20,  # 从绘制的图形分析出,8轮次后出现过耦合现象,可以停止
                    batch_size=512,
                    validation_data=(x_val, y_val))

可以通过绘制损失和经度在训练集、校验集上的图形来调整超参数:

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。

预测数据:

概率最大的就是最有可能的分类

predictions = model.predict(x_test)
print(predictions[1].shape)
print(np.sum(predictions[1]))
print(predictions[1])
print(np.argmax(predictions[1]))

第二个测试样本属于第十一类主题(0是第一类),可能性达到95%

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

铭记北宸

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值