2021-12-02 17:34:04 +01:00
|
|
|
import numpy as np
|
|
|
|
|
|
|
|
class network:
|
|
|
|
|
|
|
|
def __init__(self, inputLayerSize, *layerSizes):
|
2021-12-03 15:10:27 +01:00
|
|
|
if type(inputLayerSize) != int:
|
|
|
|
raise TypeError("The input layer size must be an int!")
|
|
|
|
|
2021-12-09 18:50:57 +01:00
|
|
|
self.__weights = []
|
|
|
|
self.__inputLayerSize = inputLayerSize
|
|
|
|
oldLayerSize = inputLayerSize
|
2021-12-02 17:34:04 +01:00
|
|
|
for layerSize in layerSizes:
|
2021-12-09 18:50:57 +01:00
|
|
|
self.__weights.append( np.random.default_rng(42).random((oldLayerSize, layerSize)) )
|
|
|
|
oldLayerSize = layerSize
|
|
|
|
self.__biases = [[0]*layerSize for layerSize in layerSizes]
|
|
|
|
self.__weights = np.array(self.__weights, dtype=object)
|
|
|
|
self.__biases = np.array(self.__biases, dtype=object)
|
2021-12-02 17:34:04 +01:00
|
|
|
|
2021-12-14 10:44:48 +01:00
|
|
|
def __reLu(value, derivative=False):
|
|
|
|
if (derivative):
|
|
|
|
return 0 if (value == 0) else 1
|
2021-12-02 17:34:04 +01:00
|
|
|
return max(0, value)
|
|
|
|
|
2021-12-14 10:44:48 +01:00
|
|
|
def __sigmoid(value, derivative=False):
|
|
|
|
if (derivative):
|
|
|
|
return __sigmoid(value) * (1 - __sigmoid(value))
|
|
|
|
return 1/(1+np.exp(-value))
|
|
|
|
|
|
|
|
def process(self, input, storeValues=False):
|
2021-12-02 17:34:04 +01:00
|
|
|
if type(input) != np.ndarray:
|
2021-12-03 15:10:27 +01:00
|
|
|
raise TypeError("The input must be a vector!")
|
2021-12-09 18:50:57 +01:00
|
|
|
if input.size != self.__inputLayerSize:
|
2021-12-03 15:10:27 +01:00
|
|
|
raise ValueError("The input vector has the wrong size!")
|
2021-12-02 17:34:04 +01:00
|
|
|
if input.dtype != np.float64:
|
2021-12-03 15:10:27 +01:00
|
|
|
raise TypeError("The input vector must contain floats!")
|
|
|
|
|
2021-12-09 18:50:57 +01:00
|
|
|
for layerWeights, bias in zip(self.__weights, self.__biases):
|
2021-12-03 15:10:27 +01:00
|
|
|
input = np.matmul(input, layerWeights)
|
2021-12-02 17:34:04 +01:00
|
|
|
input = np.add(input, bias)
|
2021-12-03 15:10:27 +01:00
|
|
|
#reLu application
|
2021-12-02 17:34:04 +01:00
|
|
|
with np.nditer(input, op_flags=['readwrite']) as layer:
|
|
|
|
for neuron in layer:
|
2021-12-09 18:50:57 +01:00
|
|
|
neuron = network.__reLu(neuron)
|
2021-12-03 15:10:27 +01:00
|
|
|
|
2021-12-09 18:50:57 +01:00
|
|
|
return input
|
|
|
|
|
|
|
|
def train(self, inputs, results):
|
2021-12-14 10:44:48 +01:00
|
|
|
self.__outputs = 1
|
|
|
|
#for j in range(1,):
|
|
|
|
#partialDerivatives
|
|
|
|
|
|
|
|
def __Error(layer, output, desiredOutput):
|
|
|
|
return __ErrorFinalLayerFromValue() if (layer == 1)
|
|
|
|
|
|
|
|
def __ErrorFinalLayer(self, neuron):
|
|
|
|
return __reLu(value, true) * (output - desiredOutput)
|