as written in https://pythonprogramming.net/introduction-deep-learning-python-tensorflow-keras/ Introduction to Deep Learning - Deep Learning basics with Python, TensorFlow and Keras p.1
In [1]:
import tensorflow.keras as keras
import tensorflow as tf
print(tf.__version__)
In [2]:
mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test) = mnist.load_data()
In [3]:
print(x_train[0])
In [4]:
import matplotlib.pyplot as plt
In [5]:
plt.imshow(x_train[0],cmap=plt.cm.binary)
plt.show()
In [6]:
print(y_train[0])
In [15]:
x_train = tf.keras.utils.normalize(x_train, axis=1).reshape(x_train.shape[0], -1)
x_test = tf.keras.utils.normalize(x_test, axis=1).reshape(x_test.shape[0], -1)
In [8]:
print(x_train[0])
In [10]:
plt.imshow(x_train[0],cmap=plt.cm.binary)
plt.show()
In [16]:
model = tf.keras.models.Sequential()
#model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu, input_shape= x_train.shape[1:]))
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(10, activation=tf.nn.softmax)) #10 because dataset is numbers from 0 - 9
In [17]:
model.compile(optimizer='adam', # Good default optimizer to start with
loss='sparse_categorical_crossentropy', # how will we calculate our "error." Neural network aims to minimize loss.
metrics=['accuracy']) # what to track
In [18]:
model.fit(x_train, y_train, epochs=3)
Out[18]:
In [19]:
val_loss, val_acc = model.evaluate(x_test, y_test)
print(val_loss)
print(val_acc)
In [20]:
model.save('epic_num_reader.model')
In [21]:
new_model = tf.keras.models.load_model('epic_num_reader.model')
In [22]:
predictions = new_model.predict(x_test)
In [23]:
print(predictions)
In [24]:
import numpy as np
In [25]:
print(np.argmax(predictions[0]))
In [28]:
## gives error:
#plt.imshow(x_test[0],cmap=plt.cm.binary)
#plt.show()
In [ ]: