PT21-22-Reseau-Neurones/sobek/network.py

38 lines
1.4 KiB
Python
Raw Normal View History

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-02 17:34:04 +01:00
self.weights = []
self.inputLayerSize = inputLayerSize
self.oldLayerSize = inputLayerSize
for layerSize in layerSizes:
self.weights.append( np.random.default_rng(42).random((self.oldLayerSize, layerSize)) )
self.oldLayerSize = layerSize
self.biases = [[0]*layerSize for layerSize in layerSizes]
2021-12-03 15:10:27 +01:00
self.weights = np.array(self.weights, dtype=object)
self.biases = np.array(self.biases, dtype=object)
2021-12-02 17:34:04 +01:00
def reLu(value):
return max(0, value)
def process(self, input):
if type(input) != np.ndarray:
2021-12-03 15:10:27 +01:00
raise TypeError("The input must be a vector!")
2021-12-02 17:34:04 +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!")
for layerWeights, bias in zip(self.weights, self.biases):
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:
neuron = network.reLu(neuron)
2021-12-03 15:10:27 +01:00
return input