How to Calculate Class Weights for Imbalanced Data

Calculate Class Weights for Imbalanced Data – Your Expert Guide :root { –primary-color: #004a99; –success-color: #28a745; –background-color: #f8f9fa; –text-color: #333; –white: #fff; –border-color: #ddd; –shadow-color: rgba(0, 0, 0, 0.1); } body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: var(–background-color); color: var(–text-color); line-height: 1.6; margin: 0; padding: 0; display: flex; flex-direction: column; align-items: center; min-height: 100vh; } .container { width: 100%; max-width: 980px; margin: 20px auto; padding: 20px; background-color: var(–white); border-radius: 8px; box-shadow: 0 4px 12px var(–shadow-color); box-sizing: border-box; } h1, h2, h3 { color: var(–primary-color); text-align: center; margin-bottom: 20px; } h1 { font-size: 2.5em; margin-bottom: 30px; } h2 { font-size: 1.8em; border-bottom: 2px solid var(–primary-color); padding-bottom: 10px; margin-top: 30px; } h3 { font-size: 1.3em; margin-top: 20px; color: #555; } .calculator-section { background-color: var(–white); padding: 30px; border-radius: 8px; box-shadow: 0 2px 8px var(–shadow-color); margin-bottom: 30px; } .loan-calc-container { display: flex; flex-direction: column; gap: 20px; } .input-group { display: flex; flex-direction: column; gap: 8px; } .input-group label { font-weight: bold; color: var(–primary-color); } .input-group input[type="number"], .input-group select { padding: 12px; border: 1px solid var(–border-color); border-radius: 4px; font-size: 1em; box-sizing: border-box; width: 100%; } .input-group .helper-text { font-size: 0.85em; color: #666; margin-top: 4px; } .error-message { color: #dc3545; font-size: 0.8em; margin-top: 4px; height: 1.2em; /* Reserve space for error message */ } .button-group { display: flex; gap: 15px; margin-top: 25px; flex-wrap: wrap; /* Allow wrapping on smaller screens */ } button { padding: 12px 20px; border: none; border-radius: 5px; cursor: pointer; font-size: 1em; font-weight: bold; transition: background-color 0.3s ease; min-width: 150px; /* Ensure buttons have a decent minimum width */ } button.primary { background-color: var(–primary-color); color: var(–white); } button.primary:hover { background-color: #003366; } button.secondary { background-color: #6c757d; color: var(–white); } button.secondary:hover { background-color: #5a6268; } button.reset { background-color: #ffc107; color: var(–text-color); } button.reset:hover { background-color: #e0a800; } #results { margin-top: 30px; padding: 25px; background-color: #e9ecef; border: 1px solid #ced4da; border-radius: 5px; display: flex; flex-direction: column; gap: 15px; } #results h3 { text-align: left; margin-top: 0; color: var(–primary-color); } .result-item { display: flex; justify-content: space-between; align-items: center; padding: 10px 0; border-bottom: 1px dashed #ccc; } .result-item:last-child { border-bottom: none; } .result-label { font-weight: bold; color: #555; } .result-value { font-size: 1.1em; font-weight: bold; color: var(–primary-color); } .primary-result { font-size: 1.8em; color: var(–success-color); background-color: var(–white); padding: 15px 20px; border-radius: 5px; text-align: center; margin: 10px 0; box-shadow: 0 2px 6px var(–shadow-color); } .formula-explanation { font-size: 0.9em; color: #444; margin-top: 15px; background-color: var(–white); padding: 15px; border-left: 4px solid var(–primary-color); } .chart-container { margin-top: 30px; padding: 25px; background-color: var(–white); border-radius: 8px; box-shadow: 0 2px 8px var(–shadow-color); display: flex; flex-direction: column; align-items: center; } .chart-container h3 { text-align: center; margin-bottom: 20px; } canvas { max-width: 100%; height: auto; } .table-container { margin-top: 30px; overflow-x: auto; /* For responsiveness on small screens */ } table { width: 100%; border-collapse: collapse; margin-bottom: 20px; background-color: var(–white); box-shadow: 0 2px 8px var(–shadow-color); border-radius: 8px; overflow: hidden; /* To ensure rounded corners */ } th, td { padding: 12px 15px; text-align: left; border-bottom: 1px solid var(–border-color); } th { background-color: var(–primary-color); color: var(–white); font-weight: bold; } tr:last-child td { border-bottom: none; } tbody tr:nth-child(even) { background-color: #f2f2f2; } caption { caption-side: bottom; font-style: italic; color: #777; margin-top: 10px; text-align: center; font-size: 0.9em; } .article-content { width: 100%; max-width: 980px; margin: 20px auto; padding: 20px; background-color: var(–white); border-radius: 8px; box-shadow: 0 4px 12px var(–shadow-color); box-sizing: border-box; } .article-content h2, .article-content h3 { text-align: left; margin-top: 30px; } .article-content p, .article-content ul, .article-content ol { margin-bottom: 20px; } .article-content a { color: var(–primary-color); text-decoration: none; font-weight: bold; } .article-content a:hover { text-decoration: underline; } .faq-list { list-style: none; padding: 0; } .faq-item { margin-bottom: 20px; border-left: 4px solid var(–primary-color); padding-left: 15px; background-color: #fdfdfd; padding-top: 10px; padding-bottom: 10px; } .faq-item strong { display: block; color: var(–primary-color); margin-bottom: 5px; } .related-links ul { list-style: none; padding: 0; } .related-links li { margin-bottom: 10px; } .related-links span { font-size: 0.9em; color: #555; display: block; margin-top: 5px; } /* Responsive adjustments */ @media (min-width: 768px) { .container { margin-top: 40px; padding: 30px; } h1 { font-size: 3em; } .button-group { justify-content: center; } }

How to Calculate Class Weights for Imbalanced Data

Class Weight Calculator

The total count of all data points in your dataset.
The number of samples in the most frequent class.
The number of samples in the least frequent class.
Inverse Frequency Balanced
Choose how class weights are calculated.

Calculation Results

Majority Class Weight
Minority Class Weight
Total Samples (N)
Majority Samples (N_maj)
Minority Samples (N_min)
Formula Used:

Weights are calculated based on the selected scheme. For 'Inverse Frequency', weights are typically 1 / (count of samples). For 'Balanced', weights are n_samples / (n_classes * n_samples_of_class).

Class Weight Distribution

Visual representation of calculated class weights.

Input Data Summary

Class Number of Samples Calculated Weight
Majority Class
Minority Class
Summary of input samples and their corresponding calculated weights.

{primary_keyword} Definition

Understanding how to calculate class weights for imbalanced data is crucial for building effective machine learning models. In many real-world datasets, the distribution of classes is uneven. This means one class (the majority class) has significantly more samples than another (the minority class). For instance, in fraud detection, legitimate transactions vastly outnumber fraudulent ones. If not handled properly, a model trained on such imbalanced data may become biased towards the majority class, leading to poor performance in identifying the minority class, which is often the class of interest (e.g., detecting rare diseases, identifying fraudulent activities).

Who should use class weights? Data scientists, machine learning engineers, researchers, and anyone involved in building classification models that face uneven class distributions. This includes applications in finance (fraud detection, credit scoring), healthcare (disease prediction), cybersecurity (intrusion detection), and anomaly detection.

Common misconceptions about class weights include believing they are a magic bullet that solves all imbalanced data problems (they are one tool among many), or that simply assigning the inverse frequency is always the best approach (the optimal weighting often requires experimentation).

{primary_keyword} Formula and Mathematical Explanation

The core idea behind class weighting is to penalize misclassifications of the minority class more heavily than misclassifications of the majority class. This encourages the model to pay more attention to the underrepresented samples during training. There are several common strategies for calculating class weights:

1. Inverse Frequency Weighting

This is a straightforward method where the weight assigned to a class is inversely proportional to the number of samples in that class. The formula can be simplified as:

Weight_class = Total Samples / (Number of Classes * Samples in Class)

Or a simpler form often used is just:

Weight_class = Total Samples / Samples in Class

However, the `balanced` option in many libraries like Scikit-learn uses the first, more robust formula. Let's stick to the definition provided by common libraries for clarity.

2. Balanced Weighting

This method automatically adjusts weights inversely proportional to class frequencies. It's designed to give equal importance to all classes. The formula is:

Weight_class = Total Samples / (Number of Classes * Samples in Class)

Where:

  • Total Samples (N): The total number of data points in the dataset.
  • Number of Classes (C): The total number of distinct classes in the target variable (e.g., 2 for binary classification).
  • Samples in Class (N_class): The number of samples belonging to a specific class.

Variables Table

Variable Meaning Unit Typical Range
N Total Number of Samples Count ≥ 1
N_maj Number of Samples in Majority Class Count ≥ 0
N_min Number of Samples in Minority Class Count ≥ 0
C Number of Classes Count ≥ 2
W_maj Calculated Weight for Majority Class Unitless Typically 0 < W_maj ≤ 1 (or higher if inverted)
W_min Calculated Weight for Minority Class Unitless Typically W_min > 1 (or higher if inverted)

Practical Examples (Real-World Use Cases)

Example 1: Credit Card Fraud Detection

A bank is building a model to detect fraudulent credit card transactions. Their dataset has 10,000 transactions.

  • Total Samples (N): 10,000
  • Majority Class (Legitimate Transactions): 9,900 samples (N_maj)
  • Minority Class (Fraudulent Transactions): 100 samples (N_min)
  • Number of Classes (C): 2

Using the balanced weighting scheme:

  • Majority Weight (W_maj) = 10000 / (2 * 9900) ≈ 0.505
  • Minority Weight (W_min) = 10000 / (2 * 100) = 50

Interpretation: A fraudulent transaction is 50 times more important to correctly classify than a legitimate one. By applying these weights, the model is forced to learn patterns associated with fraud, even with few examples. This is a prime use case for how to calculate class weights for imbalanced data.

Example 2: Medical Diagnosis for a Rare Disease

A research hospital is developing a system to predict the presence of a rare disease based on patient data. Their dataset contains 5,000 patient records.

  • Total Samples (N): 5,000
  • Majority Class (No Disease): 4,950 samples (N_maj)
  • Minority Class (Disease Present): 50 samples (N_min)
  • Number of Classes (C): 2

Using the balanced weighting scheme:

  • Majority Weight (W_maj) = 5000 / (2 * 4950) ≈ 0.505
  • Minority Weight (W_min) = 5000 / (2 * 50) = 50

Interpretation: Similar to the fraud example, the model needs to prioritize identifying patients with the rare disease. Assigning a high weight to the minority class ensures that misclassifying a patient with the disease has a significant impact on the model's training loss, pushing it to improve its detection capabilities. Properly implementing how to calculate class weights for imbalanced data is key here.

How to Use This Class Weight Calculator

  1. Input Sample Counts: Enter the 'Total Number of Samples', 'Majority Class Samples', and 'Minority Class Samples' into the respective fields. Ensure these numbers accurately reflect your dataset.
  2. Select Weighting Scheme: Choose either 'Inverse Frequency' (simpler ratio) or 'Balanced' (standard approach, recommended).
  3. Calculate: Click the 'Calculate Weights' button.
  4. Review Results: The calculator will display the calculated weights for both the majority and minority classes. The primary result highlights the minority class weight, emphasizing its importance. Key intermediate values like the total and class-specific sample counts are also shown.
  5. Interpret: The calculated weights tell you the relative importance of correctly classifying samples from each class. A higher weight for the minority class means its correct classification is prioritized.
  6. Visualize & Summarize: Examine the generated chart for a visual comparison of weights and the table for a structured summary.
  7. Copy/Reset: Use the 'Copy Results' button to easily share or save the output. Use 'Reset' to clear the fields and start over. Understanding how to calculate class weights for imbalanced data becomes straightforward with this tool.

Key Factors That Affect Class Weighting Results

While the formulas for calculating class weights are deterministic based on sample counts, the *effectiveness* of these weights in improving model performance depends on several factors:

  1. Degree of Imbalance: The more skewed the data, the more significant the impact of class weights. In mildly imbalanced datasets, weights might offer only marginal improvements, while in highly imbalanced scenarios, they can be transformative.
  2. Choice of Weighting Scheme: While 'balanced' is standard, different algorithms or specific problem contexts might benefit from custom weight adjustments. Experimentation is often needed. For instance, sometimes `sklearn.utils.class_weight.compute_class_weight` allows for custom weight definitions beyond simple inverse frequency or balanced.
  3. Model Algorithm: Some algorithms are inherently more sensitive to class imbalance than others. For example, tree-based methods (like Random Forests, Gradient Boosting) often handle imbalance better than methods like Logistic Regression or SVMs without explicit weighting. Class weights are particularly beneficial for algorithms sensitive to sample imbalance.
  4. Evaluation Metrics: The choice of metric is critical. Accuracy can be misleading with imbalanced data. Metrics like Precision, Recall, F1-Score, ROC AUC, and PR AUC are more informative. Class weights aim to improve these more nuanced metrics, especially recall for the minority class. Remember to evaluate your model using appropriate metrics after applying weights.
  5. Feature Engineering: Well-engineered features that effectively separate the classes can reduce the need for extreme class weighting. If features strongly correlate with the target, the model might learn to distinguish classes even with imbalance. Poor feature engineering may necessitate stronger weights. This ties into effective feature selection.
  6. Data Quality and Noise: If the minority class samples are noisy or mislabeled, increasing their weight might amplify the negative impact of this noise. Ensuring data quality is paramount before or alongside applying class weights.
  7. Threshold Tuning: After training with class weights, the classification threshold (often implicitly 0.5 for binary classification) might need adjustment to optimize for specific precision/recall trade-offs, especially if the goal is to maximize detection of the minority class.
  8. Dataset Size: While weights help, they cannot fully compensate for a severely small minority class in a very large dataset. If the minority class has only a handful of samples, techniques like oversampling (e.g., SMOTE) or data augmentation might be necessary in addition to class weighting strategies.

Frequently Asked Questions (FAQ)

  • Q: What is the main goal of calculating class weights?

    A: The primary goal is to make the learning algorithm pay more attention to the minority class, improving its ability to correctly identify samples from underrepresented groups, thus mitigating bias caused by data imbalance.

  • Q: Can class weights completely solve the problem of imbalanced data?

    A: No, class weights are a powerful technique but are typically one part of a broader strategy. Depending on the severity of imbalance and the dataset, it might be used in conjunction with other methods like resampling (oversampling/undersampling), ensemble methods, or anomaly detection algorithms.

  • Q: Which weighting scheme is best: Inverse Frequency or Balanced?

    A: The 'Balanced' scheme is generally preferred and widely used as it's mathematically sound and scales well. It automatically adjusts weights to give equal importance to all classes. 'Inverse Frequency' can be simpler but might require manual tuning for optimal results.

  • Q: How do I know if my weights are effective?

    A: Effectiveness is measured by evaluating your trained model using appropriate metrics for imbalanced data, such as Recall, F1-score, Precision-Recall AUC, or ROC AUC. Compare these metrics to a baseline model trained without weights.

  • Q: What if I have more than two classes (multi-class imbalance)?

    A: The 'Balanced' formula works for multi-class problems as well. The calculator assumes a binary case for simplicity, but the principle extends. You would calculate weights for each class based on its proportion relative to the total samples and the number of classes.

  • Q: Should I use class weights during validation or testing?

    A: Class weights are a training hyperparameter. They should only be applied during the model training phase. Validation and testing sets should reflect the natural, imbalanced distribution of the data to provide a realistic assessment of performance in the real world.

  • Q: Can I manually set class weights?

    A: Yes, some algorithms allow you to define custom weights. This is useful if you have domain expertise suggesting certain classes are more critical than others, or if automatic methods don't yield satisfactory results. This requires careful consideration and experimentation.

  • Q: What is the relationship between class weights and undersampling/oversampling?

    A: Class weighting modifies the loss function to emphasize minority classes without altering the dataset size. Resampling techniques, conversely, change the dataset by duplicating minority samples (oversampling) or removing majority samples (undersampling). They can be used together or independently.

© 2023 Your Company Name. All rights reserved.

var totalSamplesInput = document.getElementById('totalSamples'); var majorityClassSamplesInput = document.getElementById('majorityClassSamples'); var minorityClassSamplesInput = document.getElementById('minorityClassSamples'); var weightingSchemeSelect = document.getElementById('weightingScheme'); var totalSamplesError = document.getElementById('totalSamplesError'); var majorityClassSamplesError = document.getElementById('majorityClassSamplesError'); var minorityClassSamplesError = document.getElementById('minorityClassSamplesError'); var majorityWeightOutput = document.getElementById('majorityWeight'); var minorityWeightOutput = document.getElementById('minorityWeight'); var primaryResultOutput = document.getElementById('primaryResult'); var formulaTextOutput = document.getElementById('formulaText'); var resultTotalSamplesOutput = document.getElementById('resultTotalSamples'); var resultMajoritySamplesOutput = document.getElementById('resultMajoritySamples'); var resultMinoritySamplesOutput = document.getElementById('resultMinoritySamples'); var tableMajoritySamples = document.getElementById('tableMajoritySamples'); var tableMinoritySamples = document.getElementById('tableMinoritySamples'); var tableMajorityWeight = document.getElementById('tableMajorityWeight'); var tableMinorityWeight = document.getElementById('tableMinorityWeight'); var chart; var chartContext; var initialData = { totalSamples: 1000, majorityClassSamples: 900, minorityClassSamples: 100, weightingScheme: 'balanced' }; function validateInput(inputElement, errorElement, minValue, maxValue) { var value = parseFloat(inputElement.value); var isValid = true; errorElement.textContent = "; if (isNaN(value)) { errorElement.textContent = 'Please enter a valid number.'; isValid = false; } else if (inputElement.id === 'totalSamples' && value <= 0) { errorElement.textContent = 'Total samples must be positive.'; isValid = false; } else if (value < 0) { errorElement.textContent = 'Value cannot be negative.'; isValid = false; } else if (minValue !== undefined && value maxValue) { errorElement.textContent = 'Value cannot exceed ' + maxValue + '.'; isValid = false; } else { var total = parseFloat(totalSamplesInput.value) || 0; var majority = parseFloat(majorityClassSamplesInput.value) || 0; var minority = parseFloat(minorityClassSamplesInput.value) || 0; if (inputElement.id === 'majorityClassSamples' && majority + minority > total) { errorElement.textContent = 'Sum of class samples cannot exceed total samples.'; isValid = false; } if (inputElement.id === 'minorityClassSamples' && majority + minority > total) { errorElement.textContent = 'Sum of class samples cannot exceed total samples.'; isValid = false; } if (inputElement.id === 'totalSamples' && value 0) { majorityWeight = totalSamples / majorityClassSamples; } else { majorityWeight = Infinity; // Avoid division by zero } if (minorityClassSamples > 0) { minorityWeight = totalSamples / minorityClassSamples; } else { minorityWeight = Infinity; // Avoid division by zero } } else if (scheme === 'balanced') { formulaExplanationText = "Weights are calculated as: Total Samples / (Number of Classes * Samples in Class). This normalizes weights to account for class frequency and number of classes."; if (majorityClassSamples > 0) { majorityWeight = totalSamples / (numClasses * majorityClassSamples); } else { majorityWeight = Infinity; } if (minorityClassSamples > 0) { minorityWeight = totalSamples / (numClasses * minorityClassSamples); } else { minorityWeight = Infinity; } } formulaTextOutput.textContent = formulaExplanationText; // Ensure weights are finite numbers, otherwise display as '–' majorityWeight = isFinite(majorityWeight) ? majorityWeight.toFixed(3) : '–'; minorityWeight = isFinite(minorityWeight) ? minorityWeight.toFixed(3) : '–'; majorityWeightOutput.textContent = majorityWeight; minorityWeightOutput.textContent = minorityWeight; resultTotalSamplesOutput.textContent = totalSamples.toLocaleString(); resultMajoritySamplesOutput.textContent = majorityClassSamples.toLocaleString(); resultMinoritySamplesOutput.textContent = minorityClassSamples.toLocaleString(); // Determine primary result (usually minority weight for imbalanced data focus) var primaryResultLabel = "Minority Class Weight"; var primaryResultValue = minorityWeight; if (minorityWeight === '–' || parseFloat(minorityWeight) < parseFloat(majorityWeight) && majorityWeight !== '–') { primaryResultLabel = "Majority Class Weight"; primaryResultValue = majorityWeight; } primaryResultOutput.textContent = primaryResultValue; primaryResultOutput.dataset.label = primaryResultLabel; // Store label for copy functionality // Update table tableMajoritySamples.textContent = majorityClassSamples.toLocaleString(); tableMinoritySamples.textContent = minorityClassSamples.toLocaleString(); tableMajorityWeight.textContent = majorityWeight; tableMinorityWeight.textContent = minorityWeight; updateChart(majorityWeight, minorityWeight); } function resetCalculator() { totalSamplesInput.value = initialData.totalSamples; majorityClassSamplesInput.value = initialData.majorityClassSamples; minorityClassSamplesInput.value = initialData.minorityClassSamples; weightingSchemeSelect.value = initialData.weightingScheme; // Clear errors totalSamplesError.textContent = ''; majorityClassSamplesError.textContent = ''; minorityClassSamplesError.textContent = ''; totalSamplesInput.style.borderColor = '#ccc'; majorityClassSamplesInput.style.borderColor = '#ccc'; minorityClassSamplesInput.style.borderColor = '#ccc'; calculateWeights(); // Recalculate with default values } function copyResults() { var majorityWeight = majorityWeightOutput.textContent; var minorityWeight = minorityWeightOutput.textContent; var primaryResultLabel = primaryResultOutput.dataset.label || "Primary Result"; var primaryResultValue = primaryResultOutput.textContent; var totalSamples = resultTotalSamplesOutput.textContent; var majoritySamples = resultMajoritySamplesOutput.textContent; var minoritySamples = resultMinoritySamplesOutput.textContent; var scheme = weightingSchemeSelect.options[weightingSchemeSelect.selectedIndex].text; var formula = formulaTextOutput.textContent; var textToCopy = "Class Weight Calculation Results:\n\n"; textToCopy += "Selected Scheme: " + scheme + "\n"; textToCopy += "Formula Used: " + formula + "\n\n"; textToCopy += "— Key Values —\n"; textToCopy += "Total Samples: " + totalSamples + "\n"; textToCopy += "Majority Class Samples: " + majoritySamples + "\n"; textToCopy += "Minority Class Samples: " + minoritySamples + "\n\n"; textToCopy += "— Calculated Weights —\n"; textToCopy += "Majority Class Weight: " + majorityWeight + "\n"; textToCopy += "Minority Class Weight: " + minorityWeight + "\n\n"; textToCopy += primaryResultLabel + ": " + primaryResultValue + "\n"; if (navigator.clipboard && window.isSecureContext) { navigator.clipboard.writeText(textToCopy).then(function() { // Optionally provide user feedback, e.g., a temporary message var copyButton = document.querySelector('button.secondary'); var originalText = copyButton.textContent; copyButton.textContent = 'Copied!'; setTimeout(function() { copyButton.textContent = originalText; }, 1500); }).catch(function(err) { console.error('Failed to copy text: ', err); // Fallback for older browsers or environments where clipboard API is not available var textArea = document.createElement("textarea"); textArea.value = textToCopy; textArea.style.position = "fixed"; textArea.style.left = "-9999px"; document.body.appendChild(textArea); textArea.focus(); textArea.select(); try { document.execCommand('copy'); var copyButton = document.querySelector('button.secondary'); var originalText = copyButton.textContent; copyButton.textContent = 'Copied!'; setTimeout(function() { copyButton.textContent = originalText; }, 1500); } catch (e) { console.error('Fallback copy failed: ', e); alert("Could not copy text. Please manually select and copy."); } document.body.removeChild(textArea); }); } else { // Fallback for older browsers or non-HTTPS environments var textArea = document.createElement("textarea"); textArea.value = textToCopy; textArea.style.position = "fixed"; textArea.style.left = "-9999px"; document.body.appendChild(textArea); textArea.focus(); textArea.select(); try { document.execCommand('copy'); var copyButton = document.querySelector('button.secondary'); var originalText = copyButton.textContent; copyButton.textContent = 'Copied!'; setTimeout(function() { copyButton.textContent = originalText; }, 1500); } catch (e) { console.error('Fallback copy failed: ', e); alert("Could not copy text. Please manually select and copy."); } document.body.removeChild(textArea); } } function updateChart(majWeight, minWeight) { var labels = ['Majority Class Weight', 'Minority Class Weight']; var dataValues = []; // Handle cases where weights are '–' or Infinity var majVal = parseFloat(majWeight); var minVal = parseFloat(minWeight); // Ensure values are numbers for charting, otherwise use 0 or a placeholder // For visualization, large weights can be problematic. Consider scaling or capping if necessary. // Here, we'll use the calculated values directly, assuming they are reasonable for visualization. dataValues.push(isNaN(majVal) ? 0 : majVal); dataValues.push(isNaN(minVal) ? 0 : minVal); if (!chart) { chartContext = document.getElementById('classWeightChart').getContext('2d'); chart = new Chart(chartContext, { type: 'bar', // Using bar chart for clarity data: { labels: labels, datasets: [{ label: 'Class Weight', data: dataValues, backgroundColor: [ 'rgba(0, 74, 153, 0.6)', // Primary color for Majority 'rgba(40, 167, 69, 0.6)' // Success color for Minority ], borderColor: [ 'rgba(0, 74, 153, 1)', 'rgba(40, 167, 69, 1)' ], borderWidth: 1 }] }, options: { responsive: true, maintainAspectRatio: false, scales: { y: { beginAtZero: true, title: { display: true, text: 'Weight Value' } } }, plugins: { legend: { position: 'top', }, title: { display: true, text: 'Calculated Class Weights' } } } }); } else { chart.data.datasets[0].data = dataValues; chart.update(); } } // Initial calculation on page load window.onload = function() { // Small delay to ensure canvas element is ready for Chart.js setTimeout(function() { calculateWeights(); }, 100); }; // Add event listeners for real-time updates on input changes totalSamplesInput.addEventListener('input', calculateWeights); majorityClassSamplesInput.addEventListener('input', calculateWeights); minorityClassSamplesInput.addEventListener('input', calculateWeights); weightingSchemeSelect.addEventListener('change', calculateWeights);

Leave a Comment