import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
Read the dataset:
python
data = pd.read_csv('your_data_file.csv')
Prepare the dataset:
Select the features (past three years' averaged prices) and the target variable (yearly averaged price):
python
X = data[['feature1', 'feature2', 'feature3']]
y = data['target']
Split the data into training and testing sets:
python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
(Optional) Fine-tune the model: If the model's performance is not satisfactory, you can try feature scaling, adding more features, or using different regression algorithms.
Remember to replace 'your_data_file.csv' with the path to your dataset file. After following these steps, you will have a Linear Regression model that can predict the yearly averaged price using averaged prices in the past three years.
User
Plot the prediction and ground truth of yearly averaged price against time
Assistant
To plot the prediction and ground truth of yearly averaged price against time, you can use the following code snippet:
Import necessary libraries:
python
import matplotlib.pyplot as plt
import seaborn as sns
Prepare the data for plotting:
python
# Ensure that the index in the DataFrame is in date format
data['year'] = pd.to_datetime(data.index).year
# Create a new DataFrame that only contains the year and the target variable
year_data = data[['year', 'target']]
# Add the predicted values to the DataFrame
year_data['predicted_target'] = y_pred
Plot the data:
python
plt.figure(figsize=(12, 6))
# Create a line plot for the ground truth
sns.lineplot(data=year_data, x='year', y='target', label='Ground Truth', marker='o')
# Create a line plot for the predictions
sns.lineplot(data=year_data, x='year', y='predicted_target', label='Prediction', marker='o', linestyle='--')
# Add labels and title
plt.xlabel('Year')
plt.ylabel('Average Price')
plt.title('Yearly Averaged Price vs Time')
# Add a legend and show the plot
plt.legend()
plt.show()
This code snippet will create a line plot with the ground truth (actual yearly averaged prices) in solid lines and the predictions (using the Linear Regression model) in dashed lines. The x-axis represents the years, and the y-axis represents the average price.