我已经为一个简单的多维数据集创建了一个h5文件,然后通过python读取了该文件,最后使用RegularGridInterpolator
函数进行插值。一切对我来说都很完美。但是,我想知道如何更改代码,以便可以从此插值函数中派生代码?为了您的方便,我在这里提供了我的代码:
import numpy as np
import h5py
def f(x,y,z):
return 2 * x**3 + 3 * y**2 - z
x = np.linspace(-1, 1, 2)
y = np.linspace(-1, 1, 2)
z = np.linspace(-1, 1, 2)
mesh_data = f(*np.meshgrid(x, y, z, indexing='ij', sparse=True))
h5file = h5py.File('cube.h5', 'w')
h5file.create_dataset('/x', data=x)
h5file.create_dataset('/y', data=y)
h5file.create_dataset('/z', data=z)
h5file.create_dataset('/mesh_data', data=mesh_data)
h5file.close()
import numpy as np
import h5py
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from scipy.interpolate import RegularGridInterpolator
from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection
f = h5py.File('cube.h5', 'r')
list(f.keys())
dset = f[u'mesh_data']
dset.shape
dset.value.shape
dset[0:2,0:2,0:2]
x = np.linspace(-1, 1, 2)
y = np.linspace(-1, 1, 2)
z = np.linspace(-1, 1, 2)
my_interpolating_function = RegularGridInterpolator((x, y, z), dset.value, method='nearest')
pts = np.array([0.2, 0.9, 0.6])
my_interpolating_function(pts)
答案 0 :(得分:0)
我不确定您要寻找什么。这是一个一维示例,用于说明在对函数的导数进行数值估计时要考虑的要点:
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
def f(x, y, z):
return 2 * x**3 + 3 * y**2 - z
x_fine = np.linspace(-1, 1, 50) # used for the plots
# Coarse sampling, only two points:
x_coarse = np.linspace(-1, 1, 2)
# Interpolation
interpolator_coarse = interp1d(x_coarse, f(x_coarse, 0, 0), kind='linear')
plt.plot(x_fine, f(x_fine, 0, 0), label='analytical')
plt.plot(x_coarse, f(x_coarse, 0, 0), 'ok', label='coarse sampling')
plt.plot(x_fine, interpolator_coarse(x_fine), '--r', label='interpolation based on the sampling')
plt.xlabel('x'); plt.ylabel('f(x, 0, 0)');
plt.legend();
图形为:
在x = 0处,“真”导数的值为零(平坦斜率)。但是,如果根据采样数据(在x = -1和x = 1时)计算导数,则不管执行哪种插值,估计值都将为2 ...
必须增加采样点的数量:
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
def f(x, y, z):
return 2 * x**3 + 3 * y**2 - z
x_fine = np.linspace(-1, 1, 50) # used for the plots
# Coarse sampling:
x_coarse = np.linspace(-1, 1, 4)
# Interpolation
interpolator_coarse = interp1d(x_coarse, f(x_coarse, 0, 0), kind='linear')
interpolator_cubic = interp1d(x_coarse, f(x_coarse, 0, 0), kind='cubic')
plt.plot(x_fine, f(x_fine, 0, 0), 'k', label='analytical')
plt.plot(x_coarse, f(x_coarse, 0, 0), 'ok', label='coarse sampling')
plt.plot(x_fine, interpolator_coarse(x_fine), '--r', label='linear interpolation')
plt.plot(x_fine, interpolator_cubic(x_fine), '--b', label='cubic interpolation')
plt.xlabel('x'); plt.ylabel('f(x, 0, 0)');
plt.legend();
x = 0处的斜率现在更接近于零。问题的下一部分是从采样数据中估计导数,例如参见Numerical_differentiation。