Documentos de Académico
Documentos de Profesional
Documentos de Cultura
1. Primera Semana.
El rendimiento de una red tradicional, mejora a medida que incrementamos la cantidad de datos
de entrada, pero llega un punto en el que se estabiliza.
Es decir, por la disminución de los teléfonos móviles, cámaras, aplicaciones, etc., se tienen un gran
numero de datos, con los que usar Deep learning se justifica. Estamos en una era digital, en la que
pasamos mucho tiempo en nuestro ordenadores, internet.
A mayor tamaño de la red (más conexiones, unidades ocultas, parámetros), mayor rendimiento
con mayor número de datos. Para sacarle provecho debes ser capaz de entrenar una red grande,
que aproveche la gran cantidad de datos.
Notación:
2. Second Week
Loss function (función error): computes the error for a single training example.
Cost function is the average of the loss functions of the entire training set.
Want to find w, b that minimize J(w,b, por lo que se realciona con el conceptomde derivada,
(pendiente). Se inicializan w y b en algún punto. Y desde ahí busca el camino de descenso más
rápido.
Notación, dvar para la derivada de la salida (variable que nos interesa). Las derivadas dJ/dv, se
representan como dv, ya que todas las derivadas serán respecto a la última variable (J).
Z=np.dot(w.T,X) +b
A=sigmoid(Z)
So, dZ=A-Y
db=np.sum(dZ)
dW=1/m XdZ.T
Exercises
https://kfxaifespuovrbuhcgbnkv.coursera-apps.org/notebooks/Week%202/Python%20Basics
%20with%20Numpy/Python_Basics_With_Numpy_v3a.ipynb#1.1---sigmoid-function,-np.exp()
https://kfxaifespuovrbuhcgbnkv.coursera-apps.org/notebooks/Week%202/Logistic%20Regression
%20as%20a%20Neural
%20Network/Logistic_Regression_with_a_Neural_Network_mindset_v6a.ipynb#
3. Tercera semana
What is a neural network?
Entre corchetes tendremos el numero de capas, siendo [1] la capa de entrada y [2]. La de salida. Y
se calcula el parámetro z[1], luego el a[1] (Sigmoide de z[1]). Y con a[1], calculamos z[2] y a[2] será
la salida. Es decir, la red neuronal tiene la misma forma de la regresión, pero usada un mayor
numero de veces. Se usa la propagación hacia atrás para calcular las variables necesarias en cada
capa.
a[0]=X (valores de entrada), el termino a se conoce también como activaciones, se refiere a los
valores que las diferentes capas están pasando a las capas posteriores. La output hidden, genera a
su vez un conjunto de activaciones a[1]. El vector tendrá la dimensionalidad del numero de nodos
en la capa.
La layer hidden tendrá valores w y b asociados con la capa 1. W, será un vector de dimensiones
(nodos layer hidden, características de entrada).
Lo anterior, se puede hacer con un bucle for, sin embargo, el coste computacional es alto. Resulta
más viable, realizar una matriz que contenga toda la información necesaria de Z[1], es decir
contiene cada z de los nodos de la capa.
W [ 1] T X +b [ 1] =Z [ 1]
a [ 1] =SIGMOIDE( Z [ 1 ] )
3.3 One hidden layer Neural Network. Vectorizing across multiple examples.
Hasta el momento se ha observado como entrenar la red, con solo un conjunto de entrenamiento.
Ahora, se verá como hacerlo con un mayor número de conjuntos de entrenamiento.
La excepción es la capa de salida, ya que si la salida es un valor y E {0,1}, entonces tiene sentido
que 0<=y_hat<=1. Es decir, en los casos que se están haciendo clasificaciones binarias, se usaría en
la capa de salida una función de activación, sigmoide.
Una desventaja de las funciones de activación sigmoide y tanh, es que si los valores de z es muy
grande o muy pequeño, la pendiente de la función se hace muy cercana a cero.
Si no estas seguro de que función usar en la capa oculta, usar ReLU. Usando está función la red
neuronal aprenderá más rápido que usando las otras funciones de activación.
Sigmoide, a menos que se tenga clasificación binaria no usarla. Ya que tanh es siempre superior.
Una posibilidad es probar con las posibles funciones de activación con un conjunto de pruebas y
elegir la que mejores resultados genere.
Pero, en las capas ocultas, el usar una función lineal hace que se hagan innecesarias usarlas, pues
se termina con el caso de una regresión logística estándar. Incluso, si en la salida se tiene valores
que no sean negativos, si puede usar una función ReLU de activación.
Tanh, g’(z)=1-(g(z))^2)=1-a^2
ReLU, g(z)=max(0,z)
N_x=n[0]=Parametros de entrada
n[1]=unidades ocultas
Gradient descent
d Z [ 2 ] = A[ 2 ] −Y
Y =¿ ¿
1
d W [2 ]= d Z [ 2] A [ 2 ] T
m
1
d b[ 2 ] = np . ∑ (d Z [ 2 ] , axis=1, keepdims=true)
m
El anterior comando, es para sumar horizontalmente en Python.
'
d Z [ 1 ] =W [ 2 ] T ∗d Z [ 2]∗g[ 1] ( Z[ 1] )
1
d W [1 ]= d Z [ 1] X T
m
1
d b[ 1 ] = np . ∑ ( d Z [ 1 ] , axis=1 , keepdims=true )
m
6. Random Initialization
¿Qué pasa si inicias pesos en cero?
Las unidades de la capa oculta estarán calculando la misma función en todas las iteraciones, por lo
que no tendría razón de ser usar más de un nodo en la capa oculta.
w1=np.random.randn((2,2))*0,01
Se multiplica por 0,001, para inicializar en valores pequeños, esto se hace porque las derivadas de
las funciones de activación sigmoide y tangente hiperbólico tienden a cero en valores grandes.
El numero 0,01 da buenos resultados para una red poco profunda (pocas capas ocultas)
Por otro lado, b no tiene el problema de ruptura de simetría entonces está bien inicializar con solo
ceros.
b1=np.zero((2,1))
Preguntas
The tanh activation usually works better than sigmoid activation function for hidden units because
the mean of its output is closer to zero, and so it centers the data better for the next layer. True.
Forward propagation
Logistic Regression doesn't have a hidden layer. If you initialize the weights to zeros, the first
example x fed in the logistic regression will output zero but the derivatives of the Logistic
Regression depend on the input x (because there's no hidden layer) which is not zero. So at the
second iteration, the weights values follow x's distribution and are different from each other if x is
not a constant vector.
Assigment
Visualiza el conjunto de datos usando matplotlib. Los datos parecen una "flor" con algunos puntos
rojos (etiqueta y=0) y algunos puntos azules (y=1). Tu objetivo es construir un modelo que se
ajuste a estos datos. En otras palabras, queremos que el clasificador defina las regiones como rojas
o azules.
Tenemos,
Ejercicio: ¿Cuántos ejemplos de entrenamiento tiene? Además, ¿cuál es la forma (tamaño) de las
variables X e Y?
shape_X = X.shape=(2,400)
shape_Y = Y.shape=(1,400)
Before building a full neural network, lets first see how logistic regression performs on this
problem. You can use sklearn's built-in functions to do that. Run the code below to train a logistic
regression classifier on the dataset.
clf = sklearn.linear_model.LogisticRegressionCV();
clf.fit(X.T, Y.T);
You can now plot the decision boundary of these models. Run the code below.
Interpretation: The dataset is not linearly separable, so logistic regression doesn't perform well.
Hopefully a neural network will do better. Let's try this now!
Dadas las predicciones de todos los ejemplos, también se puede calcular el costo J de la siguiente
manera:
3. Lazo:
- Calcular la pérdida
A menudo se construyen funciones de ayuda para calcular los pasos 1-3 y luego se fusionan en una
función que llamamos nn_model(). Una vez que has construido nn_model() y aprendido los
parámetros correctos, puedes hacer predicciones sobre nuevos datos.
Arguments:
Make sure your parameters' sizes are right. Refer to the neural network figure above if needed.
The loop
Values needed in the backpropagation are stored in "cache". The cache will be given as an input to
the backpropagation function
Returns:
A2 -- The sigmoid output of the second activation
Z1 = np.dot(W1,X) + b1
A1 = sigmoid(Z1)
Z2 = np.dot(W2,A1) + b2
A2 = sigmoid(Z2)
Cost Function J
Tenga en cuenta que si utiliza np.multiply seguido de np.sum el resultado final será un tipo de
float, mientras que si utiliza np.dot, el resultado será un arreglo numérico 2D. Podemos usar
np.squeeze() para eliminar las dimensiones redundantes (en el caso de un solo float, esto se
reducirá a un array de cero dimensiones). Podemos moldear el array como un tipo de flotador
usando float().
There are many ways to implement the cross-entropy loss. To help you, we give you how we
would have implemented
No entiendo porque usan está ecuación “reducida”, sin embargo es claro que la ecuación extensa
está mal, la anterior usada era:
logprobs = np.multiply(np.log(A2),Y)
cost = - np.sum(logprobs)
logprobs = (np.multiply(np.log(A2),Y)+np.multiply((1-Y),np.log(1-A2)))
cost = - 1/m*np.sum(logprobs)
Backward propagation
Backpropagation is usually the hardest (most mathematical) part in deep learning. To help you,
here again is the slide from the lecture on backpropagation. You'll want to use the six equations on
the right of this slide, since you are building a vectorized implementation.
Tips:
Para computar dZ1 se requiere la derivada de g[1]. Ahora, como g[1] es la función de activación
tanh, y a=g[1](Z), se tiene que g’[1]=1-A[1]^2. Que se puede hacer en Python: (1 - np.power(A1,
2)).
dZ2 = A2-Y
dW2 = 1/m*np.dot(dZ2,A1.T)
db2 = 1/m*(np.sum(dZ2,axis=1,keepdims=True))
dZ1 = np.dot(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))
Usar (dW1, db1, dW2, db2) para actualizar (W1, b1, W2, b2)
learning_rate = 1.2
W1 = W1-learning_rate*dW1
b1 = b1-learning_rate*db1
W2 = W2-learning_rate*dW2
b2 = b2-learning_rate*db2
The neural network model has to use the previous functions in the right order.
Returns:
parameters -- parameters learnt by the model. They can then be used to predict.
Nota: Me generaba error en las salidas esperadas, debido a que no me fije en la imagen del
modelo. Las funciones de activación para las unidades ocultas, es el tanh, mientras que a la salida
es el sigmoide.
Predictions
Use your model to predict by building predict(). Use forward propagation to predict results.
As an example, if you would like to set the entries of a matrix X to 0 and 1 based on a threshold
you would do: X_new = (X > threshold)
Se usan los parametros obtenidos del paso anterior, para calcular una salida (A2).
predictions = A2>0.5
Prueba
Accuracy: 90%
Accuracy is really high compared to Logistic Regression. The model has learnt the leaf patterns of
the flower! Neural networks are able to learn even highly non-linear decision boundaries, unlike
logistic regression.
Now, let's try out several hidden layer sizes.
The larger models (with more hidden units) are able to fit the training set better, until eventually
the largest models overfit the data.
The best hidden layer size seems to be around n_h = 5. Indeed, a value around here seems to fits
the data well without also incurring noticeable overfitting.
You will also learn later about regularization, which lets you use very large models (such as n_h =
50) without much overfitting.
a[l]=g(z[l])
a, is (n[l],1)
b, (n[l],1)
Las derivadas dw, y db, deben ser las mismas que sus respectivos parámetros, W y b.
Vectorized implementation
Z mayúscula, representa la matriz formada por columnas con los m conjuntos de entrenamiento. Y
el numero de filas será el numero de nodos. Esto para cada layer. Es decir, se hace necesario un
for para que realice la operación con el número de layers.
Informally, there are functions you can compute with a “small” L-layer deep neural network that
shallower networks require exponentially more hidden units to compute.
Resulta conveniente guardar un cache con el valor de z[l], w y b, ya que se usa para la backward
propagation.
Diagrama de forward and backpropagation.
Vectorizado
Hallar el valor de Alpha suele ser un proceso empírico, llevado a cabo mediante un proceso
iterativo. Para ellos buscamos un valor que minimice la función del costo.
Vectorization allows you to compute forward propagation in an LL-layer neural network without
an explicit for-loop (or any other explicit iterative loop) over the layers l=1, 2, …,L. True/False?
Assume we store the values for n^[l] in an array called layers, as follows: layer_dims =
[n_x,4,3,2,1]. So, layer 1 has four hidden units, layer 2 has 3 hidden units and so on. Which of the
following for-loops will allow you to initialize the parameters for the model?
L=4, As seen in lecture, the number of layers is counted as the number of hidden layers + 1. The
input and output layers are not counted as hidden layers.
During forward propagation, in the forward function for a layer ll you need to know what is the
activation function in a layer (Sigmoid, tanh, ReLU, etc.). During backpropagation, the
corresponding backward function also needs to know what is the activation function for layer ll,
since the gradient depends on it. True.
Yes, as you've seen in the week 3 each activation has a different derivative. Thus, during
backpropagation you need to know which activation was used in the forward propagation to be
able to compute the correct derivative.
(i) To compute the function using a shallow network circuit, you will need a large network (where
we measure size by the number of logic gates in the network), but (ii) To compute it using a deep
network circuit, you need only an exponentially smaller network. True/False?
- Write functions (e.g. forward propagation, backward propagation, logistic loss, etc...) that would
help you decompose your code and ease the process of building a neural network.
- Initialize the parameters for a two-layer network and for an L -layer neural network.
- Implement the forward propagation module (shown in purple in the figure below)
Complete the LINEAR part of a layer's forward propagation step (resulting in Z[l]).
We give you the ACTIVATION function (relu/sigmoid)
Combine the previous two steps into a new [LINEAR->ACTIVATION] forward function
Stack the [LINEAR->RELU] forward function L-1 time (for layers 1 through L-1) and add a
[LINEAR->SIGMOID] at the end (for the final layer L). This gives you a new
L_model_forward function.
- Compute the loss
- Implement the backward propagation module (denoted in red in the figure below)
Complete the LINEAR part of a layer's backward propagation step
We give you the gradient of the ACTIVATE function (relu_backward/sigmoid_backward)
Combine the previous two steps into a new [LINEAR->ACTIVATION] backward function
Stack [LINEAR->RELU] backward L-1 times and add [LINEAR->SIGMOID] backward in a new
L_model_backward function.
- Finally update the parameters.
Nota Importante, para inicializar en ceros, con np es necesario usar doble paréntesis para que se
entienda que son las dimensiones y no los otros argumentos de entrada de la función
np.zeros(shape, type, others)
Remember that when we compute WX++b in python, it carries out broadcasting. For example, if:
Then, WX+b will be:
We will store n[l], the number of units in different layers, in a variable layer_dims. For example,
the layer_dims for the "Planar Data classification model" from last week would have been [2,4,1]:
There were two inputs, one hidden layer with 4 hidden units, and an output layer with 1 output
unit. This means W1's shape was (4,2), b1 was (4,1), W2 was (1,4) and b2 was (1,1). Now you will
generalize this to L layers!
- LINEAR
- LINEAR -> ACTIVATION where ACTIVATION will be either ReLU or Sigmoid
- [LINEAR -> RELU] × (L-1) -> LINEAR -> SIGMOID (whole model)
The linear forward module (vectorized over all the examples) computes the following equations:
Reminder, The mathematical representation of this unit is Z[l]=W[l]A[l−1]+b[l]. You may also find
np.dot() useful. If your dimensions don't match, printing W.shape may help.
Arguments:
A -- activations from previous layer (or input data): (size of previous layer, number of examples)
W -- weights matrix: numpy array of shape (size of current layer, size of previous layer)
Returns:
cache -- a python tuple containing "A", "W" and "b" ; stored for computing the backward pass
efficiently
Z = np.dot(W,A)+b
Arguments:
A_prev -- activations from previous layer (or input data): (size of previous layer, number of
examples)
W -- weights matrix: numpy array of shape (size of current layer, size of previous layer)
activation -- the activation to be used in this layer, stored as a text string: "sigmoid" or "relu"
Returns:
A -- the output of the activation function, also called the post-activation value
Arguments:
Returns:
every cache of linear_activation_forward() (there are L-1 of them, indexed from 0 to L-1)
caches = []
A=X
Note, el calculo de la perdida se realiza siempre en la ultima capa. (Es lógico, se compara el valor
que se obtuvo con el valor real de salida)
Arguments:
AL -- probability vector corresponding to your label predictions, shape (1, number of examples)
Y -- true "label" vector (for example: containing 0 if non-cat, 1 if cat), shape (1, number of
examples)
Returns:
Now, similar to forward propagation, you are going to build the backward propagation in three
steps:
- LINEAR backward
- LINEAR -> ACTIVATION backward where ACTIVATION computes the derivative of either the
ReLU or sigmoid activation
- [LINEAR -> RELU] × (L-1) -> LINEAR -> SIGMOID backward (whole model)
The three outputs are computed using the input dZ[l]. Here are the formulas you need:
Reminder, db = (1/m)*np.sum(dZ,axis=1,keepdims=True)
Arguments:
dZ -- Gradient of the cost with respect to the linear output (of current layer l)
cache -- tuple of values (A_prev, W, b) coming from the forward propagation in the current layer
Returns:
dA_prev -- Gradient of the cost with respect to the activation (of the previous layer l-1), same
shape as A_prev
dW -- Gradient of the cost with respect to W (current layer l), same shape as W
db -- Gradient of the cost with respect to b (current layer l), same shape as b
- sigmoid_backward: Implements the backward propagation for SIGMOID unit. You can call
it as follows:
dZ = sigmoid_backward(dA, activation_cache)
- relu_backward: Implements the backward propagation for RELU unit. You can call it as
follows:
dZ = relu_backward(dA, activation_cache)
Arguments:
activation -- the activation to be used in this layer, stored as a text string: "sigmoid" or "relu"
Returns:
dA_prev -- Gradient of the cost with respect to the activation (of the previous layer l-1), same
shape as A_prev
dW -- Gradient of the cost with respect to W (current layer l), same shape as W
db -- Gradient of the cost with respect to b (current layer l), same shape as b
A[L]=σ(Z[L]). Your code thus needs to compute To do so, use this formula (derived
using calculus which you don't need in-depth knowledge of):
You can then use this post-activation gradient dAL to keep going backward. As seen in Figure 5,
you can now feed in dAL into the LINEAR->SIGMOID backward function you implemented (which
will use the cached values stored by the L_model_forward function). After that, you will have to
use a for loop to iterate through all the other layers using the LINEAR->RELU backward function.
You should store each dA, dW, and db in the grads dictionary. To do so, use this formula :
Arguments:
every cache of linear_activation_forward() with "relu" (it's caches[l], for l in range(L-1) i.e
l = 0...L-2)
Returns:
grads -- A dictionary with the gradients
En este paso, tengo varias dudas, en lo que se refiere a los cahes. Sin embargo, el cache almacena,
el valor de A_previo, W, b y Z. Y los caches, almacena cada cache de las capas en el paso hacia el
frente, de modo que se pueden usar en los pasos hacia adelante. Sin embargo, en el
backpropagation, la entrada debe ser la da de la capa mayor a la que se está analizando. (creo)
# Lth layer (SIGMOID -> LINEAR) gradients. Inputs: "dAL, current_cache". Outputs: "grads["dAL-1"],
grads["dWL"], grads["dbL"]
current_cache = caches[L-1]
for l in reversed(range(L-1)):
current_cache = caches[l]
return grads
9.5.4 Update Parameters
In this section you will update the parameters of the model, using gradient descent:
where α is the learning rate. After computing the updated parameters, store them in the
parameters dictionary.
- Learn how to use all the helper functions you built in the previous assignment to build a
model of any structure you want.
- Experiment with different model architectures and see how each one behaves.
- Recognize that it is always easier to build your helper functions before attempting to build a
neural network from scratch.