Facebook
From Innocent Teal, 2 Months ago, written in Python.
Embed
Download Paste or View Raw
Hits: 42
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import keras
  4. from keras.datasets import mnist
  5. from keras.models import Sequential
  6. from keras.layers import Dense
  7. from keras.optimizers import Adam
  8. from keras.utils.np_utils import to_categorical
  9. import random
  10.  
  11. np.random.seed(0)
  12. (X_train,y_train),(X_test,y_test)=mnist.load_data()
  13.  
  14. assert(X_train.shape[0]==y_train.shape[0]), 'The number of images is not equal to the number of labels.'
  15. assert(X_test.shape[0]==y_test.shape[0]), 'The number of images is not equal to the number of labels.'
  16. assert(X_train.shape[1:]==(28,28)), 'The number of images are not 28x28.'
  17. assert(X_test.shape[1:]==(28,28)), 'The number of images are not 28x28.'
  18.  
  19. num_of_samples=[]
  20. cols = 5
  21. num_classes = 10
  22.  
  23. fig, axs = plt.subplots(nrows=num_classes, ncols = cols, figsize=(5, 8))
  24. fig.tight_layout()
  25.  
  26. for i in range(cols):
  27.     for j in range(num_classes):
  28.         x_selected = X_train[y_train == j]
  29.         axs[j][i].imshow(x_selected[random.randint(0, len(x_selected - 1)), :, :], cmap=plt.get_cmap("gray"))
  30.         axs[j][i].axis("off")
  31.         if i == 2:
  32.             axs[j][i].set_title(str(j))
  33.             num_of_samples.append(len(x_selected))
  34.  
  35. print(num_of_samples)
  36. plt.figure(figsize=(12, 4))
  37. plt.bar(range(0, num_classes), num_of_samples)
  38. plt.title("Distribution of the training dataset")
  39. plt.xlabel("Class number")
  40. plt.ylabel("Number of images")
  41.  
  42. y_train = to_categorical(y_train, 10)
  43. y_test = to_categorical(y_test, 10)
  44.  
  45. X_train = X_train/255
  46. X_test = X_test/255
  47.  
  48. num_pixels = 784
  49. X_train = X_train.reshape(X_train.shape[0], num_pixels)
  50. X_test = X_test.reshape(X_test.shape[0], num_pixels)
  51.  
  52. def create_model():
  53.     model = Sequential()
  54.     model.add(Dense(10, input_dim=num_pixels, activation='relu'))
  55.     model.add(Dense(30, activation='relu'))
  56.     model.add(Dense(10, activation='relu'))
  57.     model.add(Dense(num_classes, activation='softmax'))
  58.     model.compile(Adam(lr=0.01), loss='categorical_crossentropy', metrics=['accuracy'])
  59.     return model
  60.  
  61. model=create_model()
  62. print(model.summary())
  63.  
  64. h=model.fit(X_train,y_train,validation_split=0.1,epochs=10,batch_size=200,verbose=1, shuffle=1)
  65.  
  66. plt.plot(h.history['loss'])
  67. plt.plot(h.history['val_loss'])
  68. plt.plot(h.history['accuracy'])
  69.  
  70. score=model.evaluate(X_test,y_test, verbose=0)
  71. print(score)
  72.  
  73. import requests
  74. from PIL import Image
  75.  
  76. url = 'https://www.researchgate.net/profile/Jose_Sempere/publication/221258631/figure/fig1/AS:305526891139075@1449854695342/Handwritten-digit-2.png'
  77. response=requests.get(url,stream=True)
  78. print(response)
  79. img=Image.open(response.raw)
  80. plt.imshow(img)
  81.  
  82. import cv2
  83. img_array=np.asarray(img)
  84. resized=cv2.resize(img_array,(28,28))
  85. grey_scale=cv2.cvtColor(resized,cv2.COLOR_BGR2GRAY)
  86. image=cv2.bitwise_not(grey_scale)
  87. image=image/255
  88. image=image.reshape(1,784)
  89.  
  90. prediction=model.predict_classes(image)
  91. print('predicited digits',str(prediction))
  92.