Using a similar approach to @Cam.Davidson.Pilon, I wrote a couple functions to help demo this approach in Python. It can be expanded by adding more terms in the np.concatenate
vectors. The output for the y_pred
would not change, but getting the coefficients, regr.coef_[0][2]
, would need to be included.
from sklearn import linear_model
import numpy as np
from matplotlib import pyplot as plt
def regress_2nd_order(x, y):
# The x values are transformed into the second order matrix
X = np.concatenate([x, x**2], axis=1)
# Use model to fit to the data
regr.fit(X, y)
# Extract the values of interest for forming the equation...
# y_pred = c0 + c1 * x + c2 * x^2
c0 = round(regr.intercept_[0],2)
c1 = round(regr.coef_[0][0],2)
c2 = round(regr.coef_[0][1],4)
# c3 = round(regr.coef_[0][2],4)
# Another way to get this is using the `regr.predict` function
# Predict will calculate the values for you
y_pred = regr.predict(X)
# Print the intercept (c0) and the corresponding coefficients
print('Scikit learn - \nEquation: %.2f + %.2f*T + %.5f*T^2' % (c0,c1,c2) )
# return y_pred, (c0, c1, c2, c3)
return y_pred, (c0, c1, c2)
def socket_temp(x, y):
# Include only the predicted y-vector
y_pred = regress_2nd_order(x, y)[0]
fig, ax = plt.subplots(1,1, figsize=(10,10))
ax.plot(x, y_pred, ls='', marker='*', label='predicted')
ax.plot(x, y, ls='', marker='.', label='iddt')
ax.legend()
For my use, I had temperature as my y
variable, and a dynamic supply current (IDDT) output as my x
variable. Here are the values I used for x
and y
and the output vector, y_pred
:
'iddt' 'temp' 'y_pred'
0 627.23 20.0 20.42
1 627.38 19.9 20.52
2 612.39 9.7 10.32
3 612.48 9.7 10.38
4 597.73 -0.1 0.19
5 597.78 -0.2 0.22
6 583.24 -10.1 -9.99
7 583.24 -10.0 -9.99
8 569.22 -19.9 -19.99
9 568.97 -19.9 -20.17
10 555.62 -29.8 -29.83
11 555.99 -29.8 -29.56
12 541.15 -40.1 -40.45
13 541.50 -40.1 -40.19
14 639.88 30.3 28.89
15 640.11 30.2 29.05
16 656.61 40.2 39.92
17 656.62 40.3 39.92
18 672.73 50.4 50.33
19 672.68 50.4 50.30
20 689.56 60.6 61.01
21 689.26 60.6 60.82
22 705.30 70.8 70.79
23 705.22 70.8 70.75
24 722.27 81.0 81.14
25 722.24 81.0 81.12
