根据dataframe完善后面的代码并完整输出,要求 1、变量名有变化,对以dataframe的变量名为准,请修改 2、高温模型加上“降水最大值”“降水最小值”…
- User
根据dataframe完善后面的代码并完整输出,要求 1、变量名有变化,对以dataframe的变量名为准,请修改 2、高温模型加上“降水最大值”“降水最小值” 3、降水模型加上“温度最大值”“温度最小值” data = pd.DataFrame({ 'longitude': lon_grid.flatten(), 'latitude': lat_grid.flatten(), 'high_temp_count': high_temp_count.flatten(), 'heavy_rain_count': resampled_variables['heavy_rain_count'].flatten(), 'elevation': dem_resampled.flatten(), 'avg_temp': avg_temp_data.flatten(), 'min_temp': min_temp_data.flatten(), 'max_temp': max_temp_data.flatten(), 'avg_precip': resampled_variables['avg_precip_data'].flatten(), 'min_precip': resampled_variables['min_precip_data'].flatten(), 'max_precip': resampled_variables['max_precip_data'].flatten() })
from tqdm import tqdm import numpy as np import pandas as pd import geopandas as gpd from shapely.geometry import Point import matplotlib.pyplot as plt import statsmodels.api as sm from mgwr.gwr import MGWR from mgwr.sel_bw import Sel_BW
设置中文字体支持
plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False
假设 gdf 是已经加载的数据
1. 优化数据类型
gdf['elevation'] = gdf['elevation'].astype('float32') gdf['temperatur'] = gdf['temperatur'].astype('float32') # 假设包含气温数据 gdf['precipitat'] = gdf['precipitat'].astype('float32') # 假设包含降水数据 gdf['high_temp_'] = gdf['high_temp_'].astype('float32') gdf['heavy_rain'] = gdf['heavy_rain'].astype('float32')
2. 减少数据精度
gdf['longitude'] = gdf['longitude'].round(4) gdf['latitude'] = gdf['latitude'].round(4) gdf['elevation'] = gdf['elevation'].round(2) gdf['temperatur'] = gdf['temperatur'].round(2) gdf['precipitat'] = gdf['precipitat'].round(2) gdf['high_temp_'] = gdf['high_temp_'].round(2) gdf['heavy_rain'] = gdf['heavy_rain'].round(2)
打印去除缺失值前的数据行数
print(f"去除缺失值前数据行数: {gdf.shape[0]}")
去除缺失值
gdf = gdf.dropna(subset=['high_temp_', 'heavy_rain', 'elevation', 'temperatur', 'precipitat']).reset_index(drop=True)
去除缺失值后的数据行数
print(f"去除缺失值后数据行数: {gdf.shape[0]}")
检查去除缺失值后数据是否为空
if gdf.shape[0] == 0: raise ValueError("去除缺失值后数据为空,请检查数据。")
3. 暂时不进行采样,使用 1% 的数据
0.0018 0.0028 0.0038 0.0078
gdf_sampled = gdf.sample(frac=0.00228, random_state=42).reset_index(drop=True)
提取坐标
coords = list(zip(gdf_sampled.geometry.x, gdf_sampled.geometry.y))
提取自变量和因变量
X_high_temp = gdf_sampled[['elevation', 'precipitat']] # 添加气温和降水作为自变量 X_high_temp = sm.add_constant(X_high_temp) # 添加常数项 X_heavy_rain = gdf_sampled[['elevation', 'temperatur']] # 添加气温和降水作为自变量 X_heavy_rain = sm.add_constant(X_heavy_rain) # 添加常数项 Y_high_temp = gdf_sampled['high_temp_'].values.reshape(-1, 1) # 维度调整为二维 Y_heavy_rain = gdf_sampled['heavy_rain'].values.reshape(-1, 1) # 维度调整为二维
检查数据形状,确保没有维度问题
print(f"X_high_temp shape: {X_high_temp.shape}") # 自变量矩阵 print(f"Y_high_temp shape: {Y_high_temp.shape}") # 因变量
检查是否有缺失值
if np.any(np.isnan(X_high_temp)) or np.any(np.isnan(Y_high_temp)): raise ValueError("输入数据中存在缺失值,请处理缺失值。")
确保行数大于列数
if X_high_temp.shape[0] <= X_high_temp.shape[1]: raise ValueError("自变量矩阵的行数应大于列数,请检查输入数据。")
获取样本数量
n_samples = gdf_sampled.shape[0]
设置带宽的最小值和最大值
bw_min = int(n_samples * 0.05) # 最小带宽为样本数的 20% bw_max = int(n_samples * 0.3) # 最大带宽为样本数的 50%
4. 选择带宽,设置 multi=True 启用 MGWR 并启用并行计算
print("选择高温日频率带宽中...")
设置带宽的最小值和最大值
bw_min = int(n_samples * 0.2) # 最小带宽为样本数的 20%
bw_max = int(n_samples * 0.5) # 最大带宽为样本数的 50%
选择带宽
selector = Sel_BW(coords, Y_high_temp, X_high_temp, multi=True) bws = selector.search(bw_min=bw_min, bw_max=bw_max) print(f"高温日频率的 MGWR 模型最佳带宽:{bws}")
5. 构建 MGWR 模型(高温日频率),启用并行计算
print("构建高温日频率 MGWR 模型中...")
mgwr_model = MGWR(coords, Y_high_temp, X_high_temp, selector, n_jobs=-1) # 启用并行计算 mgwr_results = mgwr_model.fit()
print(mgwr_results.summary())
6.提取 MGWR 结果,绘制系数的空间分布
对高温日频率的 MGWR 模型提取系数
gdf_sampled['mgwr_elevation_coef_high_temp'] = mgwr_results.params[:, 1]
gdf_sampled['mgwr_temperature_coef_high_temp'] = mgwr_results.params[:, 2]
gdf_sampled['mgwr_precipitation_coef_high_temp'] = mgwr_results.params[:, 2]
7. 绘制高温日频率 MGWR 模型的高程、气温、降水系数分布
fig, ax = plt.subplots(1, 1, figsize=(8, 6)) gdf_sampled.plot(column='mgwr_elevation_coef_high_temp', ax=ax, cmap='coolwarm', legend=True) ax.set_title('高温日频率 MGWR 模型的高程系数分布') plt.xlabel('经度') plt.ylabel('纬度') plt.show()
fig, ax = plt.subplots(1, 1, figsize=(8, 6))
gdf_sampled.plot(column='mgwr_temperature_coef_high_temp', ax=ax, cmap='coolwarm', legend=True)
ax.set_title('高温日频率 MGWR 模型的气温系数分布')
plt.xlabel('经度')
plt.ylabel('纬度')
plt.show()
fig, ax = plt.subplots(1, 1, figsize=(8, 6)) gdf_sampled.plot(column='mgwr_precipitation_coef_high_temp', ax=ax, cmap='coolwarm', legend=True) ax.set_title('高温日频率 MGWR 模型的降水系数分布') plt.xlabel('经度') plt.ylabel('纬度') plt.show()
8. 选择带宽(对于暴雨日频率)
设置带宽的最小值和最大值
bw_min = int(n_samples * 0.05) # 最小带宽为样本数的 20% bw_max = int(n_samples * 0.5) # 最大带宽为样本数的 50%
print("选择暴雨日频率带宽中...") selector_rain = Sel_BW(coords, Y_heavy_rain, X_heavy_rain, multi=True) bws_rain = selector_rain.search(bw_min=bw_min, bw_max=bw_max) print(f"暴雨日频率的 MGWR 模型最佳带宽:{bws_rain}")
9. 构建 MGWR 模型(暴雨日频率),启用并行计算
print("构建暴雨日频率 MGWR 模型中...")
mgwr_model_rain = MGWR(coords, Y_heavy_rain, X_heavy_rain, selector_rain, n_jobs=-1) # 启用并行计算 mgwr_results_rain = mgwr_model_rain.fit()
print(mgwr_results_rain.summary())
10. 提取 MGWR 结果,绘制系数的空间分布
对暴雨日频率的 MGWR 模型提取系数
gdf_sampled['mgwr_elevation_coef_rain'] = mgwr_results_rain.params[:, 1] gdf_sampled['mgwr_temperature_coef_rain'] = mgwr_results_rain.params[:, 2]
gdf_sampled['mgwr_precipitation_coef_rain'] = mgwr_results_rain.params[:, 3]
11. 绘制暴雨日频率 MGWR 模型的高程、气温、降水系数分布
fig, ax = plt.subplots(1, 1, figsize=(8, 6)) gdf_sampled.plot(column='mgwr_elevation_coef_rain', ax=ax, cmap='coolwarm', legend=True) ax.set_title('暴雨日频率 MGWR 模型的高程系数分布') plt.xlabel('经度') plt.ylabel('纬度') plt.show()
fig, ax = plt.subplots(1, 1, figsize=(8, 6)) gdf_sampled.plot(column='mgwr_temperature_coef_rain', ax=ax, cmap='coolwarm', legend=True) ax.set_title('暴雨日频率 MGWR 模型的气温系数分布') plt.xlabel('经度') plt.ylabel('纬度') plt.show()
fig, ax = plt.subplots(1, 1, figsize=(8, 6))
gdf_sampled.plot(column='mgwr_precipitation_coef_rain', ax=ax, cmap='coolwarm', legend=True)
ax.set_title('暴雨日频率 MGWR 模型的降水系数分布')
plt.xlabel('经度')
plt.ylabel('纬度')
plt.show()
- Assistant
Here is the updated and complete code based on your requirements:
from tqdm import tqdm import numpy as np import pandas as pd import geopandas as gpd from shapely.geometry import Point import matplotlib.pyplot as plt import statsmodels.api as sm from mgwr.gwr import MGWR from mgwr.sel_bw import Sel_BW # 设置中文字体支持(如果需要) # plt.rcParams['font.sans-serif'] = ['SimHei'] # plt.rcParams['axes.unicode_minus'] = False # 假设 data 已经存在,包含您的数据 # 请确保在运行此代码之前定义了 data DataFrame # data = pd.DataFrame({...}) # 将经度和纬度转换为几何对象 data['geometry'] = [Point(xy) for xy in zip(data['longitude'], data['latitude'])] gdf = gpd.GeoDataFrame(data, geometry='geometry') # 1. 优化数据类型 gdf['elevation'] = gdf['elevation'].astype('float32') gdf['avg_temp'] = gdf['avg_temp'].astype('float32') gdf['min_temp'] = gdf['min_temp'].astype('float32') gdf['max_temp'] = gdf['max_temp'].astype('float32') gdf['avg_precip'] = gdf['avg_precip'].astype('float32') gdf['min_precip'] = gdf['min_precip'].astype('float32') gdf['max_precip'] = gdf['max_precip'].astype('float32') gdf['high_temp_count'] = gdf['high_temp_count'].astype('float32') gdf['heavy_rain_count'] = gdf['heavy_rain_count'].astype('float32') # 2. 减少数据精度 gdf['longitude'] = gdf['longitude'].round(4) gdf['latitude'] = gdf['latitude'].round(4) gdf['elevation'] = gdf['elevation'].round(2) gdf['avg_temp'] = gdf['avg_temp'].round(2) gdf['min_temp'] = gdf['min_temp'].round(2) gdf['max_temp'] = gdf['max_temp'].round(2) gdf['avg_precip'] = gdf['avg_precip'].round(2) gdf['min_precip'] = gdf['min_precip'].round(2) gdf['max_precip'] = gdf['max_precip'].round(2) gdf['high_temp_count'] = gdf['high_temp_count'].round(2) gdf['heavy_rain_count'] = gdf['heavy_rain_count'].round(2) # 打印去除缺失值前的数据行数 print(f"去除缺失值前数据行数: {gdf.shape[0]}") # 去除缺失值 gdf = gdf.dropna(subset=['high_temp_count', 'heavy_rain_count', 'elevation', 'avg_temp', 'min_temp', 'max_temp', 'avg_precip', 'min_precip', 'max_precip']).reset_index(drop=True) # 去除缺失值后的数据行数 print(f"去除缺失值后数据行数: {gdf.shape[0]}") # 检查去除缺失值后数据是否为空 if gdf.shape[0] == 0: raise ValueError("去除缺失值后数据为空,请检查数据。") # 3. 使用部分数据进行采样 gdf_sampled = gdf.sample(frac=0.00228, random_state=42).reset_index(drop=True) # 提取坐标 coords = list(zip(gdf_sampled.geometry.x, gdf_sampled.geometry.y)) # 提取自变量和因变量(高温模型) # 包含“降水最大值”“降水最小值” X_high_temp = gdf_sampled[['elevation', 'avg_precip', 'min_precip', 'max_precip']] X_high_temp = sm.add_constant(X_high_temp) # 添加常数项 Y_high_temp = gdf_sampled['high_temp_count'].values.reshape(-1, 1) # 调整维度 # 提取自变量和因变量(降水模型) # 包含“温度最大值”“温度最小值” X_heavy_rain = gdf_sampled[['elevation', 'avg_temp', 'min_temp', 'max_temp']] X_heavy_rain = sm.add_constant(X_heavy_rain) # 添加常数项 Y_heavy_rain = gdf_sampled['heavy_rain_count'].values.reshape(-1, 1) # 调整维度 # 检查数据形状,确保没有维度问题 print(f"X_high_temp shape: {X_high_temp.shape}") # 自变量矩阵 print(f"Y_high_temp shape: {Y_high_temp.shape}") # 因变量 print(f"X_heavy_rain shape: {X_heavy_rain.shape}") # 自变量矩阵 print(f"Y_heavy_rain shape: {Y_heavy_rain.shape}") # 因变量 # 检查是否有缺失值 if np.any(np.isnan(X_high_temp)) or np.any(np.isnan(Y_high_temp)): raise ValueError("高温模型输入数据中存在缺失值,请处理缺失值。") if np.any(np.isnan(X_heavy_rain)) or np.any(np.isnan(Y_heavy_rain)): raise ValueError("降水模型输入数据中存在缺失值,请处理缺失值。") # 确保行数大于列数 if X_high_temp.shape[0] <= X_high_temp.shape[1]: raise ValueError("高温模型自变量矩阵的行数应大于列数,请检查输入数据。") if X_heavy_rain.shape[0] <= X_heavy_rain.shape[1]: raise ValueError("降水模型自变量矩阵的行数应大于列数,请检查输入数据。") # 获取样本数量 n_samples = gdf_sampled.shape[0] # 设置带宽的最小值和最大值 bw_min_ht = int(n_samples * 0.05) # 最小带宽为样本数的 5% bw_max_ht = int(n_samples * 0.3) # 最大带宽为样本数的 30% bw_min_hr = int(n_samples * 0.05) # 最小带宽为样本数的 5% bw_max_hr = int(n_samples * 0.3) # 最大带宽为样本数的 30% # 4. 选择带宽(高温模型) print("选择高温日频率带宽中...") selector_ht = Sel_BW(coords, Y_high_temp, X_high_temp, multi=True) bws_ht = selector_ht.search(bw_min=bw_min_ht, bw_max=bw_max_ht) print(f"高温日频率的 MGWR 模型最佳带宽:{bws_ht}") # 5. 构建 MGWR 模型(高温模型) print("构建高温日频率 MGWR 模型中...") mgwr_model_ht = MGWR(coords, Y_high_temp, X_high_temp, selector_ht, n_jobs=-1) # 启用并行计算 mgwr_results_ht = mgwr_model_ht.fit() print(mgwr_results_ht.summary()) # 6. 提取 MGWR 结果(高温模型) gdf_sampled['mgwr_const_coef_ht'] = mgwr_results_ht.params[:, 0] gdf_sampled['mgwr_elevation_coef_ht'] = mgwr_results_ht.params[:, 1] gdf_sampled['mgwr_avg_precip_coef_ht'] = mgwr_results_ht.params[:, 2] gdf_sampled['mgwr_min_precip_coef_ht'] = mgwr_results_ht.params[:, 3] gdf_sampled['mgwr_max_precip_coef_ht'] = mgwr_results_ht.params[:, 4] # 7. 绘制高温日频率 MGWR 模型的系数分布 # 高程系数 fig, ax = plt.subplots(1, 1, figsize=(8, 6)) gdf_sampled.plot(column='mgwr_elevation_coef_ht', ax=ax, cmap='coolwarm', legend=True) ax.set_title('高温日频率 MGWR 模型的高程系数分布') plt.xlabel('经度') plt.ylabel('纬度') plt.show() # 平均降水系数 fig, ax = plt.subplots(1, 1, figsize=(8, 6)) gdf_sampled.plot(column='mgwr_avg_precip_coef_ht', ax=ax, cmap='coolwarm', legend=True) ax.set_title('高温日频率 MGWR 模型的平均降水系数分布') plt.xlabel('经度') plt.ylabel('纬度') plt.show() # 最小降水系数 fig, ax = plt.subplots(1, 1, figsize=(8, 6)) gdf_sampled.plot(column='mgwr_min_precip_coef_ht', ax=ax, cmap='coolwarm', legend=True) ax.set_title('高温日频率 MGWR 模型的最小降水系数分布') plt.xlabel('经度') plt.ylabel('纬度') plt.show() # 最大降水系数 fig, ax = plt.subplots(1, 1, figsize=(8, 6)) gdf_sampled.plot(column='mgwr_max_precip_coef_ht', ax=ax, cmap='coolwarm', legend=True) ax.set_title('高温日频率 MGWR 模型的最大降水系数分布') plt.xlabel('经度') plt.ylabel('纬度') plt.show() # 8. 选择带宽(降水模型) print("选择暴雨日频率带宽中...") selector_hr = Sel_BW(coords, Y_heavy_rain, X_heavy_rain, multi=True) bws_hr = selector_hr.search(bw_min=bw_min_hr, bw_max=bw_max_hr) print(f"暴雨日频率的 MGWR 模型最佳带宽:{bws_hr}") # 9. 构建 MGWR 模型(降水模型) print("构建暴雨日频率 MGWR 模型中...") mgwr_model_hr = MGWR(coords, Y_heavy_rain, X_heavy_rain, selector_hr, n_jobs=-1) # 启用并行计算 mgwr_results_hr = mgwr_model_hr.fit() print(mgwr_results_hr.summary()) # 10. 提取 MGWR 结果(降水模型) gdf_sampled['mgwr_const_coef_hr'] = mgwr_results_hr.params[:, 0] gdf_sampled['mgwr_elevation_coef_hr'] = mgwr_results_hr.params[:, 1] gdf_sampled['mgwr_avg_temp_coef_hr'] = mgwr_results_hr.params[:, 2] gdf_sampled['mgwr_min_temp_coef_hr'] = mgwr_results_hr.params[:, 3] gdf_sampled['mgwr_max_temp_coef_hr'] = mgwr_results_hr.params[:, 4] # 11. 绘制暴雨日频率 MGWR 模型的系数分布 # 高程系数 fig, ax = plt.subplots(1, 1, figsize=(8, 6)) gdf_sampled.plot(column='mgwr_elevation_coef_hr', ax=ax, cmap='coolwarm', legend=True) ax.set_title('暴雨日频率 MGWR 模型的高程系数分布') plt.xlabel('经度') plt.ylabel('纬度') plt.show() # 平均温度系数 fig, ax = plt.subplots(1, 1, figsize=(8, 6)) gdf_sampled.plot(column='mgwr_avg_temp_coef_hr', ax=ax, cmap='coolwarm', legend=True) ax.set_title('暴雨日频率 MGWR 模型的平均温度系数分布') plt.xlabel('经度') plt.ylabel('纬度') plt.show() # 最小温度系数 fig, ax = plt.subplots(1, 1, figsize=(8, 6)) gdf_sampled.plot(column='mgwr_min_temp_coef_hr', ax=ax, cmap='coolwarm', legend=True) ax.set_title('暴雨日频率 MGWR 模型的最小温度系数分布') plt.xlabel('经度') plt.ylabel('纬度') plt.show() # 最大温度系数 fig, ax = plt.subplots(1, 1, figsize=(8, 6)) gdf_sampled.plot(column='mgwr_max_temp_coef_hr', ax=ax, cmap='coolwarm', legend=True) ax.set_title('暴雨日频率 MGWR 模型的最大温度系数分布') plt.xlabel('经度') plt.ylabel('纬度') plt.show()代码解读:
-
变量名更新:根据您的要求,所有变量名都已更新为与 DataFrame 中的变量名一致。例如,
high_temp_count、heavy_rain_count、avg_temp等。 -
添加新变量到模型:
- 高温模型:在自变量中添加了
min_precip和max_precip,即最小和最大降水量。 - 降水模型:在自变量中添加了
min_temp和max_temp,即最小和最大温度。
- 高温模型:在自变量中添加了
-
数据处理:
- 优化数据类型:将相关列转换为
float32类型,以减小内存占用。 - 减少数据精度:对数值进行了四舍五入,减少数据的存储精度。
- 处理缺失值:在进行分析之前,删除了包含缺失值的行。
- 数据采样:为了提高计算效率,随机采样了一部分数据进行分析。
- 优化数据类型:将相关列转换为
-
模型构建:
- 带宽选择:使用
Sel_BW类为每个模型选择了最佳带宽。 - MGWR 模型:使用选定的带宽构建了 MGWR 模型,并输出了模型摘要。
- 带宽选择:使用
-
结果提取和可视化:
- 提取系数:将模型估计的参数(系数)添加到 GeoDataFrame 中。
- 绘图:使用
matplotlib和geopandas绘制了每个自变量的系数空间分布图。
请确保在运行此代码之前,已经正确加载并构建了
dataDataFrame,且包含以下列:longitude:经度latitude:纬度high_temp_count:高温日频数heavy_rain_count:暴雨日频数elevation:高程avg_temp:平均温度min_temp:最小温度max_temp:最大温度avg_precip:平均降水min_precip:最小降水max_precip:最大降水
运行此代码后,将得到模型的摘要信息,以及每个变量系数的空间分布图。
-