1

Необходимо перенести значение dW1 из класса Regularization метода l1_grad.

Ниже указано два класса.

class Regularization:
    """ 
    Regularization class

    Arguments:
    lambda_1 -- regularization coeficient for l1 regularization
    lambda_2 -- regularization coeficient for l2 regularization
    """
    def __init__(self, lambda_1, lambda_2):
        self.lambda_1 = lambda_1
        self.lambda_2 = lambda_2
        
        
    def l1(self, W1, W2, m):
        """ 
        Compute l1 regularization part

        Arguments:
        W1 -- weigts of shape (n_hidden_units, n_features) 
        W2 -- weigts of shape (output_size, n_hidden_units) 
        m -- n_examples

        Returns:
        l1_term -- float, check formula (6)
        """
        ### START CODE HERE ###
        return (self.lambda_1/(m)) * (np.linalg.norm(W1, ord=1) + np.linalg.norm(W2, ord=1))
        ### END CODE HERE ###
        
    def l1_grad(self, W1, W2, m):
        """ 
        Compute l1 regularization term

        Arguments:
        W1 -- weigts of shape (n_hidden_units, n_features) 
        W2 -- weigts of shape (output_size, n_hidden_units) 
        m -- n_examples

        Returns:
         dict with l1_grads "dW1" and "dW2"
            which are grads by corresponding weights
        """
        ### START CODE HERE ###
        dW1 = self.lambda_1/m*np.sign(W1)
        
        dW2 = self.lambda_1/m*np.sign(W2)

        l1_grads = {"dW1": dW1,
                 "dW2": dW2}
        return(l1_grads)
        ### END CODE HERE ###

    def l2(self, W1, W2, m):
        """ 
        Compute l2 regularization term

        Arguments:
        W1 -- weigts of shape (n_hidden_units, n_features) 
        W2 -- weigts of shape (output_size, n_hidden_units) 
        m -- n_examples

        Returns:
        l2_term: float, check formula (6)
        """
        ### START CODE HERE ###
        return (self.lambda_2 / (m * 2) * (np.sum(np.square(W1)) + np.sum(np.square(W2))))
        ### END CODE HERE ###
        
    def l2_grad(self, W1, W2, m):
        """ 
        Compute l2 regularization term

        Arguments:
        W1 -- weigts of shape (n_hidden_units, n_features) 
        W2 -- weigts of shape (output_size, n_hidden_units) 
        m -- n_examples

        Returns:
        l2_grads: dict with keys "dW1" and "dW2"
        """
        ### START CODE HERE ###
        dW1 = self.lambda_2/m*W1
        
        dW2 = self.lambda_2/m*W2

        l2_grads = {"dW1": dW1,
                 "dW2": dW2}
        return(l2_grads)
        ### END CODE HERE ###

