# 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.5.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"})

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.998)
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")

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: 0
incorrect: 900
Total percentage correct: 0.0

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")

In [14]:

net.train(epochs=10000, accuracy=1.0, report_rate=50,
tolerance=0.4, batch_size=len(net.dataset.train_inputs),
plot=True, record=100)

========================================================================
|  Training |  Training |  Validate |  Validate
Epochs |     Error |  Accuracy |     Error |  Accuracy
------ | --------- | --------- | --------- | ---------
# 7729 |   0.26827 |   1.00000 |   0.26607 |   1.00000

In [15]:

net.plot_activation_map(scatter=net.test(tolerance=0.4, interactive=False),
symbols=symbols, title="After Training")

In [16]:

net.get_weights("output")

Out[16]:

[[[3.3333942890167236], [-6.821496486663818]], [1.604598879814148]]

In [17]:

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 [18]:

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.1  0.2  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.1  0.2  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.1  0.2  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.1  0.2  0.4  0.5  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.1  0.2  0.4  0.5  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.1  0.2  0.4  0.5  0.7  0.8  0.9  0.9  1.0

In [19]:

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))


# 3.2. Non-Linearly Separable¶

In [20]:

import math

In [21]:

def distance(x1, y1, x2, y2):
return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)

In [22]:

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 [23]:

scatter([
["Positive", positives],
["Negative", negatives],
],
height=8.0,
width=8.0,
symbols={"Positive": "bo", "Negative": "ro"})

In [24]:

net = Network("Non-Linearly Separable", 2, 5, 1, activation="sigmoid")

In [25]:

net

Out[25]:

In [26]:

ds = Dataset()

In [27]:

ds.load([(p, [ 1.0], "Positive") for p in positives] +
[(n, [ 0.0], "Negative") for n in negatives])

In [28]:

ds.shuffle()

In [29]:

ds.split(.1)

In [30]:

net.set_dataset(ds)

In [31]:

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 [32]:

net.dashboard()

In [33]:

net.plot_activation_map(scatter=net.test(interactive=False), symbols=symbols, title="Before Training")


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 [35]:

net.train(epochs=10000, accuracy=1.0, report_rate=50,
tolerance=0.4, batch_size=len(net.dataset.train_inputs),
plot=True, record=100)

========================================================================
|  Training |  Training |  Validate |  Validate
Epochs |     Error |  Accuracy |     Error |  Accuracy
------ | --------- | --------- | --------- | ---------
#14856 |   0.02812 |   1.00000 |   0.01998 |   1.00000

In [36]:

net.plot_activation_map(scatter=net.test(interactive=False), symbols=symbols, title="After Training")

In [37]:

net.get_weights("hidden")

Out[37]:

[[[-10.24807071685791,
-3.3982436656951904,
-5.170109748840332,
2.7826385498046875,
-13.015877723693848],
[-3.794675827026367,
-7.523599624633789,
-0.7802948951721191,
8.869245529174805,
12.65350341796875]],
[4.493064880371094,
8.14928913116455,
-4.387434482574463,
-8.400566101074219,
4.322581768035889]]

In [38]:

net.get_weights_as_image("hidden").resize((400, 200))

Out[38]:

In [39]:

net.get_weights("output")

Out[39]:

[[[-15.507240295410156],
[8.740614891052246],
[0.7526621222496033],
[-13.142610549926758],
[12.83068561553955]],
[-11.701411247253418]]

In [40]:

net.get_weights_as_image("output").resize((500, 100))

Out[40]:

In [41]:

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()

 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  0.0  0.0  0.1  0.3  0.8  0.8  0.3  0.0
0.0  0.0  0.1  0.4  1.0  1.0  1.0  0.7  0.1
0.0  0.0  0.2  0.9  1.0  1.0  1.0  0.9  0.2
0.0  0.0  0.7  1.0  1.0  1.0  1.0  1.0  0.4
0.0  0.0  0.7  1.0  1.0  1.0  1.0  1.0  0.5
0.0  0.0  0.2  0.6  0.9  1.0  1.0  0.9  0.5
0.0  0.0  0.0  0.0  0.1  0.3  0.5  0.5  0.2
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 [42]:

net.playback(lambda net, epoch: net.plot_activation_map(title="Epoch: %s" % epoch,
scatter=net.test(interactive=False),
symbols=symbols,
interactive=False))


## 3.2.1. Non-Linearly Separable - Deeper¶

In [43]:

net = Network("Non-Linearly Separable", 2, 5, 2, 1, activation="sigmoid")

In [44]:

net.set_dataset(ds)

In [45]:

net.dashboard()

In [46]:

net.train(epochs=25000, accuracy=1.0, report_rate=50,
tolerance=0.4, batch_size=len(net.dataset.train_inputs),
plot=True, record=100)

========================================================================
|  Training |  Training |  Validate |  Validate
Epochs |     Error |  Accuracy |     Error |  Accuracy
------ | --------- | --------- | --------- | ---------
#11268 |   0.01345 |   1.00000 |   0.00938 |   1.00000

In [48]:

net.plot_activation_map()
net.plot_activation_map("hidden2")

In [49]:

net.playback(lambda net, epoch: net.plot_activation_map(title="Epoch %s" % epoch,
scatter=net.test(interactive=False),
symbols=symbols,
interactive=False))

In [54]:

%%time
net.movie(lambda net, epoch: net.plot_activation_map(title="Epoch %s" % epoch,
scatter=net.test(interactive=False),
symbols=symbols,
interactive=False, format="pil"),
step=1, duration=200)

CPU times: user 46.6 s, sys: 34 s, total: 1min 20s
Wall time: 41.6 s

Out[54]: