import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
import pandas as pd
from model import AttentionModel
import numpy as np
from sklearn.model_selection import train_test_split
import joblib
import matplotlib.pyplot as plt
import os
# Dataset Definition
class BitcoinDataset(Dataset):
def __init__(self, data, sequence_length=100):
self.sequence_length = sequence_length
self.data = data.values.astype(np.float32)
self.features = data.columns.tolist()
self.feature_size = data.shape[1] - 1 # Exclude target
def __len__(self):
return len(self.data) - self.sequence_length
def __getitem__(self, idx):
x = self.data[idx:idx + self.sequence_length, :-1]
y = self.data[idx + self.sequence_length, -1]
return torch.tensor(x), torch.tensor(y)
def train():
# Load and split data
train_df = pd.read_csv('data/train_data.csv')
val_size = 0.1
train_data, val_data = train_test_split(train_df, test_size=val_size, shuffle=False)
# Parameters
sequence_length = 100
batch_size = 64
num_epochs = 8#50
learning_rate = 0.001
input_size = train_data.shape[1] - 1 # Exclude target
# Create datasets and loaders
train_dataset = BitcoinDataset(train_data, sequence_length)
val_dataset = BitcoinDataset(val_data, sequence_length)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, drop_last=True)
val_loader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False, drop_last=True)
# Initialize model, loss function, and optimizer
model = AttentionModel(input_size=input_size)
criterion = nn.MSELoss()
mae_loss = nn.L1Loss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, patience=5, factor=0.5, verbose=True)
# Device configuration
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model.to(device)
# Early stopping parameters
early_stopping = False
patience = 10
min_val_loss = np.Inf
epochs_no_improve = 0
# Training loop
train_losses = []
val_losses = []
for epoch in range(num_epochs):
model.train()
epoch_train_loss = 0
for sequences, targets in train_loader:
sequences = sequences.to(device)
targets = targets.to(device)
outputs = model(sequences)
loss = criterion(outputs.squeeze(), targets)
optimizer.zero_grad()
loss.backward()
optimizer.step()
epoch_train_loss += loss.item()
avg_train_loss = epoch_train_loss / len(train_loader)
train_losses.append(avg_train_loss)
# Validation
model.eval()
epoch_val_loss = 0
with torch.no_grad():
for sequences, targets in val_loader:
sequences = sequences.to(device)
targets = targets.to(device)
outputs = model(sequences)
loss = criterion(outputs.squeeze(), targets)
epoch_val_loss += loss.item()
avg_val_loss = epoch_val_loss / len(val_loader)
val_losses.append(avg_val_loss)
scheduler.step(avg_val_loss)
print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {avg_train_loss:.6f}, Val Loss: {avg_val_loss:.6f}')
# Early Stopping Check
if avg_val_loss < min_val_loss:
min_val_loss = avg_val_loss
epochs_no_improve = 0
torch.save(model.state_dict(), 'models/best_model.pth')
else:
epochs_no_improve += 1
if epochs_no_improve == patience:
print('Early stopping!')
early_stopping = True
break
# Plotting training and validation loss
plt.figure(figsize=(10,5))
plt.plot(train_losses, label='Training Loss')
plt.plot(val_losses, label='Validation Loss')
plt.legend()
plt.savefig('models/loss_plot.png')
plt.show()
# Load the best model
model.load_state_dict(torch.load('models/best_model.pth'))
print("Best model loaded from models/best_model.pth")
if __name__ == "__main__":
train()
Это моя модель для предсказания цены BitcoinUSDT, основываясь на предыдущих шагах.
Вот так выглядит обучение:
Epoch [1/8], Train Loss: 0.000977, Val Loss: 0.000083
Epoch [2/8], Train Loss: 0.000111, Val Loss: 0.000059
Epoch [3/8], Train Loss: 0.000062, Val Loss: 0.000033
Epoch [4/8], Train Loss: 0.000056, Val Loss: 0.000035
Epoch [5/8], Train Loss: 0.000053, Val Loss: 0.000043
Epoch [6/8], Train Loss: 0.000045, Val Loss: 0.000035
Epoch [7/8], Train Loss: 0.000041, Val Loss: 0.000025
Вот так выглядит test:
Test RMSE: 76.41
Test MAE: 52.25
Test MAPE: 0.19%
Нужно убрать Bidirectional LSTM, ведь в реальности мы не можем получить данные из будущего.
Проверь, не перемешиваются ли тренировочные и тестовые наборы данных.
Важно, чтобы при обучении выборки по 100 шагов были последовательно
Примени все свои навыки ML-специалиста и произведи улучшения.
Приведи обновленные файлы.
Я хочу, чтобы test.py работал иначе - он брал бы случайные 100 шагов из тестового набора, рисовал бы их. После чего, оранжевым рисовал бы 101-й шаг, предсказанный моделью. И поверх него зеленым цветом реальный 101-й шаг.
Sure, I understand your requirements and will implement the necessary changes to improve your Bitcoin price prediction model. Here's a summary of the changes we'll make:
Remove Bidirectional LSTM: Modify the AttentionModel to use a unidirectional LSTM instead of a bidirectional one.
Ensure Sequential Data Handling: Adjust the train.py to avoid shuffling the data during training to maintain the temporal order of the sequences.
Enhance test.py: Update the testing script to randomly select 100-step sequences from the test set and plot the 101st predicted and actual values as per your specifications.
Below are the updated files with detailed explanations.
1. Updated model.py
Changes Made:
Unidirectional LSTM: Changed the LSTM from bidirectional to unidirectional by setting bidirectional=False.
Adjusted Attention and Fully Connected Layers: Updated the dimensions of the Attention and Fully Connected layers to match the unidirectional LSTM output.
Removed Shuffling During Training: Set shuffle=False in the DataLoader for training to maintain the sequential order of data.
Increased num_epochs: Optionally, you might consider increasing the number of epochs for better training, but this is left as is (num_epochs = 8) based on your current setup.
python
3. Updated test.py
Changes Made:
Random Selection of 100-Step Sequences: The script now randomly selects a starting index from the test dataset to extract a 100-step sequence.
Plotting Predictions: After predicting the 101st step, it plots the 100-step sequence, the predicted 101st value in orange, and the actual 101st value in green.
python
4. Optional: data_loader.py
While you didn't specify needing changes here, it's good practice to ensure that the directories exist before saving files. Here's an enhanced version to ensure that:
python
# data_loader.py
import requests
import pandas as pd
import numpy as np
import time
from datetime import datetime, timedelta
from tqdm import tqdm
import os
def get_data(start_time, end_time, interval):
url = "https://api.binance.com/api/v3/klines"
params = {
'symbol': 'BTCUSDT',
'interval': interval,
'startTime': start_time,
'endTime': end_time,
'limit': 1000
}
response = requests.get(url, params=params)
data = response.json()
return data
def add_indicators(df):
# [Same as your original function]
# ... (No changes)
# [Ensure all indicators are correctly calculated]
# Return the modified dataframe
return df
def collect_data(start_date_str, end_date_str):
interval = '5m'
start_date = datetime.strptime(start_date_str, '%Y-%m-%d')
end_date = datetime.strptime(end_date_str, '%Y-%m-%d')
start_time = int(start_date.timestamp() * 1000)
end_time = int(end_date.timestamp() * 1000)
total_requests = (end_time - start_time) // (1000 * 60 * 5 * 1000) + 1
all_data = []
with tqdm(total=total_requests, desc="Collecting data") as pbar:
while start_time < end_time:
data = get_data(start_time, end_time, interval)
if not data:
break
all_data.extend(data)
start_time = data[-1][6] + 1
time.sleep(0.5)
pbar.update(1)
columns = ['Open Time', 'Open', 'High', 'Low', 'Close', 'Volume',
'Close Time', 'Quote Asset Volume', 'Number of Trades',
'Taker Buy Base Asset Volume', 'Taker Buy Quote Asset Volume', 'Ignore']
df = pd.DataFrame(all_data, columns=columns)
df['Open Time'] = pd.to_datetime(df['Open Time'], unit='ms')
df['Close Time'] = pd.to_datetime(df['Close Time'], unit='ms')
numeric_columns = ['Open', 'High', 'Low', 'Close', 'Volume']
df[numeric_columns] = df[numeric_columns].astype(float)
df.reset_index(drop=True, inplace=True)
# Ensure directories exist
os.makedirs('data', exist_ok=True)
os.makedirs('models', exist_ok=True)
df.to_csv('data/raw_data.csv', index=False)
print("Data successfully saved to data/raw_data.csv")
df = add_indicators(df)
df.dropna(inplace=True)
df.reset_index(drop=True, inplace=True)
df.to_csv('data/processed_data.csv', index=False)
print("Data with indicators saved to data/processed_data.csv")
def preprocess_data():
df = pd.read_csv('data/processed_data.csv')
# [Same as your original function]
# ... (No changes)
# Ensure directories exist
os.makedirs('models', exist_ok=True)
# Further preprocessing steps
# ...
if __name__ == "__main__":
start_date_str = '2022-09-01'
end_date_str = '2023-09-30'
print(f"Collecting data from {start_date_str} to {end_date_str}")
collect_data(start_date_str, end_date_str)
print("Preprocessing data")
preprocess_data()
5. Summary of Improvements
Unidirectional LSTM: Aligns the model with real-world scenarios where future data isn't accessible during prediction.
Sequential Data Handling: Ensures that the temporal structure of the data is preserved during training, which is crucial for time series forecasting.
Enhanced Testing Visualization: Provides clear visual comparisons between predicted and actual prices, which can aid in better understanding the model's performance.
Directory Checks: Ensures that the required directories exist before saving files, preventing potential file I/O errors.
6. Additional Recommendations
Hyperparameter Tuning: Consider experimenting with different hyperparameters such as hidden_size, num_layers, learning_rate, and sequence_length to potentially improve model performance.
Extended Training Epochs: Depending on the convergence behavior, increasing the number of training epochs might lead to better performance.
Cross-Validation: Implement cross-validation techniques tailored for time series data, such as TimeSeriesSplit, to robustly evaluate model performance.
Feature Engineering: Explore additional technical indicators or external data sources (e.g., sentiment analysis from news) to enrich the feature set.
Model Evaluation: Besides RMSE, MAE, and MAPE, consider other evaluation metrics like R-squared for a more comprehensive assessment.
By implementing these changes and recommendations, your Bitcoin price prediction model should become more robust and better aligned with real-world application scenarios.
Dataset releases
Not yet included in a published release.
# train.py
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
import pandas as pd
from model import AttentionModel
import numpy as np
from sklearn.model_selection import train_test_split
import joblib
import matplotlib.pyplot as plt
import os
# Dataset Definition
class BitcoinDataset(Dataset):
def __init__(self, data, sequence_length=100):
self.sequence_length = sequence_length
self.data = data.values.astype(np.float32)
self.features = data.columns.tolist()
self.feature_size = data.shape[1] - 1 # Exclude target
def __len__(self):
return len(self.data) - self.sequence_length
def __getitem__(self, idx):
x = self.data[idx:idx + self.sequence_length, :-1]
y = self.data[idx + self.sequence_length, -1]
return torch.tensor(x), torch.tensor(y)
def train():
# Load and split data
train_df = pd.read_csv('data/train_data.csv')
val_size = 0.1
train_data, val_data = train_test_split(train_df, test_size=val_size, shuffle=False)
# Parameters
sequence_length = 100
batch_size = 64
num_epochs = 8 # Consider increasing for better performance
learning_rate = 0.001
input_size = train_data.shape[1] - 1 # Exclude target
# Create datasets and loaders
train_dataset = BitcoinDataset(train_data, sequence_length)
val_dataset = BitcoinDataset(val_data, sequence_length)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=False, drop_last=True) # shuffle=False
val_loader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False, drop_last=True)
# Initialize model, loss function, and optimizer
model = AttentionModel(input_size=input_size)
criterion = nn.MSELoss()
mae_loss = nn.L1Loss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, patience=5, factor=0.5, verbose=True)
# Device configuration
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model.to(device)
# Early stopping parameters
early_stopping = False
patience = 10
min_val_loss = np.Inf
epochs_no_improve = 0
# Training loop
train_losses = []
val_losses = []
for epoch in range(num_epochs):
model.train()
epoch_train_loss = 0
for sequences, targets in train_loader:
sequences = sequences.to(device)
targets = targets.to(device)
outputs = model(sequences)
loss = criterion(outputs.squeeze(), targets)
optimizer.zero_grad()
loss.backward()
optimizer.step()
epoch_train_loss += loss.item()
avg_train_loss = epoch_train_loss / len(train_loader)
train_losses.append(avg_train_loss)
# Validation
model.eval()
epoch_val_loss = 0
with torch.no_grad():
for sequences, targets in val_loader:
sequences = sequences.to(device)
targets = targets.to(device)
outputs = model(sequences)
loss = criterion(outputs.squeeze(), targets)
epoch_val_loss += loss.item()
avg_val_loss = epoch_val_loss / len(val_loader)
val_losses.append(avg_val_loss)
scheduler.step(avg_val_loss)
print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {avg_train_loss:.6f}, Val Loss: {avg_val_loss:.6f}')
# Early Stopping Check
if avg_val_loss < min_val_loss:
min_val_loss = avg_val_loss
epochs_no_improve = 0
torch.save(model.state_dict(), 'models/best_model.pth')
else:
epochs_no_improve += 1
if epochs_no_improve >= patience:
print('Early stopping!')
early_stopping = True
break
# Plotting training and validation loss
plt.figure(figsize=(10,5))
plt.plot(train_losses, label='Training Loss')
plt.plot(val_losses, label='Validation Loss')
plt.legend()
plt.title('Training and Validation Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.savefig('models/loss_plot.png')
plt.show()
# Load the best model
model.load_state_dict(torch.load('models/best_model.pth'))
print("Best model loaded from models/best_model.pth")
if __name__ == "__main__":
train()
# test.py
import torch
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from model import AttentionModel
import joblib
from sklearn.metrics import mean_squared_error, mean_absolute_error
import random
class BitcoinTestDataset:
def __init__(self, data, sequence_length=100):
self.sequence_length = sequence_length
self.data = data.values.astype(np.float32)
self.features = data.columns.tolist()
self.feature_size = data.shape[1] - 1 # Exclude target
def __len__(self):
return len(self.data) - self.sequence_length
def __getitem__(self, idx):
x = self.data[idx:idx + self.sequence_length, :-1]
y = self.data[idx + self.sequence_length, -1]
return torch.tensor(x), torch.tensor(y)
def inverse_transform(scaled_values, scaler, feature_name):
idx = scaler.feature_names_in_.tolist().index(feature_name)
min_ = scaler.data_min_[idx]
max_ = scaler.data_max_[idx]
return scaled_values * (max_ - min_) + min_
def test():
# Load data
test_df = pd.read_csv('data/test_data.csv')
test_dataset = BitcoinTestDataset(test_df, sequence_length=100)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=1, shuffle=False)
# Load scaler
scaler = joblib.load('models/scaler.gz')
# Initialize model
input_size = test_df.shape[1] - 1 # Exclude target
model = AttentionModel(input_size=input_size)
model.load_state_dict(torch.load('models/best_model.pth'))
model.eval()
# Device configuration
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model.to(device)
# Prepare full test set predictions
predictions = []
actuals = []
with torch.no_grad():
for sequences, targets in test_loader:
sequences = sequences.to(device)
outputs = model(sequences)
predictions.append(outputs.cpu().numpy().flatten()[0])
actuals.append(targets.numpy().flatten()[0])
# Inverse transform
predictions_inverse = inverse_transform(np.array(predictions), scaler, 'Close')
actuals_inverse = inverse_transform(np.array(actuals), scaler, 'Close')
# Evaluation metrics
rmse = np.sqrt(mean_squared_error(actuals_inverse, predictions_inverse))
mae = mean_absolute_error(actuals_inverse, predictions_inverse)
mape = np.mean(np.abs((actuals_inverse - predictions_inverse) / actuals_inverse)) * 100
print(f'Test RMSE: {rmse:.2f}')
print(f'Test MAE: {mae:.2f}')
print(f'Test MAPE: {mape:.2f}%')
# Plotting random sequences with predictions
num_plots = 5 # Number of random plots you want
for _ in range(num_plots):
if len(test_df) <= 100:
print("Test dataset is too small for plotting.")
return
# Random start index ensuring there's at least 101 steps
start_idx = random.randint(0, len(test_df) - 101)
end_idx = start_idx + 100
sequence = test_df.iloc[start_idx:end_idx]
actual_next = test_df.iloc[end_idx]['Close']
predicted_next = predictions_inverse[end_idx - 100]
# Plot the 100-step sequence
plt.figure(figsize=(15,5))
plt.plot(sequence['Open Time'], sequence['Close'], label='Actual Prices')
# Plot the predicted 101st step
plt.scatter(test_df.iloc[end_idx]['Open Time'], predicted_next, color='orange', label='Predicted 101st Price')
# Plot the actual 101st step
plt.scatter(test_df.iloc[end_idx]['Open Time'], actual_next, color='green', label='Actual 101st Price')
plt.legend()
plt.title('Bitcoin Price Prediction for 101st Step')
plt.xlabel('Time')
plt.ylabel('Price (USD)')
plt.savefig(f'models/test_prediction_{_+1}.png')
plt.show()
if __name__ == "__main__":
test()