首页 > 解决方案 > Python中有一个函数可以将数据向量放入(X,Y)表中吗?

问题描述

我正在寻找 Python 中的函数,以将如下所示的数据向量放入带有 X 和 Y 箱的 2D 表中。我一直在寻找类似的东西,但只找到了一些称为“直方图视图”的闭源程序。

X; Y; Z
2; 16; 0
3; 20; 1
2; 22; 1
3; 21; 2
2; 22; 2
2; 30; 3
2; 35; 5
3; 40; 5
4; 42; 4
5; 43; 3
6; 39; 2
6; 37; 2
7; 35; 3
9; 30; 4
6; 17; 4
7; 13; 2
9; 11; 1

我想要达到的效果是如下 表Generated table

X/Y 2 4 6 8 10
10 0,0 0,0 2,9 1,4 1,0
20 1,2 1,5 3.6 1,8 1,0
30 3,2 2,0 2,4 3,7 4,0
40 5,0 4,1 2,3 3,0 4,0
50 5,0 3,6 3,0

问题在于数据不完全落入箱中,例如行“7;35;3” - X 介于 6 和 7 之间,Y 介于 30 和 40 之间。我正在寻找某种反向插值方法使用所有度量来生成表。

任何指示如何做到这一点,非常感谢。先感谢您!

标签: python

解决方案


试图将其拟合为 3 次多项式。蓝色是给定的 x、y、z 点,红色是 x、y、new_z 点。近似函数在objective()中,见下面的代码。

输出

z = 0.02589 * x ^ 3 + -0.43303 * x ^ 2 + 2.17399 * x + -0.00030 * y ^ 3 + 0.02214 * y ^ 2 + -0.40954 * y + 0.51728
a: 0.02589, b: -0.43303, c: 2.17399, d: -0.00030, e: 0.02214, f: -0.40954, g: 0.51728

prediction:
x: 4, y: 42, z: 3.566527711031233

在此处输入图像描述

代码

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


x = [ 2,  3,  2,  3,  2,  2,  2,  3,  4,  5,  6,  6,  7,  9,  6,  7,  9]
y = [16, 20, 22, 21, 22, 30, 35, 40, 42, 43, 39, 37, 35, 30, 17, 13, 11]
z = [ 0,  1,  1,  2,  2,  3,  5,  5,  4,  3,  2,  2,  3,  4,  4,  2,  1]


# our objective function
def objective(V, a, b, c, d, e, f, g):
    """
    r = a*x^3 + b*x^2 + c*x + d*y^3 + e*y^2 + f*y + g
    """
    x, y = V
    r = a*x**3 + b*x**2 + c*x + d*y**3 + e*y**2 + f*y + g
    return r


popt, _ = curve_fit(objective, (x, y), z)

# parameter values
a, b, c, d, e, f, g = popt

print(f'z = {a:0.5f} * x ^ 3 + {b:0.5f} * x ^ 2 + {c:0.5f} * x + {d:0.5f} * y ^ 3 + {e:0.5f} * y ^ 2 + {f:0.5f} * y + {g:0.5f}')
print(f'a: {a:0.5f}, b: {b:0.5f}, c: {c:0.5f}, d: {d:0.5f}, e: {e:0.5f}, f: {f:0.5f}, g: {g:0.5f}')
print()

ax = plt.axes(projection='3d')
ax.plot3D(x, y, z, 'blue')
z_new = [objective((i, j), a, b, c, d, e, f, g) for i, j in zip(x, y)]

plt.plot(x, y, list(z_new), '--', color='red')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')

# Prediction
print('prediction:')
x = 4
y = 42
z = objective((x, y), a, b, c, d, e, f, g)
print(f'x: {x}, y: {y}, z: {z}')

plt.show()


推荐阅读