Sure! Below are the two Python scripts you need to solve the problem:
-
Training Script (train_model.py): This script reads the training data, preprocesses it by handling NaN values, trains a linear regression model, and saves the trained model to a file.
-
Prediction Script (predict.py): This script is designed to run in a restricted environment. It downloads the saved model, processes the input test data, makes predictions using the loaded model, and outputs the predictions in the required format.
1. Training Script (train_model.py)
#!/usr/bin/env python3
import pandas as pd
import numpy as np
import os
import pickle
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error
# Path to the training data
TRAINING_DATA_PATH = 'train.csv' # Replace with your actual training data path
MODEL_FILENAME = 'linear_regression_model.pkl'
def preprocess_data(df):
"""
Preprocess the training data by handling NaN values and preparing features and target.
"""
# Fill NaN values with 0
df_filled = df.fillna(0)
# Assume that 'close_volume' is the target variable
# All other columns except 'symbol_id', 'date_id', and 'close_volume' are features
feature_columns = [col for col in df_filled.columns if col not in ['symbol_id', 'date_id', 'close_volume']]
X = df_filled[feature_columns]
y = df_filled['close_volume']
return X, y
def train_model(X, y):
"""
Train a Linear Regression model.
"""
model = LinearRegression()
model.fit(X, y)
return model
def main():
# Check if training data exists
if not os.path.exists(TRAINING_DATA_PATH):
print(f"Training data file '{TRAINING_DATA_PATH}' not found.")
return
# Read the training data
print("Reading training data...")
df = pd.read_csv(TRAINING_DATA_PATH)
# Preprocess the data
print("Preprocessing data...")
X, y = preprocess_data(df)
# Split the data for validation (optional)
# X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)
# Train the model
print("Training the model...")
model = train_model(X, y)
# (Optional) Evaluate the model
# y_pred = model.predict(X_val)
# mae = mean_absolute_error(y_val, y_pred)
# print(f"Validation Mean Absolute Error: {mae}")
# Save the trained model
print(f"Saving the model to '{MODEL_FILENAME}'...")
with open(MODEL_FILENAME, 'wb') as f:
pickle.dump(model, f)
print("Model training and saving completed successfully.")
if __name__ == '__main__':
main()
Explanation of train_model.py:
-
Data Loading: The script assumes that the training data is in a file named train.csv. Ensure this file is in the same directory as the script or provide the correct path.
-
Preprocessing:
- Handling NaNs: All
NaN values in the dataset are filled with 0. Depending on your data, you might choose a different imputation strategy.
- Feature Selection: Exclude
symbol_id, date_id, and close_volume from the features. close_volume is the target variable.
-
Model Training: A simple LinearRegression model from scikit-learn is trained on the preprocessed data.
-
Model Saving: The trained model is saved to a file named linear_regression_model.pkl using pickle.
-
Optional Validation: There's commented-out code for splitting the data into training and validation sets and calculating the Mean Absolute Error (MAE) to evaluate the model's performance.
2. Prediction Script (predict.py)
#!/usr/bin/env python3
import pandas as pd
import numpy as np
import os
import pickle
import requests
from sklearn.linear_model import LinearRegression
# Restricted environment libraries versions
# requests@2.22.0, beautifulsoup4@4.8.1, pycrypto@2.6.1, cryptography@2.8,
# python-dateutil@2.8.1, urllib3@1.25.7, pyyaml@5.2, numpy@1.16.5,
# scipy@1.2.2, sympy@1.4, scikit-learn@0.20.4, nltk@3.4.5,
# pandas@0.24.2, statsmodels@0.10.2
MODEL_URL = "https://github.com/yourusername/yourrepo/raw/main/linear_regression_model.pkl" # Replace with your model's URL
MODEL_FILENAME = "linear_regression_model.pkl"
def download_file(url, filename):
"""
Download a file from a URL and save it locally.
"""
response = requests.get(url)
if response.status_code == 200:
with open(filename, 'wb') as file:
file.write(response.content)
else:
raise Exception(f"Failed to download file from {url}. Status code: {response.status_code}")
def preprocess_test_data(df):
"""
Preprocess the test data by handling NaN values and preparing features.
"""
# Fill NaN values with 0
df_filled = df.fillna(0)
# Assume that 'symbol_id' and 'date_id' are present
# Features are all columns except 'symbol_id' and 'date_id'
feature_columns = [col for col in df_filled.columns if col not in ['symbol_id', 'date_id']]
X = df_filled[feature_columns]
return X, df_filled['symbol_id']
def main():
# Read input filename from standard input
import sys
if sys.version_info[0] < 3:
filename = raw_input()
else:
filename = sys.stdin.read().strip()
# Check if the input file exists
if not os.path.exists(filename):
print(f"Input file '{filename}' not found.")
return
# Read the test data
df_test = pd.read_csv(filename)
# Preprocess the test data
X_test, symbol_ids = preprocess_test_data(df_test)
# Download the model if it doesn't exist
if not os.path.exists(MODEL_FILENAME):
try:
print("Downloading the model...")
download_file(MODEL_URL, MODEL_FILENAME)
print("Model downloaded successfully.")
except Exception as e:
print(str(e))
return
# Load the model
with open(MODEL_FILENAME, 'rb') as f:
model = pickle.load(f)
# Make predictions
predictions = model.predict(X_test)
# Ensure that predictions are non-negative
predictions = np.maximum(predictions, 0)
# Prepare the output DataFrame
output_df = pd.DataFrame({
'symbol_id': symbol_ids,
'close_volume': predictions.round(1) # Round to one decimal as per sample output
})
# Print the output in the required format
print("symbol_id,close_volume")
for index, row in output_df.iterrows():
print(f"{int(row['symbol_id'])},{row['close_volume']}")
if __name__ == '__main__':
main()
Explanation of predict.py:
-
Model Downloading:
- The script downloads the trained model (
linear_regression_model.pkl) from a specified GitHub repository. Replace the MODEL_URL with the actual URL where you've uploaded your model.
- The
download_file function handles the downloading process and saves the model locally.
-
Preprocessing:
- Handling NaNs: Similar to the training script, all
NaN values in the test data are filled with 0.
- Feature Selection: Exclude
symbol_id and date_id from the features. Only numerical features are used for prediction.
-
Model Loading: The downloaded model is loaded using pickle.
-
Prediction:
- The model predicts the
close_volume for each symbol_id.
- Predictions are ensured to be non-negative by taking the maximum of the predicted value and
0.
- Predictions are rounded to one decimal place to match the sample output format.
-
Output:
-
Usage:
- Ensure that the
linear_regression_model.pkl is uploaded to a public GitHub or GitLab repository and replace the MODEL_URL with the raw URL of the model file.
- To run the prediction script, provide the input CSV filename via standard input.
Additional Notes:
-
Model Hosting: After training the model using train_model.py, you need to upload the linear_regression_model.pkl file to a public repository (e.g., GitHub or GitLab). Make sure the repository is public so that the predict.py script can download the model without authentication.
-
Dependencies:
- Ensure that all required libraries are installed in your environment where you run
train_model.py.
- The
predict.py script is restricted to use only the specified library versions. Ensure compatibility when training the model.
-
Handling Different Data Structures: The scripts assume that the training and test data have a similar structure, with features matching the ones used during training. If your data has different features or requires additional preprocessing, adjust the scripts accordingly.
-
Error Handling: The scripts include basic error handling for missing files and download failures. You can enhance them further based on specific requirements.
-
Security: As per the problem statement, ensure that the prediction script only downloads the model file and does not misuse network access.
Example Usage:
-
Train the Model:
python3 train_model.py
Ensure that train.csv is present in the same directory or provide the correct path.
-
Upload the Model:
- Upload
linear_regression_model.pkl to your GitHub repository.
- Obtain the raw URL of the uploaded model file.
-
Modify Prediction Script:
- Replace the
MODEL_URL in predict.py with the raw URL of your uploaded model.
-
Make Predictions:
echo "test_input.csv" | python3 predict.py
Replace test_input.csv with the actual test CSV filename.
This setup ensures that you can train your model and deploy it in a restricted environment effectively.