码迷,mamicode.com
首页 > 其他好文 > 详细

利用keras自带路透社数据集进行多分类训练

时间:2019-10-05 12:57:22      阅读:95      评论:0      收藏:0      [点我收藏+]

标签:code   div   ati   nbsp   softmax   lib   color   class   cat   

 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()

 

利用keras自带路透社数据集进行多分类训练

标签:code   div   ati   nbsp   softmax   lib   color   class   cat   

原文地址:https://www.cnblogs.com/rising-sun/p/11624243.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!