Home > Mobile >  Predicting future x values using polynomial regression
Predicting future x values using polynomial regression

Time:02-01

I have made a function to predict a future y value using polynomial Regression. I need to make a function to predict a future x value how would I go about doing this? This is what I have for y:

def predict_y():
    """Now we can use the information we have gathered to predict future values."""
    import numpy

    x = [1, 2, 3, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 18, 19, 21, 22]
    y = [100, 90, 80, 60, 60, 55, 60, 65, 70, 70, 75, 76, 78, 79, 90, 99, 99, 100]

    my_model = numpy.poly1d(numpy.polyfit(x, y, 3))
    y_value = my_model(17)  # 17 is time of day

    print("y :", y_value)

CodePudding user response:

Maybe you can use np.roots?

import numpy as np

x = np.array([1, 2, 3, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 18, 19, 21, 22])
y = np.array([100, 90, 80, 60, 60, 55, 60, 65, 70, 70, 75, 76, 78, 79, 90, 99, 99, 100])

def predict_x(yn):
    roots = np.roots(np.polyfit(x, y - yn, deg=3))
    reals = abs(roots.imag) < 1e-6
    return roots.real[reals]

Test:

# For y=100, there are 3 solutions:
# x <- 1 without imaginary part
# x <- 22 with imaginary part  /- 1j
>>> predict_x(100)
array([0.96479053])

# For x=70, there are also 3 solutions with only real part
>>> predict_x(70)
array([27.66728164, 12.44388509,  4.19269035])
  • Related