这是我的代码:
import numpy as np
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline
X_arr = []
Y_arr = []
with open('input.txt') as fp:
for line in fp:
b = line.split("|")
x,y = b
X_arr.append(int(x))
Y_arr.append(int(y))
X=np.array([X_arr]).T
print(X)
y=np.array(Y_arr)
print(y)
model = make_pipeline(PolynomialFeatures(degree=2),
LinearRegression(fit_intercept = False))
model.fit(X,y)
X_predict = np.array([[3]])
print(model.predict(X_predict))
请,我有一个问题:
model = make_pipeline(PolynomialFeatures(degree=2),
请,我该如何选择该值(2或3或4等)?有没有一种方法可以动态设置此值?
例如,我有以下测试文件:
1 1
2 4
4 16
5 75
对于前三行,模型是
y=a*x*x+b*x + c (b=c=0)
对于最后一行,模型是:
y=a*x*x*x+b*x+c (b=c=0)
答案 0 :(得分:0)
这绝不是解决问题的万无一失的方法,但我想我理解您想要的,也许是:
import math
epsilon = 1e-2
# Do your error checking on size of array
...
# Warning: This only works for positive x, negative logarithm is not proper.
# If you really want to, do an `abs(X_arr[0])` and check the degree is even.
deg = math.log(Y_arr[0], X_arr[0])
assert deg % 1 < epsilon
for x, y in zip(X_arr[1:], Y_arr[1:]):
if x == y == 1: continue # All x^n fits this and will cause divide by 0
assert abs(math.log(y, x) - deg) < epsilon
...
PolynomialFeature(degree=int(deg))
这将检查度数是否为整数值,以及所有其他数据点是否都适合同一多项式。
这纯粹是一种试探法。如果您有大量(1,1)的数据点,则无法确定实际的度数。在没有任何数据假设的情况下,您无法确定多项式x ^ n的次数。
这只是您如何实现这种启发式的示例,请不要在生产中使用此。