# 2020-04-06 | IA | Perceptron ###### tags: `swift` `ia` `gobelins` ## Import ``` import Foundation ``` ## Class Perceptron ### Variables et constructeur ``` class Perceptron { var weights:[Double] var bias:Double = 0.01 init(nbInput:Int) { weights = [] for i in 0..<nbInput { weights.append(0.0) } } } ``` ### Fonction Predict ``` func predict(nbInput:[Double]) -> Double { var result: Double = 0.0 for i in 0..<nbInput.count { result += nbInput[i] * self.weights[i] } var sumOfProducts:Double = result + bias // print (sumOfProducts) return activate(sum:sumOfProducts) } ``` ### Fonction Activate ``` func activate(sum:Double) -> Double { if sum <= 0 { return 0 } else { return 1 } } ``` ### Fonction Train ``` // dataSet = tableau de tuple // 1er => données // 2eme => result // lr = learningRate func train(dataSet[([Double],Double)],epoch:Int,lr:Double){ for ep in 0..<epoch { for data in dataSet { let pred = self.predict(nbInput:data.0) let error = data.1 - pred var inputError = [Double]() for entry in data.0 { inputError.append(entry * error) } // Mettre à jour les poids for i in 0..<inputError.count { weights[i] += inputError[i] * lr } // Mettre à jour le biais bias += error * lr } } } ``` ## Call ``` let perceptron = Perceptron(nbInput:3) print("Before training :") print(perceptron.predict(nbInput:[1.0,0.3,4.0])) print(perceptron.predict(nbInput:[0.0,0.5,1.0])) // Création du dataset let dataset = [([1.0,0.3,4.0],0.0),([0.0,0.5,1.0],0.0)] // Training perceptron.train(dataSet:dataset,epoch:6,lr:0.01) // Test print("After training :") print(perceptron.predict(nbInput:[1.0,0.3,4.0])) print(perceptron.predict(nbInput:[0.0,0.5,1.0])) ``` ## Result ``` Before training : 1.0 1.0 After training : 0.0 0.0 ```