Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package logic
- import java.util.Random
- class Perceptron {
- lateinit var weights : DoubleArray
- var threshold : Double = 0.0
- fun train(inputs: Array<DoubleArray>, outputs: IntArray, threshold: Double, lrate: Double, epoch: Int) {
- val r = Random()
- weights = DoubleArray(inputs[0].size,
- { _ -> r.nextDouble() })
- this.threshold = threshold
- val n = inputs[0].size
- val p = outputs.size
- for (i in 0 until epoch) {
- var totalError = 0
- for (j in 0 until p) {
- val output = calculate(inputs[j])
- val error = outputs[j] - output
- totalError += error
- for (k in 0 until n) {
- val delta = lrate * inputs[j][k] * error.toDouble()
- weights[k] += delta
- }
- }
- println(weights.toList());
- if (totalError == 0)
- break
- }
- }
- fun spla(inputs: Array<DoubleArray>, outputs: IntArray, threshold: Double, times: Int) {
- val r = Random()
- weights = DoubleArray(inputs[0].size + 1,
- { _ -> r.nextDouble() })
- this.threshold = threshold
- for (i in 0 until times) {
- val ind = r.nextInt(inputs.size)
- if (calculate(inputs[ind]) != outputs[ind]) {
- for (j in 0 until inputs[0].size) {
- weights[j+1] += inputs[ind][j] * outputs[ind].toDouble()
- }
- weights[0] += outputs[ind].toDouble()
- }
- val correctInputs = inputs.filterIndexed { index, input -> (calculate(input) == outputs[index]) }
- val correct = correctInputs.count()
- if (correct == inputs.size) {
- println("Break happend")
- break
- }
- println(weights.toList());
- }
- }
- // fun calculate(input: DoubleArray): Int {
- // val sum = input.indices.sumByDouble { weights[it] * input[it] }
- // return if (sum > threshold) 1 else 0
- // }
- fun calculate(input: DoubleArray): Int {
- val inputFixed = doubleArrayOf(1.0)+input
- val sum = inputFixed.indices.sumByDouble { weights[it] * inputFixed[it] }
- return if (sum > 0) 1 else -1
- }
- }
- fun main(args: Array<String>) {
- val p = Perceptron()
- val inputs = arrayOf(doubleArrayOf(0.0, 0.0), doubleArrayOf(0.0, 1.0), doubleArrayOf(1.0, 0.0), doubleArrayOf(1.0, 1.0))
- val outputs = intArrayOf(-1, -1, 1, -1)
- // p.train(inputs, outputs, 0.2, 0.2, 40_000)
- p.spla(inputs, outputs, 0.2,40000)
- println(p.calculate(doubleArrayOf(0.0, 0.0)))
- println(p.calculate(doubleArrayOf(0.0, 1.0)))
- println(p.calculate(doubleArrayOf(1.0, 0.0)))
- println(p.calculate(doubleArrayOf(1.0, 1.0)))
- }
Advertisement
Add Comment
Please, Sign In to add comment