# 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.5


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: 126
incorrect: 774
Total percentage correct: 0.14

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

if net.saved():
net.plot_loss_acc()
else:
net.train(epochs=10000, accuracy=1.0, report_rate=50,
tolerance=0.4, batch_size=len(net.dataset.train_inputs),
plot=True, record=100, save=True)

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.1935768127441406], [-6.435564994812012]], [1.541886329650879]]

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

In [21]:

net.movie(lambda net, epoch: net.plot_activation_map(title="Epoch %s" % epoch,
scatter=net.test(tolerance=0.4, interactive=False),
symbols=symbols,
format="pil",
interactive=False))

Out[21]:


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

In [26]:

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

In [27]:

net

Out[27]:

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


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

if net.saved():
net.plot_loss_acc()
else:
net.train(epochs=10000, accuracy=1.0, report_rate=50,
tolerance=0.4, batch_size=len(net.dataset.train_inputs),
plot=True, record=100, save=True)

In [37]:

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

In [38]:

net.get_weights("hidden")

Out[38]:

[[[-9.149601936340332,
-4.0610246658325195,
10.262177467346191,
-0.6209477782249451,
-4.8985066413879395],
[-7.123647212982178,
-12.391748428344727,
-7.9103899002075195,
17.104597091674805,
15.856489181518555]],
[10.923587799072266,
4.499300956726074,
2.171931505203247,
-1.5372891426086426,
-0.7165727615356445]]

In [39]:

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

Out[39]:

In [40]:

net.get_weights("output")

Out[40]:

[[[15.102004051208496],
[-17.419124603271484],
[15.24399185180664],
[-16.155254364013672],
[14.260066986083984]],
[-18.752614974975586]]

In [41]:

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

Out[41]:

In [42]:

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

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

In [44]:

net.movie(lambda net, epoch: net.plot_activation_map(title="Epoch %s" % epoch,
scatter=net.test(tolerance=0.4, interactive=False),
symbols=symbols,
format="pil",
interactive=False))

Out[44]:


## 3.2.1. Non-Linearly Separable - Deeper¶

In [45]:

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

In [46]:

net.set_dataset(ds)

In [47]:

net.dashboard()

In [48]:

if net.saved():
net.plot_loss_acc()
else:
net.train(epochs=25000, accuracy=1.0, report_rate=50,
tolerance=0.4, batch_size=len(net.dataset.train_inputs),
plot=True, record=100, save=True)

In [49]:

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

In [50]:

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

In [48]:

%%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 47.8 s, sys: 19.9 s, total: 1min 7s
Wall time: 49.9 s

Out[48]: