Certainly! The primary issue with your current code is that it doesn't handle the labels correctly. Specifically:
-
Missing Labels Extraction: The code parses the CSV file and extracts only the features but does not extract the labels (target values) required for training the logistic regression model.
-
Incorrect model.fit Parameters: The model.fit function is being called with normalizedData as both the input (x) and the target (y), which is incorrect. The target should be the labels extracted from the CSV.
Below is the revised version of your code with these issues fixed. The corrections include:
- Parsing and Extracting Labels: The
parseCSV function now extracts the label from the last column of each row.
- Processing Labels: The
processData function now processes both features and labels, converting them into tensors suitable for TensorFlow.js.
- Training the Model Correctly: The
trainModel function now correctly passes both the input features and the labels to the model.fit function.
<!DOCTYPE html>
<html>
<head>
<title>Logistic Regression Predictor</title>
<!-- Load TensorFlow.js and Google Charts -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<style>
.container {
margin: 20px;
font-family: Arial, sans-serif;
}
.progress {
width: 100%;
height: 20px;
background-color: #f0f0f0;
margin-top: 10px;
border-radius: 5px;
overflow: hidden;
}
.progress-bar {
width: 0%;
height: 100%;
background-color: #4CAF50;
transition: width 0.5s;
}
#chart_div {
margin-top: 20px;
}
</style>
</head>
<body>
<div class="container">
<h2>Client Purchase Prediction Model</h2>
<input type="file" id="csvFile" accept=".csv" />
<div id="progress" class="progress">
<div id="progressBar" class="progress-bar"></div>
</div>
<div id="chart_div" style="width: 800px; height: 500px;"></div>
</div>
<script>
// Load Google Charts
google.charts.load('current', { 'packages': ['corechart'] });
// Initialize variables
let model;
let normalizedData;
let labelsTensor;
let dates;
// Handle file upload
document.getElementById('csvFile').addEventListener('change', handleFileSelect);
async function handleFileSelect(event) {
try {
const file = event.target.files[0];
if (!file) {
alert('Please select a CSV file.');
return;
}
const text = await file.text();
const data = parseCSV(text);
await processData(data);
} catch (error) {
handleError(error);
}
}
function parseCSV(text) {
const lines = text.split('\n').filter(line => line.trim() !== '');
const headers = lines[0].split(',').map(header => header.trim());
const data = [];
for (let i = 1; i < lines.length; i++) {
const values = lines[i].split(',').map(value => value.trim());
if (values.length !== headers.length) {
console.warn(`Skipping line ${i + 1} due to incorrect number of fields.`);
continue; // Skip lines with incorrect number of fields
}
const row = {};
row.date = values[0];
row.features = values.slice(1, -1).map(Number);
const label = Number(values[values.length - 1]);
if (isNaN(label)) {
console.warn(`Skipping line ${i + 1} due to invalid label.`);
continue; // Skip lines with invalid labels
}
row.label = label;
data.push(row);
}
if (data.length === 0) {
throw new Error('No valid data found in the CSV file.');
}
return { headers, data };
}
async function processData(parsedData) {
dates = parsedData.data.map(row => row.date);
const features = parsedData.data.map(row => row.features);
const labels = parsedData.data.map(row => row.label);
// Check if labels are binary
const uniqueLabels = Array.from(new Set(labels));
if (uniqueLabels.length !== 2 || !uniqueLabels.includes(0) || !uniqueLabels.includes(1)) {
throw new Error('Labels must be binary (0 and 1) for logistic regression.');
}
// Normalize features
normalizedData = normalizeFeatures(features);
// Convert labels to tensor
labelsTensor = tf.tensor1d(labels).reshape([-1, 1]);
// Create and train model
await createAndTrainModel(normalizedData, labelsTensor);
}
function normalizeFeatures(features) {
const tensorData = tf.tensor2d(features);
const min = tensorData.min(0);
const max = tensorData.max(0);
const normalized = tensorData.sub(min).div(max.sub(min));
return normalized;
}
async function createAndTrainModel(normalizedData, labelsTensor) {
// Define a simple logistic regression model
model = tf.sequential();
model.add(tf.layers.dense({
units: 1,
activation: 'sigmoid',
inputShape: [normalizedData.shape[1]]
}));
// Compile model
model.compile({
optimizer: tf.train.adam(0.01),
loss: 'binaryCrossentropy',
metrics: ['accuracy']
});
// Train model
const epochs = 100;
await trainModel(normalizedData, labelsTensor, epochs);
}
async function trainModel(normalizedData, labelsTensor, epochs) {
const progressBar = document.getElementById('progressBar');
progressBar.style.width = '0%';
try {
await model.fit(normalizedData, labelsTensor, {
epochs: epochs,
shuffle: true,
callbacks: {
onEpochEnd: (epoch, logs) => {
// Update progress bar
const progress = ((epoch + 1) / epochs) * 100;
progressBar.style.width = progress + '%';
progressBar.innerText = `${Math.round(progress)}%`;
}
}
});
// Make predictions after training
makePredictions(normalizedData);
} catch (error) {
handleError(error);
}
}
async function makePredictions(normalizedData) {
try {
const predictions = model.predict(normalizedData);
const predictionData = await predictions.data();
drawChart(predictionData);
} catch (error) {
handleError(error);
}
}
function drawChart(predictions) {
const data = new google.visualization.DataTable();
data.addColumn('number', 'Client');
data.addColumn('number', 'Prediction');
// Prepare data for chart
const chartData = predictions.map((pred, index) => {
return [index + 1, pred];
});
data.addRows(chartData);
const options = {
title: 'Client Purchase Predictions',
hAxis: {
title: 'Client Number',
minValue: 0,
viewWindow: {
min: 0,
max: chartData.length + 1
}
},
vAxis: {
title: 'Prediction Probability',
minValue: 0,
maxValue: 1
},
legend: 'none',
pointSize: 5,
trendlines: {
0: {
type: 'linear',
color: '#000000',
opacity: 1
}
}
};
const chart = new google.visualization.ScatterChart(
document.getElementById('chart_div')
);
chart.draw(data, options);
}
function handleError(error) {
console.error('Error:', error);
alert('An error occurred: ' + error.message);
}
</script>
</body>
</html>
Detailed Explanation of Fixes
-
Parsing and Extracting Labels:
- Before: The
parseCSV function extracted only the date and features from each row, excluding the last column (assumed to be the label).
- After: The
parseCSV function now also extracts the label from the last column of each row. It includes error handling to skip lines with incorrect field counts or invalid labels.
row.label = Number(values[values.length - 1]);
if (isNaN(label)) {
console.warn(`Skipping line ${i + 1} due to invalid label.`);
continue; // Skip lines with invalid labels
}
-
Processing Labels:
- Before: The
processData function only handled features and did not process labels.
- After: The
processData function now extracts the labels and converts them into a tensor suitable for TensorFlow.js.
const labels = parsedData.data.map(row => row.label);
// Check if labels are binary
const uniqueLabels = Array.from(new Set(labels));
if (uniqueLabels.length !== 2 || !uniqueLabels.includes(0) || !uniqueLabels.includes(1)) {
throw new Error('Labels must be binary (0 and 1) for logistic regression.');
}
// Convert labels to tensor
labelsTensor = tf.tensor1d(labels).reshape([-1, 1]);
-
Training the Model Correctly:
- Before: The
model.fit was incorrectly called with normalizedData as both the input (x) and the target (y).
- After: The
model.fit is now correctly called with normalizedData as the input and labelsTensor as the target.
await model.fit(normalizedData, labelsTensor, {
epochs: epochs,
shuffle: true,
callbacks: {
onEpochEnd: (epoch, logs) => {
// Update progress bar
const progress = ((epoch + 1) / epochs) * 100;
progressBar.style.width = progress + '%';
progressBar.innerText = `${Math.round(progress)}%`;
}
}
});
-
Additional Enhancements:
- Progress Bar Visibility: Added a transition effect for smoother updates and set initial width to 0%.
- Label Verification: Ensured that labels are binary (0 and 1) before training, which is essential for logistic regression.
Usage Instructions
-
CSV File Format: Ensure that your CSV file follows this structure:
- First Column:
date (or any identifier; it won't be used in training).
- Middle Columns: Feature columns containing numerical values.
- Last Column:
label with binary values 0 or 1.
Example:
date,feature1,feature2,feature3,label
2023-01-01,5.1,3.5,1.4,0
2023-01-02,4.9,3.0,1.4,0
2023-01-03,6.2,3.4,5.4,1
-
Running the Application:
- Open the HTML file in a web browser.
- Click on the "Choose File" button to upload your CSV file.
- The progress bar will update as the model trains.
- Once training is complete, a scatter chart will display the prediction probabilities for each client.
-
Troubleshooting:
- No Data Processed: Ensure that your CSV file does not contain empty lines and that all rows have the correct number of columns.
- Invalid Labels: Make sure that the label column contains only
0 or 1.
- Feature Values: Ensure all feature values are numerical and properly formatted.
Conclusion
By correctly handling the labels and ensuring that the model is trained with the appropriate inputs and targets, the logistic regression predictor should now function as expected. Additionally, the enhanced error handling and user feedback mechanisms will make the application more robust and user-friendly.