第一个答案很好地解释了处理这个问题的主要方法。只是想通过展示 sklearn 包和机器学习回归的强大功能来说明另一种方法。
在 3D 中进行网格网格会产生一个非常大的 numpy 数组,
import numpy as np
N = 5
xmin, xmax = 0, 1
ymin, ymax = 0, 1
zmin, zmax = 0, 1
x = np.linspace(xmin, xmax, N)
y = np.linspace(ymin, ymax, N)
z = np.linspace(zmin, zmax, N)
grid = np.array(np.meshgrid(x,y,z, indexing='ij'))
grid.shape = (3, 5, 5, 5) # 2*5*5*5 = 250 numbers
250 个数字在视觉上不是很直观。使用不同的可能索引('ij' 或 'xy')。使用回归,我们可以用很少的输入点 (15-20) 得到相同的结果。
# building random combinations from (x,y,z)
X = np.random.choice(x, 20)[:,None]
Y = np.random.choice(y, 20)[:,None]
Z = np.random.choice(z, 20)[:,None]
xyz = np.concatenate((X,Y,Z), axis = 1)
data = np.multiply.reduce(xyz, axis = 1)
所以输入(网格)只是一个 2D numpy 数组,
xyz.shape
(20, 3)
有了相应的数据,
data.shape = (20,)
现在回归函数和积分,
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import Pipeline
from scipy import integrate
pipe=Pipeline([('polynomial',PolynomialFeatures(degree=3)),('modal',LinearRegression())])
pipe.fit(xyz, data)
def func(x,y,z):
return pipe.predict([[x, y, z]])
ranges = [[0,1], [0,1], [0,1]]
result, error = integrate.nquad(func, ranges)
print(result)
0.1257
这种方法在点数有限的情况下很有用。