|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
import torch |
|
import numpy as np |
|
|
|
|
|
class LSTMPredictor(torch.nn.Module): |
|
def __init__(self, input_dim, hidden_dim, output_dim, forecast_horizon, n_layers, dropout): |
|
super(LSTMPredictor, self).__init__() |
|
self.lstm = torch.nn.LSTM(input_dim, hidden_dim, n_layers, dropout=dropout, batch_first=True) |
|
self.fc = torch.nn.Linear(hidden_dim, output_dim) |
|
self.forecast_horizon = forecast_horizon |
|
|
|
def forward(self, x): |
|
|
|
lstm_out, _ = self.lstm(x) |
|
|
|
out = self.fc(lstm_out[:, -1, :]) |
|
return out |
|
|
|
|
|
def load_model(model_path): |
|
model_state = torch.load(model_path) |
|
model = LSTMPredictor( |
|
input_dim=model_state['model_architecture']['input_dim'], |
|
hidden_dim=model_state['model_architecture']['hidden_dim'], |
|
output_dim=model_state['model_architecture']['output_dim'], |
|
forecast_horizon=model_state['model_architecture']['forecast_horizon'], |
|
n_layers=model_state['model_architecture']['n_layers'], |
|
dropout=model_state['model_architecture']['dropout'] |
|
) |
|
model.load_state_dict(model_state['model_state_dict']) |
|
model.eval() |
|
return model |
|
|
|
|
|
def predict(model, features): |
|
|
|
input_tensor = torch.FloatTensor(features) |
|
|
|
|
|
with torch.no_grad(): |
|
predictions = model(input_tensor).numpy() |
|
|
|
return predictions.tolist() |
|
|
|
|
|
if __name__ == "__main__": |
|
|
|
model = load_model('lstm_crisis_severity_predictor_20241116_092126.pt') |
|
|
|
|
|
test_features = np.array([[1.23, 4.56, 7.89, 10.11]]) |
|
|
|
|
|
test_features = test_features.reshape((test_features.shape[0], 1, test_features.shape[1])) |
|
|
|
|
|
predictions = predict(model, test_features) |
|
|
|
|
|
print("Predictions:", predictions) |
|
|
|
|