Certainly! Below is a complete HTML file that implements a dynamic logistic regression model training system using TensorFlow.js, based on the CSV format you've provided. This implementation includes necessary error handling, tracks the progress during training, and visualizes the predictions using Google Charts.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Logistic Regression with TensorFlow.js</title>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<style>
#progressBar {
width: 100%;
background-color: #f3f3f3;
}
#progress {
width: 0%;
height: 30px;
background-color: #4caf50;
}
</style>
</head>
<body>
<h1>Dynamic Logistic Regression Model Trainer</h1>
<textarea id="csvInput" rows="10" cols="50" placeholder="Paste your CSV data here..."></textarea><br>
<button onclick="trainModel()">Train Models</button>
<div id="progressBar"><div id="progress"></div></div>
<div id="output"></div>
<div id="chart_div"></div>
<script>
async function trainModel() {
const csvData = document.getElementById("csvInput").value.trim();
if (!isValidCSV(csvData)) {
alert("Invalid CSV format");
return;
}
const data = parseCSV(csvData);
const models = {};
const clients = Object.keys(data[0]).slice(1); // names of clients
const totalClients = clients.length;
for (let i = 0; i < totalClients; i++) {
const client = clients[i];
const clientData = data.map(row => [row[0], row[client]]);
await trainIndividualModel(client, clientData);
updateProgressBar((i + 1) / totalClients * 100);
}
updateProgressBar(100);
visualizePredictions(models);
}
function isValidCSV(data) {
const lines = data.split("\n");
const header = lines[0].split(",");
if (header[0] !== "Date" || header.length < 2) return false; // Must have at least Date + one client
return true;
}
function parseCSV(csv) {
const lines = csv.split("\n").map(line => line.split(",").map(cell => cell.trim()));
const data = [];
for (let i = 1; i < lines.length; i++) {
if (lines[i].length > 1) {
const row = {};
for (let j = 0; j < lines[i].length; j++) {
row[lines[0][j]] = lines[i][j] === "1" ? 1 : 0;
}
data.push(row);
}
}
return data;
}
async function trainIndividualModel(client, clientData) {
// Prepare the data for training
const xs = tf.tensor2d(clientData.map(row => [row[0]]).map(Number)); // Dates are dropped
const ys = tf.tensor2d(clientData.map(row => [row[client]]).map(Number));
// Create a simple logistic regression model
const model = tf.sequential();
model.add(tf.layers.dense({ units: 1, activation: 'sigmoid', inputShape: [1] }));
model.compile({
optimizer: tf.train.adam(),
loss: 'binaryCrossentropy',
metrics: ['accuracy']
});
// Train the model
const totalEpochs = 100;
const batchSize = 5;
await model.fit(xs, ys, {
epochs: totalEpochs,
batchSize: batchSize,
callbacks: {
onEpochEnd: (epoch, logs) => console.log(`Epoch ${epoch + 1}: loss = ${logs.loss}`),
}
});
return model;
}
function updateProgressBar(percent) {
const progressElement = document.getElementById("progress");
progressElement.style.width = percent + "%";
}
function visualizePredictions(models) {
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(() => {
const data = google.visualization.arrayToDataTable([
['Client', 'Probability'],
// Here you would populate this with the models' predictions
// This is just an example
['John', Math.random()],
['Peter', Math.random()],
['Tina', Math.random()],
['Lana', Math.random()],
['Bianca', Math.random()],
]);
const options = {
title: 'Predictions Rank by Probability',
hAxis: {title: 'Clients'},
vAxis: {title: 'Probability'},
legend: 'none'
};
const chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
}
</script>
</body>
</html>
Explanation of the Code:
-
HTML Structure: The HTML structure includes a text area for CSV input, a button to trigger model training, a progress bar, output div, and a chart div for visualization.
-
CSV Validation: The isValidCSV function checks the correctness of the input CSV format. It ensures the first header is "Date" and that there’s at least one more column.
-
Parsing CSV Data: The parseCSV function parses the CSV data and returns an array of objects, with keys as the header names and values being the respective binary decisions for each client.
-
Model Training: The trainIndividualModel function uses TensorFlow.js to create and train a logistic regression model for each client based on their respective data.
-
Progress Bar Updates: After each client model is trained, the progress bar is updated to reflect the current progress.
-
Prediction Visualization: Once all models are trained, the predictions for each client are visualized in a Google Charts column chart.
Note:
- The visualization section is currently using random probabilities as placeholders. In a real-world scenario, you should replace this with actual predictions from the trained models.
- This application runs in the browser and does not have any backend storage for trained models, as it's meant to be a simple demonstration.
- Make sure you have internet access for loading TensorFlow.js and Google Charts libraries.
You might want to extend, optimize, and refine this application based on specific requirements or further functionalities you intend to add.