空间区域:25&25正方形格子点区域,坐标原点在整个正方形区域的左下角,数据点的坐标为(ui,vi)=(0.5mod((i-1)/25),0.5int((i-1)/25)),i=1,2,...,625 模型:y = β1(ui,vi) + β2(ui,vi)*xi + εi,xi-U(0,2) ,εi-N(0,0.25) 核函数和窗宽:Gauss核;h由CV方法确定 重复次数:100次 最终估计:100次重复的平均值 取如下三组系数函数: G1:β1(u,v)=(u+v)/6 β2(u,v)=u/3 G2:β1(u,v)=4sin((Πu)/12) β2(u,v)=(36-(6-u)^2)(36-(6-v)^2)/324 G3:β1(u,v)=3sin(根号下(2(6-u)^2)+2(6-v)^2))/根号下(2(6-u)^2)+2(6-v)^2)) β2(u,v)=2(u-2)exp(-01((6-u)^2+(6-v)^2)) 绘制原始图像,绘制GWR估计和局部GWR估计后的三维空间曲面图,python实现
时间: 2023-10-07 10:09:48 浏览: 128
首先,我们需要安装必要的库,包括`numpy`、`pandas`、`sklearn`和`plotly`。可以使用以下命令进行安装:
```python
!pip install numpy pandas sklearn plotly
```
接下来,我们可以使用以下代码生成数据集:
```python
import numpy as np
import pandas as pd
# 生成数据点的坐标
coords = []
for i in range(1, 626):
u = 0.5 * (i - 1) % 25
v = 0.5 * (i - 1) // 25
coords.append((u, v))
coords = np.array(coords)
# 生成自变量和误差项
X = np.random.uniform(0, 2, size=(625,))
epsilon = np.random.normal(0, 0.25, size=(625,))
# 定义三组系数函数
def beta1_g1(u, v):
return (u + v) / 6
def beta2_g1(u, v):
return u / 3
def beta1_g2(u, v):
return 4 * np.sin(np.pi * u / 12)
def beta2_g2(u, v):
return (36 - (6 - u) ** 2) * (36 - (6 - v) ** 2) / 324
def beta1_g3(u, v):
return 3 * np.sin(np.sqrt(2 * (6 - u) ** 2 + 2 * (6 - v) ** 2)) / np.sqrt(2 * (6 - u) ** 2 + 2 * (6 - v) ** 2)
def beta2_g3(u, v):
return 2 * (u - 2) * np.exp(-0.1 * ((6 - u) ** 2 + (6 - v) ** 2))
# 生成因变量
y = beta1_g1(coords[:, 0], coords[:, 1]) + beta2_g1(coords[:, 0], coords[:, 1]) * X + epsilon
df = pd.DataFrame({'x':coords[:,0], 'y':coords[:,1], 'z':y})
```
接下来,我们可以使用以下代码来进行GWR估计和局部GWR估计,其中`h`是通过交叉验证确定的窗宽:
```python
from sklearn.model_selection import GridSearchCV
from sklearn.neighbors import KernelDensity
from sklearn.metrics import make_scorer
from sklearn.linear_model import LinearRegression
# 定义GWR模型
class GWR:
def __init__(self, coords, X, y, kernel='gaussian', metric='euclidean'):
self.coords = coords
self.X = X
self.y = y
self.kernel = kernel
self.metric = metric
def fit(self, h):
self.h = h
self.model = []
for i in range(len(self.coords)):
# 计算每个点的权重
kde = KernelDensity(kernel=self.kernel, bandwidth=self.h, metric=self.metric).fit(self.coords)
weights = np.exp(kde.score_samples([self.coords[i]]))[0]
# 用加权最小二乘法拟合每个点的局部模型
X_local = np.concatenate([[1], [self.coords[i][0]], [self.coords[i][1]], [self.X[i]]])
y_local = self.y[i]
model_local = LinearRegression().fit([X_local], [y_local], sample_weight=[weights])
self.model.append(model_local)
def predict(self, X_new):
y_pred = []
for i in range(len(X_new)):
# 计算每个新点到原数据点的距离
distances = np.linalg.norm(self.coords - X_new[i], axis=1)
# 计算每个点的权重
weights = np.exp(-0.5 * (distances / self.h) ** 2)
# 用加权最小二乘法拟合每个点的局部模型
X_local = np.concatenate([[1], [X_new[i][0]], [X_new[i][1]], [self.X[i]]])
y_local = np.sum(weights * self.y) / np.sum(weights)
model_local = LinearRegression().fit([X_local], [y_local], sample_weight=weights)
y_pred.append(model_local.predict([X_local])[0])
return y_pred
# 交叉验证确定窗宽
params = {'bandwidth': np.linspace(0.1, 2, 20)}
kde = KernelDensity(kernel='gaussian')
gwr_cv = GridSearchCV(kde, params, scoring=make_scorer(lambda y_true, y_pred: -np.mean((y_true - y_pred) ** 2)), cv=5)
gwr_cv.fit(coords)
h = gwr_cv.best_params_['bandwidth']
# 进行GWR估计和局部GWR估计
gwr_g1 = GWR(coords, X, y, kernel='gaussian')
gwr_g1.fit(h)
y_pred_g1 = gwr_g1.predict(coords)
gwr_g2 = GWR(coords, X, y, kernel='gaussian')
gwr_g2.fit(h)
y_pred_g2 = gwr_g2.predict(coords)
gwr_g3 = GWR(coords, X, y, kernel='gaussian')
gwr_g3.fit(h)
y_pred_g3 = gwr_g3.predict(coords)
```
最后,我们可以使用以下代码生成三维空间曲面图:
```python
import plotly.express as px
fig = px.scatter_3d(df, x='x', y='y', z='z', opacity=0.7)
fig.add_trace(px.scatter_3d(pd.DataFrame({'x':coords[:,0], 'y':coords[:,1], 'z':y_pred_g1}), x='x', y='y', z='z', opacity=0.7).data[0])
fig.add_trace(px.scatter_3d(pd.DataFrame({'x':coords[:,0], 'y':coords[:,1], 'z':y_pred_g2}), x='x', y='y', z='z', opacity=0.7).data[0])
fig.add_trace(px.scatter_3d(pd.DataFrame({'x':coords[:,0], 'y':coords[:,1], 'z':y_pred_g3}), x='x', y='y', z='z', opacity=0.7).data[0])
fig.update_traces(marker=dict(size=2))
fig.show()
```
完整代码如下:
阅读全文