时空数据分析实战:GTWR模型原理与Python实现全解析
时空数据建模是地理信息系统和空间统计领域的重要课题,传统回归方法往往忽略了数据在空间和时间维度上的非平稳性。本文将深入探讨地理时空加权回归(GTWR)模型,从数学原理到代码实现,带你全面掌握这一强大的分析工具。
1. GTWR模型的核心原理
GTWR(Geographically and Temporally Weighted Regression)是在GWR(地理加权回归)基础上发展而来的时空建模方法。与普通线性回归的全局参数估计不同,GTWR允许回归系数随地理位置和时间变化,从而更准确地捕捉时空异质性。
1.1 数学模型解析
GTWR模型的基本表达式为:
y_i = β_0(u_i,v_i,t_i) + Σ[β_k(u_i,v_i,t_i)x_ik] + ε_i其中:
- (u_i,v_i)表示第i个样本点的空间坐标
- t_i表示观测时间点
- y_i是因变量值
- x_ik是第k个解释变量
- ε_i为误差项
- β_k(u_i,v_i,t_i)是时空变化的回归系数
与传统GWR相比,GTWR引入了时间维度权重,使得模型能够同时考虑空间邻近性和时间邻近性对回归结果的影响。
1.2 时空权重矩阵构建
权重矩阵W是GTWR的核心,决定了各样本点对当前点估计的影响程度。时空权重通常由空间权重和时间权重的组合构成:
W_uvt = W_u * W_v * W_t常用的权重函数包括:
- 高斯函数:w(d) = exp(-(d/b)^2)
- Bi-square函数:w(d) = [1-(d/b)^2]^2 (当d≤b时)
其中b是带宽参数,控制权重随距离衰减的速度。
2. 数据准备与预处理
在应用GTWR模型前,需要对数据进行适当的预处理。以下是一个完整的数据准备流程:
2.1 数据格式要求
GTWR模型通常需要以下数据列:
- 空间坐标(经度、纬度)
- 时间戳(可以是日期或连续时间值)
- 解释变量(特征)
- 因变量(目标变量)
import numpy as np import pandas as pd # 生成模拟数据 np.random.seed(42) n_samples = 1000 # 生成空间坐标(0-10范围内的随机点) coords = np.random.uniform(0, 10, (n_samples, 2)) # 生成时间序列(0-24个月) t = np.random.uniform(0, 24, (n_samples, 1)) # 生成解释变量 X1 = np.random.normal(5, 2, (n_samples, 1)) X2 = np.random.poisson(3, (n_samples, 1)) # 生成时空变化的回归系数 beta0 = 2 + np.sin(coords[:,0]/5) + np.cos(t/12) beta1 = 1 + (coords[:,0]+coords[:,1])/20 beta2 = 3 - (t-12)**2/144 # 生成因变量 y = beta0 + beta1*X1.flatten() + beta2*X2.flatten() + np.random.normal(0, 0.5, n_samples) # 构建DataFrame data = pd.DataFrame({ 'lng': coords[:,0], 'lat': coords[:,1], 'time': t.flatten(), 'X1': X1.flatten(), 'X2': X2.flatten(), 'y': y })2.2 时空尺度统一
由于空间距离和时间距离的单位不同,需要进行标准化处理:
from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler() data[['lng','lat']] = scaler.fit_transform(data[['lng','lat']]) data['time'] = scaler.fit_transform(data[['time']])3. 模型参数优化
GTWR模型有两个关键参数需要确定:空间带宽(bw)和时间尺度参数(tau)。参数选择直接影响模型性能。
3.1 黄金分割搜索法
from mgtwr.sel_bws import Sel_bws # 准备数据 coords = data[['lng','lat']].values t = data[['time']].values y = data[['y']].values X = data[['X1','X2']].values # 参数搜索 sel = Sel_bws(coords, t, y, X, kernel='gaussian', fixed=True) bw, tau = sel.search(bw_max=10, tau_max=5, verbose=True) print(f"最优参数: bw={bw:.2f}, tau={tau:.2f}")3.2 交叉验证法
对于更精确的参数选择,可以使用交叉验证:
from mgtwr.gtwr import GTWR from sklearn.model_selection import TimeSeriesSplit tscv = TimeSeriesSplit(n_splits=5) scores = [] for bw_candidate in np.linspace(0.1, 5, 10): for tau_candidate in np.linspace(0.1, 3, 5): fold_scores = [] for train_idx, test_idx in tscv.split(X): model = GTWR(coords[train_idx], t[train_idx], y[train_idx], X[train_idx], bw=bw_candidate, tau=tau_candidate, kernel='gaussian').fit() pred = model.predict(coords[test_idx], t[test_idx], X[test_idx]) score = np.mean((pred - y[test_idx])**2) fold_scores.append(score) scores.append({ 'bw': bw_candidate, 'tau': tau_candidate, 'score': np.mean(fold_scores) }) # 找出最优参数 best_params = min(scores, key=lambda x: x['score'])4. 模型训练与结果分析
4.1 模型拟合
# 使用最优参数拟合模型 gtwr_model = GTWR(coords, t, y, X, bw=best_params['bw'], tau=best_params['tau'], kernel='gaussian').fit() # 模型摘要 print(f"R平方: {gtwr_model.R2:.4f}") print(f"调整后R平方: {gtwr_model.adj_R2:.4f}") print(f"AIC: {gtwr_model.AIC:.2f}")4.2 结果可视化
import matplotlib.pyplot as plt # 绘制系数空间分布 plt.figure(figsize=(15,5)) plt.subplot(131) plt.scatter(coords[:,0], coords[:,1], c=gtwr_model.betas[:,1], cmap='coolwarm') plt.colorbar(label='X1系数') plt.title('X1系数空间分布') plt.subplot(132) plt.scatter(coords[:,0], coords[:,1], c=gtwr_model.betas[:,2], cmap='coolwarm') plt.colorbar(label='X2系数') plt.title('X2系数空间分布') plt.subplot(133) plt.scatter(t, gtwr_model.betas[:,1], alpha=0.3) plt.xlabel('时间') plt.ylabel('X1系数') plt.title('X1系数随时间变化') plt.tight_layout() plt.show()5. 高级应用与扩展
5.1 多尺度GTWR模型
当不同解释变量具有不同的空间或时间尺度时,可以使用多尺度GTWR(MGTWR):
from mgtwr.gtwr import MGTWR from mgtwr.sel_bws import Sel_bws # 多尺度参数搜索 sel_multi = Sel_bws(coords, t, y, X, kernel='gaussian', fixed=True, multi=True) multi_bw, multi_tau = sel_multi.search(multi_bw_min=[0.1], verbose=True) # 拟合多尺度模型 mgtwr_model = MGTWR(coords, t, y, X, sel_multi, kernel='gaussian', fixed=True).fit()5.2 时空预测
训练好的GTWR模型可用于新数据的预测:
# 生成新时空点 new_coords = np.random.uniform(0, 1, (100, 2)) new_t = np.random.uniform(0, 1, (100, 1)) new_X = np.random.normal(0, 1, (100, 2)) # 预测 predictions = gtwr_model.predict(new_coords, new_t, new_X)6. 实际应用案例
以城市空气质量分析为例,演示GTWR的实际应用:
# 加载空气质量数据 air_quality = pd.read_csv('air_quality.csv') # 预处理 coords = air_quality[['longitude','latitude']].values dates = pd.to_datetime(air_quality['date']) t = (dates - dates.min()).dt.days.values.reshape(-1,1) y = air_quality['PM2.5'].values.reshape(-1,1) X = air_quality[['temperature','wind_speed','humidity']].values # 拟合GTWR模型 gtwr_air = GTWR(coords, t, y, X, bw=0.5, tau=0.3, kernel='gaussian').fit() # 分析结果 plt.figure(figsize=(12,6)) plt.scatter(coords[:,0], coords[:,1], c=gtwr_air.betas[:,1], cmap='coolwarm') plt.colorbar(label='温度系数') plt.title('温度对PM2.5影响的空间变异')通过GTWR模型,我们可以发现温度对PM2.5浓度的影响在不同区域和不同季节存在显著差异,这为精准的环境治理提供了科学依据。