Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

# 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));
```
Why not register and get more from Qiita?
1. We will deliver articles that match you
By following users and tags, you can catch up information on technical fields that you are interested in as a whole
2. you can read useful information later efficiently
By "stocking" the articles you like, you can search right away