1

Вот код, в процессе обучения вероятности распределяются равномерно, а не должны. В чём может быть проблема?

import numpy as np
import random

def softmax(t):
    out = np.exp(t)
    return out / np.sum(out)

def activationFunc(x):
    return 1/(1 + np.exp(-x))

def activationFunc_deriv(x):
    return activationFunc(x)*(1 - activationFunc(x))

def sparseCrossEntropy(z, y):
    return -np.log(z[y])

def toFull(y, num_classes):
    y_full = np.zeros((1, num_classes))
    y_full[0, y] = 1
    return y_full

dataset1 = [{
    "output": 0,
    "input": [
        0,1,1,1,0,
        1,0,0,0,1,
        1,0,0,0,1,
        1,0,0,0,1,
        1,0,0,0,1,
        1,0,0,0,1,
        0,1,1,1,0]
    },{
    "output": 1,
    "input": [
        0,0,1,0,0,
        0,1,1,0,0,
        0,0,1,0,0,
        0,0,1,0,0,
        0,0,1,0,0,
        0,0,1,0,0,
        0,1,1,1,0]
    },{
    "output": 2,
    "input": [
        0,1,1,1,0,
        1,0,0,0,1,
        0,0,0,0,1,
        0,0,0,1,0,
        0,0,1,0,0,
        0,1,0,0,0,
        1,1,1,1,1]
    },{
    "output": 3,
    "input": [
        0,1,1,1,0,
        1,0,0,0,1,
        0,0,0,0,1,
        0,0,1,1,0,
        0,0,0,0,1,
        1,0,0,0,1,
        0,1,1,1,0]
    },{
    "output": 4,
    "input": [
        1,0,0,0,1,
        1,0,0,0,1,
        1,0,0,0,1,
        1,1,1,1,1,
        0,0,0,0,1,
        0,0,0,0,1,
        0,0,0,0,1]
    },{
    "output": 5,
    "input": [
        1,1,1,1,1,
        1,0,0,0,0,
        1,0,0,0,0,
        1,1,1,1,0,
        0,0,0,0,1,
        0,0,0,0,1,
        1,1,1,1,0]
    },{
    "output": 6,
    "input": [
        0,1,1,1,0,
        1,0,0,0,1,
        1,0,0,0,0,
        1,1,1,1,0,
        1,0,0,0,1,
        1,0,0,0,1,
        0,1,1,1,0]
    },{
    "output": 7,
    "input": [
        1,1,1,1,1,
        0,0,0,0,1,
        0,0,0,1,0,
        0,0,1,0,0,
        0,0,1,0,0,
        0,1,0,0,0,
        1,0,0,0,0]
    },{
    "output": 8,
    "input": [
        0,1,1,1,0,
        1,0,0,0,1,
        1,0,0,0,1,
        0,1,1,1,0,
        1,0,0,0,1,
        1,0,0,0,1,
        0,1,1,1,0]
    },{
    "output": 9,
    "input": [
        0,1,1,1,0,
        1,0,0,0,1,
        1,0,0,0,1,
        0,1,1,1,1,
        0,0,0,0,1,
        0,0,0,0,1,
        0,1,1,1,0]
    }]

dataset2 = [{
    "output": 0,
    "input": [0,0]
    },{
    "output": 0,
    "input": [0,1]
    },{
    "output": 1,
    "input": [1,0]
    },{
    "output": 0,
    "input": [1,1]
    }]

class NeuralNetwork:
    def __init__(self, *neurons_on_layer, **kwargs):
        if len(neurons_on_layer) <= 1: raise ValueError(
            f"The neural network must have at least 2 layers, but you tried to create a neural network with {len(neurons_on_layer)} layer.")

        self.learning_rate = kwargs["learning_rate"] if "learning_rate" in kwargs else 0.001
        
        self.input_layer = np.random.randn(neurons_on_layer[0])
        self.layers = []
        
        for layer in range(len(neurons_on_layer)-1):
            self.layers.append({
                "weight": np.random.randn(
                    neurons_on_layer[layer],
                    neurons_on_layer[layer+1]
                    ),
                "bias": np.random.randn(
                    neurons_on_layer[layer+1]
                    )})
        self.layers.append({})

    def feedForward(self, input_value):
        if len(input_value) != len(self.input_layer): raise ValueError(
            f"The neural network takes {len(self.input_layer)} values ​​as input, but {len(input_value)} were transferred.")
            
        self.layers[0]["result"] = np.array(input_value)
        
        for layer in range(len(self.layers)-1):
            self.layers[layer+1]["result"] = activationFunc(
                self.layers[layer]["result"] @
                self.layers[layer]["weight"] +
                self.layers[layer]["bias"])

        return softmax(self.layers[-1]["result"])
            
    def learn(self, learning_data):
        Z = self.feedForward(
            learning_data["input"])
        
        error = sparseCrossEntropy(Z, learning_data["output"])

        y_full = toFull(
            learning_data["output"],
            len(self.layers[-1]["result"]))
        
        dE_dt = Z - y_full

        dE_dt = dE_dt[0]
        
        for layer in range(len(self.layers)-2, -1, -1):
            
            self.layers[layer]["delta_weight"] = self.layers[layer+1]["result"].T @ dE_dt

            self.layers[layer]["delta_bias"] = dE_dt
            
            self.layers[layer]["delta_result"] = dE_dt @ self.layers[layer]["weight"].T

            dE_dt = self.layers[layer]["delta_result"] * activationFunc_deriv(self.layers[layer]["result"])
            
        for layer in range(len(self.layers)-1):
            
            self.layers[layer]["weight"] -= self.learning_rate * self.layers[layer]["delta_weight"]
            self.layers[layer]["bias"] -= self.learning_rate * self.layers[layer]["delta_bias"]

if __name__ == "__main__":
    NN1 = NeuralNetwork(35, 50, 20, 10, learning_rate=0.001)
    NN2 = NeuralNetwork(2, 4, 2, learning_rate=0.001)

    NN = NN1
    dataset = dataset1

    epoch = 10000
    epoch_100 = epoch // 10

    for ep in range(epoch):
        if ep % epoch_100 == 0:
            print((ep // epoch_100) * 10, "%")
            
        for data in dataset:
            NN.learn(data)  

    for data in dataset:
        result = NN.feedForward(data["input"])
        print(np.argmax(result))

upd. Веса и смещения улетают в космос, пока не знаю как исправить

1 ответ 1

1

Ошибка здесь:

def activationFunc_deriv(x):
    return activationFunc(x)*(1 - activationFunc(x))

Формула верна если туда передавать входные значения слоя, но вы передаёте значение сигмоиды:

activationFunc_deriv(self.layers[layer]["result"])

Поэтому переделайте фукнцию производной:

def activationFunc_deriv(x):
    return x*(1 - x)
1
  • > def activationFunc_deriv(x): return x*(1 - x) Не помогло, мне кажется проблема в алгоритме, но сколько я не тестил, не могу найти ошибку
    – ZICZIN
    12 мар 2023 в 17:09

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.