def __init__(self, structure, lr=0.1, af=sigmoid): self.structure = structure self.outputs = [] self.errors = [] self.weights = [] self.biases = [] self.lr = lr self.af = af # check if structure is ok if len(self.structure) < 2: print(">>> Cannot create Neural Network from given Structure!") elif len(self.structure) == 2: self.input_nodes = self.structure[0] self.output_nodes = self.structure[1] self.weights.append(matrix.Matrix(self.output_nodes, self.input_nodes, mat_type="random")) self.biases.append(matrix.Matrix(self.output_nodes, 1, mat_type="random")) else: # Declaration of input layer self.input_nodes = self.structure[0] self.first_hidden_nodes = self.structure[1] self.weights.append(matrix.Matrix(self.first_hidden_nodes, self.input_nodes, mat_type="random")) self.biases.append(matrix.Matrix(self.first_hidden_nodes, 1, mat_type="random")) # Declaration of hidden layers for i in range(1, len(structure) - 2): self.weights.append(matrix.Matrix(self.structure[i + 1], self.structure[i], mat_type="random")) self.biases.append(matrix.Matrix(self.structure[i + 1], 1, mat_type="random")) # Declaration of output layer self.output_nodes = self.structure[-1] self.last_hidden_nodes = self.structure[-2] self.weights.append(matrix.Matrix(self.output_nodes, self.last_hidden_nodes, mat_type="random")) self.biases.append(matrix.Matrix(self.output_nodes, 1, mat_type="random"))
def load_json(name): with open(name) as infile: data = json.load(infile) nn = NeuralNetwork(data["structure"], lr=data["lr"]) nn.weights = [] nn.biases = [] for weight in data["weights"]: nn.weights.append(matrix.Matrix(data=weight)) for bias in data["biases"]: nn.biases.append(matrix.Matrix(data=bias)) return nn