import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from sklearn.datasets import make_moons
1. Make toy data using sklearn.make_moons
= make_moons(n_samples=(500, 500), noise=0.1, random_state=42)
X, y 0], X[:,1], c=y, cmap=plt.cm.Spectral); plt.scatter(X[:,
2. Build and train a simple MLP model
=tf.keras.Sequential([
model100, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
tf.keras.layers.Dense(
])
compile(loss='binary_crossentropy',
model.='adam',
optimizer=['accuracy'])
metrics
= model.fit(X, y, epochs=200, verbose=0) log
'accuracy'], label='accuracy')
plt.plot(log.history['loss'], label='loss')
plt.plot(log.history[
plt.legend(); plt.show()
3. Plot decision boundary
def show_boundary(X, y, model):
= X[:, 0].min() - 0.5,
x_min = X[:, 0].max() + 0.5
x_max = X[:, 1].min() - 0.5
y_min = X[:, 1].max() + 0.5
y_max
# generate meshgrid
= np.meshgrid(np.linspace(x_min, x_max, 200),
xx, yy 200))
np.linspace(y_min, y_max, = np.c_[xx.ravel(), yy.ravel()]
X_mesh
# predict on meshgrid points
= model.predict(X_mesh)
y_preds # convert to labels
if y_preds.shape[1] > 1:
= np.argmax(y_preds, axis=1)
y_preds else:
= np.round(y_preds)
y_preds
# reshape predictions for plotting
= y_preds.reshape(xx.shape)
y_preds
# plot the decision boundary
=(8,6))
plt.figure(figsize
= plt.cm.Spectral
cmap =cmap, alpha=.5)
plt.contourf(xx, yy, y_preds, cmap0], X[:, 1], c=y, s=40, cmap=cmap)
plt.scatter(X[:,
min(), xx.max())
plt.xlim(xx.min(), yy.max())
plt.ylim(yy.
show_boundary(X, y, model)