首页 > 其他分享 >多项式回归模型(Office Prices)

多项式回归模型(Office Prices)

时间:2023-05-31 16:01:05浏览次数:52  
标签:res Office int 多项式 range Vector double Prices alpha

 

分析:还是上次的房价预测题目,指明要用多项式回归拟合。在多元多项式拟合时候,目标函数表示如下


    

多项式回归模型(Office Prices)_#include


     对其目标函数求偏导得到


     

多项式回归模型(Office Prices)_i++_02


     很容易写出代码。


代码:

#coding:utf-8

import math

class Data:
	def __init__(self):
		self.x = []
		self.y = 0.0

def makeMatrix(row, col, fill = 0.0):
	mat = []
	for i in range(row):
		mat.append([fill] * col)
	return mat

def WX(d, w, b):
	res = 0.0
	for k in range(len(d.x)):
		for j in range(b + 1):
			res += w[k][j] * math.pow(d.x[k], j)
	return res

def Gradient(d, w, f, b, alpha):
	for k in range(f):
		for j in range(b + 1):
			t1, t2 = 0.0, 0.0
			for i in range(len(d)):
				t1 += (WX(d[i], w, b) - d[i].y) * math.pow(d[i].x[k], j)
			w[k][j] -= alpha * t1

def getValues(d, w, b):
	res = 0.0
	for i in range(len(d)):
		tmp = WX(d[i], w, b)
		res += 0.5 * (d[i].y - tmp) * (d[i].y - tmp)
	return res

def Iterator(d, w, f, b):
	alpha = 0.003
	delta = 0.5
	oldVal = getValues(d, w, b)
	Gradient(d, w, f, b, alpha)
	newVal = getValues(d, w, b)
	while abs(oldVal - newVal) > delta:
		oldVal = newVal
		Gradient(d, w, f, b, alpha)
		newVal = getValues(d, w, b)

def main():
	while True:
		try:
			F, N = map(int, raw_input().split())
			d = []
			b = 5
			w = makeMatrix(F, b + 1)
			for i in range(0, N):
				t = Data()
				t.x = map(float, raw_input().split())
				t.y = t.x.pop()
				d.append(t)
			Iterator(d, w, F, b)
			N = int(raw_input())
			for i in range(0, N):
				t = Data()
				t.x = map(float, raw_input().split())
				print '%.2f'% WX(t, w, b)
		except EOFError:
			break

if __name__ == '__main__':
	main()


不过,上述代码得到的结果偏差比较大,需要重新考虑。除了上述方式外,还有一种特征组合方法效果不错。


代码:

#include <iostream>
#include <string.h>
#include <fstream>
#include <stdio.h>
#include <math.h>
#include <vector>
 
#define Vector vector
using namespace std;
 
struct Data
{
    Vector<double> x;
    double y;
};

double WX(const Data& d, const Vector<double>& w)
{
    double ans = 0;
    for(int i = 0; i < w.size(); i++)
        ans += w[i] * d.x[i];
    return ans;
}

void Gradient(const Vector<Data>& d, Vector<double> &w, double alpha)
{
    for(int i = 0; i < w.size(); i++)
    {
        double tmp = 0;
        for(int j = 0; j < d.size(); j++)
			tmp += alpha * d[j].x[i] * (WX(d[j], w) - d[j].y);
        w[i] -= tmp;
    }
}

double getValues(const Vector<Data>& d, Vector<double> w)
{
	double res = 0;
	for(int i = 0; i < d.size(); i++)
	{
		double tmp = WX(d[i], w);
		res += fabs(d[i].y - tmp);
	}
	return res;
}

void Iterator(const Vector<Data>& d, Vector<double> &w)
{
	double alpha = 0.3 / d.size();
	double delta = 0.5;
	double oldVal = getValues(d, w);  
	Gradient(d, w, alpha);  
	double newVal = getValues(d, w); 
	while(fabs(oldVal - newVal) > delta)
	{
		oldVal = newVal;
		Gradient(d, w, alpha);
		newVal = getValues(d, w);
	}
}

Vector<double> getFeatures(Vector<double> x)
{
	Vector<double> res;
	int n = x.size();
	for(int i = 0; i < n; i++)
		for(int j = i; j < n; j++)
			for(int k = j; k < n; k++)
				res.push_back(x[i] * x[j] * x[k]);
	return res;
}
 
int main()
{
	int F, N;
    Vector<double> w;
    Vector<Data> d;
    while(scanf("%d %d", &F, &N) != EOF)
	{
		d.clear();
		w.clear();
		int features = 0;
        for(int i = 0; i < N; i++)
		{
			Data t;
			double _x, _y;
			t.x.push_back(1);
			for(int j = 1; j <= F; j++)
			{
				scanf("%lf", &_x);
				t.x.push_back(_x);
			}
			t.x = getFeatures(t.x);
			features = t.x.size();
			scanf("%lf", &_y);
			t.y = _y;
			d.push_back(t);
		}
		for(int i = 0; i < features; i++)
			w.push_back(0);
		Iterator(d, w);
		d.clear();
		scanf("%d", &N);
		for(int i = 0; i < N; i++)
		{
			Data t;
			double _x;
			t.x.push_back(1);
			for(int j = 1; j <= F; j++)
			{
				scanf("%lf", &_x);
				t.x.push_back(_x);
			}
			t.x = getFeatures(t.x);
			printf("%.2lf\n", WX(t, w));
		}
	}
    return 0;
}


