C/C++感知机实现简单逻辑电路

感知机算法是深度学习的基础。
感知机(Perceptron)定义 : 二类分类的线性分类模型,其输入为实例的特征向量,输出为实例的类别。
我们使用C/C++实现简单的逻辑门电路 :

#include <iostream>

using namespace std;

class Perceptron {
    
    
	public:
		int AND(int x1, int x2); //与门 
		int NAND(int x1, int x2);//与非门 
		int OR(int x1, int x2);  //或门 
		int XOR(int x1, int x2); //异或门
};

int Perceptron::AND(int x1, int x2) {
    
    
	//与门:任一输入为 0 时,则输出为 0 	
	double w1 = 0.5, w2 = 0.5;//权重
	double theta = 0.7;       //阈值
	
	double tmp = (x1 * w1) + (x2 * w2); 
	
	return tmp > theta ? 1 : 0;
}

int Perceptron::NAND(int x1, int x2) {
    
    
	//与非门:任一输入为 0 时, 则输出不为 0 
	double w1 = -0.5, w2 = -0.5;//权重
	double theta = -0.7;       //阈值
	
	double tmp = (x1 * w1) + (x2 * w2); 
	
	return tmp > theta ? 1 : 0;
}

int Perceptron::OR(int x1, int x2) {
    
    
	//或门:任一输入为 1 时,则输出为 1 	
	double w1 = 0.5, w2 = 0.5;//权重
	double theta = 0.2;       //阈值
	
	double tmp = (x1 * w1) + (x2 * w2); 
	
	return tmp > theta ? 1 : 0;
}

int Perceptron::XOR(int x1, int x2) {
    
    
	//异或门:仅当某一输出为 1 时,则输出为 1 
	//异或门表达式图像分割为非线性空间,需要通过多层感知机实现 
	int s1 = NAND(x1, x2);
	int s2 = OR(x1, x2);
	int res = AND(s1, s2);
	
	return res;
}

void test(int (Perceptron::*p)(int x1, int x2)) {
    
    
	//测试感知机是否正常
	Perceptron tmp;
	
	cout << (tmp.*p)(0, 0) << endl; 
	cout << (tmp.*p)(1, 0) << endl;
	cout << (tmp.*p)(0, 1) << endl;
	cout << (tmp.*p)(1, 1) << endl;
} 

int main() {
    
    
	Perceptron per;
	
	cout << "与门" << endl; 
	test(&per.AND);
	cout << "与非门" << endl; 
	test(&per.NAND);
	cout << "或门" << endl; 
	test(&per.OR);
	cout << "异或门" << endl; 
	test(&per.XOR);
	
	return 0;
} 

运行结果:

与门
0
0
0
1
与非门
1
1
1
0
或门
0
1
1
1
异或门
0
1
1
0

在感知机的可视化中, 与门, 与非门, 或门的表达式图形经过分割为线性空间, 所以他们的感知机实现结构是一样的, 只是其中的权重与阈值不同而已 (如上述代码所示) .
但是异或门却是非线性空间, 无法像与门, 与非门, 或门一样使用单层感知机实现, 但我们可以通过感知机叠加, 使用多层感知机实现(如上述代码所示) .

异或门逻辑电路图 :
在这里插入图片描述

毕。

猜你喜欢

转载自blog.csdn.net/weixin_45711556/article/details/108917625
今日推荐