Skip to content

Instantly share code, notes, and snippets.

@KatagiriSo
Created October 24, 2017 03:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KatagiriSo/040d5a6729497559b443521a5b9c4df5 to your computer and use it in GitHub Desktop.
Save KatagiriSo/040d5a6729497559b443521a5b9c4df5 to your computer and use it in GitHub Desktop.
perceptron code
//
// RDPerceptron.swift
// RDPerceptronSwift
//
// Created by KatagiriSo on 2017/10/24.
// Copyright © 2017年 RodhosSoft. All rights reserved.
//
import Foundation
func *(left:[Float], right:[Float]) -> Float {
return zip(left,right).reduce(0.0) {
$0.0 + $0.1.0 * $0.1.1
}
}
func step(_ x:Float) -> Float {
return x>0 ? 1:0
}
func foward(input:[Float], weight:[Float]) -> Float {
let u = weight * input;
return step(u)
}
func train(weight:[Float], input:[Float], t:Float, e:Float) -> [Float] {
let z = foward(input: input, weight: weight)
let output_w = zip(weight, input).map { $0.0 + (t - z) * $0.1 * e }
return output_w
}
func string(weight:[Float]) -> String {
let desc = weight.enumerated().reduce("") { $0.0 + "w\($0.1.offset) " + "\($0.1.element) " }
return desc
}
func learning(weight:[Float],input:[[Float]], t:[Float], e:Float) -> [Float] {
let w = zip(input, t).enumerated().reduce(weight) {
let tmpw = train(weight: $0.0, input: $0.1.element.0, t: $0.1.element.1, e: e)
return tmpw
}
return w
}
func learning(weight:[Float],input:[[Float]], t:[Float], e:Float, times:Int) -> [Float] {
var w = weight
(1...times).forEach {epoch in
w = learning(weight: w, input: input, t: t, e: e)
print("epoch \(epoch) \(string(weight:w))")
}
return w
}
func test() {
let x:[[Float]] = [[1.0,0.0,0.0], [1.0,0.0,1.0], [1.0,0.0,1.0], [1.0,1.0,1.0]]
let t:[Float] = [0.0,0.0,0.0,1.0, 0.0, 0.0, 1.0]// and
let w:[Float] = [0.0,0.0,0.0]
let e:Float = 0.1
let res_w = learning(weight: w, input: x, t: t, e: e, times:10)
check(weight: res_w)
}
func check(weight:[Float]) {
let x:[[Float]] = [[1.0,0.0,0.0], [1.0,0.0,1.0], [1.0,0.0,1.0], [1.0,1.0,1.0]]
let t:[Float] = [0.0,0.0,0.0,1.0, 0.0, 0.0, 1.0]// and
print("check")
let ans = x.map { foward(input: $0, weight: weight) }
zip(x,zip(ans,t)).forEach{
print(string(weight: $0.0))
print("pc ans \($0.1.0) correct ans \($0.1.1) \($0.1.0==$0.1.1 ? "ok":"ng")")
}
let correct = zip(ans,t).filter { $0.0 == $0.1 }.count
let all = ans.count
let p = Float(correct)/Float(all)
print("result = \(correct)/\(all) = \(p)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment