# 10.3 实现逻辑异或门

## 10.3 实现逻辑异或门⚓︎

### 10.3.1 代码实现⚓︎

#### 准备数据⚓︎

• init() 初始化方法：因为父类的初始化方法要求有两个参数，代表train/test数据文件
• ReadData()方法：父类方法是直接读取数据文件，此处直接在内存中生成样本数据，并且直接令训练集等于原始数据集（不需要归一化），令测试集等于训练集
• GenerateValidationSet()方法，由于只有4个样本，所以直接令验证集等于训练集

class XOR_DataReader(DataReader):
self.XTrainRaw = np.array([0,0,0,1,1,0,1,1]).reshape(4,2)
self.YTrainRaw = np.array([0,1,1,0]).reshape(4,1)
self.XTrain = self.XTrainRaw
self.YTrain = self.YTrainRaw
self.num_category = 1
self.num_train = self.XTrainRaw.shape[0]
self.num_feature = self.XTrainRaw.shape[1]
self.XTestRaw = self.XTrainRaw
self.YTestRaw = self.YTrainRaw
self.XTest = self.XTestRaw
self.YTest = self.YTestRaw
self.num_test = self.num_train

def GenerateValidationSet(self, k = 10):
self.XVld = self.XTrain
self.YVld = self.YTrain


#### 测试函数⚓︎

def Test(dataReader, net):
print("testing...")
A = net.inference(X)
diff = np.abs(A-Y)
result = np.where(diff < 1e-2, True, False)
return True
else:
return False


#### 主过程代码⚓︎

if __name__ == '__main__':
......
n_hidden = 2
n_output = 1
eta, batch_size, max_epoch = 0.1, 1, 10000
eps = 0.005
hp = HyperParameters2(n_input, n_hidden, n_output, eta, max_epoch, batch_size, eps, NetType.BinaryClassifier, InitialMethod.Xavier)
net = NeuralNet2(hp, "Xor_221")
......


• n_input = dataReader.num_feature，值为2，而且必须为2，因为只有两个特征值
• n_hidden=2，这是人为设置的隐层神经元数量，可以是大于2的任何整数
• eps精度=0.005是后验知识，笔者通过测试得到的停止条件，用于方便案例讲解
• 网络类型是NetType.BinaryClassifier，指明是二分类网络
• 最后要调用Test函数验证精度

### 10.3.2 运行结果⚓︎

......
epoch=5799, total_iteration=23199
loss_train=0.005553, accuracy_train=1.000000
loss_valid=0.005058, accuracy_valid=1.000000
epoch=5899, total_iteration=23599
loss_train=0.005438, accuracy_train=1.000000
loss_valid=0.004952, accuracy_valid=1.000000
W= [[-7.10166559  5.48008579]
[-7.10286572  5.48050039]]
B= [[ 2.91305831 -8.48569781]]
W= [[-12.06031599]
[-12.26898815]]
B= [[5.97067802]]
testing...
1.0
None
testing...
A2= [[0.00418973]
[0.99457721]
[0.99457729]
[0.00474491]]
True


x1 x2 XOR Inference diff
0 0 0 0.0041 0.0041
0 1 1 0.9945 0.0055
1 0 1 0.9945 0.0055
1 1 0 0.0047 0.0047

ch10, Level1