数据集 某市10个不同县区的五年负荷值,第一列是时间间隔为15min的时间戳,第二列为对应时刻的负荷值,如下图所示:
timer模型 文章:arxiv.org/abs/2402.02…
github:github.com/thuml/Large…
huggingface:huggingface.co/collections…
zero-shot实现 直接使用huggingface上timer模型已经训练好的权重,实现滑动窗口预测并计算准确率等评价指标。
导入库 import torch import pandas as pd import numpy as np import matplotlib.pyplot as plt from transformers import AutoModelForCausalLM import warnings from tqdm import tqdm AI写代码 python 运行 数据清洗 需要删去数据中负荷值为的null部分,否则测得的MSE等评价指标或者训练过程中的loss会为nan值
def load_and_clean_data(csv_file_path): """ 加载CSV文件并进行数据清洗 Args: csv_file_path (str): CSV文件路径 Returns: pd.DataFrame: 清洗后的数据 """ print("正在加载数据...") # 读取CSV文件 df = pd.read_csv(csv_file_path)
print(f"原始数据形状: {df.shape}")
print(f"列名: {df.columns.tolist()}")
# 假设第一列是时间,第二列是负荷值
time_col = df.columns[0]
load_col = df.columns[1]
print(f"时间列: {time_col}")
print(f"负荷列: {load_col}")
# 处理时间列
try:
df[time_col] = pd.to_datetime(df[time_col])
except:
print("时间列转换失败,尝试推断格式...")
df[time_col] = pd.to_datetime(df[time_col], infer_datetime_format=True)
# 检查缺失值
print(f"时间列缺失值数量: {df[time_col].isnull().sum()}")
print(f"负荷列缺失值数量: {df[load_col].isnull().sum()}")
# 删除包含缺失值的行
df_clean = df.dropna(subset=[time_col, load_col])
print(f"清洗后数据形状: {df_clean.shape}")
# 按时间排序
df_clean = df_clean.sort_values(time_col).reset_index(drop=True)
# 检查负荷值是否为数值型
df_clean[load_col] = pd.to_numeric(df_clean[load_col], errors='coerce')
# 再次删除转换失败的行
df_clean = df_clean.dropna(subset=[load_col]).reset_index(drop=True)
print(f"最终清洗后数据形状: {df_clean.shape}")
return df_clean
AI写代码 python 运行
准备Timer模型的输入数据 def prepare_timer_input(data, mean_val=None, std_val=None): """ 准备Timer模型的输入数据 Args: data (np.array): 时序数据 mean_val (float): 预设的均值,用于标准化 std_val (float): 预设的标准差,用于标准化 Returns: tuple: (标准化数据, 均值, 标准差) """ if mean_val is None or std_val is None: mean_val = np.mean(data) std_val = np.std(data)
if std_val == 0:
normalized_data = data - mean_val
else:
normalized_data = (data - mean_val) / std_val
# 转换为torch tensor并添加batch维度
seqs = torch.tensor(normalized_data).unsqueeze(0).float()
return seqs, mean_val, std_val
AI写代码 python 运行
滑动窗口实现 注意滑动窗口的滑动步长的大小要与预测长度相等,不然会导致同一个时间点进行了多次预测,使结果虚高。
以forecast_length=96, lookback_length=1440为例,即用1440个时刻的负荷数据去预测后面96个时刻的负荷数据,假设滑动窗口的滑动步长大小为1,第一个窗口就是使用负荷数据的编号为[1,1440]的数据预测[1441,1496]的负荷,因为滑动步长为1,则第二次预测是使用[2,1441]的数据去预测[1442,1497]的负荷,这就导致[1442,1496]的数据重复预测,将滑动步长调整为与forecast_length大小一样的可以避免这个问题。
def sliding_window_forecast(csv_file_path, forecast_length=96, lookback_length=1440): """ 使用Timer模型进行滑动窗口时序预测 Args: csv_file_path (str): CSV文件路径 forecast_length (int): 每次预测长度 lookback_length (int): 回看长度 Returns: dict: 预测结果和真实值 """ # 1. 加载和清洗数据 df_clean = load_and_clean_data(csv_file_path)
# 获取负荷数据列
load_col = df_clean.columns[1]
load_data = df_clean[load_col].values
time_data = df_clean[df_clean.columns[0]]
print(f"负荷数据统计:")
print(f" 数据总长度: {len(load_data)}")
print(f" 均值: {np.mean(load_data):.2f}")
print(f" 标准差: {np.std(load_data):.2f}")
print(f" 最小值: {np.min(load_data):.2f}")
print(f" 最大值: {np.max(load_data):.2f}")
# 检查数据长度是否足够
if len(load_data) < lookback_length + forecast_length:
print(f"错误: 数据长度 ({len(load_data)}) 不足以进行预测")
print(f"需要至少 {lookback_length + forecast_length} 个数据点")
return None
# 2. 加载Timer模型
print("正在加载Timer模型...")
try:
model = AutoModelForCausalLM.from_pretrained('thuml/timer-base-84m', trust_remote_code=True)
print("模型加载成功!")
except Exception as e:
print(f"模型加载失败: {e}")
return None
# 3. 计算预测范围
if forecast_length == 1:
total_windows = len(load_data) - lookback_length
total_predictions = total_windows
else:
total_windows = (len(load_data) - lookback_length - forecast_length + 1) // forecast_length + 1
total_predictions = min(len(load_data) - lookback_length, total_windows * forecast_length)
print(f"将进行 {total_windows} 次预测窗口")
print(f"总预测点数: {total_predictions}")
print(f"预测范围: 第 {lookback_length + 1} 到第 {min(len(load_data), lookback_length + total_predictions)} 个时刻")
# 4. 滑动窗口预测
all_predictions = []
all_true_values = []
prediction_indices = []
# 使用整个数据集的统计信息进行标准化
global_mean = np.mean(load_data)
global_std = np.std(load_data)
print("开始滑动窗口预测...")
# 预测每个可能的时刻
# forecast_length > 1需调整滑动步长
step_size = forecast_length if forecast_length > 1 else 1
for i in tqdm(range(lookback_length, len(load_data) - forecast_length + 1, step_size), desc="预测进度"):
try:
# 获取历史数据
history_data = load_data[i-lookback_length:i]
# 准备输入
seqs, _, _ = prepare_timer_input(history_data, global_mean, global_std)
# 进行预测
with torch.no_grad():
normed_output = model.generate(seqs, max_new_tokens=forecast_length)
prediction_normed = normed_output[:, -forecast_length:] # 取预测部分
# 反标准化
if global_std == 0:
prediction = prediction_normed.numpy() + global_mean
else:
prediction = prediction_normed.numpy() * global_std + global_mean
prediction = prediction.squeeze()
# 如果只预测一个点,保持一维
if forecast_length == 1:
prediction = [prediction] if np.isscalar(prediction) else prediction
# 保存结果
for j, pred in enumerate(prediction):
if i + j < len(load_data):
all_predictions.append(pred)
all_true_values.append(load_data[i + j])
prediction_indices.append(i + j)
except Exception as e:
print(f"第 {i} 次预测失败: {e}")
continue
if len(all_predictions) == 0:
print("预测失败,未能生成任何预测结果")
return None
print(f"预测完成!成功预测了 {len(all_predictions)} 个时刻")
# 5. 整理结果
results = {
'predictions': np.array(all_predictions),
'true_values': np.array(all_true_values),
'prediction_indices': np.array(prediction_indices),
'original_data': load_data,
'time_data': time_data,
'lookback_length': lookback_length,
'forecast_length': forecast_length,
'load_column_name': load_col,
'global_mean': global_mean,
'global_std': global_std
}
return results
AI写代码 python 运行
计算预测准确率 准确率是基ERMSE计算的:accuracy = (1 - ermse) * 100
def calculate_ermse(y_true, y_pred): """计算ERMSE(Error Root Mean Square Error)""" mse = np.mean(((y_true - y_pred) / np.clip(np.abs(y_true), 1e-6, None)) ** 2) ermse = np.sqrt(mse) return ermse
def calculate_accuracy(y_true, y_pred): """计算准确率(基于ERMSE)""" ermse = calculate_ermse(y_true, y_pred) accuracy = (1 - ermse) * 100 return accuracy, ermse
def calculate_window_metrics(predictions, true_values, forecast_length, lookback_length, lv=0.85): """ 计算滑动窗口的评估指标 Args: predictions: 预测值数组 true_values: 真实值数组 forecast_length: 预测长度 lookback_length: 回看长度 lv: 准确率阈值,用于计算高准确率的平均值 Returns: dict: 评估指标字典 """ # 重新组织数据为窗口形式进行逐窗口评估 if forecast_length == 1: # 逐点预测,每个点作为一个窗口 all_window_acc = [] all_window_acc_filtered = []
for i in range(len(predictions)):
y_pred = np.array([predictions[i]])
y_true = np.array([true_values[i]])
# 计算单点指标
mse = np.mean((y_true - y_pred) ** 2)
rmse = np.sqrt(mse)
mae = np.mean(np.abs(y_true - y_pred))
mape = np.mean(np.abs((y_true - y_pred) / np.clip(np.abs(y_true), 1e-6, None))) * 100
accuracy, ermse = calculate_accuracy(y_true, y_pred)
all_window_acc.append(accuracy)
if accuracy > lv * 100:
all_window_acc_filtered.append(accuracy)
else:
# 多步预测,按预测长度分组评估
num_windows = len(predictions) // forecast_length
all_window_acc = []
all_window_acc_filtered = []
for w in range(num_windows):
start_idx = w * forecast_length
end_idx = start_idx + forecast_length
if end_idx <= len(predictions):
y_pred = predictions[start_idx:end_idx]
y_true = true_values[start_idx:end_idx]
# 计算窗口指标
mse = np.mean((y_true - y_pred) ** 2)
rmse = np.sqrt(mse)
mae = np.mean(np.abs(y_true - y_pred))
mape = np.mean(np.abs((y_true - y_pred) / np.clip(np.abs(y_true), 1e-6, None))) * 100
accuracy, ermse = calculate_accuracy(y_true, y_pred)
print(f"窗口 {w+1} 预测结果:MSE: {mse:.6f}, RMSE: {rmse:.6f}, MAE: {mae:.6f}, "
f"MAPE: {mape:.6f}, ERMSE: {ermse:.6f}, Acc: {accuracy:.2f}%")
all_window_acc.append(accuracy)
if accuracy > lv * 100:
all_window_acc_filtered.append(accuracy)
# 计算全局指标
global_mse = np.mean((true_values - predictions) ** 2)
global_mae = np.mean(np.abs(true_values - predictions))
global_rmse = np.sqrt(global_mse)
global_mape = np.mean(np.abs((true_values - predictions) / np.clip(np.abs(true_values), 1e-6, None))) * 100
global_accuracy, global_ermse = calculate_accuracy(true_values, predictions)
# 计算准确率统计
avg_acc = np.mean(all_window_acc) if all_window_acc else float('nan')
avg_acc_filtered = np.mean(all_window_acc_filtered) if all_window_acc_filtered else float('nan')
# 计算其他指标
ss_res = np.sum((true_values - predictions) ** 2)
ss_tot = np.sum((true_values - np.mean(true_values)) ** 2)
r2 = 1 - (ss_res / ss_tot) if ss_tot != 0 else float('-inf')
correlation = np.corrcoef(true_values, predictions)[0, 1] if len(true_values) > 1 else float('nan')
return {
'Global_MSE': global_mse,
'Global_MAE': global_mae,
'Global_RMSE': global_rmse,
'Global_MAPE': global_mape,
'Global_ERMSE': global_ermse,
'Global_Accuracy': global_accuracy,
'Average_Window_Accuracy': avg_acc,
f'Average_Accuracy_Above_{int(lv*100)}%': avg_acc_filtered,
'R2': r2,
'Correlation': correlation,
'Total_Windows': len(all_window_acc),
'High_Accuracy_Windows': len(all_window_acc_filtered),
'High_Accuracy_Ratio': len(all_window_acc_filtered) / len(all_window_acc) if all_window_acc else 0
}
AI写代码 python 运行
可视化窗口 def visualize_sliding_results(results, save_path='timer_sliding_prediction.png', show_full_data=True, lv=0.85): """ 可视化滑动窗口预测结果 Args: results (dict): 预测结果字典 save_path (str): 图片保存路径 show_full_data (bool): 是否显示完整数据,False则只显示预测部分 lv (float): 准确率过滤阈值 """ if results is None: print("无法可视化,预测结果为空") return None
predictions = results['predictions']
true_values = results['true_values']
prediction_indices = results['prediction_indices']
original_data = results['original_data']
lookback_length = results['lookback_length']
forecast_length = results['forecast_length']
# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei', 'Arial Unicode MS', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False
# 计算评估指标(使用WPMixer风格)
print(f"\n======== 开始计算评估指标 ========")
metrics = calculate_window_metrics(predictions, true_values, forecast_length, lookback_length, lv)
# 创建图形
plt.figure(figsize=(24, 10))
if show_full_data:
# 显示完整数据
plt.subplot(2, 1, 1)
# 历史数据(用于训练的部分)
history_x = range(lookback_length)
history_data = original_data[:lookback_length]
plt.plot(history_x, history_data, label='history_data', color='gray', alpha=0.7, linewidth=1)
# 真实值
plt.plot(prediction_indices, true_values, label='Actual value', color='#1f77b4', linewidth=2, linestyle='--')
# 预测值
plt.plot(prediction_indices, predictions, label='Predictive value', color='#E67E00', linewidth=2, linestyle='-')
# 添加分界线
plt.axvline(x=lookback_length, color='green', linestyle='-', alpha=0.7, linewidth=2, label='start')
plt.title('Timer - result', fontsize=16, fontweight='bold')
plt.xlabel('Time', fontsize=12)
plt.ylabel('Load', fontsize=12)
plt.legend(fontsize=12)
plt.grid(True, alpha=0.3)
# 显示预测部分的放大图
plt.subplot(2, 1, 2)
# 预测部分对比图
plt.plot(prediction_indices, true_values, label='Actual value', color='#1f77b4', linewidth=1.6, linestyle='--')
plt.plot(prediction_indices, predictions, label='Predictive value', color='#E67E00', linewidth=1.8, linestyle='-')
title = f'Timer Model Prediction vs Actual\naverage accuracy: {metrics["Average_Window_Accuracy"]:.2f}%'
plt.title(title, fontsize=16, fontweight='bold')
plt.xlabel('Time', fontsize=12)
plt.ylabel('Load', fontsize=12)
plt.legend(fontsize=12)
plt.grid(True, alpha=0.3)
plt.tight_layout()
# 保存图片
try:
plt.savefig(save_path, dpi=1200, bbox_inches='tight')
print(f"图片已保存到: {save_path}")
# 同时保存PDF版本
pdf_path = save_path.replace('.png', '.pdf')
plt.savefig(pdf_path, dpi=600, bbox_inches='tight')
print(f"PDF版本已保存到: {pdf_path}")
except Exception as e:
print(f"图片保存失败: {e}")
plt.show()
# 显示统计信息(与WPMixer格式对齐)
print(f"\n======== 滑动窗口预测统计 ========")
print(f"总预测窗口数: {metrics['Total_Windows']}")
print(f"预测数据长度: {len(predictions)}")
print(f"预测数据范围: 第 {prediction_indices[0]+1} 到第 {prediction_indices[-1]+1} 个时刻")
print(f"回看长度: {lookback_length}")
print(f"预测长度: {forecast_length}")
print(f"\n======== 预测结果统计 ========")
print(f"真实值均值: {np.mean(true_values):.2f}")
print(f"预测值均值: {np.mean(predictions):.2f}")
print(f"真实值标准差: {np.std(true_values):.2f}")
print(f"预测值标准差: {np.std(predictions):.2f}")
print(f"\n======== 评估指标 ========")
print(f"MSE (均方误差): {metrics['Global_MSE']:.6f}")
print(f"MAE (平均绝对误差): {metrics['Global_MAE']:.6f}")
print(f"RMSE (均方根误差): {metrics['Global_RMSE']:.6f}")
print(f"MAPE (平均绝对百分比误差): {metrics['Global_MAPE']:.6f}")
print(f"ERMSE (相对均方根误差): {metrics['Global_ERMSE']:.6f}")
print(f"全局准确率: {metrics['Global_Accuracy']:.2f}%")
print(f"平均窗口准确率: {metrics['Average_Window_Accuracy']:.2f}%")
print(f"高准确率窗口平均: {metrics[f'Average_Accuracy_Above_{int(lv*100)}%']:.2f}%")
print(f"高准确率窗口比例: {metrics['High_Accuracy_Ratio']:.2%}")
print(f"R² (决定系数): {metrics['R2']:.4f}")
print(f"相关系数: {metrics['Correlation']:.4f}")
# 保存评估指标
metrics_df = pd.DataFrame([metrics])
metrics_save_path = save_path.replace('.png', '_metrics.csv')
try:
metrics_df.to_csv(metrics_save_path, index=False)
print(f"评估指标已保存到: {metrics_save_path}")
except Exception as e:
print(f"评估指标保存失败: {e}")
# 保存详细预测结果
results_df = pd.DataFrame({
'time_step': prediction_indices,
'true_value': true_values,
'predicted_value': predictions,
'absolute_error': np.abs(true_values - predictions),
'relative_error': np.abs((true_values - predictions) / np.clip(np.abs(true_values), 1e-6, None)) * 100,
'accuracy': [(1 - calculate_ermse(np.array([tv]), np.array([pv]))) * 100
for tv, pv in zip(true_values, predictions)]
})
results_save_path = save_path.replace('.png', '_results.csv')
try:
results_df.to_csv(results_save_path, index=False)
print(f"详细预测结果已保存到: {results_save_path}")
except Exception as e:
print(f"详细结果保存失败: {e}")
return metrics
AI写代码 python 运行
主函数 if name == 'main': # 使用示例 csv_file_path = "load.csv" # 替换为预测的CSV文件路径 # 参数设置 forecast_length = 96 # 每次预测的步长 lookback_length = 672 # 回看步长
print("开始Timer模型滑动窗口时序预测...")
print(f"预测参数: 回看长度={lookback_length}, 预测步长={forecast_length}")
# 执行滑动窗口预测
results = sliding_window_forecast(
csv_file_path=csv_file_path,
forecast_length=forecast_length,
lookback_length=lookback_length
)
# 可视化结果
if results is not None:
metrics = visualize_sliding_results(
results,
save_path='timer_sliding_prediction.png',
show_full_data=True # 设置为False只显示预测部分
)
print(f"\n滑动窗口预测完成!")
print(f"成功预测了 {len(results['predictions'])} 个时刻的负荷值")
else:
print("预测失败,请检查数据和模型")
AI写代码 python 运行
finetune实现 模型的微调指在模型经过大规模的无标签数据集上接受训练后,再通过输入特定领域的数据集,使模型学习该领域知识,从而优化大模型在特定领域的能力。
超参数设置 模型微调并不是将数据集输入模型后直接运行run.py即可,超参数的设置对大模型的微调的效果影响很大,根据数据集和任务需要设置合适的超参数至关重要。常见的超参数如epoch等在此不再赘述,这里主要详细说明与warmup_steps相关的超参数和一些timer模型特有的超参数:
warmup_steps warmup_steps和warmup_ratio是控制学习率调度的。训练开始后学习率从很小值线性增长到初始学习率的步数就是warmup_steps,它是为了避免训练初期学习率过大导致模型不稳定,比如如果你设置warmup_steps=500,那么前 500 个训练 step内学习率会从 0 慢慢升高到设定的峰值(比如 2e-5)。step指每喂模型一个batch并完成前向传播 + 反向传播 + 参数更新, 就是1个step。warmup_ratio是warmup_steps 的一种比例写法,它是用来指定warmup占总训练步数的百分比,如果同时指定了warmup_steps和warmup_ratio,优先级往往是 warmup_steps > warmup_ratio,通常warmup_steps会设置为总训练步数的5-10%。
batch_size batch_size的设置也会对模型微调有影响,当batch_size过大时,每次参数更新需要消耗大量数据,导致训练步数过少,可能影响模型训练效果。反之,适当减小batch_size可以增加训练步数,使模型获得更多参数更新机会,从而提升学习效果。以五年内每15分钟记录一次的负荷数据为例,假设batch_size=1024,五年的总数据量为175200。此时每个epoch仅有约171个训练步数。若默认设置的warmup_steps超过170,会导致模型在一轮训练中无法充分学习。因此需要根据数据集情况,合理调整batch_size或warmup_steps的设置。
patience 当验证损失停止下降时,允许继续训练的轮数上限。该参数用于早停机制,防止模型过拟合。
模型参数 d_model 、d_ff、e_layers、n_heads等是模型结构参数,他们在微调时最好设置为默认值,否则可能因结构改变导致运行报错。
序列长度 seq_len为历史长度,pred_len为预测长度,输出长度output_len与预测长度要保持一致 。
准备工作 数据集 将十个地区的负荷数据按时间顺序对齐,生成一个n×11的输入矩阵,注意第一列需命名为"date"作为时间序列标识,并将其放在dataset文件夹下。
下载checkpoint 从timer模型代码中的scripts文件夹下的readme提供的网址下载预训练后的.ckpt文件(Google Drive or Baidu Drive)并放在checkpoint文件夹下。
微调训练代码 #!/bin/bash
模型和路径配置
model_name=Timer data=multiregion_load root_path=./dataset/ data_path=merged_data.csv ckpt_path=./checkpoints/Timer_forecast_1.0.ckpt
序列长度配置
seq_len=672
label_len=576
pred_len=96
output_len=96 # 输出长度与预测长度一致
patch_len=96 # 补丁长度
模型参数
d_model=1024
d_ff=2048
e_layers=8 # 编码器层数
n_heads=16
dropout=0.1
训练参数
train_epochs=2
finetune_epochs=2
batch_size=128
learning_rate=1e-5
patience=20
微调执行
python run.py
--task_name forecast
--is_training 1
--is_finetuning 1
--ckpt_path root_path
--data_path data
--model_id model_name
--features M
--target region1
--freq 15min
--seq_len label_len
--pred_len output_len
--patch_len e_layers
--d_model d_ff
--n_heads dropout
--factor 3
--train_epochs finetune_epochs
--batch_size learning_rate
--patience $patience
--loss MSE
--lradj type1
--num_workers 4
--subset_rand_ratio 1
--itr 1
--gpu 0
--use_gpu 1
--checkpoints ./checkpoints/
--des load_finetune
AI写代码
调用训练后的模型 timer模型的__init__方法如下:
def init(self, configs): super().init() self.task_name = configs.task_name self.ckpt_path = configs.ckpt_path self.patch_len = configs.patch_len self.stride = configs.patch_len self.d_model = configs.d_model self.d_ff = configs.d_ff self.layers = configs.e_layers self.n_heads = configs.n_heads self.dropout = configs.dropout
self.output_attention = configs.output_attention
self.backbone = TimerBackbone.Model(configs)
# Decoder
self.decoder = self.backbone.decoder
self.proj = self.backbone.proj
self.enc_embedding = self.backbone.patch_embedding
if self.ckpt_path != '':
if self.ckpt_path == 'random':
print('loading model randomly')
else:
print('loading model: ', self.ckpt_path)
if self.ckpt_path.endswith('.pth'):
self.backbone.load_state_dict(torch.load(self.ckpt_path))
elif self.ckpt_path.endswith('.ckpt'):
sd = torch.load(self.ckpt_path, map_location="cpu")["state_dict"]
sd = {k[6:]: v for k, v in sd.items()}
self.backbone.load_state_dict(sd, strict=True)
else:
raise NotImplementedError
AI写代码
init 必须接收一个configs对象,并且在里面读取了许多属性,训练得到的checkpoint 文件只保存了模型权重,没有保存configs,所以需要自己手动创建一个 configs 对象:
import torch import pandas as pd import numpy as np import matplotlib.pyplot as plt from transformers import AutoModelForCausalLM import warnings from tqdm import tqdm import os import sys
添加Timer项目路径到sys.path
sys.path.append('timer/Large-Time-Series-Model-main') from models.Timer import Model as TimerModel
warnings.filterwarnings('ignore') class Configs: def init(self): self.task_name = 'forecast' # 任务类型(forecast / imputation / anomaly_detection) self.ckpt_path = '' # 这里不要再传checkpoint路径,否则会再次load self.patch_len = 96 # patch长度,需和训练时一致 self.d_model = 1024 # 模型隐藏维度 self.d_ff = 2048 # FFN隐藏维度 self.e_layers = 8 # 编码层数 self.n_heads = 16 # 注意力头数 self.dropout = 0.1 # dropout 概率 self.output_attention = False self.factor = 3 # 是否返回注意力权重 self.activation = 'gelu'
def load_finetuned_timer_model(checkpoint_path): """ 加载微调后的Timer模型 """ print("正在加载微调后的Timer模型...")
try:
# 加载checkpoint
checkpoint = torch.load('checkpoint.pth') #替换为训练后得到的checkpoint路径
print(f"成功加载checkpoint: {checkpoint_path}")
# 创建模型实例
configs = Configs()
model = TimerModel(configs)
model.load_state_dict(checkpoint, strict=False)
model.eval()
print("微调模型加载成功!")
return model
except Exception as e:
print(f"加载微调模型失败: {e}")
print("尝试使用原始预训练模型...")
return AutoModelForCausalLM.from_pretrained('thuml/timer-base-84m', trust_remote_code=True)
AI写代码
服务器遇到的问题 在服务器上新建虚拟环境的时候报错:
ProxyError: Conda cannot proceed due to an error in your proxy configuration. Check for typos and other configuration errors in any '.netrc' file in your home directory, any environment variables ending in '_PROXY', and any other system-wide proxy configuration settings. AI写代码 在命令行中检查是否设置了与代理相关的环境变量。可以使用以下命令查看环境变量中是否有 _PROXY相关设置:
env | grep -i proxy AI写代码 如果有,尝试取消这些环境变量:
unset HTTP_PROXY unset HTTPS_PROXY unset http_proxy
————————————————
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。