如何从输入和输出列表中找到函数 f?
How to find a function f from a list of input and outputs?
我正在抓取一些数据,发现绘图上的值是从我有 x1,y1 并得到 x2,y2 的转换创建的,似乎映射是一对一的,这意味着要生成y2 我只需要 y1 而要生成 x2 我只需要 x1。
这是我对 x1 和 x2 的点的示例:
x1 = 13.431585526415347, x2 = 138.2
x1 = 21.776351639704004, x2 = = 129.7
如何找到函数 f 使 f(x1) = x2?
由于你只有2个点,最简单的曲线拟合2个点就是一条直线。描述直线的函数是y=mx+c
,其中m
是斜率,c
是y-intercept。
因此,要为您的 2 个数据点获得独特的功能,我们需要找到 m
和 c
的值。您可以这样找到它们:
import numpy as np
from scipy.optimize import curve_fit
x = np.array([13.431585526415347, 21.776351639704004])
y = np.array([138.2, 129.7])
def fit_func(x, m, c):
return m*x + c
params = curve_fit(fit_func, x, y)
[m, c] = params[0]
print(m, c)
>>> -1.0186025449490008 151.88144719990683
所以你的函数是:f(x) = -1.0186025449490008*x + 151.88144719990683
如果需要,您可以绘制某些点(例如 1 到 10)的函数:
import matplotlib.pyplot as plt
plt.plot([m*x+c for x in range(10)], '*-')
现在,正如 Mad Physicist 在 his/her 评论中指出的那样,如果您提供更多数据点,您会发现它不再是一条直线 - 它可以是任何东西。
下面是使用最小二乘多项式拟合来拟合 2 个数据点的示例:
import numpy as np
import matplotlib.pyplot as plt
points = np.array([(13.431585526415347, 138.2), (21.776351639704004, 129.7),]) # enter more data points like this: (x1,x2)
# get x and y vectors
x = points[:,0]
y = points[:,1]
# calculate polynomial
z = np.polyfit(x, y, 3)
f = np.poly1d(z)
# calculate new x's and y's
x_new = np.linspace(x[0], x[-1], 50)
y_new = f(x_new)
plt.plot(x,y,'o', x_new, y_new)
plt.xlim([x[0]-1, x[-1] + 1 ])
plt.show()
一旦你提供了更多的数据点,你就可以尝试不同的拟合函数,看看哪一个最适合你的数据。
我正在抓取一些数据,发现绘图上的值是从我有 x1,y1 并得到 x2,y2 的转换创建的,似乎映射是一对一的,这意味着要生成y2 我只需要 y1 而要生成 x2 我只需要 x1。
这是我对 x1 和 x2 的点的示例:
x1 = 13.431585526415347, x2 = 138.2
x1 = 21.776351639704004, x2 = = 129.7
如何找到函数 f 使 f(x1) = x2?
由于你只有2个点,最简单的曲线拟合2个点就是一条直线。描述直线的函数是y=mx+c
,其中m
是斜率,c
是y-intercept。
因此,要为您的 2 个数据点获得独特的功能,我们需要找到 m
和 c
的值。您可以这样找到它们:
import numpy as np
from scipy.optimize import curve_fit
x = np.array([13.431585526415347, 21.776351639704004])
y = np.array([138.2, 129.7])
def fit_func(x, m, c):
return m*x + c
params = curve_fit(fit_func, x, y)
[m, c] = params[0]
print(m, c)
>>> -1.0186025449490008 151.88144719990683
所以你的函数是:f(x) = -1.0186025449490008*x + 151.88144719990683
如果需要,您可以绘制某些点(例如 1 到 10)的函数:
import matplotlib.pyplot as plt
plt.plot([m*x+c for x in range(10)], '*-')
现在,正如 Mad Physicist 在 his/her 评论中指出的那样,如果您提供更多数据点,您会发现它不再是一条直线 - 它可以是任何东西。
下面是使用最小二乘多项式拟合来拟合 2 个数据点的示例:
import numpy as np
import matplotlib.pyplot as plt
points = np.array([(13.431585526415347, 138.2), (21.776351639704004, 129.7),]) # enter more data points like this: (x1,x2)
# get x and y vectors
x = points[:,0]
y = points[:,1]
# calculate polynomial
z = np.polyfit(x, y, 3)
f = np.poly1d(z)
# calculate new x's and y's
x_new = np.linspace(x[0], x[-1], 50)
y_new = f(x_new)
plt.plot(x,y,'o', x_new, y_new)
plt.xlim([x[0]-1, x[-1] + 1 ])
plt.show()
一旦你提供了更多的数据点,你就可以尝试不同的拟合函数,看看哪一个最适合你的数据。