-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfourier.py
59 lines (50 loc) · 1.83 KB
/
fourier.py
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
import pandas as pd
import numpy as np
import torch
import csv
# Load dataset
dataset_path = 'Fourier_test.csv'
dataset = pd.read_csv(dataset_path)
rate_values = torch.FloatTensor(dataset['RATE'].values).view(-1, 1).squeeze()
# Fourier series expansion
def create_fourier_series(data, num_terms, period):
x = torch.FloatTensor(np.arange(len(data))).unsqueeze(1)
fourier_terms = x.clone()
for n in range(1, num_terms + 1):
cos_term = torch.cos(n * 2 * np.pi * x / period)
sin_term = torch.sin(n * 2 * np.pi * x / period)
fourier_terms = torch.cat((fourier_terms, cos_term, sin_term), axis=1)
return fourier_terms[:, 1:]
# Model definition
class FourierLinearRegression(torch.nn.Module):
def __init__(self, input_feature):
super(FourierLinearRegression, self).__init__()
self.linear = torch.nn.Linear(input_feature, 1)
def forward(self, x):
return self.linear(x).squeeze()
# Hyperparameters
N = 30
period = 2030
learning_rate = 0.05
num_epochs = 2000
# Data preparation
fourier_series = create_fourier_series(rate_values, N, period)
input_feature = fourier_series.shape[1]
# Model initialization
model = FourierLinearRegression(input_feature)
loss_function = torch.nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
# Training loop
for epoch in range(num_epochs):
optimizer.zero_grad()
predictions = model(fourier_series)
loss = loss_function(predictions, rate_values)
loss.backward()
optimizer.step()
if (epoch + 1) % 100 == 0:
print(f'Epoch {epoch + 1}, Loss: {loss.item()}')
# Save predictions
with open('Fourier_output.csv', 'w', newline='') as file:
writer = csv.writer(file)
for value in model(fourier_series).detach().numpy():
writer.writerow([value])