How can I link the trained model (ipynb or python file in local) into javascript (Front-end?
- I have a trained XGB model using some features(float) to predict one
value (carbon intensity). - I want to save the model as a file and load the model to use in
javascript. It will ask user to input the one record(22 features) in javascript and pass to ML model, which finally return and print the predicted value(carbon intensity). - I have known the model can be saved as a json/pickle/joblib file.
Below is the model training code in python:
# 1. Load the Data
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# Load the dataset from an Excel file
df = pd.read_excel(r"C:UsersRYDesktopJupitertest.xlsx", sheet_name="Sheet1")
# Keep only the relevant columns (excluding the first two columns)
df = df.iloc[:, 2:]
# Categorize features based on their module (boiler, turbine, power, coal, carbon emissions)
# Features: 1(date) + 7(boiler) + 6(turbine) + 3(power) + 5(coal quality) + 2(carbon emissions) + 1(runtime) + 1(predicted carbon intensity)
# Define feature names for each module (adjust based on your actual column names)
boiler_features = ['Boiler Feedwater Temperature', 'Air Supply Temperature', 'Oxygen Level',
'Air Preheater Leakage Rate', 'Calculated Flue Gas Temperature',
'Oxygen Content (%)', 'Flue Gas Flow Rate']
turbine_features = ['Main Steam Temperature', 'Main Steam Pressure', 'Reheat Steam Temperature',
'Exhaust Steam Temperature', 'Vacuum', 'Average Load']
power_features = ['Load', 'Plant Power Consumption Rate', 'Operating Hours']
coal_features = ['Carbon Content (Air Dry, %)', 'Volatile Matter (Received, %)',
'Ash Content (Received, %)', 'Net Calorific Value (kJ/kg, Received)',
'Moisture Content (%)']
carbon_emission_features = ['CO2 Concentration', 'Carbon Emission', 'Carbon Intensity']
# Combine features in the specified order
sorted_columns = boiler_features + turbine_features + power_features + coal_features + carbon_emission_features
df = df[sorted_columns]
# Split data into features (X1) and target (y1)
X1 = df.drop('Carbon Intensity', axis=1).drop('Carbon Emission', axis=1)
y1 = df['Carbon Intensity']
# 2. Split Data into Training and Testing Sets
from sklearn.model_selection import train_test_split
X1_train, X1_test, y1_train, y1_test = train_test_split(X1, y1, test_size=0.2, random_state=42)
# Display basic statistics of the feature dataset
X1.describe()
# 3. Train the Model
from xgboost import XGBRegressor
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score, mean_absolute_percentage_error
# Initialize the XGBoost regressor
xgb_model = XGBRegressor(
n_estimators=300, # Number of trees
max_depth=3, # Maximum tree depth
learning_rate=0.1, # Learning rate
subsample=0.8, # Fraction of samples per tree
colsample_bytree=0.8, # Fraction of features per tree
random_state=42
)
# Train the model on the training data
xgb_model.fit(X1_train, y1_train)
# Make predictions on the test set
xgb_y1_pred = xgb_model.predict(X1_test)
# 4. Make Predictions on one record
# Example: Predict carbon intensity for a single data point
xgb_model.predict([X1_train.iloc[0].values])
# 5. Save the Model
# Save the trained model as a JSON file
xgb_model.save_model("xgb_model.json")
how can I save and then load the model in javascript?
One record input and out put example:
[array([ 2.42860000e+02, 1.97800000e+01, 4.59000000e+00, 2.43000000e+00,
1.27770000e+02, 9.60153257e-02, 6.51605003e+05, 5.42320000e+02,
1.26000000e+01, 5.12910000e+02, 3.18000000e+01, -9.78800000e+01,
1.97080000e+02, 1.93096475e+02, 5.45000000e+00, 2.40000000e+01,
5.36500000e+01, 2.41800000e+01, 2.18900000e+01, 1.86225000e+04,
1.53000000e+01, 3.33225000e+03])]
array([865.6147], dtype=float32)