首页 > 解决方案 > python numpy (v1.15.0) 无法拟合抛物线

问题描述

我很难理解为什么 numpy 很难将抛物线拟合到这些数据?

def make_poly(x, coefs):
    # generate a polynomial from an array of coefficients
    f = numpy.zeros(len(x))
    for i in range(len(coefs)):
        f = f + coefs[-1-i]*x**i
    return(f)


xx = [1443.56, 1443.56, 1450.83, 1447.59, 1454.9, 1434.77, 1423.74, 1426.87, 1438.75, 1447.59, 1454.9, 1444.36, 1454.9, 1426.09, 1454.08, 1453.27, 1447.59, 1449.2, 1451.64, 1454.08, 1454.08, 1454.9, 1454.9, 1455.71, 1452.45, 1450.01, 1453.27, 1430.81, 1454.9, 1448.39, 1432.39, 1452.45, 1445.16, 1431.6, 1447.59, 1447.59, 1425.3, 1443.56, 1453.27, 1424.52, 1429.23, 1421.4, 1454.08, 1445.97, 1427.66, 1429.23, 1433.18, 1430.81, 1440.35,1429.23]

yy = [120.15, 120.15, 123.09, 122.07, 123.52, 116.35, 104.75, 108.34, 119.13, 122.07, 124.27, 120.29, 124.27, 106.6, 124.27, 124.13, 122.07, 122.2,  122.34, 123.37, 124.27, 124.27, 124.27, 124.41, 122.34, 122.2,  123.24, 111.95, 124.27, 121.31, 113.71, 123.24, 121.18, 113.71, 121.31, 122.07, 106.6,  121.04, 124.13, 105.61, 110.96, 100.31, 123.37, 121.18, 109.21, 111.83, 114.58, 112.83, 118.38, 110.96]

fit_result = numpy.polyfit(x=xx, y=yy, deg=2, full=True)
newX = numpy.linspace(1420, 1460, 100)
pyplot.scatter(xx, yy)
pyplot.plot(newX, make_poly(newX, fit_result[0]), 'g', linewidth =.5)
pyplot.show()

运行它也会抛出消息:

Python(35100,0x7fff9cda3380) malloc: *** mach_vm_map(size=18446744072151506944) failed (error code=3)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
init_dgelsd failed init

我在 OS High Sierra、Python 3.7.0、numpy 1.15.0(使用自制软件安装)上运行它。

标签: pythonnumpypolynomial-approximations

解决方案


示例中提供的代码运行良好。所以,我想问题在于包版本状态。可能要修复错误,您必须确保 wheel、setuptools 和 pip + 您正在使用的软件包是最新的。为此,请使用以下命令:

pip install --upgrade pip setuptools wheel
pip install -I numpy matplotlib # + Other packages.

安装完成后重试。如果错误仍然存​​在,请使用您正在使用的 python 和包的版本扩展问题(以便它可以重现)。

更新:

上面的答案已经解决了这个问题,尤其是从 numpy 升级1.15.01.15.1


推荐阅读