Skip to content

Instantly share code, notes, and snippets.

func activate(bias: Double, bW: Double, x: [Double], w: [Double]) -> Int {
var sum = 0.0
for i in 0..<x.count {
sum += x[i] * w[i]
}
sum += bias * bW
return step(sum)
}
class Perceptron {
var bias: Double
// weights[0] is the weight for the bias input
var weights: [Double]
init(numInputs: Int, bias: Double) {
self.bias = bias
self.weights = [Double]()
mutating func backProp(input: [Double], output: Int) {
let prediction = feedForward(input)
let error = output - prediction
for i in 0..<weights.count {
weights[i] += learningRate * Double(error) * input[i]
}
}
struct PerceptronTrainer {
let data: [PerceptronDataPair]
func train(inout p: Perceptron) -> Int {
var error: Int = 0
for d in data {
error = p.backProp(d.input, output: d.output)
}
return error
}
func randomDouble() -> Double {
return Double(arc4random()) / Double(UINT32_MAX)
}
func createData(numPoints: Int) -> [PerceptronDataPair] {
var data = [PerceptronDataPair]()
for _ in 0..<numPoints {
let x = [2.0 * (randomDouble() - 0.5)]
let y = line(x[0])
let testData = createData(100)
func evaluatePerceptron(p: Perceptron, testData: [PerceptronDataPair]) -> Double {
var correct = 0
for d in testData {
let prediction = p.feedForward(d.input)
if (prediction == d.output) {
correct += 1
}
}
func sign(z: Double) -> Int {
// Note that 0 is not considered positive or negative
return (z > 0) ? 1 : -1
}
@klgraham
klgraham / hello-luajit.c
Last active May 20, 2024 07:10
A simple example of embedding LuaJIT in C
#include <stdio.h>
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
#include "luajit.h"
int main(int argc, char *argv[])
{
int status;
lua_State *L;
@klgraham
klgraham / factorial-luajit.c
Last active April 9, 2023 21:02
Example of using Lua C API to call a Lua function from C
#include <stdio.h>
#include <stdlib.h>
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
#include "luajit.h"
int main(int argc, char *argv[])
{
lua_State *L;
@klgraham
klgraham / StringReversal.java
Created August 6, 2016 02:16
Recursive string reversal
package org.klgraham;
/**
* Created by klogram on 8/5/16.
*/
public class StringReversal {
public static String reverseStringIterative(final String s) {
StringBuilder sb = new StringBuilder();