1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
|
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import random
import math
from scipy.linalg import expm, sinm, cosm
name_file = './data_ffnn_3classes.txt'
columns = ['x1', 'x2', 'y']
data_in = pd.read_csv(name_file,
names=columns,
sep='\t',
skiprows=1)
x1 = np.asarray(data_in['x1'])
x2 = np.asarray(data_in['x2'])
y = np.asarray(data_in['y'])
plt.figure(1)
colors = ['red','green','blue']
plt.scatter(x1, x2, c=y, cmap=matplotlib.colors.ListedColormap(colors))
def sigmoid(matrice):
result = (1 + np.exp(np.negative(matrice)))
return result
def SSE(gg, yy):
erreur = 0
erreur = (1/2) * sum([((gg[i][j]-yy[i])**2) for i in range(gg.shape[0]) for j in range(gg.shape[1])])
return erreur
K = 2
v = np.random.uniform(low=0, high=1, size=(3,K))
w = np.random.uniform(low=0, high=1, size=((K+1),1))
x = np.c_[x1,x2]
x_barre = np.c_[np.ones(x.shape[0]), x]
x_barre_barre = np.dot(x_barre,v)
f = np.reciprocal(sigmoid(x_barre_barre))
f_barre = np.c_[np.ones(f.shape[0]), f]
f_barre_barre = np.dot(f_barre,w)
g = np.reciprocal(sigmoid(f_barre_barre))
erreur_SSE = SSE(g,y)
print("SSE error : " + str(erreur_SSE))
def BGD(X, gg, yy, fbarre, v, w, f, Xbarre):
#On initilise theta
iterations = 6500
optiv = v
optiw = w
ve = v
we = w
ve2 = v
we2 = w
erreurs = list()
learning_ratev = 0.00742
learning_ratew = 0.00742
g = yy
f_barre = fbarre
ff = f
x_barre = Xbarre
abscisses = [i for i in range (iterations)]
for i in range(0, iterations):
#print(gg.shape)
x_barre_barre = np.dot(x_barre,ve)
ff = np.reciprocal(sigmoid(x_barre_barre))
f_barre = np.c_[np.ones(ff.shape[0]), ff]
f_barre_barre = np.dot(f_barre,we)
g = np.reciprocal(sigmoid(f_barre_barre))
d_Ew = sum([((g[l]-yy[l])* g[l]*(1-gg[l])* f_barre[l]) for l in range(0,g.shape[0]) ])
d_Ev = sum([(((g[l]-yy[l])*g[l]*(1-gg[l])*we[k]*ff[l]*(1-ff[l])*x_barre[l][k])) for l in range(0,g.shape[0]) for k in range (0,2)])
for o in range (1,we.shape[1]):
we = we2- (learning_rate * d_Ew)
ve = ve2- (learning_ratew)* d_Ev
ve2=ve
we2=we
erreur = SSE( g,yy)
erreurs.append(erreur)
toutG = g
optiv = ve
optiw = we
if i%500==0:
print("Itération [" + str(i)+ "] : Erreur = " + str(erreur))
plt.figure(20)
plt.plot(abscisses, erreurs, label = "Evolution de l'erreur")
plt.xlabel('Iteration')
plt.ylabel('Error')
plt.legend()
return toutG, optiv, optiw
gai, optiv, optiw = BGD(x, g, y, f_barre,v, w, f, x_barre)
colors = ['red','green','blue']
plt.figure(2)
plt.scatter(x1, x2, c=gai, cmap=matplotlib.colors.ListedColormap(colors)) |
Partager