Save clustering result (aka dictionary) in JSON and Reuse loaded result

CK CK 3788 
Created at  
381 0 0

Saving processed data allows for significant time and resource savings by eliminating the need to re-process raw data each time an analysis is needed. Reloading previously processed data dramatically accelerates subsequent analyses, facilitates reproducibility of results, and reduces computational costs, especially with large datasets where initial processing can be computationally intensive.

This reuse promotes efficiency and allows researchers or analysts to focus on interpretation and further analysis rather than repetitive data manipulation.

Save clustering result (aka dictionary) in JSON and Reuse loaded result

You can save the calculated clustering results (such as cluster labels and centroids if applicable) in a JSON file and reload them later. Here's how you can extend the example using Agglomerative Clustering to save the labels into a JSON file and reload them:

 

Modified Code with JSON Saving and Loading

import numpy as np
import json
from sklearn.cluster import AgglomerativeClustering
from sklearn.preprocessing import StandardScaler
from scipy.cluster.hierarchy import dendrogram, linkage
import matplotlib.pyplot as plt

# Example high school score data
data = np.array([
    [85, 78, 90],
    [72, 88, 85],
    [95, 92, 98],
    [60, 65, 70],
    [75, 80, 79],
    [90, 85, 88],
    [55, 60, 58],
    [80, 83, 85],
    [98, 99, 100],
    [65, 70, 68]
])

# Standardize the data
scaler = StandardScaler()
data_scaled = scaler.fit_transform(data)

# Perform Agglomerative Clustering
agg_clustering = AgglomerativeClustering(n_clusters=3, linkage='ward')
labels = agg_clustering.fit_predict(data_scaled)

# Save results to JSON
result = {
    "data": data.tolist(),
    "labels": labels.tolist(),
    "scaler_mean": scaler.mean_.tolist(),
    "scaler_scale": scaler.scale_.tolist()
}

with open("clustering_results.json", "w") as file:
    json.dump(result, file, indent=4)

print("Clustering results saved to clustering_results.json")

# Reload results from JSON
with open("clustering_results.json", "r") as file:
    loaded_result = json.load(file)

# Reconstruct data from the loaded JSON
data_reloaded = np.array(loaded_result["data"])
labels_reloaded = np.array(loaded_result["labels"])
scaler_mean = np.array(loaded_result["scaler_mean"])
scaler_scale = np.array(loaded_result["scaler_scale"])

# Validate reloaded results
print("Reloaded Data:\n", data_reloaded)
print("Reloaded Labels:", labels_reloaded)

# Rescale if needed
scaler_reloaded = StandardScaler()
scaler_reloaded.mean_ = scaler_mean
scaler_reloaded.scale_ = scaler_scale
data_rescaled = scaler_reloaded.transform(data_reloaded)

# Optional: Visualize reloaded labels
plt.scatter(data_rescaled[:, 0], data_rescaled[:, 1], c=labels_reloaded, cmap='viridis', s=100)
plt.title("Reloaded Agglomerative Clustering Results")
plt.xlabel("Standardized Math Score")
plt.ylabel("Standardized English Score")
plt.show()

Key Points

  1. Save Results to JSON:
    • data.tolist() converts the NumPy array into a list, which is JSON serializable.
    • Save labels, raw data, and scaling parameters (mean and scale) to reconstruct the process later.
  2. Reload and Reconstruct:
    • Reload JSON and convert lists back into NumPy arrays.
    • Use the saved scaling parameters to recreate the StandardScaler and rescale the data.
  3. Validation:
    • Print and visualize the reloaded data and labels to confirm the clustering results are correctly restored.

This approach allows you to save the clustering process for later analysis or use without rerunning the entire computation.

 

Saving the clustering result in an array and reloading

Yes, you can load the clustering results directly from an in-memory array rather than a file. This approach avoids file I/O and is useful when working in environments where data is transferred or stored in memory structures like Python dictionaries or NumPy arrays. Here's how to modify the code to load the results from an array:

Example: Save and Load from Array

import numpy as np
from sklearn.cluster import AgglomerativeClustering
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt

# Example high school score data
data = np.array([
    [85, 78, 90],
    [72, 88, 85],
    [95, 92, 98],
    [60, 65, 70],
    [75, 80, 79],
    [90, 85, 88],
    [55, 60, 58],
    [80, 83, 85],
    [98, 99, 100],
    [65, 70, 68]
])

# Standardize the data
scaler = StandardScaler()
data_scaled = scaler.fit_transform(data)

# Perform Agglomerative Clustering
agg_clustering = AgglomerativeClustering(n_clusters=3, linkage='ward')
labels = agg_clustering.fit_predict(data_scaled)

# Save results to an in-memory array (dictionary)
clustering_result = {
    "data": data,
    "labels": labels,
    "scaler_mean": scaler.mean_,
    "scaler_scale": scaler.scale_
}

# Simulate loading from an array
loaded_result = clustering_result  # Directly use the saved array

# Extract data from the in-memory array
data_reloaded = np.array(loaded_result["data"])
labels_reloaded = np.array(loaded_result["labels"])
scaler_mean = np.array(loaded_result["scaler_mean"])
scaler_scale = np.array(loaded_result["scaler_scale"])