另外利用Python的机器学习开源库sklearn很方便处理。具体可以参考如下链接。


题解:http://blog.guozengxin.cn/2015/01/08/hackerrank-predicting-office-space-price/

sklearn官网:http://scikit-learn.org/stable/

sklearn源代码:https://github.com/scikit-learn/scikit-learn/


标签:res,Office,int,多项式,range,Vector,double,Prices,alpha
From: https://blog.51cto.com/u_16146153/6387824

相关文章

  • 基于FPGA的LFSR16位伪随机数产生算法实现,可以配置不同的随机数种子和改生成多项式,包
    1.算法仿真效果vivado2019.2仿真结果如下:2.算法涉及理论知识概要LFSR(线性反馈移位寄存器)提供了一种在微控制器上快速生成非序列数字列表的简单方法。生成伪随机数只需要右移操作和XOR操作。LFSR完全由其多项式指定。例如,6千-次多项式与每个项存在用方程x表示6+x5+x4+x3......
  • 求职必备技能:擅长Office
    本文首发自公粽hao「林行学长」,欢迎来撩,免费领取20个求职工具资源包。了解校招、分享校招知识的学长来了!今天学长在愉快地刷手机的时候,一则新闻热搜跳了出来:实习生说他熟练掌握Excel。学长嗅到了一丝搞笑的气息,点进去一看,果不其然这位实习生翻车得很离谱。这么一看,夸大的内容真是......
  • onlyoffice - docker 安装
    docker安装请参考这篇随笔【  https://www.cnblogs.com/c2g5201314/p/17440979.html  】1.安装docker安装onlyoffice镜像sudodockerpullonlyoffice/documentserver等待,直到出现 查看镜像,发现多了个 说明安装成功2.启动dockerrun-i-t-d-p8001:8......
  • 小灰灰机器学习day3——多项式拟合(最高项系数为2)
    importnumpyasnpTime=np.array([1,2,4,8,16,32,64])Temp=np.array([0,1,2,3,4,5,6])importmatplotlib.pyplotaspltplt.figure()plt.plot(Time,Temp,'bo')plt.xlabel("Time")plt.ylabel("Temp")plt.title(�......
  • 一元多项式的乘法与加法运算
    设计函数分别求两个一元多项式的乘积与和。输入格式:输入分2行,每行分别先给出多项式非零项的个数,再以指数递降方式输入一个多项式非零项系数和指数(绝对值均为不超过1000的整数)。数字间以空格分隔。输出格式:00。输入样例:434-5261-203520-7431输出样例:1......
  • 转载:PageOffice调用本地office实现多人在线同时编辑Word文档
    说明:多人同时在线编辑文件大多数会出现文档相互覆盖的问题,后保存的文档会覆盖先保存的文档。pageoffice的这个功能可以用程序控制不同用户打开文件后,编辑Word文档中属于自己的区域,并且不会互相影响。1、环境:前端:vue后端:springboot、pageoffice5.4.0.3版本vue+springboot集成......
  • 5-22|pywintypes.com_error: (-2147352567, '发生意外。', (0, 'Microsoft Office Exc
    pywintypes.com_error:(-2147352567,'发生意外。',(0,'MicrosoftOfficeExcel','Excel无法打开文件“pywintypes.com_error:(-2147352567,'发生意外。',(0,'MicrosoftOfficeExcel','Excel无法打开文件“价格(手工调整1).xlsx”,因为文件格式或文件扩展......
  • 用pageOffice控件实现 office word文档在线编辑 表格中写数据的方法
    PageOffice对Word文档中Table的操作,包括给单元格赋值和动态添加行的效果。1应用场景OA办公中,经常要在文档的指定位置表格,填充后端指定数据。如word文档中,表格数据如下表格中人员信息怎么把后端的关键数据,填充到word文档表格中呢?2实现方法文档中设置好书签,设置好表......
  • PHP用PhpOffice->PhpSpreadsheet导出excel
    phpexcel由于版本陈旧性能低下官方放弃维护转而开发PhpSpreadsheet用了最新得psr标准因而对php版本不向下兼容需要注意!。PhpSpreadsheet是一个用纯PHP编写的库,提供了一组类,使您可以读取和写入不同的电子表格文件格式PhpSpreadsheet提供了丰富的API接口,可以设置诸多单元格以及文......
  • day 36 多项式之和
     1.有数组a,a[i+1]=a[i]/(i+1);2.有数组b,b[i+1]=b[i]+a[i+1];3.输出b[49];  #include<iostream>usingnamespacestd;intmain(void){doublea[50],b[50];a[0]=b[0]=1;for(inti=0;i<50;i++){a[i+1]=a[i]/(i+1);b[i+1]=b[i]+a[i+1];......