題目:
分析:還是上次的房價**題目,指明要用多項式回歸擬合。在多元多項式擬合時候,目標函式表示如下
對其目標函式求偏導得到
很容易寫出**。
**:
#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):
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()
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 #include #include #include #include #include #define vector vector
using namespace std;
struct data
;double wx(const data& d, const vector& w)
void gradient(const vector& d, vector&w, double alpha)
}double getvalues(const vector& d, vectorw)
return res;
}void iterator(const vector& d, vector&w)
}vectorgetfeatures(vectorx)
int main()
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++)
t.x = getfeatures(t.x);
printf("%.2lf\n", wx(t, w));
} }return 0;
}
另外利用python的機器學習開源庫sklearn很方便處理。具體可以參考如下鏈結。
題解:
sklearn官網:
sklearn源**:
TensorFlow 多項式回歸模型
import numpy as np import tensorflow as tf import matplotlib.pyplot as plt plt.rcparams figure.figsize 14,8 視覺化的時候設定的長和寬 n observations 100 樣本點的個數 xs ...
多項式回歸
import numpy as np import matplotlib.pyplot as plt x np.random.uniform 3,3,size 100 x x.reshape 1,1 y 0.5 x 2 x 2 np.random.normal 0,1,100 plt.scatter...
多項式回歸
多項式回歸 import torch import numpy defmake features x 獲取 x,x 2,x 3 的矩陣 x x.unsqueeze 1 將一維資料變為 n,1 二維矩陣形式 return torch.cat x i for i in range 1 4 1 按列拼接 ...