Aprendizaje automático

El aprendizaje es un bucle

Un modelo de ML se entrena mediante bucles sobre los datos varias veces.

Para cada iteración, se ajustan los valores de ponderación.

El entrenamiento se completa cuando las iteraciones no logran reducir el costo .

Entréname para encontrar la línea de mejor ajuste:


Descenso de gradiente

Gradient Descent es un algoritmo popular para resolver problemas de IA.

Se puede usar un modelo de regresión lineal simple para demostrar un descenso de gradiente.

El objetivo de una regresión lineal es ajustar un gráfico lineal a un conjunto de puntos (x, y). Esto se puede resolver con una fórmula matemática. Pero un algoritmo de aprendizaje automático también puede resolver esto.

Esto es lo que hace el ejemplo anterior.

Comienza con un gráfico de dispersión y un modelo lineal (y = wx + b).

Luego entrena al modelo para encontrar una línea que se ajuste a la trama. Esto se hace modificando el peso (pendiente) y el sesgo (intersección) de la línea.

A continuación se muestra el código de un Objeto Entrenador que puede resolver este problema (y muchos otros problemas).


Un objeto de entrenador

Cree un objeto Trainer que pueda tomar cualquier número de valores (x,y) en dos matrices (xArr,yArr).

Establezca tanto el peso como el sesgo en cero.

Se debe establecer una constante de aprendizaje (learnc) y se debe definir una variable de costo:

Ejemplo

function Trainer(xArray, yArray) {
  this.xArr = xArray;
  this.yArr = yArray;
  this.points = this.xArr.length;
  this.learnc = 0.00001;
  this.weight = 0;
  this.bias = 1;
  this.cost;

función de costo

Una forma estándar de resolver un problema de regresión es con una "función de costo" que mide qué tan buena es la solución.

La función usa el peso y el sesgo del modelo (y = wx + b) y devuelve un error, en función de qué tan bien se ajusta la línea a una gráfica.

La forma de calcular este error es recorrer todos los puntos (x,y) del gráfico y sumar las distancias al cuadrado entre el valor y de cada punto y la línea.

La forma más convencional es elevar al cuadrado las distancias (para asegurar valores positivos) y hacer diferenciable la función de error.

this.costError = function() {
  total = 0;
  for (let i = 0; i < this.points; i++) {
    total += (this.yArr[i] - (this.weight * this.xArr[i] + this.bias)) **2;
  }
  return total / this.points;
}

Otro nombre para la Función de Costo es Función de Error .

La fórmula utilizada en la función es en realidad esta:

Fórmula
  • E es el error (costo)
  • N es el número total de observaciones (puntos)
  • y es el valor (etiqueta) de cada observación
  • x es el valor (característica) de cada observación
  • m es la pendiente (peso)
  • b es intersección (sesgo)
  • mx + b es la predicción
  • 1/N * N∑1 is the squared mean value

The Train Function

We will now run a gradient descent.

The gradient descent algorithm should walk the cost function towards the best line.

Each iteration should update both m and b towards a line with a lower cost (error).

To do that, we add a train function that loops over all the data many times:

this.train = function(iter) {
  for (let i = 0; i < iter; i++) {
    this.updateWeights();
  }
  this.cost = this.costError();
}

An Update Weights Function

The train function above should update the weights and biases in each iteration.

The direction to move is calculated using two partial derivatives:

this.updateWeights = function() {
  let wx;
  let w_deriv = 0;
  let b_deriv = 0;
  for (let i = 0; i < this.points; i++) {
    wx = this.yArr[i] - (this.weight * this.xArr[i] + this.bias);
    w_deriv += -2 * wx * this.xArr[i];
    b_deriv += -2 * wx;
  }
  this.weight -= (w_deriv / this.points) * this.learnc;
  this.bias -= (b_deriv / this.points) * this.learnc;
}

Create Your Own Library

Library Code

function Trainer(xArray, yArray) {
  this.xArr = xArray;
  this.yArr = yArray;
  this.points = this.xArr.length;
  this.learnc = 0.000001;
  this.weight = 0;
  this.bias = 1;
  this.cost;

// Cost Function
this.costError = function() {
  total = 0;
  for (let i = 0; i < this.points; i++) {
    total += (this.yArr[i] - (this.weight * this.xArr[i] + this.bias)) **2;
  }
  return total / this.points;
}

// Train Function
this.train = function(iter) {
  for (let i = 0; i < iter; i++) {
    this.updateWeights();
  }
  this.cost = this.costError();
}

// Update Weights Function
this.updateWeights = function() {
  let wx;
  let w_deriv = 0;
  let b_deriv = 0;
  for (let i = 0; i < this.points; i++) {
    wx = this.yArr[i] - (this.weight * this.xArr[i] + this.bias);
    w_deriv += -2 * wx * this.xArr[i];
    b_deriv += -2 * wx;
  }
  this.weight -= (w_deriv / this.points) * this.learnc;
  this.bias -= (b_deriv / this.points) * this.learnc;
}

} // End Trainer Object

Now you can include the library in HTML:

<script src="myailib.js"></script>