scipy 优化 curve_fit 中可能的不平衡元组解包

问题描述 投票:0回答:1

我的代码中出现了来自 pylint 的错误。我不知道如何解决这个问题。你能帮帮我吗?

代码在这里:

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

# Define the two points
x1, y1 = 4, 0
x2, y2 = 15, 1

# Define the square root function
def sqrt_func(x, a, b):
    return a * np.sqrt(x - x1) + y1

# Fit the curve to the two points
popt, pcov = curve_fit(sqrt_func, [x1, x2], [y1, y2])

# Generate intermediate x values between 4 and 15
x_values = np.linspace(4, 15, num=100)

# Use the fitted curve to calculate y values
y_values = sqrt_func(x_values, *popt)

# Plot the curve and the two points
plt.plot(x_values, y_values)
plt.scatter([x1, x2], [y1, y2])
plt.show()

在下面这行我有这个错误:** 可能不平衡的元组解包与 scipy.optimize._minpack_py 第 885 行定义的序列:左侧有 2 个标签,右侧有 5 个值 **

popt, pcov = curve_fit(sqrt_func, [x1, x2], [y1, y2])
python curve-fitting pylint scipy-optimize
1个回答
0
投票

因为 curve_fit 函数返回一个包含两个元素的元组,但您正试图将其解压缩为两个变量 popt 和 pcov。

你可以修改这一行,只解包元组的第一个元素,即 popt,并使用下划线 _ 作为占位符变量忽略第二个元素 pcov:

popt, _ = curve_fit(sqrt_func, [x1, x2], [y1, y2])

# pylint: disable=unpacking-non-sequence
popt, pcov = curve_fit(sqrt_func, [x1, x2], [y1, y2])

这告诉 pylint 忽略“Possible unbalanced tuple unpacking”错误

© www.soinside.com 2019 - 2024. All rights reserved.