Certainly! I can help you enhance your Training.jsx component by adding a Material-UI (MUI) form that allows users to input parameters for OneClassSvm_param and HealthScore_param. These parameters will then be sent to your backend /train API endpoint when the user initiates training.
Here's a step-by-step guide to achieve this:
- Define State Variables for Parameters
- Create the MUI Form for Parameter Input
- Handle Form Inputs and Updates
- Modify the
handleTrain Function to Include Parameters
- Update the Backend to Receive and Utilize the Parameters
Let's go through each step in detail.
1. Define State Variables for Parameters
First, you need to define state variables that will hold the values of OneClassSvm_param and HealthScore_param. We'll use React's useState hook for this purpose.
// Add these imports at the top
import { TextField, Select, MenuItem, InputLabel, FormControl } from '@mui/material';
const Training = ({ darkMode }) => {
// Existing state variables ...
// State for OneClassSvm_param
const [oneClassSvmParam, setOneClassSvmParam] = useState({
kernel: 'rbf',
gamma: 'auto',
nu: 0.05,
});
// State for HealthScore_param
const [healthScoreParam, setHealthScoreParam] = useState({
low_score: 75,
high_score: 95,
n_levels: 15,
});
// ... rest of your component
2. Create the MUI Form for Parameter Input
Next, let's create a form using MUI components where users can input or select the parameters.
return (
<div style={{ padding: '20px'}}>
<SectionBar title="訓練" />
<Paper elevation={3} style={{ padding: '20px', marginTop: '20px' }}>
{/* Existing content... */}
{/* New Form Section */}
{jobType === "healthScore" && codeLabelMapping && (
<div>
{/* Existing label selection buttons... */}
{/* One-Class SVM Parameters */}
<Box sx={{ mt: 4 }}>
<Typography variant="h6" gutterBottom>
One-Class SVM Parameters
</Typography>
<Grid container spacing={2}>
<Grid item xs={12} sm={4}>
<FormControl fullWidth>
<InputLabel id="kernel-label">Kernel</InputLabel>
<Select
labelId="kernel-label"
label="Kernel"
value={oneClassSvmParam.kernel}
onChange={(e) =>
setOneClassSvmParam({ ...oneClassSvmParam, kernel: e.target.value })
}
>
<MenuItem value="rbf">RBF</MenuItem>
<MenuItem value="linear">Linear</MenuItem>
<MenuItem value="poly">Polynomial</MenuItem>
<MenuItem value="sigmoid">Sigmoid</MenuItem>
</Select>
</FormControl>
</Grid>
<Grid item xs={12} sm={4}>
<FormControl fullWidth>
<InputLabel id="gamma-label">Gamma</InputLabel>
<Select
labelId="gamma-label"
label="Gamma"
value={oneClassSvmParam.gamma}
onChange={(e) =>
setOneClassSvmParam({ ...oneClassSvmParam, gamma: e.target.value })
}
>
<MenuItem value="scale">Scale</MenuItem>
<MenuItem value="auto">Auto</MenuItem>
<MenuItem value="0.1">0.1</MenuItem>
<MenuItem value="1">1</MenuItem>
</Select>
</FormControl>
</Grid>
<Grid item xs={12} sm={4}>
<TextField
label="Nu"
type="number"
inputProps={{ min: 0.0, max: 1.0, step: 0.01 }}
fullWidth
value={oneClassSvmParam.nu}
onChange={(e) =>
setOneClassSvmParam({ ...oneClassSvmParam, nu: parseFloat(e.target.value) })
}
/>
</Grid>
</Grid>
</Box>
{/* Health Score Parameters */}
<Box sx={{ mt: 4 }}>
<Typography variant="h6" gutterBottom>
Health Score Parameters
</Typography>
<Grid container spacing={2}>
<Grid item xs={12} sm={4}>
<TextField
label="Low Score"
type="number"
inputProps={{ min: 0, max: 100 }}
fullWidth
value={healthScoreParam.low_score}
onChange={(e) =>
setHealthScoreParam({ ...healthScoreParam, low_score: parseInt(e.target.value) })
}
/>
</Grid>
<Grid item xs={12} sm={4}>
<TextField
label="High Score"
type="number"
inputProps={{ min: 0, max: 100 }}
fullWidth
value={healthScoreParam.high_score}
onChange={(e) =>
setHealthScoreParam({ ...healthScoreParam, high_score: parseInt(e.target.value) })
}
/>
</Grid>
<Grid item xs={12} sm={4}>
<TextField
label="Number of Levels"
type="number"
inputProps={{ min: 1, max: 100 }}
fullWidth
value={healthScoreParam.n_levels}
onChange={(e) =>
setHealthScoreParam({ ...healthScoreParam, n_levels: parseInt(e.target.value) })
}
/>
</Grid>
</Grid>
</Box>
</div>
)}
{/* Existing sharedState display... */}
{/* Existing Train Button */}
<Button
variant="contained"
color="primary"
onClick={handleTrain}
disabled={running}
style={{ marginTop: '20px' }}
>
{running ? 'Training...' : 'Start Training'}
</Button>
{/* Existing Training Message */}
{trainingMessage && <Typography variant="body1" style={{ marginTop: '20px' }}>{trainingMessage}</Typography>}
</Paper>
<NavigationButton nextRoute="/edge" validate={validate} style={{ marginTop: '20px' }}>
Next
</NavigationButton>
</div>
);
Explanation:
This structured form ensures that users can input or select necessary parameters easily.
3. Handle Form Inputs and Updates
The form inputs are controlled components, meaning their values are tied to the component's state. The onChange handlers update the state accordingly. This ensures that the latest parameter values are always stored and ready to be sent to the backend.
4. Modify the handleTrain Function to Include Parameters
Now, update the handleTrain function to include the new parameters in the POST request to the backend.
const handleTrain = async () => {
setRunning(true);
setTrainingMessage('');
try {
const payload = {
labelColumn: sharedState.labelColumn,
columns: sharedState.columns,
featureData: sharedState.featureData,
codeLabelMapping: sharedState.codeLabelMapping,
jobType: sharedState.jobType,
framework: sharedState.framework,
modelOption: sharedState.modelOption,
selectedHealthScoreLabelArray: sharedState.selectedHealthScoreLabelArray,
oneClassSvmParam: oneClassSvmParam, // Add SVM params
healthScoreParam: healthScoreParam, // Add HealthScore params
};
const response = await axios.post('http://localhost:5000/api/train', payload);
setTrainingMessage(response.data.message);
} catch (error) {
console.error("Error during training:", error);
setTrainingMessage('Error during training, please try again.');
} finally {
setRunning(false);
}
};
Explanation:
- Payload Update: The
payload object now includes oneClassSvmParam and healthScoreParam, which are sent to the backend.
- Backend Awareness: Ensure that your backend is prepared to receive these new fields.
5. Update the Backend to Receive and Utilize the Parameters
Your backend needs to be updated to handle the incoming parameters. Here's how you can modify your /train route to incorporate the received oneClassSvmParam and healthScoreParam.
@api.route('/train', methods=['POST'])
def train_model():
# access the models directory
MODELS_DIR = current_app.config['MODELS_DIR']
try:
# Get data from the request
label_column = request.json.get('labelColumn')
columns = request.json.get('columns')
feature_data = request.json.get('featureData')
codeLabelMapping = request.json.get('codeLabelMapping')
job_type = request.json.get('jobType')
framework = request.json.get('framework')
model_option = request.json.get('modelOption')
selectedHealthScoreLabelArray = request.json.get('selectedHealthScoreLabelArray')
oneClassSvmParam = request.json.get('oneClassSvmParam', {})
healthScoreParam = request.json.get('healthScoreParam', {})
# Check if label_column is None
if job_type in ['regression', 'classification', 'timeSeriesForecasting'] and label_column is None:
return jsonify({'message': 'Error: For supervised learning, label_column cannot be None.'}), 400
# Convert feature_data to a DataFrame
df = pd.DataFrame(feature_data, columns=columns)
# Filter data based on selected labels if label_column and labels are provided
if label_column and selectedHealthScoreLabelArray:
if label_column not in df.columns:
return jsonify({'message': f'Label column "{label_column}" not found in data.'}), 400
# Filter the DataFrame to only include selected labels
df = df[df[label_column].isin(selectedHealthScoreLabelArray)]
if df.empty:
return jsonify({'message': 'No data left after filtering with the selected labels.'}), 400
# Exclude the label column from features
if label_column and label_column in df.columns:
feature_columns = [col for col in df.columns if col != label_column]
else:
feature_columns = df.columns.tolist()
# Prepare the feature matrix X
X = df[feature_columns].values
# Get today's date
today_date = datetime.now().strftime('%Y-%m-%d')
# Create the model filename
model_filename = f'{model_option}_model_{today_date}.pkl'
if framework == "sklearn":
if job_type == "healthScore":
# Perform the scaler and PCA to reduce dimensionality to 2
scaler = MinMaxScaler() # This scales the data between 0 and 1
pca = PCA(n_components=2) # Reduces dimensionality to 2
# Create a pipeline that first scales and then applies PCA
pca_pipeline = Pipeline(steps=[
('scaler', scaler),
('pca', pca)
])
# Fit and transform the feature data using the pipeline
X_pca = pca_pipeline.fit_transform(X)
# Extract parameters from request
one_class_svm_params = oneClassSvmParam or {}
health_score_params = healthScoreParam or {}
# Set default parameters if not provided
svm_kernel = one_class_svm_params.get('kernel', 'rbf')
svm_gamma = one_class_svm_params.get('gamma', 'auto')
svm_nu = one_class_svm_params.get('nu', 0.05)
low_score = health_score_params.get('low_score', 75)
high_score = health_score_params.get('high_score', 95)
n_levels = health_score_params.get('n_levels', 15)
# Parameters for One-Class SVM
OneClassSvm_param = {
'kernel': svm_kernel,
'gamma': svm_gamma,
'nu': svm_nu
}
# HealthScore parameters
HealthScore_param = {
'low_score': low_score,
'high_score': high_score,
'n_levels': n_levels
}
# Fit One-Class SVM
model_one_class_svm = OneClassSVM(
kernel=OneClassSvm_param['kernel'],
gamma=OneClassSvm_param['gamma'],
nu=OneClassSvm_param['nu']
).fit(X_pca)
# Generate a mesh grid for decision function visualization (optional)
xx_boundary = [X_pca[:, 0].min() - 1, X_pca[:, 0].max() + 1]
yy_boundary = [X_pca[:, 1].min() - 1, X_pca[:, 1].max() + 1]
xx, yy = np.meshgrid(
np.linspace(xx_boundary[0], xx_boundary[1], 500),
np.linspace(yy_boundary[0], yy_boundary[1], 500)
)
grid = np.c_[xx.ravel(), yy.ravel()]
# Compute decision function scores
z = model_one_class_svm.decision_function(grid)
z = z.reshape(xx.shape)
# Prepare levels from the decision function scores
n_levels = HealthScore_param['n_levels']
levels = np.linspace(z.min(), 0, n_levels)
# Map levels to health scores
low_score = HealthScore_param['low_score']
high_score = HealthScore_param['high_score']
health_scores = np.linspace(low_score, high_score, n_levels)
# Fit Linear Regression to map decision function levels to health scores
model_health_score = LinearRegression(fit_intercept=True).fit(
levels[:, np.newaxis], health_scores
)
# Save the models to disk
models_dir = MODELS_DIR
pca_filename = os.path.join(models_dir, f'{model_option}_pca_{today_date}.joblib')
svm_filename = os.path.join(models_dir, f'{model_option}_oneclasssvm_{today_date}.joblib')
linearreg_filename = os.path.join(models_dir, f'{model_option}_linearregression_{today_date}.joblib')
joblib.dump(pca_pipeline, pca_filename)
joblib.dump(model_one_class_svm, svm_filename)
joblib.dump(model_health_score, linearreg_filename)
return jsonify({'message': 'Training completed successfully for health score.'}), 200
else:
return jsonify({'message': f'Job type {job_type} not supported with framework {framework}.'}), 400
except Exception as e:
# Log the exception (optional)
print(f"Exception during training: {e}")
return jsonify({'message': 'An error occurred during training.'}), 500
Explanation:
-
Parameter Extraction:
- Extract
oneClassSvmParam and healthScore_param from the incoming JSON. Provide default empty dictionaries if they're not present to avoid NoneType issues.
-
Default Values:
- Use
get with default values to ensure that if some parameters aren't provided, the model still uses sensible defaults.
-
Parameter Application:
- Apply the received parameters (
svm_kernel, svm_gamma, svm_nu, low_score, high_score, n_levels) instead of hard-coded values.
-
Error Handling:
- Added a generic exception handler to catch any unexpected errors during the training process.
Complete Training.jsx with Added MUI Form
For clarity, here's the complete Training.jsx component incorporating all the changes discussed:
// frontend/src/components/Training.jsx
import React, { useState, useEffect, useContext } from 'react';
import axios from 'axios'; // Import Axios
import { Typography, Button, Paper, Box, Grid, Checkbox, FormControlLabel, TextField, Select, MenuItem, InputLabel, FormControl } from '@mui/material';
import { AppContext } from './AppContext';
import SectionBar from './SectionBar';
import NavigationButton from './NavigationButton';
const Training = ({ darkMode }) => {
const { sharedState, setSharedState, updateSharedState, mergeSharedState } = useContext(AppContext);
const [running, setRunning] = useState(false); // State to store the selected job type
const [trainingMessage, setTrainingMessage] = useState('');
const [selectedHealthScoreLabel, setSelectedHealthScoreLabel] = useState(null); // State to store the selected label
const [selectedHealthScoreLabelArray, setSelectedHealthScoreLabelArray] = useState([]); // State to store the selected labels in an array
const [selectAll, setSelectAll] = useState(false); // State to track "select all" checkbox status
// Destructure values from sharedState
const {
windowValue,
labelColumn,
columns,
featureData,
codeLabelMapping,
jobType,
framework,
modelOption,
} = sharedState;
// Define state for OneClassSvm_param
const [oneClassSvmParam, setOneClassSvmParam] = useState({
kernel: 'rbf',
gamma: 'auto',
nu: 0.05,
});
// Define state for HealthScore_param
const [healthScoreParam, setHealthScoreParam] = useState({
low_score: 75,
high_score: 95,
n_levels: 15,
});
// Existing functions (generateRandomData, handleLabelClick, handleLabelsClick, handleSelectAllChange) ...
const handleTrain = async () => {
setRunning(true);
setTrainingMessage('');
try {
const payload = {
labelColumn: sharedState.labelColumn,
columns: sharedState.columns,
featureData: sharedState.featureData,
codeLabelMapping: sharedState.codeLabelMapping,
jobType: sharedState.jobType,
framework: sharedState.framework,
modelOption: sharedState.modelOption,
selectedHealthScoreLabelArray: sharedState.selectedHealthScoreLabelArray,
oneClassSvmParam: oneClassSvmParam, // Add SVM params
healthScoreParam: healthScoreParam, // Add HealthScore params
};
const response = await axios.post('http://localhost:5000/api/train', payload);
setTrainingMessage(response.data.message);
} catch (error) {
console.error("Error during training:", error);
setTrainingMessage('Error during training, please try again.');
} finally {
setRunning(false);
}
};
const validate = () => {
const { value } = sharedState;
// Check if value is not null, undefined, or an empty string
return !!value; // This will return true if value has a truthy value
};
return (
<div style={{ padding: '20px'}}>
<SectionBar title="訓練" />
<Paper elevation={3} style={{ padding: '20px', marginTop: '20px' }}>
{/* Only show the buttons if jobType is "healthScore" */}
{jobType === "healthScore" && codeLabelMapping && (
<div>
<Typography variant="h5">
健康分數
</Typography>
<Typography variant="h6" gutterBottom>
選擇欲監控的類別
</Typography>
<Box style={{ display: 'flex', flexWrap: 'wrap', marginTop: '20px' }}>
{Object.entries(codeLabelMapping).map(([key, label]) => {
// Function to calculate the width based on label length
const calculateButtonWidth = (label) => {
const labelLength = label.length; // Get the length of the label text
const minWidth = 100; // Minimum width for the button
const extraWidth = labelLength * 8; // Add extra width for each character (adjust the multiplier as needed)
return minWidth + extraWidth; // Return the total width
};
const buttonWidth = calculateButtonWidth(label);
return (
<Button
key={key}
variant="outlined"
style={{
margin: '10px',
minWidth: '100px', // Minimum width to prevent shrinking
width: selectedHealthScoreLabelArray.includes(label) ? `${buttonWidth + 20}px` : `${buttonWidth}px`, // Set dynamic width
height: '50px', // Increased height
fontSize: '18px', // Font size
whiteSpace: 'nowrap', // Prevent text wrapping to a new line
textOverflow: 'ellipsis', // Add ellipsis if text overflows
overflow: 'hidden', // Hide any overflow text
border: selectedHealthScoreLabelArray.includes(label) ? '2px solid blue' : '1px solid #ccc',
transition: 'all 0.3s',
}}
onClick={() => handleLabelsClick(label)}
>
{label}
</Button>
);
})}
</Box>
<FormControlLabel
control={<Checkbox checked={selectAll} onChange={handleSelectAllChange} />}
label="Select All (綜合訓練)"
style={{ marginBottom: '20px' }}
/>
{/* One-Class SVM Parameters */}
<Box sx={{ mt: 4 }}>
<Typography variant="h6" gutterBottom>
One-Class SVM Parameters
</Typography>
<Grid container spacing={2}>
<Grid item xs={12} sm={4}>
<FormControl fullWidth>
<InputLabel id="kernel-label">Kernel</InputLabel>
<Select
labelId="kernel-label"
label="Kernel"
value={oneClassSvmParam.kernel}
onChange={(e) =>
setOneClassSvmParam({ ...oneClassSvmParam, kernel: e.target.value })
}
>
<MenuItem value="rbf">RBF</MenuItem>
<MenuItem value="linear">Linear</MenuItem>
<MenuItem value="poly">Polynomial</MenuItem>
<MenuItem value="sigmoid">Sigmoid</MenuItem>
</Select>
</FormControl>
</Grid>
<Grid item xs={12} sm={4}>
<FormControl fullWidth>
<InputLabel id="gamma-label">Gamma</InputLabel>
<Select
labelId="gamma-label"
label="Gamma"
value={oneClassSvmParam.gamma}
onChange={(e) =>
setOneClassSvmParam({ ...oneClassSvmParam, gamma: e.target.value })
}
>
<MenuItem value="scale">Scale</MenuItem>
<MenuItem value="auto">Auto</MenuItem>
<MenuItem value="0.1">0.1</MenuItem>
<MenuItem value="1">1</MenuItem>
</Select>
</FormControl>
</Grid>
<Grid item xs={12} sm={4}>
<TextField
label="Nu"
type="number"
inputProps={{ min: 0.0, max: 1.0, step: 0.01 }}
fullWidth
value={oneClassSvmParam.nu}
onChange={(e) =>
setOneClassSvmParam({ ...oneClassSvmParam, nu: parseFloat(e.target.value) })
}
/>
</Grid>
</Grid>
</Box>
{/* Health Score Parameters */}
<Box sx={{ mt: 4 }}>
<Typography variant="h6" gutterBottom>
Health Score Parameters
</Typography>
<Grid container spacing={2}>
<Grid item xs={12} sm={4}>
<TextField
label="Low Score"
type="number"
inputProps={{ min: 0, max: 100 }}
fullWidth
value={healthScoreParam.low_score}
onChange={(e) =>
setHealthScoreParam({ ...healthScoreParam, low_score: parseInt(e.target.value) })
}
/>
</Grid>
<Grid item xs={12} sm={4}>
<TextField
label="High Score"
type="number"
inputProps={{ min: 0, max: 100 }}
fullWidth
value={healthScoreParam.high_score}
onChange={(e) =>
setHealthScoreParam({ ...healthScoreParam, high_score: parseInt(e.target.value) })
}
/>
</Grid>
<Grid item xs={12} sm={4}>
<TextField
label="Number of Levels"
type="number"
inputProps={{ min: 1, max: 100 }}
fullWidth
value={healthScoreParam.n_levels}
onChange={(e) =>
setHealthScoreParam({ ...healthScoreParam, n_levels: parseInt(e.target.value) })
}
/>
</Grid>
</Grid>
</Box>
</div>
)}
{/* Example of using the sharedState values */}
<Box sx={{ padding: 2 }}>
<Grid container spacing={2}>
<Grid item xs={12}>
<Typography variant="h6">Selected Job Type: <strong>{sharedState.jobType}</strong></Typography>
</Grid>
<Grid item xs={12}>
<Typography variant="h6">Framework: <strong>{sharedState.framework}</strong></Typography>
</Grid>
<Grid item xs={12}>
<Typography variant="h6">Model Option: <strong>{sharedState.modelOption}</strong></Typography>
</Grid>
<Grid item xs={12}>
<Typography variant="h6">Label Name: <strong>{sharedState.labelColumn}</strong></Typography>
</Grid>
<Grid item xs={12}>
<Typography variant="h6">Columns:
<Box sx={{ maxHeight: 100, overflow: 'auto', fontFamily: 'monospace', fontSize: '0.875rem' }}>
{sharedState.columns?.join(', ')}
</Box>
</Typography>
</Grid>
<Grid item xs={12}>
<Typography variant="h6">Feature Data:
<Box sx={{ maxHeight: 150, overflow: 'auto', fontFamily: 'monospace', fontSize: '0.875rem' }}>
{JSON.stringify(sharedState.featureData, null, 2)}
</Box>
</Typography>
</Grid>
</Grid>
</Box>
<Button
variant="contained"
color="primary"
onClick={handleTrain}
disabled={running}
style={{ marginTop: '20px' }}
>
{running ? 'Training...' : 'Start Training'}
</Button>
{trainingMessage && <Typography variant="body1" style={{ marginTop: '20px' }}>{trainingMessage}</Typography>}
</Paper>
<NavigationButton nextRoute="/edge" validate={validate} style={{ marginTop: '20px' }}>
Next
</NavigationButton>
</div>
);
};
export default Training;
Additional Recommendations
-
Validation:
- Add form validation to ensure that the user inputs valid parameter values. For example,
low_score should be less than high_score.
- You can use MUI's
FormHelperText to display validation messages.
-
Dynamic Parameter Options:
- If certain parameters depend on others (e.g.,
gamma options might change based on kernel), consider making the form dynamic.
-
Feedback on Training Progress:
- Enhance user experience by providing more detailed feedback during the training process, such as a progress bar or logs.
-
Error Handling:
- Ensure the backend returns clear error messages, and display them appropriately on the frontend.
-
Security:
- Validate and sanitize all inputs on the backend to prevent security vulnerabilities like injection attacks.
-
Styling:
- Adjust the styling of the form to match your application's theme and ensure responsiveness across different devices.
By following the steps above, you'll have a functional MUI form in your Training.jsx component that allows users to input and select parameters for OneClassSvm_param and HealthScore_param, which are then sent to your backend for model training. Ensure that both frontend and backend validations are robust to handle any unexpected inputs gracefully.