5) Design a neural Network for classifying news wires (Multi class classification) using
Reutersdataset.
Code:
from keras.datasets import reuters
(tr, tl), (te, tel) = reuters.load_data(num_words=10000)
d= reuters.get_word_index()
rd = dict([(y, x) for (x, y) in d.items()])
me= ' '.join([rd.get(i - 3, '?') for i in tr[0]])
print(me)
import numpy as np
trm = np.zeros((len(tr), 10000))
for i ,x in enumerate(tr):
trm[i,x]=1.
tem = np.zeros((len(te),10000))
fori ,x in enumerate(te):
tem[i,x]=1.
from keras.utils import
to_categoricaltl=to_categorical(tl)
tel=to_categorical(tel)
tx=trm[:1000]
ty=tl[:1000]
tex=tem[1000:]
tey=tel[1000:]
from keras.models import Sequential
from keras.layers
import Dense n=Sequential()
l1=Dense(64,activation='relu',input_shape=(10000,))
l2=Dense(64,activation='relu')
l3=Dense(46,activation='softmax')
n.add(l1)
n.add(l2)
n.add(l3)
n.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['accuracy'])
n.fit(tx,ty,epochs=10)
yp=n.predict(tex)
print("preicted","actual")
print(tey[0],np.argmax(yp[0]))
Output:
? ? ? said as a result of its december acquisition of space co it expects earnings per share in 1987 of 1
15 to 1 30 dlrs per share up from 70 cts in 1986 the company said pretax net should rise to nine to 10
mlndlrs from six mlndlrs in 1986 and rental operation revenues to 19 to 22 mlndlrs from 12 5 mlndlrs
it said cash flow per share this year should be 2 50 to three dlrsreuter 3
Epoch 1/10
32/32 [==============================] - 2s 17ms/step - loss: 3.0454 - accuracy: 0.4500
Epoch 2/10
32/32 [==============================] - 1s 16ms/step - loss: 1.5415 - accuracy: 0.6320
Epoch 3/10
32/32 [==============================] - 0s 15ms/step - loss: 0.9180 - accuracy: 0.8000
Epoch 4/10
32/32 [==============================] - 0s 15ms/step - loss: 0.5608 - accuracy: 0.8790
Epoch 5/10
32/32 [==============================] - 0s 16ms/step - loss: 0.3407 - accuracy: 0.9350
Epoch 6/10
32/32 [==============================] - 1s 16ms/step - loss: 0.2055 - accuracy: 0.9730
Epoch 7/10
32/32 [==============================] - 0s 16ms/step - loss: 0.1249 - accuracy: 0.9850
Epoch 8/10
32/32 [==============================] - 1s 16ms/step - loss: 0.0775 - accuracy: 0.9880
Epoch 9/10
32/32 [==============================] - 0s 15ms/step - loss: 0.0524 - accuracy: 0.9960
Epoch 10/10
32/32 [==============================] - 0s 15ms/step - loss: 0.0388 - accuracy: 0.9940
39/39 [==============================] - 0s 5ms/step
preicted actual
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] 13