Ошибка расчета в Backpropagation не работает правильно - PullRequest
1 голос
/ 28 сентября 2019

В настоящее время мы работаем над проектом, в котором задействованы нейронные сети.

Наша задача состоит в увеличении масштаба изображения 16x16 до изображения с разрешением 64x64.

У нас естьМы уже написали код и собрали достаточно большой набор данных, состоящий из 200 000 изображений, которые мы уже организовали в массивы по десять тысяч.Это означает, что у нас есть 20 наборов данных, состоящих из 10 000 изображений каждый (в коде мы работаем только с одним набором данных X и Y).Модель в примере кода состоит только из одного скрытого слоя с 5 нейронами в нем.Кроме того, скрытый слой использует функцию ReLu, а выходной - простой линейный.Активации сохраняются и загружаются, когда к ним необходимо получить доступ.

Поскольку мы попытались реализовать нашу сеть с использованием как можно меньшего количества библиотек, мы столкнулись со странной ошибкой в ​​нашем коде.Что-то не так с расчетом ошибок, и поэтому вес обновляется неправильно.Вес продолжает увеличиваться, если их положительный, и меньше, если они отрицательные.Мы разделили обратное распространение скрытого слоя и выходного слоя, поскольку они по-разному рассчитывают ошибки.Мы также чувствуем, что Mean-Squared-Error должны быть где-то там, но мы не можем точно сказать, где.Мы также получаем ошибки формы в обратном распространении для первого скрытого слоя после выходного слоя.Мы использовали веб-сайт: https://ml -cheatsheet.readthedocs.io / en / latest / backpropagation.html , чтобы вычислить наши ошибки.

Мы ни в коем случае не являемся экспертами по этой теме иМы будем рады принять любую помощь, которую мы можем получить, поэтому не стесняйтесь задавать нам любые вопросы, которые вам нравятся.

{def linearfunc(x): #The Linear Output function used for the Forward-Propagation
    return(x)

def linderiv(x):  #The Derivative of our Linear function used for the Back-Propagation
    return(1)

def backward(): #Back-Propagtion

    alpha = 0.001                                                       #Learning Rate

    Weights_Output = np.random.randn(5, 12288)   #Weights of the Output Layer / 5 is the number of neurons in the Hidden-Layer and 12228 the number of neurons in the Output Layer                                        
    Bias_Output = np.random.randn(12288,1)       #Bias of the Output Layer / 12288 is always derived from the features of the Output Image, which is 64*64*3 (3 For the RGB Values)

    Weights = np.random.randn(768,5)             #Weights of the only Hidden-Layer / The number 768 is derived from the number of input features of the images being 16*16*3
    Bias    = np.random.randn(5,1)               #Bias of the only Hidden-Layer

    #Start of the Back-Propagation for the Output-Layer
    DW_Output  = np.zeros((12288,5))                                    #Preparing the shapes of DW in the Output-Layer for the Back-Propagation
    DB_Output  = np.zeros((12288, 1))                                   #Preparing the shapes of DB in the Output-Layer for the Back-Propagation

    da_dz2    = linderiv(Z_Output)                                      #Applying the derivative of the Linear Function to our Z's in the Output-Layer / 1 Step                                                                 

    y         = np.load('DatasetY.npy')                                 #Loading our Output Features of our Dataset with the Y values            
    a         = np.load('Activations.npy')                              #Loading the Activations of the previous Layer before the Output-Layer / Our only Hidden-Layer

    Error_Output = (activations_Output-y) * da_dz2                      #Computing DZ(The Error) of our Output-Layer by using the formula Error = (Activations in the Output-Layer - Y-Values) multiplied with the derivative of the ReLu function applied to the Z's of the Output Layer
    DW_Output = np.dot(Error_Output , activations.T)                    #Computing DW of our Output-Layer by using the dot product of DZ_Output and our activations and then divide by the number of images in our Trainingset
    DB_Output = np.sum(Error_Output, axis = 1, keepdims = True) * (1/10000)#Computing DB of our Output-Layer by summing up all of the DZ's along axis 1 to get the right shape

    Weights_Output = Weights_Output - alpha * DW_Output.T               #The Weights of the Output Layer perform the Gradient Descent Step / The first time they update they all go way too high or too low
    Bias_Output = Bias_Output - alpha * DB_Output                       #The Bias of the Output Layer perform the Gradient Descent Step / The first time they update they all go way too high or too low

    #Start of the Back-Propagation for the Hidden-Layer

    dw  = np.zeros((5,768))                                                 #Preparing the shapes of dw in the only Hidden-Layer for the Back-Propagation
    db  = np.zeros((5, 1))                                                  #Preparing the shapes of dw in the only Hidden-Layer for the Back-Propagation

    a_2    = np.load('DatasetX.npy')                                        #Loading the activations of the Layer previous to out Hidden-Layer, which would be the Input Features

    da_dz   = z >= 0                                                        #Applying the derivative of the ReLu Function to our Z's in the Hidden-Layer / 1 Step               
    da_dz   = da_dz.astype(np.int)                                          #Turning all the TRUE values into 1 and all the FALSE values into 0 / 2 Step

    Error = Error_Output * np.dot(Weights_Output.T , da_dz)    #<< Gives a shape Error when Updating the Weight's #Computing dz(Error) in our Hidden-Layer by using the Weight's and the Error from the Output Layer and multiplying that with the derivative of the ReLu function applied to the  z's of the only Hidden-Layer
    dw = np.dot(Error, a_2.T) * (1/10000)                                   #Computing dw of our Hidden-Layer by using the dot product of dz and our activations and then divide by the number of images in our Trainingset
    db = (np.sum(Error, axis = 1, keepdims = True)) * (1/10000)             #Computing db of our Hidden-Layer by summing up all of the dz's along axis 1 to get the right shape

    Weights = Weights - alpha * dw.T                                        #The Weights of the Hidden-Layer perform the Gradient Descent Step / The first time they update they all go negative
    Bias = Bias - alpha * db                                                #The Bias of the Hidden-Layer perform the Gradient Descent Step / The first time they update they all go negative}
...