|
""" |
|
Train a single neuron with sigmoid activation function and no bias. |
|
|
|
This example is a digital logic buffer, so the sigmoid will have to become |
|
"squeezed" horizontally to mimic a sudden transition. |
|
|
|
Created on Fri Jan 19 22:00:06 2018 |
|
""" |
|
|
|
import numpy as np |
|
import matplotlib.pyplot as plt |
|
from tensorflow.keras.models import Sequential |
|
from tensorflow.keras.layers import Dense, Activation |
|
from tensorflow.keras import optimizers |
|
|
|
try: |
|
print(model.summary()) |
|
except NameError: |
|
model = Sequential([ |
|
Dense(1, input_shape=(1,), use_bias=False), |
|
Activation('tanh'), |
|
Dense(1, use_bias=False), |
|
]) |
|
|
|
print(model.summary()) |
|
|
|
sgd = optimizers.SGD(lr=1) |
|
model.compile(loss='mean_squared_error', optimizer=sgd) |
|
|
|
|
|
weights = model.get_weights() |
|
w0 = weights[0][0][0] |
|
w1 = weights[1][0][0] |
|
print(f'Neural net initialized with weights w0: {w0:.2f}, w1: {w1:.2f}') |
|
|
|
|
|
# Plot default function with no weighting |
|
x_plot = np.linspace(-2, +2, 1000) |
|
plt.plot(x_plot, model.predict(x_plot), label='init') |
|
plt.grid(True) |
|
|
|
# Fit the model to a (normalized, split supply) logic buffer gate. |
|
v = [ |
|
(-1.1, -1), |
|
(-1.0, -1), |
|
(-0.7, -1), |
|
(-0.1, -1), |
|
(+0.2, +1), |
|
(+0.5, +1), |
|
(+1.0, +1), |
|
(+1.1, +1), |
|
] |
|
|
|
x = [vv[0] for vv in v] |
|
y = [vv[1] for vv in v] |
|
|
|
plt.plot(x, y, '.', label='buffer data') |
|
|
|
X_train = np.array(x, ndmin=2).T |
|
Y_train = np.array(y, ndmin=2).T |
|
model.fit(X_train, |
|
Y_train, |
|
epochs=500, |
|
# verbose=0, |
|
# callbacks=[history] |
|
) |
|
|
|
# Plot after fitting |
|
plt.plot(x_plot, model.predict(x_plot), label='trained buffer') |
|
plt.legend() |
|
|
|
# Working version: https://github.com/endolith/ann-visualizer |
|
from ann_visualizer.visualize import ann_viz |
|
ann_viz(model, title="Learned single neuron", view=True) |
Simplest possible network with random weights:
Linear with bias output:
Trained against logic buffer:
Trained against inverting amplifier: