import matplotlib.pyplot as plt
plt.figure(figsize=(12, 6))
plt.plot(df['Close'])
plt.title("TCS India Stock Price")
plt.xlabel("Date")
plt.ylabel("Price (INR)")
plt.grid(True)
plt.show()
%%
df
%% [markdown]
# Plotting moving averages of 100 day
---
%%
ma100 = df.Close.rolling(100).mean()
ma100
%%
plt.figure(figsize = (12,6))
plt.plot(df.Close)
plt.plot(ma100, 'r')
plt.grid(True)
plt.title('Graph Of Moving Averages Of 100 Days')
%% [markdown]
# Defining 200 days moving averages and plotting comparision graph with 100 days moving averages
---
%%
ma200 = df.Close.rolling(200).mean()
ma200
%%
plt.figure(figsize = (12,6))
plt.plot(df.Close)
plt.plot(ma100, 'r')
plt.plot(ma200, 'g')
plt.grid(True)
plt.title('Comparision Of 100 Days And 200 Days Moving Averages')
%%
df.shape
%% [markdown]
# Spliting the dataset into training (70%) and testing (30%) set
%%
Splitting data into training and testing
train = pd.DataFrame(data[0:int(len(data)*0.70)])
test = pd.DataFrame(data[int(len(data)*0.70): int(len(data))])
print(train.shape)
print(test.shape)
%%
train.head()
%%
test.head()
%% [markdown]
# Using MinMax scaler for normalization of the dataset
Assistant
User
what about test ?
Assistant
User
how to calculate mean_absolute_error of model prediction
Assistant
---
%%
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler(feature_range=(0,1))
import tensorflow as tf
model.compile(optimizer = 'adam', loss = 'mean_squared_error', metrics=[tf.keras.metrics.MeanAbsoluteError()])
model.fit(x_train, y_train,epochs = 100)
%%
model.save('keras_model.h5')
%%
test_close.shape
%%
past_100_days = pd.DataFrame(train_close[-100:])
%%
test_df = pd.DataFrame(test_close)
%% [markdown]
Defining the final dataset for testing by including last 100 coloums of the training dataset to get the prediction from the 1st column of the testing dataset.
make proper changes so the model uses "Open", "High", "Low", "Close","volume_base", "volume_crypto", "tradecount" instead of just using "Close" and also predicts "y1","y2","y3" instead of just Close price
To adapt your code for using multiple input features (i.e., "Open", "High", "Low", "Close", "volume_base", "volume_crypto", "tradecount") for predictions and targeting multiple output features (i.e., "y1", "y2", "y3") instead of only predicting the "Close" price, follow these steps:
Scale Your Data: Ensure that all your input features and target features are scaled properly.
Change the Structure of Your Input and Output Data: Adjust the data preparation process to handle multiple features.
Adapt the Model to Output Multiple Values: Change the last layer of your model to output 3 values (for "y1", "y2", "y3") instead of 1.
Here’s how you can achieve this:
Scaling Your Data
python
from sklearn.preprocessing import MinMaxScaler
# Assuming 'data' already contains the selected features and targets
feature_columns = ["Open", "High", "Low", "Close", "volume_base", "volume_crypto", "tradecount"]
target_columns = ["y1", "y2", "y3"]
# Split your data into features and targets
features = data[feature_columns]
targets = data[target_columns]
# Scale the features and targets
feature_scaler = MinMaxScaler(feature_range=(0, 1))
target_scaler = MinMaxScaler(feature_range=(0, 1))
scaled_features = feature_scaler.fit_transform(features)
scaled_targets = target_scaler.fit_transform(targets)
Preparing Input and Output Data
You’ll need to adjust the process for creating your x_train, y_train arrays to include all selected features and targets. Additionally, you should apply the same adjustments to your test data preparation.
python
look_back = 100 # Number of previous time steps to consider for each output
x_train = []
y_train = []
for i in range(look_back, len(scaled_features)):
x_train.append(scaled_features[i-look_back:i])
y_train.append(scaled_targets[i]) # Assuming the target is the next time step
x_train, y_train = np.array(x_train), np.array(y_train)
Because you're now dealing with multiple features, ensure the input shape of your LSTM layers matches the number of features:
python
input_shape = (x_train.shape[1], x_train.shape[2]) # (time steps, number of features)
Adapting the Model Architecture
Update your model to handle multiple output values. This involves adjusting the units of the last Dense layer to match the number of targets you're predicting.
python
model = Sequential([
LSTM(50, activation='tanh', return_sequences=True, input_shape=input_shape),
Dropout(0.2),
LSTM(60, activation='tanh', return_sequences=True),
Dropout(0.3),
LSTM(80, activation='tanh', return_sequences=True),
Dropout(0.4),
LSTM(120, activation='tanh'),
Dropout(0.5),
Dense(units=len(target_columns)) # Adjust the unit to match the number of outputs
])
model.compile(optimizer='adam', loss='mean_squared_error')
Adjust the Evaluation and Prediction Steps
Remember to inverse transform your predictions and actual y values before evaluating the model performance to ensure the error metrics are computed on the original scale of your data.
python
# Scale back the predicted and actual values to their original scale
predicted = target_scaler.inverse_transform(model.predict(x_test))
actual = target_scaler.inverse_transform(y_test)
# Compute your evaluation metrics here (e.g., MAE) based on 'predicted' and 'actual'
Ensure that you adapt all subsequent steps similarly, especially when preparing your test data and making predictions, to reflect these structural changes to your model and data handling process.
Ah, yes. Let's ensure the test data handling matches the updated data structure and model. After preparing your x_train and y_train datasets with multiple input features and output targets as described, you must similarly prepare your x_test and y_test datasets.
Preparing the Test Data
To prepare the test data, you need to follow a process similar to how you prepared the training data but using your test dataset. This involves scaling the test data using the same scalers you used for the training data to ensure the model can interpret the test data correctly.
First, combine your scaled training feature data and the test feature data to ensure the continuity of sequences:
python
# Assuming you have already defined 'train' and 'test' datasets
# Scale the test data features
scaled_test_features = feature_scaler.transform(test[feature_columns])
# Note: If you have new test data completely separate from your 'data' DataFrame, scale it accordingly
# Scale the test data targets
scaled_test_targets = target_scaler.transform(test[target_columns])
# Combine the end of the training features with the test features for seamless sequence continuation
complete_test_features = np.concatenate((scaled_features[-look_back:], scaled_test_features), axis=0)
# Prepare the test sequences
x_test = []
y_test = []
for i in range(look_back, len(complete_test_features)):
x_test.append(complete_test_features[i-look_back:i])
y_test.append(scaled_test_targets[i-look_back]) # Adjust index if necessary
x_test, y_test = np.array(x_test), np.array(y_test)
This complete_test_features buffer ensures that the model has access to the necessary historical data (i.e., the last look_back days from the training set) when making predictions on the test set. The look_back adjustments in indices may need to be fine-tuned based on the exact structure of your test set and the way it's been combined.
Making Predictions
Use your prepared x_test to make predictions. Then, you can inverse scale your predictions and actual y_test targets for evaluation:
python
# Making predictions
predicted_test = model.predict(x_test)
# Inverse transformation for obtaining original scale of predictions
predicted_test_original = target_scaler.inverse_transform(predicted_test)
# Assuming y_test was prepared with actual future values
y_test_original = target_scaler.inverse_transform(y_test)
This adjustment ensures your predictions and actual values are on the same scale, facilitating accurate performance evaluation.
Evaluating the Model
For evaluation, you might calculate metrics such as Mean Absolute Error (MAE) for each of the output targets separately or together, depending on your analysis needs:
python
from sklearn.metrics import mean_absolute_error
# Evaluate MAE for each target
for i, target in enumerate(target_columns):
mae = mean_absolute_error(y_test_original[:, i], predicted_test_original[:, i])
print(f"MAE for {target}: {mae}")
If your model predicts multiple steps ahead (y1, y2, y3), it is crucial to accurately index these in your evaluation and to clearly represent what each part of your predictions and actual values represents for consistency and clarity in your analysis.
This will ensure you have a complete preparation, training, prediction, and evaluation flow adjusted for handling multiple inputs and outputs in your LSTM model.
Calculating the Mean Absolute Error (MAE) is straightforward once you have your model's predictions and the actual values. MAE provides a simple interpretation by averaging the absolute differences between predicted values and actual values, thus giving you an idea of how close your predictions are to the reality, on average. Below are steps and Python code using sklearn.metrics.mean_absolute_error to calculate the MAE for your model's predictions.
Steps for Calculating MAE
Prepare your data: Ensure your predictions and actual values are in the correct format, usually numpy arrays or similar. If you've followed the previous steps, you should have predicted_test_original for your model predictions and y_test_original for the actual values, both inverse transformed to their original scale.
Use mean_absolute_error from sklearn.metrics: This function requires two main arguments: the actual values and the predicted values.
Python Code to Calculate MAE
python
from sklearn.metrics import mean_absolute_error
# Assuming 'y_test_original' contains the actual target values
# and 'predicted_test_original' contains your model's predictions
mae = mean_absolute_error(y_test_original, predicted_test_original)
print(f"Mean Absolute Error: {mae}")
This code snippet calculates the overall MAE for your model if y_test_original and predicted_test_original are 1-dimensional arrays (e.g., if you're predicting a single target).
Calculating MAE for Multiple Targets
If your model predicts multiple targets (e.g., y1, y2, y3), and hence, y_test_original and predicted_test_original are 2-dimensional arrays, you might want to calculate MAE for each target separately to understand how well your model is performing on each prediction task. Here’s how you can do it:
python
# Calculate MAE for each target separately
for i in range(y_test_original.shape[1]): # Assuming y_test_original and predicted_test_original are 2D
mae = mean_absolute_error(y_test_original[:, i], predicted_test_original[:, i])
print(f"MAE for target {i+1}: {mae}")
This loop calculates the MAE for each column in your arrays (each target variable) individually, which can be particularly helpful for multi-output models.
Interpretation
Lower MAE values indicate better model performance with predictions closer to the actual values.
Higher MAE values suggest the model's predictions are, on average, further away from the actual values.
MAE provides a clear metric to assess and compare model performance, especially useful in tuning your model or comparing multiple models.