Keras学习之4:多分类问题(reuters路透社新闻数据为例)

本数据库包含来自路透社的11,228条新闻,分为了46个主题。与IMDB库一样,每条新闻被编码为一个词下标的序列。上代码:

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)

#vectorized sequences
def vectorize_sequences(sequences,dimension=10000):
    results = np.zeros((len(sequences),dimension))
    for i ,sequence in enumerate(sequences):
        results[i,sequence] = 1
    return results

#preparing the data
#encoding the data
x_train = vectorize_sequences(train_data)
x_test = vectorize_sequences(test_data)

# #one-hot encoding the labels
# 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)

#using keras build-in methos to change to one-hot labels
one_hot_train_labels = to_categorical(train_labels)
one_hot_test_labels = to_categorical(test_labels)

#model setup
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
model.compile(optimizer='rmsprop',loss='categorical_crossentropy',metrics=['accuracy'])

#validating our apporoach
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:]

#training the model
history = model.fit(partial_x_train,partial_y_train,epochs=20,batch_size=512,validation_data=(x_val,y_val))

#ploting the training and validation loss
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='Validating loss')
plt.title('Training and Validating loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()

#ploting the training and validation accuracy
plt.clf()
acc = history.history['acc']
val_acc = history.history['val_acc']
plt.plot(epochs,acc,'ro',label='Training acc')
plt.plot(epochs,val_acc,'r',label='Validating acc')
plt.title('Training and Validating accuracy')
plt.xlabel('Epochs')
plt.ylabel('accuracy')
plt.legend()
plt.show()

#evaluate
final_result = model.evaluate(x_test,one_hot_test_labels)
print(final_result)

结果:

1s 132us/step - loss: 0.1110 - acc: 0.9598 - val_loss: 1.0729 - val_acc: 0.7990



[1.214644479836509, 0.778717720444884]

小结:

1、多分类问题最后一层通常为softmax层。

2、Categorical crossentropy是多分类问题中经常使用的损失函数,该函数能将输出的概率分布距离最小化。

3、在多分类问题中常用的两种处理labels的方法:

     (1)将标签通过“Categorical Encoding”转变为one-hot向量,损失函数则使用categorical-crossentropy

     (2)将标签编码为整数,损失函数使用“sparse_categorical_crossentropy”。

4、如果需要将数据划分大量的类别,使用过程中需要注意网络中间层次的神经元数量不能太少,以免造成训练过程中信息丢失,中间层成为信息瓶颈。

猜你喜欢

转载自blog.csdn.net/cskywit/article/details/80900093