【发布时间】:2021-07-30 17:44:59
【问题描述】:
我正在研究一个曲线拟合问题,我打算在多个大小不等的数据集上全局估计共享模型参数。我从下面链接中的代码开始工作,其中线性回归 y = a*x + b 的常见 a 参数是在三个不同的 y 向量和一个共同的 x 向量上估计的。 How to use curve_fit from scipy.optimize with a shared fit parameter across multiple datasets?
我设法使代码示例适应更一般的情况,使用三个不同的 x 向量,一个对应于每个 y 数据向量。但是,当我想进一步扩展它以使其也适用于大小不等的数据集时,我遇到了以下错误:“ValueError: setting an array element with a sequence.”。
请在下面找到代码示例。非常感谢任何帮助!
干杯
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
x = [[0, 1, 2, 3],
[0.2, 1.2, 2.2, 3.2],
[0.3, 1.3, 2.3]]
y = [[-0.80216234, 1.41125365, 1.42565202, 2.42567754],
[ 1.34166743, 1.29731851, 2.98374731, 3.32110875],
[ 1.71398203, 3.29737756, 3.81456949]]
x = np.array(x)
y = np.array(y)
def f(x, a, b):
return a * x + b
def g(x, a, b_1, b_2, b_3):
return np.concatenate((f(x[0], a, b_1), f(x[1], a, b_2), f(x[2], a, b_3)))
(a, *b), _ = curve_fit(g, x, y.ravel())
for x_i, y_i, b_i in zip(x, y, b):
plt.plot(x_i, f(x_i, a, b_i), label=f"{a:.1f}x{b_i:+.1f}")
plt.plot(x_i, y_i, linestyle="", marker="x", color=plt.gca().lines[-1].get_color())
plt.legend()
plt.show()
关于具有多个大小相等的 x 向量的工作示例的代码,请参见下文:
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
x = [[0, 1, 2, 3],
[0.2, 1.2, 2.2, 3.2],
[0.3, 1.3, 2.3, 3.3]]
y = [[-0.80216234, 1.41125365, 1.42565202, 2.42567754],
[ 1.34166743, 1.29731851, 2.98374731, 3.32110875],
[ 1.71398203, 3.29737756, 3.81456949, 4.25]]
x = np.array(x)
y = np.array(y)
def f(x, a, b):
return a * x + b
def g(x, a, b_1, b_2, b_3):
return np.concatenate((f(x[0], a, b_1), f(x[1], a, b_2), f(x[2], a, b_3)))
(a, *b), _ = curve_fit(g, x, y.ravel())
for x_i, y_i, b_i in zip(x, y, b):
plt.plot(x_i, f(x_i, a, b_i), label=f"{a:.1f}x{b_i:+.1f}")
plt.plot(x_i, y_i, linestyle="", marker="x", color=plt.gca().lines[-1].get_color())
plt.legend()
plt.show()
【问题讨论】:
-
你能否展示多个相同大小的 x 向量的 工作 示例?问题是,numpy 既不能将
x也不能将y解析为矩阵,因为它们的长度不相等。因此它不会解析为n \times m矩阵,而是解析为list objects 的n维数组。 -
亲爱的安德烈,感谢您的回复,我将编辑帖子并添加工作示例的代码,用于多个相同大小的 x 向量。
标签: python arrays numpy curve-fitting