復現《Local GDP Estimates Around the World》論文的完整指南
1. 引言
1.1 論文概述
《Local GDP Estimates Around the World》是一篇重要的經濟地理學研究論文,作者提出了一種創新的方法來估計全球范圍內次國家層面的GDP數據。這項工作填補了全球經濟發展研究中子國家級經濟數據缺乏的空白,為區域經濟分析、政策制定和國際比較提供了寶貴的數據支持。
論文的核心貢獻在于開發了一個統一的框架,利用夜間燈光數據、人口分布信息和其他地理空間特征,通過機器學習方法預測次國家區域的GDP。這種方法克服了傳統GDP統計在子國家層面數據不完整、不一致的問題。
1.2 復現目標與意義
復現這篇論文的工作具有多重意義:
- 驗證研究結果:通過獨立復現可以驗證原論文方法和結論的可靠性
- 方法學習:深入理解空間經濟學與機器學習結合的先進方法
- 應用擴展:為后續研究建立基礎,便于改進方法和應用于其他領域
- 教學示范:為空間計量經濟學和機器學習實踐提供完整案例
本文將詳細講解如何使用R語言完整復現該論文的主要模型和算法,包括數據準備、特征工程、模型構建、結果驗證等全過程。
2. 環境準備與數據獲取
2.1 開發環境配置
復現工作使用R語言進行,需要配置以下環境:
# 安裝必要包
install.packages(c("tidyverse", "sf", "raster", "caret", "xgboost", "glmnet", "randomForest", "doParallel", "ggplot2","ggspatial", "viridis", "lightgbm", "tidymodels"))# 加載庫
library(tidyverse)
library(sf)
library(raster)
library(caret)
library(xgboost)
library(doParallel)
library(ggspatial)
2.2 數據來源與獲取
論文使用了多源數據,主要包括:
- 夜間燈光數據:來自VIIRS/DMSP衛星
- 人口數據:WorldPop項目
- 行政邊界數據:GADM數據庫
- 國家層面GDP數據:世界銀行
這些數據可以從以下渠道獲取:
# 設置數據下載函數
download_data <- function(url, destfile) {if(!file.exists(destfile)) {download.file(url, destfile, mode = "wb")}
}# 下載夜間燈光數據示例
download_data("https://eogdata.mines.edu/nighttime_light/annual/v21/2020/VNL_v21_npp_2020_global_vcmslcfg_c202205302300.average_masked.dat.tif.gz","viirs_2020.tif.gz"
)# 解壓夜間燈光數據
R.utils::gunzip("viirs_2020.tif.gz", remove = FALSE)# 下載WorldPop人口數據
download_data("https://data.worldpop.org/GIS/Population/Global_2000_2020/2020/0_Mosaicked/ppp_2020_1km_Aggregated.tif","worldpop_2020.tif"
)# 下載行政邊界數據
download_data("https://biogeo.ucdavis.edu/data/gadm3.6/gadm36_levels_shp.zip","gadm36_shp.zip"
)# 解壓行政邊界數據
unzip("gadm36_shp.zip", exdir = "gadm36")
2.3 數據預處理
將原始數據處理為可用于建模的格式:
# 加載行政邊界
admin_boundaries <- st_read("gadm36/gadm36_0.shp")# 加載夜間燈光數據
nightlight <- raster("viirs_2020.tif")# 加載人口數據
population <- raster("worldpop_2020.tif")# 統一坐標參考系統
crs_common <- st_crs(admin_boundaries)
nightlight <- projectRaster(nightlight, crs = crs_common$proj4string)
population <- projectRaster(population, crs = crs_common$proj4string)# 裁剪到研究區域范圍
study_area <- st_union(admin_boundaries)
nightlight <- crop(nightlight, study_area)
population <- crop(population, study_area)
3. 特征工程與數據構建
3.1 空間特征提取
論文使用了多種空間特征,主要包括:
- 夜間燈光強度統計量
- 人口密度統計量
- 地理空間特征(如到海岸線距離)
- 區域形態特征
# 定義計算空間特征的函數
extract_spatial_features <- function(admin_unit, nl_data, pop_data) {# 裁剪數據到當前行政單元nl_cropped <- crop(nl_data, admin_unit)nl_masked <- mask(nl_cropped, admin_unit)pop_cropped <- crop(pop_data, admin_unit)pop_masked <- mask(pop_cropped, admin_unit)# 計算夜間燈光特征nl_values <- values(nl_masked)nl_features <- c(mean(nl_values, na.rm = TRUE),median(nl_values, na.rm = TRUE),sd(nl_values, na.rm = TRUE),sum(nl_values, na.rm = TRUE),quantile(nl_values, probs = c(0.25, 0.75), na.rm = TRUE))names(nl_features) <- paste0("nl_", c("mean", "median", "sd", "sum", "q25", "q75"))# 計算人口特征pop_values <- values(pop_masked)pop_features <- c(mean(pop_values, na.rm = TRUE),sum(pop_values, na.rm = TRUE),sd(pop_values, na.rm = TRUE))names(pop_features) <- paste0("pop_", c("mean", "sum", "sd"))# 計算燈光與人口比率ratio_features <- c(sum(nl_values, na.rm = TRUE) / sum(pop_values, na.rm = TRUE),mean(nl_values, na.rm = TRUE) / mean(pop_values, na.rm = TRUE))names(ratio_features) <- c("nl_pop_ratio_sum", "nl_pop_ratio_mean")# 合并所有特征c(nl_features, pop_features, ratio_features)
}# 應用特征提取函數到所有行政單元
admin_features <- admin_boundaries %>%mutate(area = st_area(.),centroid = st_centroid(geometry),coast_dist = st_distance(centroid, st_union(st_cast(., "MULTILINESTRING")))) %>%bind_cols(map_dfr(1:nrow(.), function(i) {extract_spatial_features(.[i, ], nightlight, population)}))
3.2 國家層面特征合并
從世界銀行獲取國家層面GDP數據并合并:
# 加載世界銀行GDP數據
gdp_national <- read_csv("https://api.worldbank.org/v2/en/indicator/NY.GDP.MKTP.CD?downloadformat=csv") %>%clean_names() %>%select(country_code, gdp = x2020) %>%filter(!is.na(gdp))# 合并到行政單元數據
admin_features <- admin_features %>%left_join(gdp_national, by = c("GID_0" = "country_code")) %>%mutate(gdp_pc = gdp / as.numeric(pop_sum))
3.3 特征標準化與分割
# 對數變換和標準化
preprocess_features <- function(data) {data %>%mutate(across(c(contains("nl_"), contains("pop_")), log1p)) %>%recipe(gdp_pc ~ nl_mean + nl_sum + pop_mean + pop_sum + nl_pop_ratio_sum + area + coast_dist) %>%step_center(all_predictors()) %>%step_scale(all_predictors()) %>%prep() %>%bake(new_data = data)
}# 數據分割
set.seed(42)
train_index <- createDataPartition(admin_features$gdp_pc, p = 0.8, list = FALSE)
train_data <- preprocess_features(admin_features[train_index, ])
test_data <- preprocess_features(admin_features[-train_index, ])
4. 模型構建與訓練
論文使用了多種機器學習方法,包括彈性網絡回歸、隨機森林和梯度提升樹。我們將逐一實現這些模型。
4.1 彈性網絡回歸
# 設置交叉驗證
ctrl <- trainControl(method = "cv",number = 5,verboseIter = TRUE
)# 訓練彈性網絡模型
enet_model <- train(gdp_pc ~ .,data = train_data,method = "glmnet",trControl = ctrl,tuneLength = 10,metric = "RMSE"
)# 查看最佳參數
print(enet_model$bestTune)# 測試集評估
enet_pred <- predict(enet_model, newdata = test_data)
postResample(enet_pred, test_data$gdp_pc)
4.2 隨機森林
# 設置并行計算
cl <- makePSOCKcluster(4)
registerDoParallel(cl)# 訓練隨機森林
rf_model <- train(gdp_pc ~ .,data = train_data,method = "rf",trControl = ctrl,tuneLength = 5,importance = TRUE,metric = "RMSE"
)# 停止并行計算
stopCluster(cl)# 查看變量重要性
varImp(rf_model)# 測試集評估
rf_pred <- predict(rf_model, newdata = test_data)
postResample(rf_pred, test_data$gdp_pc)
4.3 XGBoost模型
# 準備DMatrix格式數據
dtrain <- xgb.DMatrix(data = as.matrix(select(train_data, -gdp_pc)),label = train_data$gdp_pc
)dtest <- xgb.DMatrix(data = as.matrix(select(test_data, -gdp_pc)),label = test_data$gdp_pc
)# 設置參數
params <- list(objective = "reg:squarederror",eta = 0.05,max_depth = 6,min_child_weight = 1,subsample = 0.8,colsample_bytree = 0.8
)# 交叉驗證尋找最佳迭代次數
xgb_cv <- xgb.cv(params = params,data = dtrain,nrounds = 1000,nfold = 5,early_stopping_rounds = 20,print_every_n = 10
)# 訓練最終模型
xgb_model <- xgb.train(params = params,data = dtrain,nrounds = xgb_cv$best_iteration,watchlist = list(train = dtrain, test = dtest),print_every_n = 10
)# 測試集評估
xgb_pred <- predict(xgb_model, newdata = dtest)
postResample(xgb_pred, test_data$gdp_pc)
4.4 模型集成
論文采用了模型集成策略來提高預測精度:
# 創建集成預測
ensemble_pred <- 0.4*xgb_pred + 0.3*rf_pred + 0.3*enet_pred# 評估集成模型
postResample(ensemble_pred, test_data$gdp_pc)
5. 結果分析與可視化
5.1 模型性能比較
# 收集各模型結果
results <- tibble(Model = c("Elastic Net", "Random Forest", "XGBoost", "Ensemble"),RMSE = c(postResample(enet_pred, test_data$gdp_pc)["RMSE"],postResample(rf_pred, test_data$gdp_pc)["RMSE"],postResample(xgb_pred, test_data$gdp_pc)["RMSE"],postResample(ensemble_pred, test_data$gdp_pc)["RMSE"]),R2 = c(postResample(enet_pred, test_data$gdp_pc)["Rsquared"],postResample(rf_pred, test_data$gdp_pc)["Rsquared"],postResample(xgb_pred, test_data$gdp_pc)["Rsquared"],postResample(ensemble_pred, test_data$gdp_pc)["Rsquared"])
)# 繪制性能比較圖
ggplot(results, aes(x = Model, y = RMSE, fill = Model)) +geom_bar(stat = "identity") +geom_text(aes(label = round(RMSE, 3)), vjust = -0.5) +labs(title = "Model Performance Comparison", y = "RMSE") +theme_minimal()ggplot(results, aes(x = Model, y = R2, fill = Model)) +geom_bar(stat = "identity") +geom_text(aes(label = round(R2, 3)), vjust = -0.5) +labs(title = "Model Performance Comparison", y = "R-squared") +theme_minimal()
5.2 預測結果空間可視化
# 對整個數據集進行預測
full_pred <- admin_features %>%mutate(pred_gdp_pc = predict(xgb_model, newdata = xgb.DMatrix(as.matrix(select(preprocess_features(.), -gdp_pc)))))# 繪制預測結果地圖
ggplot() +geom_sf(data = full_pred, aes(fill = log(pred_gdp_pc)), color = NA) +scale_fill_viridis_c(option = "magma", name = "Log(GDP per capita)") +labs(title = "Predicted Subnational GDP per Capita") +theme_void() +theme(plot.title = element_text(hjust = 0.5))
5.3 殘差分析
# 計算測試集殘差
test_data <- test_data %>%mutate(pred = ensemble_pred,residual = gdp_pc - pred)# 殘差分布圖
ggplot(test_data, aes(x = residual)) +geom_histogram(bins = 30, fill = "steelblue", color = "white") +labs(title = "Distribution of Residuals", x = "Residual", y = "Count") +theme_minimal()# 殘差與預測值關系圖
ggplot(test_data, aes(x = pred, y = residual)) +geom_point(alpha = 0.5) +geom_hline(yintercept = 0, linetype = "dashed", color = "red") +labs(title = "Residuals vs Predicted Values", x = "Predicted GDP per capita", y = "Residual") +theme_minimal()
6. 討論與改進
6.1 復現過程中的挑戰
在復現論文的過程中,我們遇到了幾個主要挑戰:
-
數據獲取與預處理:原始數據來源多樣,格式不統一,需要進行大量的清洗和轉換工作。特別是夜間燈光數據需要進行輻射定標和異常值處理。
-
計算資源限制:全球高分辨率空間數據的處理對計算資源要求較高,特別是內存需求大。我們采用了分塊處理和并行計算來緩解這一問題。
-
模型調參:論文中部分模型參數沒有詳細說明,需要通過交叉驗證和網格搜索來確定最佳參數組合。
-
結果差異:由于數據版本和預處理細節的差異,我們的復現結果與論文報告的結果存在微小差異,但整體趨勢一致。
6.2 改進方向
基于復現經驗,我們提出以下改進方向:
- 特征工程優化:
- 加入更多地理空間特征,如地形復雜度、土地利用類型等
- 考慮空間自相關特征,加入莫蘭指數等空間統計量
- 嘗試不同的夜間燈光數據聚合方式
# 示例:計算空間自相關特征
calculate_spatial_autocorr <- function(data, var_name) {nb <- spdep::poly2nb(data)lw <- spdep::nb2listw(nb)spdep::moran.test(data[[var_name]], lw)$estimate[1]
}
-
模型架構改進:
- 嘗試深度學習模型,如卷積神經網絡處理空間數據
- 使用空間交叉驗證代替普通交叉驗證
- 加入分層抽樣確保不同地區均衡表示
-
不確定性量化:
- 實現貝葉斯方法量化預測不確定性
- 使用分位數回歸估計預測區間
# 示例:分位數回歸
library(quantreg)
quantile_model <- rq(gdp_pc ~ ., data = train_data, tau = c(0.05, 0.5, 0.95))
7. 結論
本文詳細介紹了如何使用R語言復現《Local GDP Estimates Around the World》論文中的主要模型和方法。通過完整的流程演示,包括數據獲取、特征工程、模型構建和結果分析,我們驗證了論文提出的基于夜間燈光數據和其他空間特征預測次國家GDP方法的有效性。
復現結果表明,集成學習方法(特別是XGBoost與隨機森林的結合)能夠較好地捕捉GDP分布的空間模式,預測精度達到可接受水平。這一方法為缺乏官方統計數據的地區提供了可靠的經濟活動估算工具。
未來的研究可以進一步探索:
- 更高時空分辨率的數據應用
- 結合更多新興數據源(如社交媒體、衛星影像等)
- 動態模型構建實現時間序列預測
- 將方法擴展到其他經濟指標估計
本文提供的完整代碼框架可作為相關研究的起點,助力空間經濟學和機器學習交叉領域的研究發展。