| """ |
| 内存优化版数据预处理与 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 |
|
|
|
|
| |
| 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) |
|
|
| |
| 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 |
|
|
| |
| df[PRO_NAME] = df[PRO_NAME].fillna(0.0) |
|
|
| |
| normalizer = normalize_inplace(df, config, normalizer=normalizer) |
|
|
| |
| arr = dataframe_to_4d_array(df, config, target_upper=target_upper) |
|
|
| |
| 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) |
|
|
|
|
|
|