开始接触机器学习,今天刚刚学习了感知机并用C++实现了算法。现在整理一下,与大家分享,希望能帮到刚刚入门机器学习的同学。
一、简单叙述一下感知机算法的原理
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int N = 5;
class data_set {
public:
data_set();
~data_set();
void set_x(const double x[2]);
void set_y(const double y);
double get_x0();
double get_x1();
double get_y();
private:
double x[2];
double y;
};
double w[2] = {0, 0}; //初始化参数
double b = 0;
int counts = 0, eta = 1;
data_set::data_set() {
this->x[0] = 0;
this->x[1] = 0;
this->y = 0;
}
data_set::~data_set() {
}
void data_set::set_x(const double x[2]) {
this->x[0] = x[0];
this->x[1] = x[1];
}
void data_set::set_y(const double y) {
this->y = y;
}
double data_set::get_x0() {
return this->x[0];
}
double data_set::get_x1() {
return this->x[1];
}
double data_set::get_y() {
return this->y;
}
int read_file_data(class data_set data[N], string file_name) {
ifstream open_file;
int i = 0;
open_file.open(file_name);
if (!open_file.is_open()) {
cout << "can not open " << file_name << endl;
return -1;
}
while (!open_file.eof()) {
double x[2] = {0};
double y = 0;
open_file >> x[0] >> x[1] >> y;
data[i].set_x(x);
data[i].set_y(y);
i++;
counts++;
cout << "x[0] = " << x[0] << ", x[1] = " << x[1] << ", y = " << y << endl;
}
open_file.close();
if (i == 0) {
return -1;
}
return 0;
}
int main(int argc, char *argv[]) {
class data_set data[N];
int i = 0;
bool flag = true;
int err = read_file_data(data, "test_data.txt");
if (err < 0) {
while (1);
return 0;
}
while (flag) {
for (i = 0; i < counts; i++) {
flag = false;
if (data[i].get_y() * (data[i].get_x0() * w[0] + data[i].get_x1() * w[1] + b) <= 0) {
flag = true;
w[0] = w[0] + eta * data[i].get_y() * data[i].get_x0();
w[1] = w[1] + eta * data[i].get_y() * data[i].get_x1();
b = b + eta * data[i].get_y();
break;
}
}
}
cout << "w[0] = " << w[0] << ", w[1] = " << w[1] << ", b = " << b << endl;
while (1);
return 0;
}
网友评论