是否可以从sklean库中添加类似predict的函数?怎么做呢
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)
如果您定义一个类来处理您想要的所有逻辑,那就更好了。不过,如果你愿意 要编写完全符合fit-transform-predict协议(在sciket-learn中使用)的代码,您需要 从某个基中划分子类 scikit学习的类,例如BaseEstimator、TransformerMixin、BaseRegressor
Numpy提供了非常方便的函数vander,可以极大地帮助您 当你使用多项式的时候
让我们定义一个类
根据您的需要采用代码。希望有帮助
相关问题 更多 >
编程相关推荐