5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ゼロから作るDeep Learning Java編 第2章 パーセプトロン

Last updated at Posted at 2018-02-27

目次

#2.3 パーセプトロンの実装

##2.3.1 簡単な実装

パーセプトロンは関数(静的メソッド)として実装できます。

public static int AND(int x1, int x2) {
    double w1 = 0.5, w2 = 0.5, theta = 0.7;
    double tmp = x1 * w1 + x2 * w2;
    if (tmp <= theta)
        return 0;
    else
        return 1;
}
assertEquals(0, AND(0, 0));
assertEquals(0, AND(1, 0));
assertEquals(0, AND(0, 1));
assertEquals(1, AND(1, 1));

##2.3.2 重みとバイアスの導入

ND4Jを使うと以下のようになります。

INDArray x = Nd4j.create(new double[] {0, 1});
INDArray w = Nd4j.create(new double[] {0.5, 0.5});
double b = -0.7;
assertEquals("[0.00,0.50]", Util.string(w.mul(x)));
assertEquals(0.5, w.mul(x).sumNumber().doubleValue(), 0.000005);
assertEquals(-0.19999999999999996, w.mul(x).sumNumber().doubleValue() + b, 0.000005);

##2.3.3 重みとバイアスによる実装

「重みとバイアスによる方式」を用いれば、AND、NDND、ORゲートは次のように実装できます。

public static int AND2(int x1, int x2) {
    INDArray x = Nd4j.create(new double[] {x1, x2});
    INDArray w = Nd4j.create(new double[] {0.5, 0.5});
    double b = -0.7;
    double tmp = w.mul(x).sumNumber().doubleValue() + b;
    return tmp <= 0 ? 0 : 1;
}

public static int NAND(int x1, int x2) {
    INDArray x = Nd4j.create(new double[] {x1, x2});
    INDArray w = Nd4j.create(new double[] {-0.5, -0.5});
    double b = 0.7;
    double tmp = w.mul(x).sumNumber().doubleValue() + b;
    return tmp <= 0 ? 0 : 1;
}

public static int OR(int x1, int x2) {
    INDArray x = Nd4j.create(new double [] {x1, x2});
    INDArray w = Nd4j.create(new double[] {0.5, 0.5});
    double b = -0.2;
    double tmp = w.mul(x).sumNumber().doubleValue() + b;
    return tmp <= 0 ? 0 : 1;
}
assertEquals(0, AND2(0, 0));
assertEquals(0, AND2(1, 0));
assertEquals(0, AND2(0, 1));
assertEquals(1, AND2(1, 1));
assertEquals(1, NAND(0, 0));
assertEquals(1, NAND(1, 0));
assertEquals(1, NAND(0, 1));
assertEquals(0, NAND(1, 1));
assertEquals(0, OR(0, 0));
assertEquals(1, OR(1, 0));
assertEquals(1, OR(0, 1));
assertEquals(1, OR(1, 1));

#2.5 多層パーセプトロン

##2.5.2 XORゲートの実装

パーセプトロンを多層にするとXORゲートが実装できます。

public static int XOR(int x1, int x2) {
    int s1 = NAND(x1, x2);
    int s2 = OR(x1, x2);
    int y = AND2(s1, s2);
    return y;
}
assertEquals(0, XOR(0, 0));
assertEquals(1, XOR(1, 0));
assertEquals(1, XOR(0, 1));
assertEquals(0, XOR(1, 1));
5
3
1

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
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?