Coursera课程-机器学习基石作业一Q18-Q20(pocket on D算法 for PLA/C++ edition)

1 篇文章 0 订阅
1 篇文章 0 订阅

搞了两天,到现在终于调通了~~~

其实很简单微笑 但毕竟第一次用程序实现数学问题 昨天的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>




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值