Reuters_newswires
输入数据要求
- 分类问题
输入数据是向量,标签是one-hot类型的共有46类
数据导入
from keras.datasets import reuters (train_data, train_labels), (test_data, test_labels) = reuters.load_data(num_words=10000)### 数据观测
#输入数据是数字的数组,数字映射英文单词
#eg:[1,14,22,48,6489,9999,...,598]
#word_index是 英文字母:数字 的映射字典
word_index = imdb.get_word_index()
#键值反转, 数字:英文字母
reverse_word_index = dict(
(value, key) for (key, value) in word_index.items())
#显示第一条影评
decode_review = ' '.join(
[reverse_word_index.get(i - 3, '?') for i in train_data[0]])
### 数据处理
#目的是吧输入数据处理成显示词频的向量,有该单词则向量对应位置置1
import numpy as np
def vectorize_sequences(sequences, dimension=10000):
results = np.zeros((len(sequences),dimension))
for i, sequence in enumerate(sequences):
#print(sepuence)
results[i,sequence] = 1
return results
x_train = vectorize_sequences(train_data)
x_test = vectorize_sequences(test_data)
#将y_input转化为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
# # 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)
#法②
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'))
model.compile(optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['accuracy'])
x_val = x_train[:10000]
partial_x_train = x_train[10000:]
y_val = y_train[:10000]
partial_y_train = y_train[10000:]
history = model.fit(partial_x_train,
partial_y_train,
epochs=20,
batch_size=512,
validation_data=(x_val, y_val))
#使用512个样本的小批量,将模型训练20轮次,监控validation_data(留出的10000个样本——验证数据)
模型评估
# 画损失率和正确率的变化图
history_dict = history.history
print(history_dict.keys())
#dict_keys(['val_loss', 'val_acc', 'loss', 'acc'])
# 损失率
import matplotlib.pyplot as plt
acc = history.history['acc']
val_acc = history_dict['val_acc']
loss = history_dict['loss']
val_loss = history_dict['val_loss']
epoch = range(1, len(acc) +1)
plt.plot(epoch,loss,'bo', label='Training Loss')
plt.plot(epoch,val_loss,'b',label='Validation Loss')
plt.title('Training and validation')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()
# 正确率
plt.clf()
plt.plot(epoch,acc,'bo',label='Training acc')
plt.plot(epoch,val_acc,'b',label='Validation acc')
plt.title('Training and Validation accuracy')
plt.xlabel('Epoch')
plt.ylabel('accuracy')
plt.legend()
plt.show()
### 模型优化
>画图得知模型在8轮后过拟合了,所以8轮时停止
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]
### 模型使用
>predictions = model.predict(x_test)
>np.argmax(predictions[0])
>>>> 37 #输出种类