# Reconstruct the scaler
scaler_reloaded = StandardScaler()
scaler_reloaded.mean_ = scaler_mean
scaler_reloaded.scale_ = scaler_scale
data_rescaled = scaler_reloaded.transform(data_reloaded)

# Validate the reloaded results
print("Reloaded Data:\n", data_reloaded)
print("Reloaded Labels:", labels_reloaded)

# Visualize reloaded clustering results
plt.scatter(data_rescaled[:, 0], data_rescaled[:, 1], c=labels_reloaded, cmap='viridis', s=100)
plt.title("Reloaded Agglomerative Clustering Results (from Array)")
plt.xlabel("Standardized Math Score")
plt.ylabel("Standardized English Score")
plt.show()

Explanation

  1. Save Results:
    • Store clustering results in an in-memory dictionary (clustering_result).
    • Save data, labels, and scaler parameters (mean_ and scale_).
  2. Load Results:
    • Directly access the dictionary (loaded_result) to retrieve the saved data.
  3. Reconstruction:
    • Use saved scaler parameters to recreate the StandardScaler object.
    • Rescale the data if needed for further use or validation.
  4. Visualization:
    • Ensure the results are consistent by reusing the saved labels and data for plotting.

This method is efficient for scenarios where data needs to be shared across functions or modules in memory without file-based serialization.

Tags Centroids Cluster Labels Clustered Result Clustering Result Dictionary JSON Loading Dictionary Python Clustering Saving Dictionary dendrogram Facebook X
Comments 0
Similar posts
  1. Recommended Vector DB Structure for Amazon Bedrock Integration
    393
  2. Dynamic JSON Editor based in HTML/JavaScript
    514
  3. Simple Python Clustering Example based on the high school students' score
    345
  4. JSON format control in PHP
    696
  1. Python Flask web server tutorial from the scratch
    626
  2. Simple Web Server based in Python
    381
  3. Thread Implementation in Python
    511
  4. A shell script that activates a Python virtual environment and then runs a specific Python script
    747
  5. Learning about Python Multiprocessing Technique
    594
  6. Simple Example to get the total number of records in BigQuery with Python
    667
  7. Using BigQuery in Python
    414
  8. Python Web Programming based on Django from the Scratch
    390
  9. Flink with Python: Core Concepts, Kafka Integration, and Architectural Trade-offs
    192
  10. How do I determine the client IP type in Python - IPv4 or IPv6
    766
  11. Predicting Buyer Preferences with PyTorch: A Deep Learning Approach
    1,234
  12. PyTorch example to Forcast Stock Price based on 10 days Dataset
    653
  13. Implementing a Versatile DNS Server in Python: Handling A, AAAA, CNAME, and TXT Records
    1,078
  14. Dynamic DNS Made Easy: Building a Python-Based Solution
    796
  15. Milvus & FAISS: Decoding Their ML Synergy
    286
  16. Forecasting with Linear Regression and KNN Regression in Python
    928
  17. Forecasting the Weather with PyTorch: A Beginner's Guide to Temperature Prediction
    1,444
  18. Uvicorn, Gunicorn: Proving Your Production Prowess
    401
  19. Mastering Model Persistence: Saving and Loading Trained Machine Learning Models in Python
    1,165
  20. Harnessing the Power of Random Forest Algorithm in Python
    658
  21. Understanding and Implementing K-Nearest Neighbors (KNN) Algorithm in Python
    636
  22. Mastering Random Forest Regression: A Comprehensive Guide with Python Examples
    1,104
  23. Getting Started with PyTorch: A Beginner's Guide to Building Your First Neural Network
    801
  24. Memory Problems with Python Arrays? Discover Dask Array
    328
  25. Python Implementation of Linear Regression
    842
  26. Mastering Supervised Machine Learning with Python: A Comprehensive Guide
    1,060
  27. Mastering AI: A Beginner's Guide to Python Programming and Beyond
    1,040
Recently updated
  1. Google OAuth Token Expiration: Causes and Solutions
    28
  2. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    55
  3. Why SPF and DKIM Are Essential for Linux Email Servers?
    49
  4. How do I create animated background for Google Meet?
    22,830
  5. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    271
  6. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    103
  7. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    168
  8. Array of arguments passed to script in PHP
    97
  9. Invalid Auction Storms in Ad Tech
    106
  10. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    207
  11. The Two Clocks of Ad Server Architecture
    77
  12. Frequency Cap Architecture Overview
    526
  13. Collecting Proof-of-Play from 100,000 Screens
    152
  14. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    302
  15. What is RedisVL?
    114
  16. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    246
  17. TPU & GPU Cluster Management Tools
    257
  18. The Concept of Scaffolding in AI Agents
    244
  19. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    596
  20. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    267
  21. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    353
  22. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    206
  23. Machine Learning: Training vs. Ranking
    229
  24. The Continuous Learning Machine: Designing a Loop That Actually Turns
    228
  25. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    202
  26. Designing a Data Curation System Around a Vector Database
    230
  27. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    263
  28. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    671
  29. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    200
  30. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    232