Advertisement
Guest User

imbd.py

a guest
Nov 6th, 2018
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.23 KB | None | 0 0
  1.  
  2. import numpy as np
  3. from keras.datasets import imdb
  4. from keras import models
  5. from keras import layers
  6. from keras import optimizers
  7. from keras import losses
  8. from keras import metrics
  9. import matplotlib.pyplot as plt
  10.  
  11. (train_data,train_labels),(test_data,test_label) = imdb.load_data(num_words=10000)
  12.  
  13. # encoding of the lists of indices to turn them into tensors
  14. def vectorize_sequences(sequences,dimension=10000):
  15. results =np.zeros((len(sequences),dimension))
  16. for i, sequence in enumerate(sequences) :
  17. results[i,sequence] = 1
  18. return results
  19.  
  20. x_train = vectorize_sequences(train_data)
  21. x_test = vectorize_sequences(test_data)
  22.  
  23. y_train = np.asarray(train_labels).astype('float32')
  24. y_test = np.asarray(test_label).astype('float32')
  25.  
  26. #building the model
  27.  
  28. model = models.Sequential()
  29. model.add(layers.Dense(16,activation='relu',input_shape=(10000,)))
  30. model.add(layers.Dense(16,activation='relu'))
  31. model.add(layers.Dense(1,activation='sigmoid'))
  32. model.compile(optimizer=optimizers.RMSprop(lr=0.001),
  33. loss=losses.binary_crossentropy,
  34. metrics=[metrics.binary_accuracy])
  35.  
  36. #setting a validation set and training the models
  37.  
  38. x_val = x_train[:1000]
  39. y_val = y_train[:1000]
  40. partial_x_train = x_train[1000:]
  41. partial_y_train = y_train[1000:]
  42.  
  43. history = model.fit(partial_x_train,partial_y_train,epochs=10,batch_size=512,
  44. validation_data=(x_val,y_val))
  45.  
  46. #plotting results
  47.  
  48. history_dict = history.history
  49. loss_values = history_dict['loss']
  50. val_loss_values = history_dict['val_loss']
  51.  
  52. epochs = range(1, 10 +1)
  53.  
  54. plt.plot(epochs,loss_values,'bo',label='Training loss')
  55. plt.plot(epochs,val_loss_values,'b',label='Validation_loss')
  56. #plt.xlabel('Epochs')
  57. #plt.ylabel('Loss')
  58. #plt.legend()
  59. #plt.show()
  60.  
  61. acc_values = history_dict['binary_accuracy']
  62. val_acc_values = history_dict['val_binary_accuracy']
  63. plt.plot(epochs,acc_values,'ro',label='Traning acc')
  64. plt.plot(epochs,val_acc_values,'r',label='Validation acc')
  65. plt.title('Training and validation accuracy and loss')
  66. plt.xlabel('epochs')
  67. plt.ylabel('Loss / Accuracy')
  68. plt.legend()
  69. plt.show()
  70.  
  71.  
  72. #Testing on the test data and showing results
  73.  
  74. results = model.evaluate(x_test,y_test)
  75. print('Results : ')
  76. print(results)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement