The CSV file tracks the daily decisions (likely binary choices) made by four clients (John, Peter, Alice, and Tina) over three consecutive days.
Can you help me write an application to analyze this CSV file?
Build a logistic regression model with TensorFlow.js.
The code must be adaptable and capable of handling a variety of clients.
Display a progress bar during the training process.
Use Google charts to display predictions on a scatter plot. Horizontal axis: represents clients. Vertical axis: represents probability (0 to 1).
Incorporate a handleError function to log errors and alert users.
The entire code should be written in a single HTML block with embedded JS.
Assistant
html
<!DOCTYPE html>
<html>
<head>
<title>Logistic Regression with TensorFlow.js</title>
<!-- Include TensorFlow.js library -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@3.20.0/dist/tf.min.js"></script>
<!-- Include Google Charts library -->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<style>
.container {
width: 600px;
margin: auto;
}
#progress_bar {
width: 100%;
background-color: #ddd;
margin-top: 20px;
}
#progress {
width: 0%;
height: 30px;
background-color: #4caf50;
text-align: center;
line-height: 30px;
color: white;
}
#chart_div {
margin-top: 20px;
}
</style>
</head>
<body>
<div class="container">
<h1>Logistic Regression with TensorFlow.js</h1>
<!-- File input for CSV files -->
<input type="file" id="upload_btn" accept=".csv">
<!-- Progress bar to show training progress -->
<div id="progress_bar">
<div id="progress"></div>
</div>
<!-- Container for the Google Chart -->
<div id="chart_div" style="width: 600px; height: 400px;"></div>
<!-- Button to trigger CSV processing -->
<button onclick="process_btn()">Process Data</button>
</div>
<script type="text/javascript">
// Function to handle errors
function handleError(error) {
console.error(error);
alert('An error occurred: ' + error.message);
}
function process_btn() {
try {
const fileInput = document.getElementById('upload_btn');
if (fileInput.files.length === 0) {
alert('Please select a CSV file.');
return;
}
const file = fileInput.files[0];
const reader = new FileReader();
reader.onload = async function(event) {
const csvData = event.target.result;
const data = parseCSV(csvData);
await trainModel(data);
};
reader.onerror = function(error) {
handleError(error);
};
reader.readAsText(file);
} catch (error) {
handleError(error);
}
}
// Function to parse CSV data
function parseCSV(csv) {
const lines = csv.trim().split('\n');
const headers = lines[0].split(',');
const clients = headers.slice(1); // Exclude 'Date'
const data = [];
for (let i = 1; i < lines.length; i++) {
const tokens = lines[i].split(',');
const date = tokens[0]; // Date is currently not used
for (let j = 1; j < tokens.length; j++) {
const client = clients[j - 1];
const decision = parseFloat(tokens[j]);
data.push({ client: client, decision: decision });
}
}
return data;
}
// Function to train the logistic regression model
async function trainModel(data) {
try {
// Encode clients as integers
const clientSet = new Set(data.map(d => d.client));
const clients = Array.from(clientSet);
const clientToIndex = {};
clients.forEach((client, idx) => {
clientToIndex[client] = idx;
});
// Prepare features and labels
const xs = tf.tensor2d(data.map(d => [clientToIndex[d.client]]));
const ys = tf.tensor2d(data.map(d => [d.decision]));
// One-hot encode the client indices
const numClients = clients.length;
const xsOneHot = tf.oneHot(xs.reshape([-1]), numClients);
// Define the model
const model = tf.sequential();
model.add(tf.layers.dense({
units: 1,
inputShape: [numClients],
activation: 'sigmoid'
}));
model.compile({
optimizer: tf.train.adam(),
loss: 'binaryCrossentropy',
metrics: ['accuracy']
});
// Display progress bar
const progressBar = document.getElementById('progress');
const numEpochs = 100;
// Train the model
await model.fit(xsOneHot, ys, {
epochs: numEpochs,
callbacks: {
onEpochEnd: (epoch, logs) => {
const percentComplete = ((epoch + 1) / numEpochs) * 100;
progressBar.style.width = percentComplete + '%';
progressBar.innerHTML = Math.round(percentComplete) + '%';
}
}
});
// Make predictions
const clientIndices = clients.map((client, idx) => idx);
const xsPredict = tf.oneHot(tf.tensor1d(clientIndices, 'int32'), numClients);
const predictions = model.predict(xsPredict);
const predictedProbabilities = Array.from(predictions.dataSync());
// Prepare data for chart
const chartData = [['Client', 'Probability']];
for (let i = 0; i < clients.length; i++) {
chartData.push([clients[i], predictedProbabilities[i]]);
}
drawChart(chartData);
// Dispose tensors to free memory
tf.dispose([xs, ys, xsOneHot, xsPredict, predictions]);
} catch (error) {
handleError(error);
}
}
// Function to draw Google Chart
function drawChart(chartData) {
try {
google.charts.load('current', { 'packages': ['corechart'] });
google.charts.setOnLoadCallback(function () {
const data = google.visualization.arrayToDataTable(chartData);
const options = {
title: 'Predicted Probabilities for Clients',
hAxis: { title: 'Clients' },
vAxis: { title: 'Probability', minValue: 0, maxValue: 1 },
legend: 'none'
};
const chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
} catch (error) {
handleError(error);
}
}
</script>
</body>
</html>
Explanation:
File Input: Allows users to upload a CSV file containing the data.
Progress Bar: Visualizes the training progress of the logistic regression model.
Data Parsing: The parseCSV function reads the CSV file and parses it into a usable format for training.
Model Training:
Clients are one-hot encoded to serve as input features for the model.
A simple neural network with a sigmoid activation function is used to perform logistic regression.
The model predicts the probability of each client making a '1' decision.
Training progress updates the progress bar after each epoch.
Error Handling: The handleError function logs errors to the console and alerts the user.
Prediction and Visualization:
After training, the model predicts probabilities for each client.
The predicted probabilities are displayed using Google Charts on a scatter plot.
The horizontal axis represents clients, and the vertical axis represents the predicted probability (from 0 to 1).
Adaptability: The code dynamically handles any number of clients by parsing the CSV headers and creating appropriate one-hot encoded inputs.
Notes:
Ensure that TensorFlow.js and Google Charts libraries are properly included via the <script> tags.
The code assumes that the CSV file is correctly formatted with the first column being Date and subsequent columns being client names with their corresponding binary decisions.
The model uses a simple architecture suitable for logistic regression tasks.
Remember to allow the browser to access local files if running the code locally, or host it on a server.
Usage:
Open the HTML file in a modern web browser (e.g., Chrome, Firefox).
Click on the "Choose File" button to upload your CSV file.
Once the file is selected, click on the "Process Data" button.
The progress bar will update as the model trains.
After training, the scatter plot will display the predicted probabilities for each client.
If you encounter any errors, they will be logged to the console, and an alert will inform you of the issue.