感知機算法理解與C++實現(xiàn)

????????開始接觸機器學(xué)習(xí),今天剛剛學(xué)習(xí)了感知機并用C++實現(xiàn)了算法?,F(xiàn)在整理一下,與大家分享,希望能幫到剛剛?cè)腴T機器學(xué)習(xí)的同學(xué)。

? ? ? ? ? ? ? ? ? ?一、簡單敘述一下感知機算法的原理

#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};? //初始化參數(shù)

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;

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容