3.1. Learning

The shallowest network is one that has no hidden layers at all. But this type of network can only solve one type of problem: those that are linearly separable. This notebook explores learning linearly and non-lineraly separable datasets.

3.1.1. Linearly Separable

In [1]:
from conx import *
import random
Using Theano backend.
conx, version 3.4.3

First, let’s construct a fake linearly-separable dataset.

In [2]:
count = 500

positives = [(i/count, i/(count * 2) + random.random()/6) for i in range(count)]
negatives = [(i/count, 0.3 + i/(count * 2) + random.random()/6) for i in range(count)]
In [3]:
scatter([
         ["Positive", positives],
         ["Negative", negatives],
        ],
    height=8.0,
    width=8.0,
    symbols={"Positive": "bo", "Negative": "ro"})
_images/Learning_4_0.png
In [4]:
ds = Dataset()
In [5]:
ds.load([(p, [ 1.0], "Positive") for p in positives] +
        [(n, [ 0.0], "Negative") for n in negatives])
In [6]:
ds.shuffle()
In [7]:
ds.split(.1)
In [8]:
ds.summary()
Input Summary:
   count  : 1000 (900 for training, 100 for testing)
   shape  : [(2,)]
   range  : (0.0, 0.99800003)
Target Summary:
   count  : 1000 (900 for training, 100 for testing)
   shape  : [(1,)]
   range  : (0.0, 1.0)
In [9]:
net = Network("Linearly Separable", 2, 1, activation="sigmoid")
net.compile(error="mae", optimizer="adam")
In [10]:
net.set_dataset(ds)
In [11]:
net.dashboard()
In [12]:
net.test(tolerance=0.4)
========================================================
Testing validation dataset with tolerance 0.4...
Total count: 900
      correct: 63
      incorrect: 837
Total percentage correct: 0.07
In [13]:
symbols = {
    "Positive (correct)": "w+",
    "Positive (wrong)": "k+",
    "Negative (correct)": "w_",
    "Negative (wrong)": "k_",
}

net.plot_activation_map(scatter=net.test(tolerance=0.4, interactive=False),
                        symbols=symbols, title="Before Training")
_images/Learning_14_0.png
In [16]:
net.train(epochs=10000, accuracy=1.0, report_rate=50,
         tolerance=0.4, batch_size=len(net.dataset.train_inputs),
         plot=True, record=100)
_images/Learning_15_0.svg
========================================================================
       |  Training |  Training |  Validate |  Validate
Epochs |     Error |  Accuracy |     Error |  Accuracy
------ | --------- | --------- | --------- | ---------
# 5587 |   0.27733 |   1.00000 |   0.28856 |   0.99000
In [17]:
net.plot_activation_map(scatter=net.test(tolerance=0.4, interactive=False),
                        symbols=symbols, title="After Training")
_images/Learning_16_0.png
In [18]:
net.get_weights("output")
Out[18]:
[[[3.2305562496185303], [-6.478184223175049]], [1.5522327423095703]]
In [19]:
from conx.activations import sigmoid

def output(x, y):
    wts = net.get_weights("output")
    return sigmoid(x * wts[0][1][0] + y * wts[0][0][0] + wts[1])[0]

def ascii(f):
    return "%4.1f" % f
In [20]:
for y in frange(0, 1.1, .1):
    for x in frange(1.0, 0.1, -0.1):
        print(ascii(output(x, y)), end=" ")
    print()
 0.0  0.0  0.0  0.0  0.1  0.2  0.3  0.4  0.6
 0.0  0.0  0.0  0.1  0.1  0.2  0.3  0.5  0.6
 0.0  0.0  0.0  0.1  0.2  0.3  0.4  0.6  0.7
 0.0  0.0  0.1  0.1  0.2  0.3  0.5  0.6  0.8
 0.0  0.0  0.1  0.2  0.3  0.4  0.6  0.7  0.8
 0.0  0.1  0.1  0.2  0.3  0.5  0.6  0.8  0.9
 0.0  0.1  0.2  0.3  0.4  0.6  0.7  0.8  0.9
 0.1  0.1  0.2  0.3  0.5  0.6  0.8  0.9  0.9
 0.1  0.2  0.3  0.4  0.6  0.7  0.8  0.9  0.9
 0.1  0.2  0.3  0.5  0.6  0.8  0.9  0.9  1.0
 0.2  0.3  0.4  0.6  0.7  0.8  0.9  0.9  1.0
In [21]:
net.playback(lambda net, epoch: net.plot_activation_map(title="Epoch %s" % epoch,
                                                        scatter=net.test(tolerance=0.4, interactive=False),
                                                        symbols=symbols,
                                                        interactive=False))
_images/Learning_20_1.svg

3.2. Non-Linearly Separable

In [22]:
import math
In [23]:
def distance(x1, y1, x2, y2):
    return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
In [24]:
negatives = []
while len(negatives) < 500:
    x = random.random()
    y = random.random()
    d = distance(x, y, 0.5, 0.5)
    if d > 0.375 and d < 0.5:
        negatives.append([x, y])
positives = []
while len(positives) < 500:
    x = random.random()
    y = random.random()
    d = distance(x, y, 0.5, 0.5)
    if d < 0.25:
        positives.append([x, y])
In [25]:
scatter([
         ["Positive", positives],
         ["Negative", negatives],
        ],
    height=8.0,
    width=8.0,
    symbols={"Positive": "bo", "Negative": "ro"})
_images/Learning_25_0.png
In [26]:
net = Network("Non-Linearly Separable", 2, 5, 1, activation="sigmoid")
net.compile(error="mae", optimizer="adam")
In [27]:
net
Out[27]:
Non-Linearly SeparableLayer: output (output) shape = (1,) Keras class = Dense activation = sigmoidoutputWeights from hidden to output output/kernel has shape (5, 1) output/bias has shape (1,)Layer: hidden (hidden) shape = (5,) Keras class = Dense activation = sigmoidhiddenWeights from input to hidden hidden/kernel has shape (2, 5) hidden/bias has shape (5,)Layer: input (input) shape = (2,) Keras class = Inputinput
In [28]:
ds = Dataset()
In [29]:
ds.load([(p, [ 1.0], "Positive") for p in positives] +
        [(n, [ 0.0], "Negative") for n in negatives])
In [30]:
ds.shuffle()
In [31]:
ds.split(.1)
In [32]:
net.set_dataset(ds)
In [33]:
net.test(tolerance=0.4)
========================================================
Testing validation dataset with tolerance 0.4...
Total count: 900
      correct: 0
      incorrect: 900
Total percentage correct: 0.0
In [34]:
net.dashboard()
In [35]:
net.plot_activation_map(scatter=net.test(interactive=False), symbols=symbols, title="Before Training")
_images/Learning_35_0.png

You may want to either net.reset() or net.retrain() if the following cell doesn’t complete with 100% accuracy. Calling net.reset() may be needed if the network has landed in a local maxima; net.retrain() may be necessary if the network just needs additional training.

In [38]:
net.train(epochs=10000, accuracy=1.0, report_rate=50,
          tolerance=0.4, batch_size=len(net.dataset.train_inputs),
          plot=True, record=100)
_images/Learning_37_0.svg
========================================================================
       |  Training |  Training |  Validate |  Validate
Epochs |     Error |  Accuracy |     Error |  Accuracy
------ | --------- | --------- | --------- | ---------
#10000 |   0.22953 |   0.78556 |   0.20973 |   0.81000
In [39]:
net.plot_activation_map(scatter=net.test(interactive=False), symbols=symbols, title="After Training")
_images/Learning_38_0.png
In [40]:
net.get_weights("hidden")
Out[40]:
[[[-0.06771931052207947,
   2.4489858150482178,
   9.767735481262207,
   2.5054662227630615,
   11.376243591308594],
  [9.50147533416748,
   10.051812171936035,
   0.12285355478525162,
   -7.575393199920654,
   3.826489210128784]],
 [-8.048283576965332,
  -8.980477333068848,
  -1.4016867876052856,
  -3.3592915534973145,
  -4.48599910736084]]
In [41]:
net.get_weights_as_image("hidden").resize((400, 200))
Out[41]:
_images/Learning_40_0.png
In [42]:
net.get_weights("output")
Out[42]:
[[[-7.103164196014404],
  [-9.99889850616455],
  [5.225965976715088],
  [3.826967716217041],
  [9.866928100585938]],
 [-8.17078685760498]]
In [43]:
net.get_weights_as_image("output").resize((500, 100))
Out[43]:
_images/Learning_42_0.png
In [44]:
for y in frange(0, 1.1, .1):
    for x in frange(1.0, 0.1, -0.1):
        print(ascii(net.propagate([x, y])[0]), end=" ")
    print()
 1.0  1.0  1.0  1.0  1.0  1.0  0.9  0.2  0.0
 1.0  1.0  1.0  1.0  1.0  1.0  0.9  0.4  0.0
 1.0  1.0  1.0  1.0  1.0  1.0  1.0  0.6  0.1
 1.0  1.0  1.0  1.0  1.0  1.0  1.0  0.8  0.1
 1.0  1.0  1.0  1.0  1.0  1.0  1.0  0.9  0.2
 1.0  1.0  1.0  1.0  1.0  1.0  1.0  0.9  0.2
 0.9  1.0  1.0  1.0  1.0  1.0  1.0  0.9  0.3
 0.3  0.5  0.6  0.8  0.8  0.9  0.9  0.7  0.1
 0.0  0.0  0.0  0.1  0.1  0.1  0.2  0.1  0.0
 0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
 0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
In [45]:
net.playback(lambda net, epoch: net.plot_activation_map(title="Epoch: %s" % epoch,
                                                        scatter=net.test(interactive=False),
                                                        symbols=symbols,
                                                        interactive=False))
_images/Learning_44_1.svg

3.2.1. Non-Linearly Separable - Deeper

In [46]:
net = Network("Non-Linearly Separable", 2, 5, 2, 1, activation="sigmoid")
net.compile(error="mae", optimizer="adam")
In [47]:
net.set_dataset(ds)
In [48]:
net.dashboard()
In [49]:
net.train(epochs=25000, accuracy=1.0, report_rate=50,
          tolerance=0.4, batch_size=len(net.dataset.train_inputs),
          plot=True, record=100)
_images/Learning_49_0.svg
========================================================================
       |  Training |  Training |  Validate |  Validate
Epochs |     Error |  Accuracy |     Error |  Accuracy
------ | --------- | --------- | --------- | ---------
#11869 |   0.02021 |   1.00000 |   0.01930 |   1.00000
In [51]:
net.plot_activation_map()
net.plot_activation_map("hidden2")
_images/Learning_50_0.png
_images/Learning_50_1.png
In [52]:
net.playback(lambda net, epoch: net.plot_activation_map(title="Epoch %s" % epoch,
                                                        scatter=net.test(interactive=False),
                                                        symbols=symbols,
                                                        interactive=False))
_images/Learning_51_1.svg