class NeuralNetwork:
    """
    Arguments:
    n_features: int -- Number of features
    n_hidden_units: int -- Number of hidden units
    n_classes: int -- Number of classes
    learning_rate: float
    reg: instance of Regularization class
    """
    def __init__(self, n_features, n_hidden_units, n_classes , learning_rate, reg=Regularization(0.1, 0.2), sigm=Sigmoid()):
        self.n_features = n_features
        self.n_classes = n_classes
        self.learning_rate = learning_rate
        self.n_hidden_units = n_hidden_units
        self.reg = reg
        self.sigm = sigm
        self.W1 = None
        self.b1 = None
        self.W2 = None
        self.b2 = None
        
        self.initialize_parameters()

    def initialize_parameters(self):
        """
        W1 -- weight matrix of shape (self.n_hidden_units, self.n_features)
        b1 -- bias vector of shape (self.n_hidden_units, 1)
        W2 -- weight matrix of shape (self.n_classes, self.n_hidden_units)
        b2 -- bias vector of shape (self.n_classes, 1)
        """
        np.random.seed(42) 
    
        ### START CODE HERE ### 
        W1 = np.random.randn(self.n_hidden_units, self.n_features) * 0.01
        b1 = np.zeros((self.n_hidden_units, 1))
        W2 = np.random.randn(self.n_classes, self.n_hidden_units) * 0.01
        b2 = np.zeros((self.n_classes, 1))   
        self.W1 = W1
        self.b1 = b1
        self.W2 = W2
        self.b2 = b2
        return{"W1": W1,
                  "b1": b1,
                  "W2": W2,
                  "b2": b2}
        ### END CODE HERE ###

    def forward_propagation(self, X):
        """
        Arguments:
        X -- input data of shape (number of features, number of examples)
        
        Returns:
        dictionary containing "Z1", "A1", "Z2" and "A2"
        """
        # Implement Forward Propagation to calculate A2 (probabilities)
        ### START CODE HERE ### 
        Z1 = np.add(np.matmul(self.W1, X), self.b1)
        A1 = self.sigm(Z1)
        Z2 = np.add(np.matmul(self.W2, A1), self.b2)
        A2 = self.sigm(Z2)
        cache = {"Z1": Z1,
             "A1": A1,
             "Z2": Z2,
             "A2": A2}
        ### END CODE HERE ###

        return {
            'Z1': Z1,
            'A1': A1,
            'Z2': Z2,
            'A2': A2
        }
    
    def backward_propagation(self, X, Y, cache):
        """
        Arguments:
        X -- input data of shape (number of features, number of examples)
        Y -- one-hot encoded vector of labels with shape (n_classes, n_samples)
        cache -- a dictionary containing "Z1", "A1", "Z2" and "A2"

        Returns:
        dictionary containing gradients "dW1", "db1", "dW2", "db2"
        """
        m = X.shape[1]
        
        # Retrieve A1 and A2 from dictionary "cache".
        ### START CODE HERE ### 
        A1 = cache["A1"]
        A2 = cache["A2"]
        ### END CODE HERE ###
        
        # Calculate gradients for L1, L2 parts using attribute instance of Regularization class
        ### START CODE HERE ### 
        # **Необходимо перенести значение dW1 с класса Regularization метода l1_grad**
        
        
        ### END CODE HERE ###

        # Backward propagation: calculate dW1, db1, dW2, db2 (using obtained L1, L2 gradients)
        ### START CODE HERE ###
        dZ2 = A2 - Y
        dW2 = (1 / m) * np.dot(dZ2, A1.T)
        db2 = (1 / m) * np.sum(dZ2, axis=1, keepdims=True)
        dZ1 = np.multiply(np.dot(self.W2.T, dZ2), 1 - np.power(A1, 2))
        dW1 = (1 / m) * np.dot(dZ1, X.T)
        db1 = (1 / m) * np.sum(dZ1, axis=1, keepdims=True)
        grads = {"dW1": dW1,
             "db1": db1,
             "dW2": dW2,
             "db2": db2}
        ### END CODE HERE ###

        return {
            'dW1': dW1,
            'db1': db1,
            'dW2': dW2,
            'db2': db2}

    def update_parameters(self, grads):
        """
        Updates parameters using the gradient descent update rule 

        Arguments:
        grads -- python dictionary containing gradients "dW1", "db1", "dW2", "db2"
        """
        # Retrieve each gradient from the dictionary "grads"

        ### START CODE HERE ### 
        dW1 = grads["dW1"]
        db1 = grads["db1"]
        dW2 = grads["dW2"]
        db2 = grads["db2"]
        ## END CODE HERE ###

        # Update each parameter
        ### START CODE HERE ### 
        W1 = W1 - learning_rate * dW1
        b1 = b1 - learning_rate * db1
        W2 = W2 - learning_rate * dW2
        b2 = b2 - learning_rate * db2

        parameters = {"W1": W1,
                      "b1": b1,
                      "W2": W2,
                      "b2": b2}
        return (parameters)
        ### END CODE HERE ###

1 ответ 1

1

Сделайте l1_grads атрибутом класса Regularization:

class Regularization:
    def __init__(self, lambda_1, lambda_2):
        self.lambda_1 = lambda_1
        self.lambda_2 = lambda_2
# +++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv       
        self.l1_grads = {
            "dW1": 0,
            "dW2": 0
        }
# +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^        
        
...


import numpy as np


class Regularization:
    """ Regularization class
    Arguments:
    lambda_1 -- regularization coeficient for l1 regularization
    lambda_2 -- regularization coeficient for l2 regularization
    """
    
    def __init__(self, lambda_1, lambda_2):
        self.lambda_1 = lambda_1
        self.lambda_2 = lambda_2
# +++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv       
        self.l1_grads = {
            "dW1": 0,
            "dW2": 0
        }
