In [38]:
import typing
import tiny_dnn
import numpy as np
import pylab as pl
In [39]:
def generate_data() -> typing.Tuple[np.ndarray, np.ndarray]:
x = np.random.rand(2, 1000) - 0.5
y = np.maximum(0, np.minimum(1, np.round(np.sqrt(x[0, :] ** 2 + x[1, :] ** 2) + 0.1)))
return x, y
In [72]:
x, y = generate_data()
In [67]:
pl.figure(figsize=(5, 5))
positive = x[:, y == 1]
negative = x[:, y == 0]
pl.scatter(positive[0, :], positive[1, :], c='r')
pl.scatter(negative[0, :], negative[1, :], c='b')
pl.show()
In [73]:
net = tiny_dnn.net.Net()
net.layers.append(tiny_dnn.layer.InputLayer(x, y))
net.layers.append(tiny_dnn.layer.FullConnectLayer(8, 'relu'))
net.layers.append(tiny_dnn.layer.FullConnectLayer(4, 'relu'))
net.layers.append(tiny_dnn.layer.FullConnectLayer(2, 'relu'))
net.layers.append(tiny_dnn.layer.FullConnectLayer(1, 'sigmoid'))
costs = []
lr = 0.1
for i in range(1, 3000 + 1):
net.forward()
cost = net.cost()
costs.append(cost)
if i % 100 == 0:
print('Cost: {:.5f}'.format(cost))
if i % 1000 == 0:
lr *= 0.3
net.backward()
net.update(lr)
In [74]:
pl.plot(costs)
pl.show()
In [75]:
predict = np.round(net.data_out)
accuracy = 1.0 - np.mean(np.abs(predict - y))
print('Accuracy: {}'.format(accuracy))
In [ ]: