import numpy as np
import matplotlib.pyplot as plt
import keras
from keras.models import Sequential
from keras.layers import Dense
from tensorflow import set_random_seed
from ClassificationPlotter import plot_regions
from sklearn.datasets import make_classification
np.random.seed(136)
X, y = make_classification(n_samples=200, n_features=2, n_informative=2, n_redundant=0, n_classes=3, n_clusters_per_class=1)
#X = X + np.array([6, 13])
plt.figure(figsize=(8,6))
plt.scatter(X[:,0], X[:,1], c=y, edgecolor='k', s=60, cmap='rainbow')
plt.show()
print(X.shape)
print(y.shape)
print(y[:20])
np.random.seed(1)
set_random_seed(1)
model = Sequential()
model.add(Dense(4, input_shape=(2,), activation='relu'))
model.add(Dense(3, activation='relu'))
model.add(Dense(3, activation='softmax'))
opt = keras.optimizers.Adam(lr=0.1)
model.compile(loss='sparse_categorical_crossentropy', optimizer=opt, metrics=['accuracy'])
h = model.fit(X, y, batch_size=200, epochs=200, verbose=0)
results = model.evaluate(X, y, verbose=0)
print('Training Loss: ', results[0])
print('Training Accuracy:', results[1])
plot_regions(model, X, y, fig_size=(8,6), keras=True)
np.set_printoptions(precision=2, suppress=True)
wts = model.get_weights()
print(type(wts))
for w in wts:
print(w.shape)
W1 = np.vstack((wts[1].reshape(1,4), wts[0]))
print(W1)
print(W1.shape)
W2 = np.vstack((wts[3].reshape(1,3), wts[2]))
print(W2)
print(W2.shape)
W3 = np.vstack((wts[5].reshape(1,3), wts[4]))
print(W3)
print(W3.shape)
X_new = np.array([[0, -1], [1, 0], [0, 1], [0, 0.5]])
We expect the predicted classes for these points will be: [1 or 2, 1 or 2, 0 or 2, 0]
print(X_new.shape)
print(W1.shape)
print(W2.shape)
print(W3.shape)
def relu(M):
return np.where(M > 0, M, 0)
def softmax(M):
exp = np.exp(M)
return exp / np.sum(exp, axis=1, keepdims=True)
ones = np.ones((X_new.shape[0], 1))
input_matrix = np.hstack((ones, X_new))
print(input_matrix)
print(input_matrix.shape)
Z1 = np.dot(input_matrix, W1)
print(Z1)
print(Z1.shape)
print()
A1 = relu(Z1)
print(A1)
print(A1.shape)
ones = np.ones((A1.shape[0], 1))
input_matrix = np.hstack((ones, A1))
print(input_matrix)
print(input_matrix.shape)
Z2 = np.dot(input_matrix, W2)
print(Z2)
print(Z2.shape)
print()
A2 = relu(Z2)
print(A2)
print(A2.shape)
ones = np.ones((A2.shape[0], 1))
input_matrix = np.hstack((ones, A2))
print(input_matrix)
print(input_matrix.shape)
Z3 = np.dot(input_matrix, W3)
print(Z3)
print(Z3.shape)
print()
P = softmax(Z3)
print(P)
print(P.shape)
print(model.predict(X_new))