File size: 11,608 Bytes
3f71eec |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 |
import gradio as gr
import torch
import numpy as np
from PIL import Image
import torchvision.transforms as transforms
import pandas as pd
import os
import matplotlib.pyplot as plt
import seaborn as sns
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from torch.optim.lr_scheduler import ReduceLROnPlateau
import numpy as np
import pandas as pd
from PIL import Image
import os
import torchvision.transforms as transforms
from sklearn.model_selection import train_test_split
class ClimateNet(nn.Module):
def __init__(self, input_size=(256, 256), output_size=(64, 64)):
super(ClimateNet, self).__init__()
self.input_size = input_size
self.output_size = output_size
# Feature map sizes after two max pooling layers
self.feature_size = (input_size[0] // 4, input_size[1] // 4)
# Improved RGB Encoder with residual connections
self.rgb_encoder = nn.Sequential(
nn.Conv2d(3, 64, kernel_size=3, padding=1),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.Conv2d(64, 64, kernel_size=3, padding=1),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.MaxPool2d(2),
nn.Dropout2d(0.2),
nn.Conv2d(64, 128, kernel_size=3, padding=1),
nn.BatchNorm2d(128),
nn.ReLU(),
nn.Conv2d(128, 128, kernel_size=3, padding=1),
nn.BatchNorm2d(128),
nn.ReLU(),
nn.MaxPool2d(2),
nn.Dropout2d(0.2)
)
# Improved NDVI Encoder
self.ndvi_encoder = nn.Sequential(
nn.Conv2d(1, 64, kernel_size=3, padding=1),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.Conv2d(64, 64, kernel_size=3, padding=1),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.MaxPool2d(2),
nn.Dropout2d(0.2),
nn.Conv2d(64, 128, kernel_size=3, padding=1),
nn.BatchNorm2d(128),
nn.ReLU(),
nn.MaxPool2d(2),
nn.Dropout2d(0.2)
)
# Improved Terrain Encoder
self.terrain_encoder = nn.Sequential(
nn.Conv2d(1, 64, kernel_size=3, padding=1),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.Conv2d(64, 64, kernel_size=3, padding=1),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.MaxPool2d(2),
nn.Dropout2d(0.2),
nn.Conv2d(64, 128, kernel_size=3, padding=1),
nn.BatchNorm2d(128),
nn.ReLU(),
nn.MaxPool2d(2),
nn.Dropout2d(0.2)
)
# Improved Weather Encoder with deeper architecture
self.weather_encoder = nn.Sequential(
nn.Linear(4, 64),
nn.ReLU(),
nn.Dropout(0.2),
nn.Linear(64, 128),
nn.ReLU(),
nn.Dropout(0.2),
nn.Linear(128, 128)
)
# Improved Feature Fusion
self.fusion = nn.Sequential(
nn.Conv2d(512, 512, kernel_size=1),
nn.BatchNorm2d(512),
nn.ReLU(),
nn.Dropout2d(0.2),
nn.Conv2d(512, 512, kernel_size=1),
nn.BatchNorm2d(512),
nn.ReLU()
)
# Improved Decoders with skip connections
self.wind_decoder = nn.Sequential(
nn.ConvTranspose2d(512, 256, kernel_size=4, stride=2, padding=1),
nn.BatchNorm2d(256),
nn.ReLU(),
nn.Dropout2d(0.2),
nn.ConvTranspose2d(256, 128, kernel_size=4, stride=2, padding=1),
nn.BatchNorm2d(128),
nn.ReLU(),
nn.Dropout2d(0.2),
nn.Conv2d(128, 64, kernel_size=3, padding=1),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.Conv2d(64, 1, kernel_size=1),
nn.Sigmoid()
)
self.solar_decoder = nn.Sequential(
nn.ConvTranspose2d(512, 256, kernel_size=4, stride=2, padding=1),
nn.BatchNorm2d(256),
nn.ReLU(),
nn.Dropout2d(0.2),
nn.ConvTranspose2d(256, 128, kernel_size=4, stride=2, padding=1),
nn.BatchNorm2d(128),
nn.ReLU(),
nn.Dropout2d(0.2),
nn.Conv2d(128, 64, kernel_size=3, padding=1),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.Conv2d(64, 1, kernel_size=1),
nn.Sigmoid()
)
def forward(self, x):
batch_size = x['rgb'].size(0)
# Resize all inputs to input_size
rgb_input = F.interpolate(x['rgb'], size=self.input_size, mode='bilinear', align_corners=False)
ndvi_input = F.interpolate(x['ndvi'], size=self.input_size, mode='bilinear', align_corners=False)
terrain_input = F.interpolate(x['terrain'], size=self.input_size, mode='bilinear', align_corners=False)
# Extract features
rgb_features = self.rgb_encoder(rgb_input) # [B, 128, H/4, W/4]
ndvi_features = self.ndvi_encoder(ndvi_input) # [B, 128, H/4, W/4]
terrain_features = self.terrain_encoder(terrain_input) # [B, 128, H/4, W/4]
# Process weather features and expand to match feature map size
weather_features = self.weather_encoder(x['weather_features']) # [B, 128]
weather_features = weather_features.view(batch_size, 128, 1, 1)
weather_features = F.interpolate(
weather_features,
size=self.feature_size,
mode='nearest'
)
# Combine features
combined_features = torch.cat([
rgb_features,
ndvi_features,
terrain_features,
weather_features
], dim=1)
# Apply fusion
fused_features = self.fusion(combined_features)
# Generate predictions and resize to output_size
wind_heatmap = self.wind_decoder(fused_features)
solar_heatmap = self.solar_decoder(fused_features)
wind_heatmap = F.interpolate(wind_heatmap, size=self.output_size, mode='bilinear', align_corners=False)
solar_heatmap = F.interpolate(solar_heatmap, size=self.output_size, mode='bilinear', align_corners=False)
return wind_heatmap, solar_heatmap
class ClimatePredictor:
def __init__(self, model_path, device=None):
if device is None:
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
else:
self.device = device
print(f"Using device: {self.device}")
# Load model
self.model = ClimateNet(input_size=(256, 256), output_size=(64, 64)).to(self.device)
checkpoint = torch.load(model_path, map_location=self.device)
if "module" in list(checkpoint['model_state_dict'].keys())[0]:
self.model = torch.nn.DataParallel(self.model)
self.model.load_state_dict(checkpoint['model_state_dict'])
self.model.eval()
self.rgb_transform = transforms.Compose([
transforms.Resize((256, 256)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
self.single_channel_transform = transforms.Compose([
transforms.Resize((256, 256)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.5], std=[0.5])
])
def predict_from_inputs(self, rgb_image, ndvi_image, terrain_image,
elevation_data, wind_speed, wind_direction,
temperature, humidity):
"""Gradio ์ธํฐํ์ด์ค์ฉ ์์ธก ํจ์"""
# ์ด๋ฏธ์ง ์ ์ฒ๋ฆฌ
rgb_tensor = self.rgb_transform(Image.fromarray(rgb_image)).unsqueeze(0)
ndvi_tensor = self.single_channel_transform(Image.fromarray(ndvi_image)).unsqueeze(0)
terrain_tensor = self.single_channel_transform(Image.fromarray(terrain_image)).unsqueeze(0)
# ๊ณ ๋ ๋ฐ์ดํฐ ์ฒ๋ฆฌ
elevation_tensor = torch.from_numpy(elevation_data).float().unsqueeze(0).unsqueeze(0)
elevation_tensor = (elevation_tensor - elevation_tensor.min()) / (elevation_tensor.max() - elevation_tensor.min())
# ๊ธฐ์ ๋ฐ์ดํฐ ์ฒ๋ฆฌ
weather_features = np.array([wind_speed, wind_direction, temperature, humidity])
weather_features = (weather_features - weather_features.min()) / (weather_features.max() - weather_features.min())
weather_features = torch.tensor(weather_features, dtype=torch.float32).unsqueeze(0)
# ๋๋ฐ์ด์ค๋ก ์ด๋
sample = {
'rgb': rgb_tensor.to(self.device),
'ndvi': ndvi_tensor.to(self.device),
'terrain': terrain_tensor.to(self.device),
'elevation': elevation_tensor.to(self.device),
'weather_features': weather_features.to(self.device)
}
# ์์ธก
with torch.no_grad():
wind_pred, solar_pred = self.model(sample)
# ๊ฒฐ๊ณผ๋ฅผ numpy ๋ฐฐ์ด๋ก ๋ณํ
wind_map = wind_pred.cpu().numpy()[0, 0]
solar_map = solar_pred.cpu().numpy()[0, 0]
# ๊ฒฐ๊ณผ ์๊ฐํ
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 5))
# ํ๋ ฅ ๋ฐ์ ์ ์ฌ๋ ์๊ฐํ
sns.heatmap(wind_map, ax=ax1, cmap='YlOrRd', cbar_kws={'label': 'Wind Power Potential'})
ax1.set_title('Wind Power Potential Map')
# ํ์๊ด ๋ฐ์ ์ ์ฌ๋ ์๊ฐํ
sns.heatmap(solar_map, ax=ax2, cmap='YlOrRd', cbar_kws={'label': 'Solar Power Potential'})
ax2.set_title('Solar Power Potential Map')
plt.tight_layout()
return fig
# Gradio ์ธํฐํ์ด์ค ์์ฑ
def create_gradio_interface():
predictor = ClimatePredictor('best_model.pth')
def predict_and_visualize(rgb_image, ndvi_image, terrain_image, elevation_file,
wind_speed, wind_direction, temperature, humidity):
# Load elevation data
elevation_data = np.load(elevation_file.name)
# Generate prediction and visualization
result = predictor.predict_from_inputs(
rgb_image, ndvi_image, terrain_image, elevation_data,
wind_speed, wind_direction, temperature, humidity
)
return result
interface = gr.Interface(
fn=predict_and_visualize,
inputs=[
gr.Image(label="RGB Satellite Image", type="numpy"),
gr.Image(label="NDVI Image", type="numpy"),
gr.Image(label="Terrain Map", type="numpy"),
gr.File(label="Elevation Data (NPY file)"),
gr.Number(label="Wind Speed (m/s)", value=5.0),
gr.Number(label="Wind Direction (degrees)", value=180.0),
gr.Number(label="Temperature (ยฐC)", value=25.0),
gr.Number(label="Humidity (%)", value=60.0)
],
outputs=gr.Plot(label="Prediction Results"),
title="Renewable Energy Potential Predictor",
description="Upload satellite imagery and environmental data to predict wind and solar power potential.",
examples=[
[
"examples/rgb_example.png",
"examples/ndvi_example.png",
"examples/terrain_example.png",
"examples/elevation_example.npy",
5.0, 180.0, 25.0, 60.0
]
]
)
return interface
if __name__ == "__main__":
interface = create_gradio_interface()
interface.launch()s |