显示代码中y_rec的函数表达式:import numpy as np import matplotlib.pyplot as plt def gen_data(x1, x2): y_sample = np.sin(np.pi * x1 / 2) + np.cos(np.pi * x1 / 3) y_all = np.sin(np.pi * x2 / 2) + np.cos(np.pi * x2 / 3) return y_sample, y_all def kernel_interpolation(y_sample, x1, sig): gaussian_kernel = lambda x, c, h: np.exp(-(x - x[c]) ** 2 / (2 * (h ** 2))) num = len(y_sample) w = np.zeros(num) int_matrix = np.asmatrix(np.zeros((num, num))) for i in range(num): int_matrix[i, :] = gaussian_kernel(x1, i, sig) w = int_matrix.I * np.asmatrix(y_sample).T return w def kernel_interpolation_rec(w, x1, x2, sig): gkernel = lambda x, xc, h: np.exp(-(x - xc) ** 2 / (2 * (h ** 2))) num = len(x2) y_rec = np.zeros(num) for i in range(num): for k in range(len(w)): y_rec[i] = y_rec[i] + w[k] * gkernel(x2[i], x1[k], sig) return y_rec if name == 'main': snum =4 # control point数量 ratio =50 # 总数据点数量:snum*ratio sig = 2 # 核函数宽度 xs = -14 xe = 14 #x1 = np.linspace(xs, xe,snum) x1 = np.array([9, 9.1, 13 ]) x2 = np.linspace(xs, xe, (snum - 1) * ratio + 1) y_sample, y_all = gen_data(x1, x2) plt.figure(1) w = kernel_interpolation(y_sample, x1, sig) y_rec = kernel_interpolation_rec(w, x1, x2, sig) plt.plot(x2, y_rec, 'k') plt.plot(x2, y_all, 'r:') plt.ylabel('y') plt.xlabel('x') for i in range(len(x1)): plt.plot(x1[i], y_sample[i], 'go', markerfacecolor='none') # 计算均方根误差 rmse = np.sqrt(np.mean((y_rec - y_all) ** 2)) # 输出均方根误差值 print("均方根误差为:", rmse) plt.legend(labels=['reconstruction', 'original', 'control point'], loc='lower left') plt.title('kernel interpolation:$y=sin(\pi x/2)+cos(\pi x/3)$') plt.show()
时间: 2024-01-28 11:04:43 浏览: 70
kernel代码.py
代码中 y_rec 的函数表达式为:
```python
def kernel_interpolation_rec(w, x1, x2, sig):
gkernel = lambda x, xc, h: np.exp(-(x - xc) ** 2 / (2 * (h ** 2)))
num = len(x2)
y_rec = np.zeros(num)
for i in range(num):
for k in range(len(w)):
y_rec[i] = y_rec[i] + w[k] * gkernel(x2[i], x1[k], sig)
return y_rec
```
其中,$w$ 是控制点的权重,$x_1$ 是控制点的横坐标,$x_2$ 是所有数据点的横坐标,$\sigma$ 是高斯核函数的宽度,$gkernel$ 是高斯核函数。在函数中,我们遍历所有数据点的横坐标 $x_2$,对于每个数据点,我们遍历所有控制点的权重 $w$,然后将每个控制点对当前数据点的贡献累加起来,得到在当前数据点处通过核插值重构出来的纵坐标 $y_{rec}[i]$。
阅读全文