当前位置 : 主页 > 手机开发 > ROM >

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

来源:互联网 收集:自由互联 发布时间:2021-06-10
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 vecto
 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()
上一篇:iscsi共享存储
下一篇:B . Block Adventure
网友评论