Skip to content

Instantly share code, notes, and snippets.

@kohnakagawa
Last active November 21, 2019 07:08
Show Gist options
  • Save kohnakagawa/c87eeb1cb0a066a42f71edadce9ccc4d to your computer and use it in GitHub Desktop.
Save kohnakagawa/c87eeb1cb0a066a42f71edadce9ccc4d to your computer and use it in GitHub Desktop.
const std = @import("std");
const ok = std.testing.ok;
fn inner_product(v1: [3]f32, v2: [3]f32) f32 {
var sum: f32 = 0.0;
for (v1) |v, i| {
sum += v * v2[i];
}
return sum;
}
fn step_function(v: f32) f32 {
if (v > 0.0) {
return 1.0;
}
return 0.0;
}
fn forward(v1: [3]f32, v2: [3]f32) f32 {
return step_function(inner_product(v1, v2));
}
fn train(v1: *[3]f32, v2: [3]f32, t: f32, e: f32) void {
const z = forward(v1.*, v2);
for(v1.*) |*v, i| {
v.* += (t - z) * v2[i] * e;
}
//for (v2) |v, i| {
// v1[i] += (t - z) * v * e;
//}
}
fn get_trained_weight(icont: *[4][3]f32, ocont: [4]f32) [3]f32 {
const e = 0.3;
var w = [3]f32{0.0, 0.0, 0.0};
const epoch = 20;
var i: u16 = 0;
while (i < epoch) {
for (icont) |v, j| {
train(&w, v, (ocont[j]), e);
}
i += 1;
}
return w;
}
test "comptime const" {
// comptime {
const a = [3]f32{1.0, 0.0, 0.0};
const b = [3]f32{1.0, 1.0, 0.0};
const c = [3]f32{1.0, 0.0, 1.0};
const d = [3]f32{1.0, 1.0, 1.0};
var x = [4][3]f32{a, b, c, d};
const t = [4]f32{0.0, 0.0, 0.0, 1.0};
const w = get_trained_weight(&x, t);
const v0 = forward(w, x[0]);
const v1 = forward(w, x[1]);
const v2 = forward(w, x[2]);
const v3 = forward(w, x[3]);
ok(v0 == 0.0);
ok(v1 == 0.0);
ok(v2 == 0.0);
ok(v3 == 1.0);
// }
}
@kohnakagawa
Copy link
Author

このままだと実行できるが、comptimeの部分のコメントを復活させると、実行できずコンパイルエラーになる。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment