Home>

### python - i don't know how to adapt the sample code

I don't know what the "#solve the least squares formula to get the coefficient" part of the reference code does.
How should I write it if I want to adapt it to my own code?

Referenced code
``````# Import required libraries
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
#Generation of observation points (generate y with noise for x at equal intervals)
np.random.seed (0)
x = (np.arange (51)/50) [:, np.newaxis]
noise = (np.random.rand (51)/3) [:, np.newaxis]
y = (x * 2) + noise
y [30:38] = 3.25
# Solve the least squares equation to get the coefficient
x_ = np.concatenate ([x, np.ones (np.shape (x))], axis = 1)
w = np.dot (np.linalg.inv (np.dot (x_.T, x_)), np.dot (x_.T, y))
y_hat_ = np.dot (x_, w)``````
Code at hand
``````#Experimental value
x = np.array ([6.26379, 8.57417, 8.66527, 8.75069, 11.6708, 12.3487, 14.5032, 15.7422, 21.7646, 23.0518, 26.5069, 26.4035, 26.321, 23.0045, 19.2654, 17.9425, 14.5669, 13.513, 10.4902, 9.95136, 9.77395])
y = np.array ([3.709910308, 3.300454417, 3.219869361, 2.879991517, 2.250120678, 2.24981186, 1.859931899, 1.839996231, 1.560029151, 1.360016958, 1.210037387, 1.527926405, 1.320005022, 1.340038138, 1.618120234, 1.410033737, 1.83006856, 1.849465)
#Function I want to find
def func (x, a):
return ((-(a + (b * x))) + ((a + ((b * x) ** 2))-(4 * b * math.log (0.1))) ** 0.5)/(2 * b)``````
• Answer # 1

After all, what I want to do is to find the coefficient of the nonlinear function by the least squares method.
Then you can do it with scipy.optimize.curve_fit.
Reference: Non-linear function modeling in Python

``````import numpy as np
import math
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
#Experimental value
x = np.array ([6.26379, 8.57417, 8.66527, 8.75069, 11.6708, 12.3487, 14.5032, 15.7422, 21.7646, 23.0518, 26.5069, 26.4035, 26.321, 23.0045, 19.2654, 17.9425, 14.5669, 13.513, 10.4902, 9.95136, 9.77395])
y = np.array ([3.709910308, 3.300454417, 3.219869361, 2.879991517, 2.250120678, 2.24981186, 1.859931899, 1.839996231, 1.560029151, 1.360016958, 1.210037387, 1.527926405, 1.320005022, 1.340038138, 1.618120234, 1.410033737, 1.83006856, 1.849465)
#Function you want to find
def func (x, a, b):
return ((-(a + (b * x))) + ((a + ((b * x) ** 2))-(4 * b * math.log (0.1))) ** 0.5)/(2 * b)
param, cov = curve_fit (func, x, y)
print (f'a = {param }, b = {param }')
# a = -0.0026459965628733576, b = 0.07059577892650028
#Experimental value
plt.scatter (x, y)
#Function value
xs = np.linspace (min (x), max (x), 100)
plt.plot (xs, func (xs, param , param ), color ='red')
plt.show ()``````