【发布时间】:2023-04-10 10:09:01
【问题描述】:
是否可以从 sklean 库中添加预测功能?又该怎么做呢?
def monomial(a,b):
return lambda x : a * math.pow(x,b)
返回形成所需阶多项式的单项式列表
def polyList(order):
return [monomial(1,i) for i in range(0,order+1)]
返回给定输入的函数总和
def evaluate(functionList, x):
return sum([f(x) for f in functionList])
返回加权和,即w0f0 + w1f1 +...
def weightedSum(w,F):
if(len(w) != len(F)):
raise Exception("Function/weight size mismatch")
else:
return lambda x:sum([w[i]*F[i](x) for i in range(0,len(w))])
############
在这里,我们用权重的最大似然估计拟合给定阶数的多项式。
def polyTrain(x,y,order):
#Initialize the weight vector and design matrix
w = [1 for i in range(0,order)]
F = polyList(order)
design = [[f(i) for f in F] for i in x]
#Convert them to numpy arrays
w = numpy.asarray(w)
design = numpy.asarray(design)
#We solve Ax=b, [x values x 3][coefficients]T = [yvalues]
pinv = numpy.linalg.pinv(design)
t = numpy.asarray(y).T
#We know that the ML estimates for w are w* = pinv(design)y.T
w = numpy.dot(pinv,t)
return weightedSum(w,F)
【问题讨论】:
标签: python python-3.x scikit-learn regression