Advertisement
Guest User

Untitled

a guest
Jun 18th, 2019
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. '''
  2. Nome: Gabriel Gomes Cruz da Rocha
  3. Matricula: 201407708
  4. Atividade_-_Adaline
  5. '''
  6.  
  7. import random
  8. import numpy as np
  9. import matplotlib.pyplot as plt
  10. import math
  11.  
  12. def ufunction(X, w, b, i):
  13.  
  14. U = 0
  15.  
  16. for j in range(0,2):
  17. U = U + (w[j] * X[i][j])
  18. U = U + b
  19.  
  20. return U
  21.  
  22. def activation(U):
  23.  
  24. return math.tanh(U)
  25.  
  26. def updatew(w, a, e, X, i):
  27.  
  28. for j in range(0,2):
  29. w[j] = w[j] + (a * e[i] * X[i][j])
  30.  
  31. def erro( X, w, b, d):
  32.  
  33. aux = 0
  34. Y1 = np.zeros(4)
  35. e1 = np.zeros(4)
  36.  
  37. for i in range(4):
  38. Y1[i] = activation(ufunction(X, w, b, i))
  39. e1[i] = d[i] - Y1[i]
  40. aux = aux + pow(e1[i], 2)
  41.  
  42. return aux/4
  43.  
  44. def plotar(w1, w2, bias, title):
  45.  
  46. xvals = np.arange(-1, 3, 0.01)
  47. newyvals = (((xvals * w2) * - 1) - bias) / w1
  48. plt.plot(xvals, newyvals, 'r-')
  49. plt.title(title)
  50. plt.xlabel('X1')
  51. plt.ylabel('X2')
  52. plt.axis([-1,2,-1,2])
  53. plt.plot([0,1,0],[0,0,1], 'b^')
  54. plt.plot([1],[1], 'go')
  55. plt.xticks([0,1])
  56. plt.yticks([0,1])
  57. plt.show()
  58.  
  59. def perceptron(max_int, E, a, X, d):
  60.  
  61. w = [random.random(), random.random()]
  62. b = random.random()
  63. t = 1
  64. print("Valores Iniciais: W1 = %.4f" %w[0] ,"W2 = %.4f" %w[1] ,"bias = %.4f" %b)
  65.  
  66. Y = np.zeros(4)
  67. e = np.zeros(4)
  68. deltaMSE = 1
  69.  
  70. while(t < max_int and deltaMSE > E):
  71. MSEinicial = erro( X, w, b, d)
  72.  
  73. for i in range(0,4):
  74. Y[i] = activation(ufunction(X, w, b, i))
  75. e[i] = d[i] - Y[i]
  76. updatew(w, a, e, X, i)
  77. b = b + (a * e[i])
  78.  
  79. MSEfinal = erro(X, w, b, d)
  80. deltaMSE = MSEfinal - MSEinicial
  81. t = t + 1
  82.  
  83. print("Valores Finais: W1 = %.4f" %w[0] ,"W2 = %.4f" %w[1] ,"bias = %.4f" %b)
  84.  
  85. return(w, b)
  86.  
  87. def main():
  88.  
  89. max_int = 100
  90. E = 0.0000001
  91. alpha = 0.1
  92. X = [[0,0],[0,1],[1,0],[1,1]]
  93. d = [-1, -1, -1, 1]
  94.  
  95. w, b = perceptron(max_int, E, alpha, X, d)
  96.  
  97. plotar(w[0], w[1], b, "Porta lógica AND com Adaline")
  98.  
  99. if __name__ == "__main__":
  100. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement