Applied Machine Learning For Engineers: Artificial Neural Networks
Applied Machine Learning For Engineers: Artificial Neural Networks
FS 2020 - B. Vennemann
In [1]:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
np.random.seed(0)
Install Tensorflow
conda install tensorflow
Update Numpy
conda update numpy
Check installation
In [2]:
import tensorflow as tf
from tensorflow import keras
In [3]:
mnist = keras.datasets.mnist
In [4]:
plt.figure(figsize=(18, 10))
for i in range(20):
plt.subplot(4, 5, i+1)
plt.imshow(X_train[i].reshape((28, 28)), cmap='gray')
plt.text(24, 3, str(y_train[i]), fontsize=12, color='white')
plt.xticks([])
plt.yticks([])
plt.show()
Preprocess data
In [5]:
print("Max:", X_train.max())
print("Min:", X_train.min())
Max: 255
Min: 0
In [6]:
In [7]:
In [8]:
model = keras.models.Sequential()
model.add(keras.layers.Flatten(input_shape=[28, 28])) # turns (batch_size x 28 x 28) into
(batch_size x 784)
model.add(keras.layers.Dense(300, activation="relu")) # hidden layer
model.add(keras.layers.Dense(10, activation="softmax")) # output layer
In [9]:
model = keras.models.Sequential([
keras.layers.Flatten(input_shape=[28, 28]),
keras.layers.Dense(300, activation="relu"),
keras.layers.Dense(10, activation="softmax")
])
In [10]:
model.summary()
Model: "sequential_1"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
flatten_1 (Flatten) (None, 784) 0
_________________________________________________________________
dense_2 (Dense) (None, 300) 235500
_________________________________________________________________
dense_3 (Dense) (None, 10) 3010
=================================================================
Total params: 238,510
Trainable params: 238,510
Non-trainable params: 0
_________________________________________________________________
In [11]:
model.compile(loss="sparse_categorical_crossentropy",
optimizer="sgd",
metrics=["accuracy"])
loss = history.history['loss']
val_loss = history.history['val_loss']
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
plt.subplot(1,2,2)
plt.plot(epochs, acc, label='training accuracy')
plt.plot(epochs, val_acc, label='validation accuracy')
plt.xlabel('epoch')
plt.ylabel('accuracy')
plt.legend()
plt.grid(True)
plt.plot()
plt.show()
import pandas as pd
df = pd.DataFrame(history.history)
df.plot(figsize=(8, 5))
plt.grid(True)
plt.show()
In [16]:
i = 15
y_pred = model.predict(X_test[i].reshape(1, 28, 28))
print(y_pred)
print(y_pred.sum())
In [17]:
Predictied class : 5
Actual class : 5
In [18]:
In [ ]: