利用keras自帶路透社數據集進行多分類訓練

 1 import numpy as np
 2 from keras.datasets import reuters
 3 from keras import layers
 4 from keras import models
 5 from keras import optimizers
 6 from keras.utils.np_utils import to_categorical
 7 import matplotlib.pyplot as plt
 8 
 9 def vectorize_data(x, dim = 10000):
10     res = np.zeros((len(x), dim))
11     for i, sequence in enumerate(x):
12         res[i, sequence] = 1
13     return res
14 
15 def main():
16     (train_data, train_labels), (test_data, test_labels) = reuters.load_data(num_words=10000)
17     x_train = vectorize_data(train_data)
18     x_test = vectorize_data(test_data)
19     y_train = to_categorical(train_labels)
20     y_test = to_categorical(test_labels)
21 
22     network = models.Sequential()
23     network.add(layers.Dense(128, activation = 'relu', input_shape = (10000, )))
24     network.add(layers.Dense(64, activation = 'relu'))
25     network.add(layers.Dense(46, activation = 'softmax'))
26 
27     network.compile(optimizer = 'rmsprop', loss = 'categorical_crossentropy', metrics = ['accuracy'])
28     network.fit(x_train, y_train, epochs = 6, batch_size = 512)
29 
30     _, acc = network.evaluate(x_test, y_test)
31 
32     print(acc)
33 
34 
35 if __name__ == "__main__":
36     main()
相關文章
相關標籤/搜索