利用深度学习的感知器算法实现AND(与)操作
感知器类头文件:
#include <vector>
#include <iostream>
using namespace std;
class Perceptron//感知器
{
public:
Perceptron(){}
Perceptron(const vector<vector<double>> &input, const int times, const double rate);
double UsePerceptron(const vector<double> &input);//使用生成的权值进行计算
void CheckWeight();//打印权值
private:
vector<double> weightOutput;//计算出的权值向量
double bias;//偏置量
double Func(double x);//激活函数(阶跃函数)
};
感知器类实现文件:
#include "Perceptron.h"
Perceptron::Perceptron(const vector<vector<double>> &input, const int times, const double rate)
{
int sampleNum = input.size();//共有多少组数据
int weightNum = input[0].size() - 1;//每组数据自变量个数(最后一个为该组结果)
for (int i = 0; i < weightNum; i++)
{
weightOutput.push_back(0);
}
bias = 0;//初始化
for (int trainNum = 0; trainNum < times; trainNum++)//训练次数
{
for (int i = 0; i < sampleNum; i++)
{
double sum = bias;
for (int j = 0; j < weightNum; j++)
{
sum += input[i][j] * weightOutput[j];
}
sum = Func(sum);//每次迭代的结果
sum = input[i][weightNum] - sum;//与真实值的差
for (int j = 0; j < weightNum; j++)
{
weightOutput[j] += rate*sum*input[i][j];
}
bias += rate*sum;//更新权值
}
}
}
double Perceptron::Func(double x)//激活函数
{
if (x > 0)
return 1;
else
return 0;
}
double Perceptron::UsePerceptron(const vector<double> &input)
{
double output = bias;
for (unsigned int i = 0; i < input.size(); i++)
output += input[i] * weightOutput[i];
return Func(output);
}
void Perceptron::CheckWeight()
{
for (unsigned i = 0; i < weightOutput.size(); i++)
cout << "W: "<<weightOutput[i] << " " << endl;
cout << "bias: "<<bias << endl;
}
主函数测试感知器:
#include <iostream>
#include "Perceptron.h"
using namespace std;
int main()
{
vector<vector<double>> AND = {
{ 0, 0, 0 },
{ 0, 1, 0 },
{ 1, 0, 0 },
{ 1, 1, 1 }
};
Perceptron Cand(AND, 10, 0.1);
Cand.CheckWeight();
vector<double> test = { 1, 1 };
cout << Cand.UsePerceptron(test) << endl;
}
结果显示: