<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kaan Aslan on Medium]]></title>
        <description><![CDATA[Stories by Kaan Aslan on Medium]]></description>
        <link>https://medium.com/@mkaanaslan99?source=rss-abe091967eca------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BWj6Nuk3V5TW-sp1MDlZdg.png</url>
            <title>Stories by Kaan Aslan on Medium</title>
            <link>https://medium.com/@mkaanaslan99?source=rss-abe091967eca------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 21:38:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mkaanaslan99/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Time Series Forecasting with a Basic Transformer Model in PyTorch]]></title>
            <link>https://medium.com/@mkaanaslan99/time-series-forecasting-with-a-basic-transformer-model-in-pytorch-650f116a1018?source=rss-abe091967eca------2</link>
            <guid isPermaLink="false">https://medium.com/p/650f116a1018</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[kaggle]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Kaan Aslan]]></dc:creator>
            <pubDate>Thu, 11 Jan 2024 20:07:16 GMT</pubDate>
            <atom:updated>2024-01-29T21:50:21.331Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BFiU-WuK9qhC1RS9ND4q8g.png" /></figure><p>Time series forecasting is an essential topic that’s both challenging and rewarding, with a wide variety of techniques available to practitioners. After experiencing in traditional machine learning methods for forecasting, I decided to venture into the realm of deep learning! My latest project involved participating in the ‘Store Sales — Time Series Forecasting’¹ competition on Kaggle, which provided an excellent opportunity for practical application. <a href="https://www.kaggle.com/c/store-sales-time-series-forecasting">Here</a> is the link for the competition and its datasets.</p><p>I constructed a simple yet effective transformer² model, inspired by its successes in the area of natural language processing, and applied it to predicting store sales. The results were quite encouraging! In this article, I aim to share insights into the data, the pre-processing steps taken, outline the architecture of the transformer model, and describe my overall approach to the forecasting challenge. Through this, I hope to offer a resource that can serve as a starting point for others interested in applying transformer models to their own time series prediction tasks.</p><h3>Competition Data and Pre-processing</h3><p>In this competition, the challenge was to predict 16 days of future sales for various product families across 54 stores, creating a grand total of 1,782 unique time series. Data spanned from January 1, 2013, to August 15, 2017, and the goal was to forecast the following 16 days of sales. While I have streamlined the pre-processing for brevity, I’ll delve into the structure of the final dataset: it contains 3,029,400 entries across 20 columns, serving as inputs to my model. Each row captures a snapshot of sales data for a particular product family at a specific store on a given date, with ‘store_nbr,’ ‘family,’ and ‘date’ as key columns. The data break down into three types of variables:</p><p><strong>Past covariates</strong> are those time-related variables known up to the last date of training data, which is August 15, 2017. These include numeric variables like ‘sales,’ indicative of a product family’s sales at a particular store; ‘transactions,’ the total number of transactions at a store; ‘store_sales,’ the aggregate sales at that store; and ‘family_sales,’ representing the total sales for that product family.</p><p><strong>Future covariates</strong>, which are also time-dependent but known past the training cut-off and until the last forecast date of August 31, 2017, encompass variables like ‘onpromotion’ — the count of promoted items in a product family — and ‘dcoilwtico,’ the daily oil price. These numeric columns are complemented by the ‘holiday’ column, which denotes the presence of holidays or events and is categorically encoded to integers. Additionally, ‘time_idx,’ ‘week_day,’ ‘month_day,’ ‘month,’ and ‘year’ columns provide temporal context, also encoded as integers. Though my model is encoder-only, I’ve added the 16 days shifted values of ‘onpromotion’ and ‘dcoilwtico’ to incorporate future information without a decoder.</p><p><strong>Static covariates</strong> remain unchanged over time and include identifiers such as ‘store_nbr,’ ‘family,’ as well as the categorical variables of ‘city,’ ‘state,’ ‘type,’ and ‘cluster’ — detailing store characteristics — all of which are integer-encoded. Importantly, I’ve noted the distinct categories for embedding purposes and distinguished static from time-dependent categorical variables to account for the additional temporal dimension post-embedding. The resulting dataframe, named ‘data_all,’ is structured as follows:</p><pre>categorical_covariates = [&#39;time_idx&#39;,&#39;week_day&#39;,&#39;month_day&#39;,&#39;month&#39;,&#39;year&#39;,&#39;holiday&#39;]<br><br>categorical_covariates_num_embeddings = []<br>for col in categorical_covariates:<br>    data_all[col] = data_all[col].astype(&#39;category&#39;).cat.codes<br>    categorical_covariates_num_embeddings.append(data_all[col].nunique())<br><br>categorical_static = [&#39;store_nbr&#39;,&#39;city&#39;,&#39;state&#39;,&#39;type&#39;,&#39;cluster&#39;,&#39;family_int&#39;]<br><br>categorical_static_num_embeddings = []<br>for col in categorical_static:<br>    data_all[col] = data_all[col].astype(&#39;category&#39;).cat.codes<br>    categorical_static_num_embeddings.append(data_all[col].nunique())<br><br>numeric_covariates = [&#39;sales&#39;,&#39;dcoilwtico&#39;,&#39;dcoilwtico_future&#39;,&#39;onpromotion&#39;,&#39;onpromotion_future&#39;,&#39;store_sales&#39;,&#39;transactions&#39;,&#39;family_sales&#39;]<br><br>target_idx = np.where(np.array(numeric_covariates)==&#39;sales&#39;)[0][0]</pre><p>Before transforming the data into tensors suitable for my PyTorch model, I divided it into training and validation sets. The window size, a vital hyperparameter, denotes the sequence length per training sample, shaping inputs into the form (batch size, window size, number of features). Additionally, ‘num_val’ indicates the validation folds used, which is set to 2 in this context. Observations from January 1, 2013, up to June 28, 2017, are designated as the training dataset, with the periods from June 29, 2017, to July 14, 2017, and July 15, 2017, to July 30, 2017, serving as validation intervals.</p><p>Numeric and categorical variables are then cast into tensor format, with a logarithmic transformation applied to numeric variables for scaling purposes. This approach adheres to convention while aiming for more normalized input distributions which can be beneficial during model training.</p><pre>def dataframe_to_tensor(series,numeric_covariates,categorical_covariates,categorical_static,target_idx):<br><br>    numeric_cov_arr = np.array(series[numeric_covariates].values.tolist())<br>    category_cov_arr = np.array(series[categorical_covariates].values.tolist())<br>    static_cov_arr = np.array(series[categorical_static].values.tolist())<br><br>    x_numeric = torch.tensor(numeric_cov_arr,dtype=torch.float32).transpose(2,1)<br>    x_numeric = torch.log(x_numeric+1e-5)<br>    x_category = torch.tensor(category_cov_arr,dtype=torch.long).transpose(2,1)<br>    x_static = torch.tensor(static_cov_arr,dtype=torch.long)<br>    y = torch.tensor(numeric_cov_arr[:,target_idx,:],dtype=torch.float32)<br><br>    return x_numeric, x_category, x_static, y<br><br><br>window_size = 16<br>forecast_length = 16<br>num_val = 2<br><br>val_max_date = &#39;2017-08-15&#39;<br>train_max_date = str((pd.to_datetime(val_max_date) - pd.Timedelta(days=window_size*num_val+forecast_length)).date())<br><br>train_final = data_all[data_all[&#39;date&#39;]&lt;=train_max_date]<br>val_final = data_all[(data_all[&#39;date&#39;]&gt;train_max_date)&amp;(data_all[&#39;date&#39;]&lt;=val_max_date)]<br><br>train_series = train_final.groupby(categorical_static+[&#39;family&#39;]).agg(list).reset_index()<br>val_series = val_final.groupby(categorical_static+[&#39;family&#39;]).agg(list).reset_index()<br><br>x_numeric_train_tensor, x_category_train_tensor, x_static_train_tensor, y_train_tensor = dataframe_to_tensor(train_series,numeric_covariates,categorical_covariates,categorical_static,target_idx)<br><br>x_numeric_val_tensor, x_category_val_tensor, x_static_val_tensor, y_val_tensor = dataframe_to_tensor(val_series,numeric_covariates,categorical_covariates,categorical_static,target_idx)</pre><h3><strong>Data Loaders and Training Approach</strong></h3><p>Crafting an unbiased training strategy is essential for a fair and effective model. With 1,782 distinct time series in our dataset, a judicious approach to batching is required to maintain impartiality during training. Batch processing, if mishandled, can introduce several biases. For instance, a model might favor time series included in later batches due to more recent gradient updates. Moreover, a static time block indexing could prevent the model from experiencing the full spectrum of temporal sequences. To illustrate, training on series consistently segmented from index 0 to 15 would mean the model never learns patterns between indices 10 and 25.</p><p>To mitigate such biases, I implemented a dynamic slicing mechanism: each time series is divided into time blocks starting from a random index in the window range, ensuring the model gets exposure to diverse series segments. Yet, I consistently kept the final block fixed to encompass the freshest data points. I paired series indexes with these random time blocks, shuffled them to smooth out batch-order influence, and then batched them for training. In this setting, every batch will have random time series and their random time blocks. However in the end, the model will see every time series and their all observations in one epoch in the training phase.</p><p>The model will be trained unbiased with the current setting, however there is a type of bias that could be helpful. If the last batches of the data includes more latest observations, model could perform better in test set with recent dates. I introduced an additional hyper-parameter setting that instead of random shuffling, orders the dataset based on the starting time of the blocks. The data is then divided into five parts — reflecting our five-year dataset — each of which is internally shuffled which means the last batches will include observations from last year, but again randomly. As a result, the model’s final gradient updates are influenced by the latest year, theoretically improving forecasts for more recent periods.</p><p>The implemented data loaders will yield batches comprising ‘x_numeric’, ‘x_category’, ‘x_static’, and ‘y’ tensors. Their respective shapes will align with the following: (batch_size, window_size, num_numeric_features), (batch_size, window_size, num_category_features), (batch_size, num_static_features), and (batch_size, forecast_length). Here’s how the functions are established:</p><pre>def divide_shuffle(df,div_num):<br>    space = df.shape[0]//div_num<br>    division = np.arange(0,df.shape[0],space)<br>    return pd.concat([df.iloc[division[i]:division[i]+space,:].sample(frac=1) for i in range(len(division))])<br><br>def create_time_blocks(time_length,window_size,forecast_length):<br>    start_idx = np.random.randint(0,window_size-1)<br>    end_idx = time_length-window_size-forecast_length-1<br>    time_indices = np.arange(start_idx,end_idx+1,window_size)[:-1]<br>    time_indices = np.append(time_indices,end_idx)<br>    return time_indices<br><br>def data_loader(x_numeric_tensor, x_category_tensor, x_static_tensor, y_tensor, batch_size, time_shuffle):<br><br>    num_series = x_numeric_tensor.shape[0]<br>    time_length = x_numeric_tensor.shape[1]<br>    index_pd = pd.DataFrame({&#39;serie_idx&#39;:range(num_series)})<br>    index_pd[&#39;time_idx&#39;] = [create_time_blocks(time_length,window_size,forecast_length) for n in range(index_pd.shape[0])]<br>    if time_shuffle:<br>        index_pd = index_pd.explode(&#39;time_idx&#39;)<br>        index_pd = index_pd.sample(frac=1)<br>    else:<br>        index_pd = index_pd.explode(&#39;time_idx&#39;).sort_values(&#39;time_idx&#39;)<br>        index_pd = divide_shuffle(index_pd,5)<br>    indices = np.array(index_pd).astype(int)<br><br>    for batch_idx in np.arange(0,indices.shape[0],batch_size):<br><br>        cur_indices = indices[batch_idx:batch_idx+batch_size,:]<br><br>        x_numeric = torch.stack([x_numeric_tensor[n[0],n[1]:n[1]+window_size,:] for n in cur_indices])<br>        x_category = torch.stack([x_category_tensor[n[0],n[1]:n[1]+window_size,:] for n in cur_indices])<br>        x_static = torch.stack([x_static_tensor[n[0],:] for n in cur_indices])<br>        y = torch.stack([y_tensor[n[0],n[1]+window_size:n[1]+window_size+forecast_length] for n in cur_indices])<br><br>        yield x_numeric.to(device), x_category.to(device), x_static.to(device), y.to(device)<br><br>def val_loader(x_numeric_tensor, x_category_tensor, x_static_tensor, y_tensor, batch_size, num_val):<br><br>    num_time_series = x_numeric_tensor.shape[0]<br><br>    for i in range(num_val):<br><br>      for batch_idx in np.arange(0,num_time_series,batch_size):<br><br>          x_numeric = x_numeric_tensor[batch_idx:batch_idx+batch_size,window_size*i:window_size*(i+1),:]<br>          x_category = x_category_tensor[batch_idx:batch_idx+batch_size,window_size*i:window_size*(i+1),:]<br>          x_static = x_static_tensor[batch_idx:batch_idx+batch_size]<br>          y_val = y_tensor[batch_idx:batch_idx+batch_size,window_size*(i+1):window_size*(i+1)+forecast_length]<br><br>          yield x_numeric.to(device), x_category.to(device), x_static.to(device), y_val.to(device)</pre><h3><strong>Model Architecture</strong></h3><p>In time series forecasting, capturing the sequence information is key, and for this purpose, I utilized the Transformer architecture as described in the seminal paper <em>Attention is All You Need (2017)²</em>. My model generates block forecasts and, hence, doesn’t require causality in its attention mechanism — no masking was applied to the attention blocks.</p><p>Let’s start with the input: categorical features are passed through embedding layers to represent them in a dense form then fed to the transformer block. Then, a Multi-Layer Perceptron (MLP) takes the final encoded input to produce the forecast. The embedding dimension, the number of attention heads in each Transformer block, and the dropout probability are the model’s primary hyperparameters. Furthermore, stacking multiple Transformer blocks is controlled by the ‘num_blocks’ hyperparameter.</p><p>Below is the implementation of a single Transformer block and the overall forecasting model:</p><pre>class transformer_block(nn.Module):<br><br>    def __init__(self,embed_size,num_heads):<br>        super(transformer_block, self).__init__()<br><br>        self.attention = nn.MultiheadAttention(embed_size, num_heads, batch_first=True)<br>        self.fc = nn.Sequential(nn.Linear(embed_size, 4 * embed_size),<br>                                 nn.LeakyReLU(),<br>                                 nn.Linear(4 * embed_size, embed_size))<br>        self.dropout = nn.Dropout(drop_prob)<br>        self.ln1 = nn.LayerNorm(embed_size, eps=1e-6)<br>        self.ln2 = nn.LayerNorm(embed_size, eps=1e-6)<br><br>    def forward(self, x):<br><br>        attn_out, _ = self.attention(x, x, x, need_weights=False)<br>        x = x + self.dropout(attn_out)<br>        x = self.ln1(x)<br><br>        fc_out = self.fc(x)<br>        x = x + self.dropout(fc_out)<br>        x = self.ln2(x)<br><br>        return x<br><br>class transformer_forecaster(nn.Module):<br><br>    def __init__(self,embed_size,num_heads,num_blocks):<br>        super(transformer_forecaster, self).__init__()<br><br>        num_len = len(numeric_covariates)<br>        self.embedding_cov = nn.ModuleList([nn.Embedding(n,embed_size-num_len) for n in categorical_covariates_num_embeddings])<br>        self.embedding_static = nn.ModuleList([nn.Embedding(n,embed_size-num_len) for n in categorical_static_num_embeddings])<br><br>        self.blocks = nn.ModuleList([transformer_block(embed_size,num_heads) for n in range(num_blocks)])<br><br>        self.forecast_head = nn.Sequential(nn.Linear(embed_size, embed_size*2),<br>                                           nn.LeakyReLU(),<br>                                           nn.Dropout(drop_prob),<br>                                           nn.Linear(embed_size*2, embed_size*4),<br>                                           nn.LeakyReLU(),<br>                                           nn.Linear(embed_size*4, forecast_length),<br>                                           nn.ReLU())<br><br>    def forward(self, x_numeric, x_category, x_static):<br><br>        tmp_list = []<br>        for i,embed_layer in enumerate(self.embedding_static):<br>            tmp_list.append(embed_layer(x_static[:,i]))<br>        categroical_static_embeddings = torch.stack(tmp_list).mean(dim=0).unsqueeze(1)<br><br>        tmp_list = []<br>        for i,embed_layer in enumerate(self.embedding_cov):<br>            tmp_list.append(embed_layer(x_category[:,:,i]))<br>        categroical_covariates_embeddings = torch.stack(tmp_list).mean(dim=0)<br>        T = categroical_covariates_embeddings.shape[1]<br><br>        embed_out = (categroical_covariates_embeddings + categroical_static_embeddings.repeat(1,T,1))/2<br>        x = torch.concat((x_numeric,embed_out),dim=-1)<br><br>        for block in self.blocks:<br>            x = block(x)<br><br>        x = x.mean(dim=1)<br>        x = self.forecast_head(x)<br><br>        return x</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*yYRMGpAGlPSEW1qLI9RLyg.png" /><figcaption>Model Diagram</figcaption></figure><p>As illustrated in the diagram, the model accepts three separate input tensors: numeric features, categorical features, and static features. Categorical and static feature embeddings are averaged and combined with numeric features to form a tensor with shape (batch_size, window_size, embedding_size), ready for the Transformer block. This composite tensor also carries embedded time variables, providing essential positional information.</p><p>The Transformer block extracts sequential information, and the resulting tensor is then aggregated along the time dimension before being passed into an MLP to produce the final forecast of shape (batch_size, forecast_length). The competition uses the Root Mean Squared Logarithmic Error (RMSLE) as the evaluation metric formulated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/0*OG0pV5Q98efH1XYg" /></figure><p>Given that predictions undergo logarithmic transformation, prospects of predicting negative sales values lower than -1 — which result in undefined errors — needed to be curtailed. To avoid negative sales forecasts and the resulting NaN loss values, a final ReLU activation function is applied to the MLP layer to ensure non-negative predictions.</p><h3><strong>Training and Evaluation</strong></h3><p>As I embarked on training the model, I set several hyperparameters: window size, time shuffle, embedding size, number of heads, number of transformer blocks, dropout probability, batch size, and learning rate. Limited GPU resources constrained my ability to extensively tune these hyperparameters, but iterative experimentation led me to settle on the following configuration as the most effective:</p><pre>class RMSLELoss(nn.Module):<br><br>    def __init__(self):<br>        super().__init__()<br>        self.mse = nn.MSELoss()<br><br>    def forward(self, pred, actual):<br>        return torch.sqrt(self.mse(torch.log(pred + 1), torch.log(actual + 1)))</pre><pre>num_epoch = 1000<br>min_val_loss = 999<br><br>num_blocks = 1<br>embed_size = 500<br>num_heads = 50<br>batch_size = 128<br>learning_rate = 3e-4<br>time_shuffle = False<br>drop_prob = 0.1<br><br>model = transformer_forecaster(embed_size,num_heads,num_blocks).to(device)<br>criterion = RMSLELoss()<br>optimizer = torch.optim.Adam(model.parameters(),lr=learning_rate)<br>scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=50, gamma=0.5)</pre><p>I opted for the Adam optimizer and implemented a learning rate scheduler to gradually adjust the learning rate during training. Here’s how the training process was carried out:</p><pre>for epoch in range(num_epoch):<br><br>    batch_loader = data_loader(x_numeric_train_tensor, x_category_train_tensor, x_static_train_tensor, y_train_tensor, batch_size, time_shuffle)<br>    train_loss = 0<br>    counter = 0<br><br>    model.train()<br>    for x_numeric, x_category, x_static, y in batch_loader:<br><br>        optimizer.zero_grad()<br>        preds = model(x_numeric, x_category, x_static)<br>        loss = criterion(preds, y)<br>        train_loss += loss.item()<br>        counter += 1<br>        loss.backward()<br>        optimizer.step()<br><br>    train_loss = train_loss/counter<br>    print(f&#39;Epoch {epoch} training loss: {train_loss}&#39;)<br><br>    model.eval()<br>    val_batches = val_loader(x_numeric_val_tensor, x_category_val_tensor, x_static_val_tensor, y_val_tensor, batch_size, num_val)<br>    val_loss = 0<br>    counter = 0<br>    for x_numeric_val, x_category_val, x_static_val, y_val in val_batches:<br>        with torch.no_grad():<br>            preds = model(x_numeric_val,x_category_val,x_static_val)<br>            loss = criterion(preds,y_val).item()<br>        val_loss += loss<br>        counter += 1<br>    val_loss = val_loss/counter<br>    print(f&#39;Epoch {epoch} validation loss: {val_loss}&#39;)<br><br>    if val_loss&lt;min_val_loss:<br>      print(&#39;saved...&#39;)<br>      torch.save(model,data_folder+&#39;best.model&#39;)<br>      min_val_loss = val_loss<br><br>    scheduler.step()</pre><h3><strong>Results and Insights</strong></h3><p>After training, the model that demonstrates the lowest validation loss is retained. Despite being limited to 200 epochs due to GPU resource limitations, selected hyperparameters are worked out: the best-performing model achieved a training loss of 0.387 and a validation loss of 0.457. When applied to the test set, this model achieved a RMSLE of 0.416, landing me in the 89th position — placing me within the top 10% of the competition, all with a basic model and relatively modest dataset.</p><p>Larger embedding sizes paired with a higher number of attention heads seemed to enhance performance, yet the best outcomes were realized with a solitary transformer block, suggesting that simplicity is virtue with limited data. I also observed an improvement when forgoing full shuffling in favor of sectional shuffling; introducing a slight time bias meaningfully amplified predictive accuracy.</p><p>There is certainly room to systematize hyperparameter tuning for further gains. Additionally, incorporating future covariates information may not be fully realized by the current model architecture, suggesting an encoder-decoder configuration, akin to the Temporal Fusion Transformer³, could yield more significant benefits.</p><p>I hope this article has imparted valuable insights into time series forecasting. As someone continuing to learn and grow in this field, I welcome and truly appreciate your feedback and discourse on this and related topics. Thank you for joining me on this exploration!</p><p>[1]: Alexis Cook, DanB, inversion, Ryan Holbrook. (2021). Store Sales — Time Series Forecasting. Kaggle. <a href="https://kaggle.com/competitions/store-sales-time-series-forecasting">https://kaggle.com/competitions/store-sales-time-series-forecasting</a></p><p>[2]: Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., … &amp; Polosukhin, I. (2017). Attention is all you need. <em>Advances in neural information processing systems</em>, <em>30</em>.</p><p>[3]: Lim, B., Arık, S. Ö., Loeff, N., &amp; Pfister, T. (2021). Temporal fusion transformers for interpretable multi-horizon time series forecasting. <em>International Journal of Forecasting</em>, <em>37</em>(4), 1748–1764.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=650f116a1018" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>