LoginSignup
0
0

More than 5 years have passed since last update.

概要

cで、ニューラルネットワークやってみた。
sin問題やってみた。
cで、学習して、webで、表示してみた。

ライブラリー

写真

サンプルコード

学習して、ウェイトをjsonにする。

#include "catseye.h"

#define M_PI            3.1415926535

int main()
{
    int sample = 360;
    int u[] = {
        CATS_LINEAR, CATS_ACT_IDENTITY, 1, 1, 0, 0, 0, 500,
        CATS_LINEAR, CATS_ACT_SIGMOID, 1, 100, 0, 0, 0, 0,
        CATS_LINEAR, CATS_ACT_IDENTITY, 1, 1, 0, 0, 0, CATS_LOSS_MSE,
    };
    int layers = sizeof(u) / sizeof(int) / LPLEN;
    CatsEye cat;
    CatsEye__construct(&cat, 0, 0, layers, u);
    double x[sample];
    for (int i = 0; i < sample; i++) x[i] = 2.0 * M_PI / sample * i;
    double t[sample];
    for (int i = 0; i < sample; i++) t[i] = sin(x[i]);
    printf ("Starting training using (stochastic) gradient descent\n");
    CatsEye_train(&cat, x, t, sample, 2000, 0.01);
    printf ("Training complete\n");
    CatsEye_saveJson(&cat, "sin.json");
    CatsEye__destruct(&cat);
    return 0;
}

サンプルコード

学習した、ウェイトjsonを読み込んで、表示する。

var cat;
cat = new _CatsEye(w, u);
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
function run() {
    var hc = 220;    
    ctx.strokeStyle = "#f00";
    ctx.beginPath();
    ctx.lineWidth = 1;
    ctx.moveTo(0, hc);    
    for (var i = 0; i < 300; i++)
    {   

        var x = i;
        var y = Math.sin(i / 48);
        ctx.lineTo(x, hc - y * 200);
    }
    ctx.stroke();
    ctx.strokeStyle = "#0f0";
    ctx.beginPath();
    ctx.lineWidth = 1;
    ctx.moveTo(0, hc); 
    for (var i = 0; i < 300; i++)
    {   
        var x = i;
        var a = cat.forward([i / 48]);
        var y = cat.o[2][0];
        ctx.lineTo(x, hc - y * 200);
    }
    ctx.stroke();
}
run();

成果物

以上。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0