# +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^        
        
    def l1(self, W1, W2, m):
        """ Compute l1 regularization part
        Arguments:
        W1 -- weigts of shape (n_hidden_units, n_features) 
        W2 -- weigts of shape (output_size, n_hidden_units) 
        m -- n_examples

        Returns:
        l1_term -- float, check formula (6)
        """
        
        ### START CODE HERE ###
        return (self.lambda_1/(m)) * (np.linalg.norm(W1, ord=1) + \
            np.linalg.norm(W2, ord=1))
        ### END CODE HERE ###

# +++ l1_grad
    def l1_grad(self, W1=1, W2=2, m=3):
        """ Compute l1 regularization term
        Arguments:
        W1 -- weigts of shape (n_hidden_units, n_features) 
        W2 -- weigts of shape (output_size, n_hidden_units) 
        m -- n_examples

        Returns:
         dict with l1_grads "dW1" and "dW2"
            which are grads by corresponding weights
        """
        ### START CODE HERE ###
        dW1 = self.lambda_1 / m * np.sign(W1)
        
        dW2 = self.lambda_1 / m * np.sign(W2)

        self.l1_grads = {                                     # +++ self.
            "dW1": dW1,
            "dW2": dW2
        }
        return (self.l1_grads)                                # +++ self.
        ### END CODE HERE ###

    def l2(self, W1, W2, m):
        """ Compute l2 regularization term
        Arguments:
        W1 -- weigts of shape (n_hidden_units, n_features) 
        W2 -- weigts of shape (output_size, n_hidden_units) 
        m -- n_examples

        Returns:
        l2_term: float, check formula (6)
        """
        
        ### START CODE HERE ###
        return (self.lambda_2 / (m * 2) * (np.sum(np.square(W1)) + \
            np.sum(np.square(W2))))
        ### END CODE HERE ###
        
    def l2_grad(self, W1, W2, m):
        """ Compute l2 regularization term
        Arguments:
        W1 -- weigts of shape (n_hidden_units, n_features) 
        W2 -- weigts of shape (output_size, n_hidden_units) 
        m -- n_examples

        Returns:
        l2_grads: dict with keys "dW1" and "dW2"
        """
        ### START CODE HERE ###
        dW1 = self.lambda_2/m*W1
        
        dW2 = self.lambda_2/m*W2

        l2_grads = {"dW1": dW1,
                 "dW2": dW2}
        return(l2_grads)
        ### END CODE HERE ###


class Sigmoid:
    pass


class NeuralNetwork:
    """
    Arguments:
    n_features: int -- Number of features
    n_hidden_units: int -- Number of hidden units
    n_classes: int -- Number of classes
    learning_rate: float
    reg: instance of Regularization class
    """
    
    def __init__(self, 
        n_features=1, 
        n_hidden_units=2, 
        n_classes=1 , 
        learning_rate=0.123, 
        reg=Regularization(0.1, 0.2), 
        sigm=Sigmoid()
    ):
        self.n_features = n_features
        self.n_classes = n_classes
        self.learning_rate = learning_rate
        self.n_hidden_units = n_hidden_units
        self.reg = reg
        self.sigm = sigm
        self.W1 = None
        self.b1 = None
        self.W2 = None
        self.b2 = None
        
        self.initialize_parameters()
        
# +++
        print(f'class NeuralNetwork: reg.l1_grads = {self.reg.l1_grads}')  # +++

    def initialize_parameters(self):
        """
        W1 -- weight matrix of shape (self.n_hidden_units, self.n_features)
        b1 -- bias vector of shape (self.n_hidden_units, 1)
        W2 -- weight matrix of shape (self.n_classes, self.n_hidden_units)
        b2 -- bias vector of shape (self.n_classes, 1)
        """
        np.random.seed(42) 
    
        ### START CODE HERE ### 
        W1 = np.random.randn(self.n_hidden_units, self.n_features) * 0.01
        b1 = np.zeros((self.n_hidden_units, 1))
        W2 = np.random.randn(self.n_classes, self.n_hidden_units) * 0.01
        b2 = np.zeros((self.n_classes, 1))   
        self.W1 = W1
        self.b1 = b1
        self.W2 = W2
        self.b2 = b2
        return   {"W1": W1,
                  "b1": b1,
                  "W2": W2,
                  "b2": b2}
        ### END CODE HERE ###

    def forward_propagation(self, X):
        """
        Arguments:
        X -- input data of shape (number of features, number of examples)
        
        Returns:
        dictionary containing "Z1", "A1", "Z2" and "A2"
        """
        # Implement Forward Propagation to calculate A2 (probabilities)
        ### START CODE HERE ### 
        Z1 = np.add(np.matmul(self.W1, X), self.b1)
        A1 = self.sigm(Z1)
        Z2 = np.add(np.matmul(self.W2, A1), self.b2)
        A2 = self.sigm(Z2)
        cache = {"Z1": Z1,
             "A1": A1,
             "Z2": Z2,
             "A2": A2}
        ### END CODE HERE ###

        return {
            'Z1': Z1,
            'A1': A1,
            'Z2': Z2,
            'A2': A2
        }
    
    def backward_propagation(self, X, Y, cache):
        """
        Arguments:
        X -- input data of shape (number of features, number of examples)
        Y -- one-hot encoded vector of labels with shape (n_classes, n_samples)
        cache -- a dictionary containing "Z1", "A1", "Z2" and "A2"

        Returns:
        dictionary containing gradients "dW1", "db1", "dW2", "db2"
        """
        m = X.shape[1]
        
        # Retrieve A1 and A2 from dictionary "cache".
        ### START CODE HERE ### 
        A1 = cache["A1"]
        A2 = cache["A2"]
        ### END CODE HERE ###
        
        # Calculate gradients for L1, L2 parts using attribute instance of Regularization class
        ### START CODE HERE ### 
        
# **Необходимо перенести значение dW1 с класса Regularization метода l1_grad**
# +++
        print(self.reg.l1_grads)
        reg_l1_grads_dW1 = self.reg.l1_grads['dW1'] # +++ вот ваше значение dW1 
# +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^  
        
        ### END CODE HERE ###

        # Backward propagation: calculate dW1, db1, dW2, db2 (using obtained L1, L2 gradients)
        ### START CODE HERE ###
        dZ2 = A2 - Y
        dW2 = (1 / m) * np.dot(dZ2, A1.T)
        db2 = (1 / m) * np.sum(dZ2, axis=1, keepdims=True)
        dZ1 = np.multiply(np.dot(self.W2.T, dZ2), 1 - np.power(A1, 2))
        dW1 = (1 / m) * np.dot(dZ1, X.T)
        db1 = (1 / m) * np.sum(dZ1, axis=1, keepdims=True)
        grads = {"dW1": dW1,
             "db1": db1,
             "dW2": dW2,
             "db2": db2}
        ### END CODE HERE ###

        return {
            'dW1': dW1,
            'db1': db1,
            'dW2': dW2,
            'db2': db2}

    def update_parameters(self, grads):
        """
        Updates parameters using the gradient descent update rule 

        Arguments:
        grads -- python dictionary containing gradients "dW1", "db1", "dW2", "db2"
        """
        # Retrieve each gradient from the dictionary "grads"

        ### START CODE HERE ### 
        dW1 = grads["dW1"]
        db1 = grads["db1"]
        dW2 = grads["dW2"]
        db2 = grads["db2"]
        ## END CODE HERE ###

        # Update each parameter
        ### START CODE HERE ### 
        W1 = W1 - learning_rate * dW1
        b1 = b1 - learning_rate * db1
        W2 = W2 - learning_rate * dW2
        b2 = b2 - learning_rate * db2

        parameters = {"W1": W1,
                      "b1": b1,
                      "W2": W2,
                      "b2": b2}
        return (parameters)
        ### END CODE HERE ###


# +++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
neuralNetwork = NeuralNetwork(1, 2)
        
neuralNetwork.reg.l1_grads
neuralNetwork.reg.l1_grad()

print(f'Hello neuralNetwork.reg.l1_grads = {neuralNetwork.reg.l1_grads}') 
# +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^  
2
  • А есть возможность передать на прямую, без добавления self.l1_grads в def init class Regularization? Commented 11 июл. 2021 в 22:27
  • @RomanParkhomenko Возможность всегда есть. Например вызовите _dict = self.reg.l1_grad() из метода backward_propagation(). Если мой ответ помог вам, то не забудьте пометить как правильный, если вы не знаете, как это сделать, проверьте ru.stackoverflow.com/tour
    – S. Nick
    Commented 11 июл. 2021 в 22:39

Ваш ответ

Нажимая «Отправить ответ», вы соглашаетесь с условиями пользования и подтверждаете, что прочитали политику конфиденциальности.

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