python - 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 之间。我正在寻找某种反向插值方法使用所有度量来生成表。
任何指示如何做到这一点,非常感谢。先感谢您!
解决方案
试图将其拟合为 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()
推荐阅读
- firebase - 将 Firebase Auth 用户数据安全地存储在 Ionic Storage 中
- sql - 根据条件从查询响应中选择一条记录 | 函数 postgres
- networking - WebSockets 不适用于 GCP 中的 HTTP/2 负载均衡器后端
- java - ProcessorContext 的远程 forward() 调用抛出 NPE
- python - Python3 - 列表索引超出范围 - 从文件中提取数据
- c++ - 可以投个矢量图吗
到一个向量 - python - 基于辅助列值的颜色直方图,用于探索性分析
- javascript - 在 Javascript/jQuery 中使用 datetimepicker 在 HTML 表中过滤 FROM 和 TO 日期
- curl - 卷曲请求.curl:(6)无法解析主机:
- php - Symfony 4 Match 方法如火种