PyTorch搭建ANN实现时间序列预测(风速预测)

306 阅读2分钟

I. 数据集

在这里插入图片描述 数据集为Barcelona某段时间内的气象数据,其中包括温度、湿度以及风速等。本文将简单搭建来对风速进行预测。

II. 特征构造

对于风速的预测,除了考虑历史风速数据外,还应该充分考虑其余气象因素的影响。因此,我们根据前24个时刻的风速+其余气象数据来预测下一时刻的风速。

III. 数据处理

1.数据预处理

数据预处理阶段,主要将某些列上的文本数据转为数值型数据,同时对原始数据进行归一化处理。文本数据如下所示: 在这里插入图片描述

经过转换后,上述各个类别分别被赋予不同的数值,比如"sky is clear"为0,"few clouds"为1。

def load_data():
    df = pd.read_csv('Barcelona/Barcelona.csv')
    df.drop_duplicates(subset=[df.columns[0]], inplace=True)
    df.drop([df.columns[0], df.columns[1]], axis=1, inplace=True)
    # weather_main
    listType = df['weather_main'].unique()
    df.fillna(method='ffill', inplace=True)
    dic = dict.fromkeys(listType)
    for i in range(len(listType)):
        dic[listType[i]] = i
    df['weather_main'] = df['weather_main'].map(dic)
    # weather_description
    listType = df['weather_description'].unique()
    dic = dict.fromkeys(listType)
    for i in range(len(listType)):
        dic[listType[i]] = i
    df['weather_description'] = df['weather_description'].map(dic)
    # weather_icon
    listType = df['weather_icon'].unique()
    dic = dict.fromkeys(listType)
    for i in range(len(listType)):
        dic[listType[i]] = i
    df['weather_icon'] = df['weather_icon'].map(dic)
    # print(df)
    return df

2.数据集构造

利用前24个小时的风速数据+气象数据来预测下一时刻的风速,数据被划分为三部分:Dtr、Val以及Dte,Dtr用作训练集,Val用作验证集,Dte用作测试集,模型训练返回的是验证集上表现最优的模型。

IV. ANN模型

1.模型训练

ANN模型搭建如下:

class ANN(nn.Module):
    def __init__(self):
        super(ANN, self).__init__()
        self.seq_len = seq_len
        self.input_size = input_size
        self.nn = torch.nn.Sequential(
            nn.Linear(seq_len * input_size, 128),
            torch.nn.ReLU(),
            nn.Linear(128, 256),
            torch.nn.ReLU(),
            nn.Linear(256, 128),
            torch.nn.ReLU(),
            nn.Linear(128, 1)
        )

    def forward(self, x):
        # x(batch_size, seq_len, input_size)
        x = x.view(x.shape[0], -1)
        x = self.nn(x)
        return x

2.模型预测及表现

训练50轮,ANN在Dte上的表现如下表所示:

MAERMSE
0.961.28

V. 源码及数据

后面将陆续公开~