File size: 9,436 Bytes
613ee99 | 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 | """
内存优化版数据预处理与 Dataset。
- 从 feather 预处理到 4D npy 文件(一次)
- 训练时通过 memmap + 按需切 patch,避免 4D 大数组在多进程中拷贝多份
"""
import os
import gc
import pickle
from typing import Dict, Any, Tuple, Optional
import numpy as np
import torch
from torch.utils.data import Dataset
from sklearn.preprocessing import RobustScaler
import pyarrow.feather as feather
from process_data import optimize_floats
# 与 pipeline_new.py 中 pro_name 保持一致
PRO_NAME = ['sss', 'ssh', 'slp', 'wind', 'mld', 'sst', 'ice', 'co2', 'chl']
def _suffix(mode: str, start_year: int, end_year: int, data_name: str) -> str:
return f"{mode}_{start_year}_{end_year}_{data_name}"
def load_raw_dataframe(config: Dict[str, Any], data_name: str):
"""
从 feather 读原始 DataFrame,只选择需要的列。
"""
preprocessed_path = os.path.join(
config['preprocessed_data_dir'],
f'{data_name}.feather'
)
print(f'[mmap] read feather: {preprocessed_path}')
df = feather.read_feather(preprocessed_path, memory_map=True)
df = df[df['year'] >= 1990][config['columns']]
df = optimize_floats(df)
return df
def normalize_inplace(df, config: Dict[str, Any],
normalizer: Optional[Dict[str, RobustScaler]] = None
) -> Dict[str, RobustScaler]:
"""
使用 RobustScaler 做列归一化。
- normalizer 为 None 时会重新拟合
- 否则仅做 transform
"""
if normalizer is None:
normalizer = {}
for col in config['norm_columns']:
normalizer[col] = RobustScaler()
normalizer[col].fit(df[col].values.reshape(-1, 1))
for col in config['norm_columns']:
df[col] = normalizer[col].transform(
df[col].values.reshape(-1, 1)
).reshape(-1,)
return normalizer
def dataframe_to_4d_array(df, config: Dict[str, Any],
target_upper: float = 700.0) -> np.ndarray:
"""
把 DataFrame 转成 (lat, lon, time, feat) 的 4D float32 数组。
"""
df = df.sort_values(by=['latitude', 'longitude', 'year', 'month'])
df[[config['target']]] = np.clip(df[[config['target']]], None, target_upper)
lat_cnt = df['latitude'].unique().shape[0]
lon_cnt = df['longitude'].unique().shape[0]
feat_cnt = df.shape[-1]
arr = df.values.astype(np.float32)
arr = arr.reshape(lat_cnt, lon_cnt, -1, feat_cnt)
print(f'[mmap] 4D array shape: {arr.shape}')
return arr
def preprocess_to_npy(config: Dict[str, Any],
data_name: str,
mode: str,
start_year: int,
end_year: int,
out_dir: str,
normalizer: Optional[Dict[str, RobustScaler]] = None,
target_upper: float = 700.0
) -> Tuple[str, Dict[str, RobustScaler]]:
"""
预处理到 npy 文件。
- 若 normalizer 为 None:拟合并保存 normalizer
- 若 normalizer 已提供:仅做 transform(用于 valid/test 等)
返回:
npy_path, normalizer
"""
os.makedirs(out_dir, exist_ok=True)
suffix = _suffix(mode, start_year, end_year, data_name)
npy_path = os.path.join(out_dir, f'preprocessed_{suffix}.npy')
meta_path = os.path.join(out_dir, f'preprocessed_{suffix}_meta.npz')
norm_path = os.path.join(out_dir, f'preprocessed_{suffix}_normalizer.pkl')
if os.path.exists(npy_path) and os.path.exists(meta_path):
print(f'[mmap] found existing npy: {npy_path}')
if normalizer is None and os.path.exists(norm_path):
with open(norm_path, 'rb') as f:
normalizer = pickle.load(f)
return npy_path, normalizer
df = load_raw_dataframe(config, data_name)
# 与原 preprocess_data 中的时间窗口逻辑保持一致
shift_year = int(config['window'] // 12)
start_year_adj = start_year - shift_year
df = df[(start_year_adj <= df.year) & (df.year <= end_year)].copy()
# 与原逻辑保持一致:目标均值太小时放大
if np.abs(df[config["target"]].mean()) < 1e-6:
df[config["target"]] = df[config["target"]] * 1e8
# 环境变量特征补 NaN
df[PRO_NAME] = df[PRO_NAME].fillna(0.0)
# 归一化
normalizer = normalize_inplace(df, config, normalizer=normalizer)
# 转 4D
arr = dataframe_to_4d_array(df, config, target_upper=target_upper)
# 保存 npy + meta + normalizer
np.save(npy_path, arr)
np.savez(meta_path, shape=arr.shape)
with open(norm_path, 'wb') as f:
pickle.dump(normalizer, f)
del df, arr
gc.collect()
print(f'[mmap] saved npy to {npy_path}')
return npy_path, normalizer
def get_preprocessed_npy_path(config: Dict[str, Any],
data_name: str,
mode: str,
start_year: int,
end_year: int,
out_dir: str,
normalizer: Optional[Dict[str, RobustScaler]] = None
) -> str:
"""
返回 npy 路径;不存在时会先预处理。
"""
npy_path, _ = preprocess_to_npy(
config=config,
data_name=data_name,
mode=mode,
start_year=start_year,
end_year=end_year,
out_dir=out_dir,
normalizer=normalizer,
)
return npy_path
def load_normalizer(config: Dict[str, Any],
data_name: str,
mode: str,
start_year: int,
end_year: int,
out_dir: str
) -> Optional[Dict[str, RobustScaler]]:
"""
从磁盘加载已保存的 normalizer。
"""
suffix = _suffix(mode, start_year, end_year, data_name)
norm_path = os.path.join(out_dir, f'preprocessed_{suffix}_normalizer.pkl')
if os.path.exists(norm_path):
with open(norm_path, 'rb') as f:
normalizer = pickle.load(f)
return normalizer
return None
class OceanDatasetMmap(Dataset):
"""
内存映射 Dataset:
- 不把 4D data 全部放进 self.data
- 只保存 npy 路径 + indexes
- __getitem__ 时用 np.load(..., mmap_mode='r') 按需切 patch
"""
def __init__(self,
npy_path: str,
indexes: np.ndarray,
config: Dict[str, Any],
mode: str,
percent: float = 1.0):
self.config = config
self.lat_patch = config['patch']
self.lon_patch = config['patch']
self.window_size = config['window']
self.mode = mode
self.npy_path = npy_path
indexes = np.array(indexes, dtype=np.int64)
if mode == 'train' and percent < 1.0:
indexes = self._select_top_rows(indexes, percent)
self.indexes = torch.from_numpy(indexes)
meta_path = npy_path.replace('.npy', '_meta.npz')
meta = np.load(meta_path)
self.data_shape = tuple(meta['shape'])
meta.close()
print(f'[mmap] {mode} dataset: data_shape={self.data_shape}, '
f'indexes_shape={self.indexes.shape}')
def _select_top_rows(self, indexes: np.ndarray, percent: float) -> np.ndarray:
if percent >= 1.0:
return indexes
nan_rate = self._get_nan_rate(indexes)
top_idx = np.argsort(nan_rate)
top_idx = top_idx[:int(top_idx.shape[0] * percent)]
return indexes[top_idx]
def _get_nan_rate(self, indexes: np.ndarray) -> np.ndarray:
data = np.load(self.npy_path, mmap_mode='r')
labels = []
for (lat_s, lon_s, month_s) in indexes:
label = data[
lat_s:lat_s + self.lat_patch,
lon_s:lon_s + self.lon_patch,
month_s + self.window_size - 1,
-1
]
labels.append(label)
labels = np.stack(labels, axis=0).reshape(len(labels), -1)
nan_rate = np.isnan(labels).astype('float').sum(axis=-1) / labels.shape[-1]
return nan_rate
def _get_label(self, data: np.ndarray, d3_index) -> np.ndarray:
lat_s, lon_s, month_s = d3_index
label = data[
lat_s:lat_s + self.lat_patch,
lon_s:lon_s + self.lon_patch,
month_s + self.window_size - 1,
-1
]
return label
def __getitem__(self, idx: int):
index = self.indexes[idx].numpy()
data = np.load(self.npy_path, mmap_mode='r')
lat_s, lon_s, month_s = index
patch = np.array(
data[
lat_s:lat_s + self.lat_patch,
lon_s:lon_s + self.lon_patch,
month_s:month_s + self.window_size,
:
],
dtype=np.float32,
copy=True,
)
if self.config['add_history_target']:
patch[:, :, -1, -1] = 0
else:
patch = patch[..., :-1]
patch = np.nan_to_num(patch, nan=0.0)
label = self._get_label(data, index)
label = np.nan_to_num(label, nan=float('nan'))
data = None
return torch.from_numpy(patch), torch.tensor(label, dtype=torch.float32).unsqueeze(-1)
def __len__(self) -> int:
return len(self.indexes)
|