Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Para intentar la clasificación, un método es usar la regresión lineal y mapear todas las
predicciones mayores de 0.5 como 1 y todas menos de 0.5 como 0. Sin embargo, este
método no funciona bien porque la clasificación no es en realidad una función lineal.
El problema de clasificación es igual que el problema de regresión, excepto que los valores
que ahora deseamos predecir toman solo un pequeño número de valores discretos. Por
ahora, nos centraremos en el problema de clasificación binaria en el que y puede tomar
solo dos valores, 0 y 1. (La mayoría de lo que decimos aquí también se generalizará en el
caso de clases múltiples). Por ejemplo, si lo intentamos para construir un clasificador de
spam para correo electrónico, entoncesx ^ {(i)}x( i ) puede ser algunas características de
un correo electrónico, y y puede ser 1 si se trata de un correo no deseado, y 0 de lo
contrario. Por lo tanto, y∈ {0,1}. 0 también se denomina clase negativa y 1 clase positiva, y
a veces también se denotan con los símbolos "-" y "+". Dadox ^ {(i)}x( i ), la
correspondientey^{(i)}y( i ) también se llama la etiqueta para el ejemplo de
entrenamiento.
Suppose we want to predict, from data xxabout a tumor, whether it is malignant (y=1y=1)
or benign (y=0y=0). Our logistic regression classifier outputs, for a specific
tumor, hθ(x)=P(y=1|x;θ)=0.7, so we estimate that there is a 70% chance of this tumor
being malignant. What should be our estimate for P(y=0|x;θ), the probability the tumor is
benign?
P(y=0|x;θ)=0.3
P(y=0|x;θ)=0.7
P(y=0|x;θ)=0.72
P(y=0|x;θ)=0.3×0.7
Representación de hipótesis
Podríamos abordar el problema de clasificación ignorando el hecho de que y tiene un valor
discreto, y usar nuestro antiguo algoritmo de regresión lineal para tratar de predecir y dado
x. Sin embargo, es fácil construir ejemplos en los que este método funciona muy
mal. Intuitivamente, tampoco tiene sentido parah_ \ theta (x)hyo( x ) para tomar valores
mayores que 1 o menores que 0 cuando sabemos que y ∈ {0, 1}. Para solucionar esto,
cambiemos la forma de nuestras hipótesis.h_ \ theta (x)hyo( x ) para satisfacer0 \ leq h_ \
theta (x) \ leq 10≤hyo(x)≤1 . Esto se logra conectando\ theta ^ TxyoT xen la función
logística.
Nuestra nueva forma utiliza la "Función sigmoidea", también llamada "Función logística":
Misplaced &
La función g (z), que se muestra aquí, asigna cualquier número real al intervalo (0, 1), por
lo que es útil para transformar una función de valor arbitrario en una función más adecuada
para la clasificación.
h_ \ theta (x)hyo( x ) nos dará laprobabilidad deque nuestra salida sea 1. Por ejemplo,h_
\ theta (x) = 0.7hyo(x)=0 . 7 nos da una probabilidad del 70% de que nuestra producción
sea 1. Nuestra probabilidad de que nuestra predicción sea 0 es solo el complemento de
nuestra probabilidad de que sea 1 (p. Ej., Si la probabilidad de que sea 1 es del 70%, 0 es
30%).
Ejercicio
Consider logistic regression with two features x_1x1 and x_2x2. Suppose \theta_0 = 5θ0
=5, \theta_1 = -1θ1=−1, \theta_2 = 0θ2=0, so that h_\theta(x) = g(5 - x_1)hθ
(x)=g(5−x1). Which of these shows the decision boundary of h_\theta(x)hθ(x)?
.
.
Límite de decisión
Para obtener nuestra clasificación 0 o 1 discreta, podemos traducir la salida de la función
de hipótesis de la siguiente manera:
\ begin {align *} & h_ \ theta (x) \ geq 0.5 \ rightarrow y = 1 \ newline & h_ \ theta (x) <0.5 \ rightarrow y = 0 \ newline \ e
\ begin {align *} & g (z) \ geq 0.5 \ newline & when \; z \ geq 0 \ end {align *}
Recuerda.
\ begin {align *} z = 0, e ^ {0} = 1 \ Rightarrow g (z) = 1/2 \ newline z \ to \ infty, e ^ {- \ infty} \ to 0 \ Rightarrow g (con ) =
infty, e ^ {\ infty} \ to \ infty \ Rightarrow g (z) = 0 \ end {align *}
\ begin {align *} & h_ \ theta (x) = g (\ theta ^ T x) \ geq 0.5 \ newline & when \; \ theta ^ T x \ geq 0 \ end {align *}
\ begin {align *} & \ theta ^ T x \ geq 0 \ Rightarrow y = 1 \ newline & \ theta ^ T x <0 \ Rightarrow y = 0 \ newline \ end {
Ejemplo :
\ begin {align *} & \ theta = \ begin {bmatrix} 5 \ newline -1 \ newline 0 \ end {bmatrix} \ newline & y = 1 \; Si \; 5 + (-1) x_
newline & 5 - x_1 \ geq 0 \ newline & - x_1 \ geq -5 \ newline & x_1 \ leq 5 \ newline \ end {align *}
En este caso, nuestro límite de decisión es una línea recta vertical colocada en el gráfico
donde x_1 = 5x1=5 , y todo a la izquierda denota y = 1, mientras que todo a la derecha
denota y = 0.
Decision Boundary
In order to get our discrete 0 or 1 classification, we can translate the output of the
hypothesis function as follows:
hθ(x)≥0.5→y=1
hθ(x)<0.5→y=0
The way our logistic function g behaves is that when its input is greater than or equal to
zero, its output is greater than or equal to 0.5:
g(z)≥0.5
whenz≥0
Remember.
z=0,e0=1⇒g(z)=1/2
z→∞,e−∞→0⇒g(z)=1
z→−∞,e∞→∞⇒g(z)=0
So if our input to g is \theta^T XθTX, then that means:
hθ(x)=g(θTx)≥0.5
whenθTx≥0
From these statements we can now say:
θTx≥0⇒y=1
θTx<0⇒y=0
The decision boundary is the line that separates the area where y = 0 and where y = 1. It
is created by our hypothesis function.
Example:
Again, the input to the sigmoid function g(z) (e.g. \theta^T XθTX) doesn't need to be linear,
and could be a function that describes a circle (e.g. z = \theta_0 + \theta_1 x_1^2
+\theta_2 x_2^2z=θ0+θ1x12+θ2x22) or any shape to fit our data.
pregunta
en el video de función de costo
Consider minimizing a cost function J(\theta)J(θ). Which one of these functions is convex?
La respuesta es la 2
J( i ) = 1metro∑i = 1metroC o s t (hyo(x( i )),y( i ))C o s t (hyo(x),y) = - log( hyo(x))C o s t (hyo(x),y) = - log( 1 - h
Cuando y = 1, obtenemos la siguiente gráfica para J (\ theta)J ( θ ) vsh_ \ theta (x)hyo(x):
Tenga en cuenta que escribir la función de costo de esta manera garantiza que J (θ) es
convexo para la regresión logística.
Ejercicio de de video de
simplifiedcost función and
gradient dacent
Suppose you are running gradient descent to fit a logistic regression model with
parameter θ∈Rn+1. Which of the following is a reasonable way to make sure the learning
rate \alphaα is set properly and that gradient descent is running correctly?
Plot J(\theta)J(θ) as a function of \thetaθ and make sure it is decreasing on every iteration.
⋮
\theta_n := \theta_n - \alpha\frac{1}{m}\sum_{i=1}^{m}(h_\theta(x^{(i)}) -
y^{(i)}) \cdot x^{(i)}_nθn:=θn−αm1∑i=1m(hθ(x(i))−y(i))⋅xn(i)
Podemos comprimir los dos casos condicionales de nuestra función de costo en un caso:
J (\ theta) = - \ frac {1} {m} \ displaystyle \ sum_ {i = 1} ^ m [y ^ {(i)} \ log (h_ \ theta (x ^ {(i)})) + (1 - y ^ {(i)})
(x ^ {(i)}))]J ( θ )=−metro1i = 1∑m[y( i )lo g ( hyo(x( i ) ))+(1−y( i ) )lo g ( 1−hyo(x( i ) ))]
Descenso de gradiente
R e p e a t{yoj: = θj−α∂∂yojJ( i )}
Observe que este algoritmo es idéntico al que usamos en la regresión lineal. Todavía
tenemos que actualizar simultáneamente todos los valores en theta.
Optimización avanzada
Nota: [7:35 - '100' debería ser 100 en su lugar. El valor proporcionado debe ser un número
entero y no una cadena de caracteres.]
J( i )∂∂yojJ( i )
Podemos escribir una sola función que devuelva ambos:
Luego podemos usar el algoritmo de optimización "fminunc ()" de octava junto con la
función "optimset ()" que crea un objeto que contiene las opciones que queremos enviar a
"fminunc ()". (Nota: el valor para MaxIter debe ser un entero, no una cadena de caracteres
- errata en el video a las 7:30)
Le damos a la función "fminunc ()" nuestra función de costo, nuestro vector inicial de
valores theta y el objeto "opciones" que creamos de antemano.
Clasificación multiclase: uno contra
todo
Ahora abordaremos la clasificación de los datos cuando tengamos más de dos
categorías. En lugar de y = {0,1} expandiremos nuestra definición para que y = {0,1 ... n}.
Como y = {0,1 ... n}, dividimos nuestro problema en n + 1 (+1 porque el índice comienza en
0) problemas de clasificación binaria; en cada uno, predecimos la probabilidad de que 'y'
sea miembro de una de nuestras clases.
Misplaced &
Básicamente, estamos eligiendo una clase y luego agrupando todas las demás en una
segunda clase. Hacemos esto repetidamente, aplicando regresión logística binaria a cada
caso, y luego usamos la hipótesis que devolvió el valor más alto como nuestra predicción.
Para resumir:
Para hacer una predicción sobre una nueva x, elija la clase que maximice h_ \ theta
(x)hyo(x)
Ejercicio del video
Suppose you have a multi-class classification problem with kk classes (so y∈{1,2,…,k}).
Using the 1-vs.-all method, how many different logistic regression classifiers will you end up
training?
k-1k−1
kk
k+1k+1
Approximately \log_2(k)log2(k)
Ejercicos de cuestionario
Pregunta 1
Punto
1. Pregunta 1
Suppose that you have trained a logistic regression classifier, and it outputs on a new
example xx a prediction h_\theta(x)hθ(x) = 0.4. This means (check all that apply):
Pregunta 2
Punto
2. Pregunta 2
Suppose you have the following training set, and fit a logistic regression
classifier h_\theta(x) = g(\theta_0 + \theta_1x_1 + \theta_2 x_2)hθ(x)=g(θ0+θ1x1+θ2
x2 ).
If we train gradient descent for enough iterations, for some examples x^{(i)}x(i) in the
training set it is possible to obtain h_\theta(x^{(i)}) > 1hθ(x(i))>1.
Pregunta 3
Punto
3. Pregunta 3
For logistic regression, the gradient is given by ∂∂θjJ(θ)=1m∑mi=1(hθ(x(i))−y(i))x(i)j.
Which of these is a correct gradient descent update for logistic regression with a learning
rate of \alphaα? Check all that apply.
Pregunta 4
1
Punto
4. Pregunta 4
Which of the following statements are true? Check all that apply.
Linear regression always works well for classification if you classify by using a threshold on
the prediction made by linear regression.
For logistic regression, sometimes gradient descent will converge to a local minimum (and
fail to find the global minimum). This is the reason we prefer more advanced optimization
algorithms such as fminunc (conjugate gradient/BFGS/L-BFGS/etc).
The cost function J(\theta)J(θ) for logistic regression trained with m \geq 1m≥1 examples
is always greater than or equal to zero.
The sigmoid function g(z) = \frac{1}{1 + e^{-z}}g(z)=1+e−z1 is never greater than one
(>1>1).
Pregunta 5
Punto
5. Pregunta 5
Suppose you train a logistic classifier h_\theta(x) = g(\theta_0 + \theta_1x_1 + \theta_2
x_2)hθ(x)=g(θ0+θ1x1+θ2x2). Suppose \theta_0 = 6, \theta_1 = -1, \theta_2 = 0θ0=6,θ1
=−1,θ2=0. Which of the following figures represents the decision boundary found by your
classifier?
buensa respuesta
Figure:
Figure:
Figure:
Figure:
Punto
Pregunta 2
Punto
2. Pregunta 2 buena respuesta
Suppose you have the following training set, and fit a logistic regression
classifier h_\theta(x) = g(\theta_0 + \theta_1x_1 + \theta_2 x_2)hθ(x)=g(θ0+θ1x1+θ2
x2 ).
J(\theta)J(θ) will be a convex function, so gradient descent should converge to the global
minimum.
The positive and negative examples cannot be separated using a straight line. So, gradient
descent will fail to converge.
Because the positive and negative examples cannot be separated using a straight line,
linear regression will perform as well as logistic regression on this data.
Kkkkkkkkkkkkkkkk
Pregunta 3
1
Punto
3. Pregunta 3
For logistic regression, the gradient is given by ∂∂θjJ(θ)=1m∑mi=1(hθ(x(i))−y(i))x(i)j.
Which of these is a correct gradient descent update for logistic regression with a learning
rate of \alphaα? Check all that apply.
Pregunta 4
Punto
4. Pregunta 4
Which of the following statements are true? Check all that apply.
The one-vs-all technique allows you to use logistic regression for problems in which
each y^{(i)}y(i) comes from a fixed, discrete set of values.
For logistic regression, sometimes gradient descent will converge to a local minimum (and
fail to find the global minimum). This is the reason we prefer more advanced optimization
algorithms such as fminunc (conjugate gradient/BFGS/L-BFGS/etc).
The cost function J(\theta)J(θ) for logistic regression trained with m \geq 1m≥1 examples
is always greater than or equal to zero.
Since we train one classifier when there are two classes, we train two classifiers when
there are three classes (and we do one-vs-all classification).
Pregunta 5
Punto
5. Pregunta 5
Suppose you train a logistic classifier h_\theta(x) = g(\theta_0 + \theta_1x_1 + \theta_2
x_2)hθ(x)=g(θ0+θ1x1+θ2x2). Suppose \theta_0 = 6, \theta_1 = 0, \theta_2 = -1θ0=6,θ1
=0,θ2=−1. Which of the following figures represents the decision boundary found by your
classifier?
Figure:
Figure:
Figure:
Figure: