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 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
| import logging import os from datetime import datetime
import pandas as pd import numpy as np import torch import torch.nn as nn import winsound from sklearn.metrics import r2_score from torch.utils.data import Dataset, DataLoader from sklearn.preprocessing import StandardScaler, LabelEncoder from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt import pickle
from tqdm import tqdm
file_path = 'F:\Python\Transformer\demo\data\进口\merged_output.csv'
df = pd.read_csv(file_path, encoding='UTF-8', thousands=',', low_memory=False)
df['year'] = df['数据年月'].astype(str).str[:4].astype(int) df['month'] = df['数据年月'].astype(str).str[4:].astype(int)
categorical_cols = ['贸易伙伴编码', '商品编码', '贸易方式编码', '注册地编码', '计量单位'] continuous_cols = ['year', 'month', '数量', '人民币'] target_cols = ['单价']
df[target_cols] = df[target_cols].replace({'-': np.nan, '': np.nan}, regex=False) df[target_cols] = df[target_cols].apply(pd.to_numeric, errors='coerce')
df[target_cols] = df[target_cols].clip(lower=0) df['log_单价'] = np.log1p(df['单价']) target_cols_log = ['log_单价']
scaler_y = StandardScaler() df[target_cols_log] = scaler_y.fit_transform(df[target_cols_log])
for col in continuous_cols: df[col] = df[col].replace({'-': np.nan, '': np.nan}, regex=False) df[col] = pd.to_numeric(df[col], errors='coerce')
df.dropna(subset=categorical_cols + continuous_cols + target_cols_log, inplace=True)
label_encoders = {} for col in categorical_cols: le = LabelEncoder() df[col] = le.fit_transform(df[col].astype(str)) label_encoders[col] = le
scaler_X = StandardScaler() df[continuous_cols] = scaler_X.fit_transform(df[continuous_cols])
grouped = df.groupby('商品编码') sequences = [] seq_length = 12
for name, group in grouped: group = group.sort_values(['year', 'month']) if len(group) < seq_length + 1: continue
X_cat_group = group[categorical_cols].values X_cont_group = group[continuous_cols].values y_group = group[target_cols_log].values
for i in range(len(X_cat_group) - seq_length): x_cat_seq = X_cat_group[i:i + seq_length] x_cont_seq = X_cont_group[i:i + seq_length] y_val = y_group[i + seq_length] sequences.append((x_cat_seq, x_cont_seq, y_val))
if sequences: X_cat, X_cont, y = zip(*sequences) X_cat = np.array(X_cat) X_cont = np.array(X_cont) y = np.array(y) else: raise ValueError("没有足够数据创建序列,请检查数据或减小seq_length")
X_cat_train, X_cat_test, X_cont_train, X_cont_test, y_train, y_test = train_test_split( X_cat, X_cont, y, test_size=0.2, shuffle=False )
X_cat_train_tensor = torch.tensor(X_cat_train, dtype=torch.long) X_cont_train_tensor = torch.tensor(X_cont_train, dtype=torch.float32) y_train_tensor = torch.tensor(y_train, dtype=torch.float32)
X_cat_test_tensor = torch.tensor(X_cat_test, dtype=torch.long) X_cont_test_tensor = torch.tensor(X_cont_test, dtype=torch.float32) y_test_tensor = torch.tensor(y_test, dtype=torch.float32)
train_dataset = torch.utils.data.TensorDataset(X_cat_train_tensor, X_cont_train_tensor, y_train_tensor) train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True) test_dataset = torch.utils.data.TensorDataset(X_cat_test_tensor, X_cont_test_tensor, y_test_tensor) test_loader = DataLoader( test_dataset, batch_size=16, shuffle=False, num_workers=0, pin_memory=False if not torch.cuda.is_available() else True )
class EarlyStopping: def __init__(self, patience=10, verbose=False, delta=0, path='F:\\Python\\Transformer\\demo\\model\\trade_Transformer_LSTM\\in\\checkpoint_price.pth'): self.patience = patience self.verbose = verbose self.counter = 0 self.best_score = None self.early_stop = False self.val_loss_min = np.Inf self.delta = delta self.path = path
def __call__(self, val_loss, model): score = -val_loss
if self.best_score is None: self.best_score = score self.save_checkpoint(val_loss, model) elif score < self.best_score + self.delta: self.counter += 1 print(f'EarlyStopping counter: {self.counter} out of {self.patience}') if self.counter >= self.patience: self.early_stop = True else: self.best_score = score self.save_checkpoint(val_loss, model) self.counter = 0
def save_checkpoint(self, val_loss, model): if self.verbose: print(f'Validation loss decreased ({self.val_loss_min:.6f} --> {val_loss:.6f}). Saving model...') torch.save(model.state_dict(), self.path) self.val_loss_min = val_loss
class LearnablePositionalEncoding(nn.Module): def __init__(self, d_model, max_len=5000): super().__init__() self.position_embeddings = nn.Embedding(max_len, d_model)
def forward(self, x): positions = torch.arange(0, x.size(1), device=x.device).expand(x.size(0), -1) x = x + self.position_embeddings(positions) return x
class LSTMTransformer(nn.Module): def __init__(self, num_embeddings_list, continuous_dim, model_dim=64, hidden_size=64, num_heads=4, num_layers=2, dropout=0.3): super().__init__() self.cat_embeddings = nn.ModuleList([ nn.Embedding(num_emb, model_dim) for num_emb in num_embeddings_list ]) self.cont_proj = nn.Linear(continuous_dim, model_dim) self.pos_encoder = LearnablePositionalEncoding(model_dim)
self.lstm = nn.LSTM(model_dim, hidden_size, batch_first=True, bidirectional=False) encoder_layer = nn.TransformerEncoderLayer(d_model=hidden_size, nhead=num_heads, dropout=dropout) self.transformer = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)
self.norm = nn.LayerNorm(hidden_size) self.fc_out = nn.Linear(hidden_size, 1)
def forward(self, cat_inputs, cont_inputs): embedded_cat = torch.stack([emb(cat_inputs[:, :, i]) for i, emb in enumerate(self.cat_embeddings)], dim=0).sum(dim=0) embedded_cont = self.cont_proj(cont_inputs) x = embedded_cat + embedded_cont x = self.pos_encoder(x)
x, _ = self.lstm(x)
x = x.permute(1, 0, 2) x = self.transformer(x) x = x.mean(dim=0) x = self.norm(x) return self.fc_out(x)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
num_embeddings_list = [df[col].nunique() for col in categorical_cols]
model = LSTMTransformer( num_embeddings_list=[df[col].nunique() for col in categorical_cols], continuous_dim=len(continuous_cols), model_dim=128, hidden_size=128, num_heads=64, num_layers=10, dropout=0.6 ).to(device)
criterion = nn.MSELoss(0.5) optimizer = torch.optim.Adam(model.parameters(), lr=1e-3, weight_decay=1e-5) scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.5, patience=5, verbose=True)
epochs = 1000 best_loss = float('inf') losses = [] val_losses = []
early_stopping = EarlyStopping(patience=100, verbose=True)
print("开始训练...") for epoch in range(epochs): model.train() total_loss = 0 loop = tqdm(train_loader, desc=f"Epoch [{epoch + 1}/{epochs}]")
for x_cat_batch, x_cont_batch, y_batch in loop: x_cat_batch, x_cont_batch, y_batch = x_cat_batch.to(device), x_cont_batch.to(device), y_batch.to(device)
optimizer.zero_grad() outputs = model(x_cat_batch, x_cont_batch) loss = criterion(outputs, y_batch) loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) optimizer.step()
total_loss += loss.item() loop.set_postfix(loss=loss.item())
avg_train_loss = total_loss / len(train_loader) losses.append(avg_train_loss)
model.eval() val_loss = 0.0 with torch.no_grad(): for x_cat_val, x_cont_val, y_val in test_loader: x_cat_val, x_cont_val, y_val = x_cat_val.to(device), x_cont_val.to(device), y_val.to(device) val_outputs = model(x_cat_val, x_cont_val) loss = criterion(val_outputs, y_val) val_loss += loss.item() * x_cat_val.size(0)
val_loss /= len(test_loader.dataset)
scheduler.step(val_loss) val_losses.append(val_loss)
print(f"Epoch {epoch + 1}/{epochs} | Train Loss: {avg_train_loss:.4f} | Val Loss: {val_loss:.4f}") logging.basicConfig(filename='training_Trade_Transformer_Price.log', level=logging.INFO) logging.info(f"Epoch {epoch + 1}/{epochs}, Train Loss: {avg_train_loss:.4f}, Val Loss: {val_loss:.4f}") early_stopping(val_loss, model) if early_stopping.early_stop: print("Early stopping") break
save_path = 'F:\\Python\\Transformer\\demo\\model\\trade_Transformer_LSTM\\in\\' os.makedirs(os.path.dirname(save_path), exist_ok=True)
torch.save(model.state_dict(), save_path+'model_price.pth')
print("开始验证...") model.load_state_dict(torch.load(save_path+'model_price.pth')) model.eval()
all_preds = [] all_true = []
with torch.no_grad(): for x_cat_batch, x_cont_batch, y_batch in test_loader: x_cat_batch = x_cat_batch.to(device) x_cont_batch = x_cont_batch.to(device)
outputs = model(x_cat_batch, x_cont_batch)
all_preds.append(outputs.cpu().numpy()) all_true.append(y_batch.cpu().numpy())
y_pred = np.concatenate(all_preds, axis=0) y_true = np.concatenate(all_true, axis=0)
y_pred_unscaled = np.expm1(scaler_y.inverse_transform(y_pred)) y_true_unscaled = np.expm1(scaler_y.inverse_transform(y_true))
pred_renminbi = y_pred_unscaled
true_renminbi = y_true_unscaled
def evaluate(name, true, pred): r2 = r2_score(true, pred) mae = np.mean(np.abs(true - pred)) mse = np.mean((true - pred) ** 2) print(f"\n{name} 评估:") print(f"R² Score: {r2:.4f}") print(f"MSE: {mse:.4f}") print(f"MAE: {mae:.2f}") return r2, mse, mae
r2_q, mse_q, mae_q = evaluate("单价", true_renminbi, pred_renminbi) logging.basicConfig(filename='training_Trade_Transformer_Price.log', level=logging.INFO) time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") logging.info(f"datetime:{datetime}, R2:{r2_q}, MSE:{mse_q}, MAE:{mae_q}")
print("\n部分预测值 VS 真实值:") for i in range(5): print(f"预测: 单价={pred_renminbi[i].item():.2f}" f"真实: 单价={true_renminbi[i].item():.2f}")
plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False
plt.figure(figsize=(12, 6)) plt.plot(true_renminbi, label='真实单价', color='blue') plt.plot(pred_renminbi, label='预测单价', color='red', linestyle='--') plt.title("单价:预测值 vs 真实值") plt.xlabel("样本索引") plt.ylabel("单价") plt.legend() plt.grid(True) plt.annotate(f'R2={r2_q:.3f}', xy=(0.05, 0.9), xycoords='axes fraction', fontsize=12, color='green') plt.annotate(f'MSE={mse_q:.3f}', xy=(0.05, 0.8), xycoords='axes fraction', fontsize=12, color='green') plt.annotate(f'MAE={mae_q:.3f}', xy=(0.05, 0.7), xycoords='axes fraction', fontsize=12, color='green') plt.tight_layout() plt.savefig(save_path+'predicted_vs_true_price.png') plt.close()
errors = y_true.flatten() - y_pred.flatten() plt.figure(figsize=(8, 5)) plt.hist(errors, bins=30, color='skyblue', edgecolor='black') plt.axvline(0, color='red', linestyle='dashed', linewidth=1) plt.title("预测误差分布", fontsize=14) plt.xlabel("误差 = 真实值 - 预测值", fontsize=12) plt.ylabel("频数", fontsize=12) plt.grid(True) plt.tight_layout() plt.savefig(save_path+'error_distribution_price.png') plt.close()
plt.figure(figsize=(10, 6)) plt.plot(losses, label='Training Loss', color='blue') plt.plot(val_losses, label='Validation Loss', color='red') plt.xlabel('Epoch') plt.ylabel('Loss (MSE)') plt.title('训练损失曲线', fontsize=14) plt.legend() plt.grid(True) plt.tight_layout() plt.savefig(save_path+'training_loss_curve_price.png') plt.close()
with open(save_path+'scaler_X_price.pkl', 'wb') as f: pickle.dump(scaler_X, f)
with open(save_path+'scaler_y_price.pkl', 'wb') as f: pickle.dump(scaler_y, f)
with open(save_path+'label_encoders_price.pkl', 'wb') as f: pickle.dump(label_encoders, f)
print("✅ 模型和预处理器已成功保存!")
winsound.PlaySound("F:\\Python\\训练完成.wav", winsound.SND_FILENAME)
|