Last active
February 22, 2020 00:36
-
-
Save mariogarcia-ar/68a75bc588d7a4cab382bd8f0a0d94f0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import numpy as np | |
def predict(x,theta,theta_0=None): | |
''' | |
Funcion de prediccion | |
x un vector del training example | |
theta es el vector normal al plano | |
theta_0 es el offset | |
retorna el dot product o inner product | |
''' | |
if theta_0 is None : | |
theta_0=0 | |
return np.dot(x, theta) + theta_0 | |
# test predict | |
#t=[-1,-1]; x=[-1,-1]; print(predict(t,x)) | |
#t=[-1,-1]; x=[10,2]; print(predict(t,x)) | |
def run(theta,theta_0, X, Y, start=1, T=10): | |
''' | |
Funcion de ejecucion del Perceptron | |
Itera mostrando los sucesivos valores de theta | |
theta es el vector normal al plano | |
theta_0 es el offset (no lo uso por ahora) | |
X matrix con los training examples | |
Y matrix con los labels | |
T cantidad de iteraciones | |
retorna el theta optimo | |
''' | |
num_rows, num_cols = X.shape | |
print("\n\n****************************\nPerceptron by Mario :) \n****************************") | |
print(theta, "<----- Theta Inicial") | |
print("Arranco en el punto ",start) | |
t = 0 | |
total_thetas = 0 | |
# itero T veces | |
while t < T: | |
t += 1 | |
print("\n-------------------\nIteration ", t , "\n-------------------") | |
i = start - 1 # arranco por el punto que definieron, es menos 1 por el indice del array de python | |
# itero por cada punto | |
for k in range(num_rows): | |
#print("paso por punto ", i+1) | |
if Y[i] * predict( X[i], theta, theta_0 ) <= 0 : | |
# actualizo theta | |
theta = np.add( theta, Y[i] * X[i] ) | |
theta_0 = theta_0 + Y[i] | |
total_thetas += 1 | |
print("\n", theta, "<----- Nueva Theta \n", theta_0, " <----- Nueva Theta_0 \n Nro de Actualizacion #", total_thetas, " en el punto x",i+1) #, " Nota: clasifico mal al punto") | |
i += 1 | |
i %= num_rows # para que no se pase de ese | |
print("\n\n\n\n" ,"Theta Optima ", theta,"\n Theta_0 Optima ", theta_0) | |
print( " Cantidad de actualizaciones", total_thetas) | |
return (theta, theta_0) | |
# print(theta, theta_0) | |
# ------------------------------------------------------------- | |
X = np.array([[-4,2],[-2,1],[-1,-1],[2,2],[1,-2]]) | |
Y = np.array([1,1,-1,-1,-1]) | |
# para el 1b | |
# arranca como theta inicial en origen | |
theta = [0,0] | |
theta_0 = 0 | |
start = 1 | |
run(theta, theta_0, X, Y, start) | |
### para el 2b | |
#theta = [-4,2] | |
#theta_0 = -3 | |
#start = 1 | |
#run(theta, theta_0, X, Y, start) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment