搞了两天,到现在终于调通了~~~
其实很简单 但毕竟第一次用程序实现数学问题 昨天的Q15-17(PLA)还比较顺利 后来的pocket算法就一直搞不通(always the same value---0.297999/0.391 )
除了题意理解有偏差 后期程序肯定是哪个细节错了 换到笔记本上重写了一遍 很顺利啦 loop2000的情况下每次都在0.2的错误率以下噢
程序肯定是不优美的,刚刚起步,以后要学着用python写
<span style="font-family:Arial;font-size:14px;">#include<iostream>
#include<fstream>
#include<vector>
#include<queue>
#include<set>
#include<map>
#include<algorithm>
#include<cstdio>
#include<math.h>
#include<time.h>
#include<string.h>
#include<cstring>
#include<string>
using namespace std;
//ifstream fin("MLF_Feedback1.txt");
ifstream fin1("MLF_Feedback1_Q18_training set.txt");
ifstream fin2("MLF_Feedback1_Q18_test set.txt");
//#define cin fin
#define cin1 fin1
#define cin2 fin2
bool sign(float w[], float x[],int y)//传参时将train_set[i]和y[i]传给它(带着i)
{
float sum = 0;
for (int i = 0; i < 5; i++)
{
sum += w[i] * x[i];
}
if ((sum <= 0 && y>0) || (sum > 0 && y < 0)) return false;
else return true;
}
//float store[401][6];
float train_set[500][5], test_set[500][5];
int y[500], y2[500];
int cnt_mistakes(float ww[],float set[][5],int y[])
{
int cnt = 0;
for (int i = 0; i < 500; i++)
{
float sum = 0;
for (int j = 0; j < 5; j++)
sum += ww[j] * set[i][j];
if ((sum > 0 && y[i]<0) || (sum <= 0 && y[i]>0)){
cnt++;
// cout << "i: " << i << ", y: ";
// cout << y[i] << endl;
}
}
// cout << "errors: " << cnt << endl;
return cnt;
}
int main()
{
int i = 0;
for (; i < 500; i++)
{
train_set[i][0] = 1;
for (int j = 1; j < 5; j++)
cin1 >> train_set[i][j];
cin1 >> y[i];
}
i = 0;
for (; i < 500; i++)
{
test_set[i][0] = 1;
for (int j = 1; j < 5; j++)
cin2 >> test_set[i][j];
cin2 >> y2[i];
}
// float w[5] = { 0,-0.47,-0.4,-0.605,1.11 };
int loop = 2000, lp = loop;
float sum = 0;
while (loop--)
{
float w[5] = { 0 }, wp[5] = { 0 };
int msk_pocket = cnt_mistakes(w, train_set, y), msk_tmp = 0;
i = 0;
int update = 0;
// cout << "loop:" << lp - loop << endl;
srand(time(0));
while (update < 50)
{
if (!sign(w, train_set[i], y[i]))
{
for (int j = 0; j < 5; j++)
w[j] += y[i] * train_set[i][j];
msk_tmp = cnt_mistakes(w, train_set, y);
if (msk_tmp < msk_pocket)
{
for (int j = 0; j < 5; j++)
wp[j] = w[j];
msk_pocket = msk_tmp;
}
update++;
}
int d = rand() % 500;
// cout << "d = " << d << endl;
i += d;
i %= 500;
}
// cout << cnt_mistakes(wp, train_set,y) << endl;
// cout << cnt_mistakes(wp, test_set, y2) << endl;
float rate = (float)cnt_mistakes(wp, test_set, y2) / (float)500;
sum += rate;
}
cout << sum/lp << endl;
}</span>