Strictly adhere to PEP-8 standards, ensuring code is clean, well-structured, and follows Python's style guide for readability.
Use appropriate modules like typing for type hints, ensuring code clarity, maintainability, and leveraging Python's standard libraries effectively.
Focus on time, space, robustness, scalability; write optimized, efficient code that can handle large datasets and scale seamlessly.
Implement comprehensive error handling, catching exceptions gracefully, providing meaningful error messages, and ensuring code robustness under unexpected conditions.
Ensure the developer agent writes advanced, maintainable Python code, balancing performance and readability while adhering to best practices.
t
TASK: using below code we make advanced and professionally visualization using plotly module , make user generalised, robustness very professionally skilled to showcase your knowledge to teammates or share
NOte: save plots html format
#Import packages
import torch
from transformers import AutoProcessor, CLIPModel, AutoImageProcessor
from datasets import load_dataset
import faiss
import numpy as np
import time
#Define device
device = torch.device('cuda' if torch.cuda.is_available() else "cpu")
#Load CLIP model and processor
processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32").to(device)
#Display an image
display(dataset['train'][0]['img'])
#Add a vector to FAISS index
def add_vector_to_index(embedding, index):
#convert embedding to numpy
vector = embedding.detach().cpu().numpy()
#Convert to float32 numpy
vector = np.float32(vector)
#Normalize vector
faiss.normalize_L2(vector)
#Add to index
index.add(vector)
#Extract features of a given image
def extract_features_clip(image):
with torch.no_grad():
inputs = processor(images=image, return_tensors="pt").to(device)
image_features = model.get_image_features(**inputs)
return image_features
#Create FAISS index
index = faiss.IndexFlatL2(512)
#Process the dataset to extract all features and store in index
for image in dataset['test']:
clip_features = extract_features_clip(image['img'])
add_vector_to_index(clip_features,index)
#Write index locally. Not needed after but can be useful for future retrieval
faiss.write_index(index,"clip.index")
#Retrieve the vectors
vectors = index.reconstruct_n(0, 10000)
#Define clusters and parameters
x= vectors
ncentroids = 10
niter = 50
verbose = True
d = x.shape[1]
#cluster assignments: [array of vectors, array of indices (cluster assigned to a given vector)]
cluster_assignments = kmeans.assign(vectors)
print(cluster_assignments)
#Print indices only
clusters_ind = cluster_assignments[1]
print(clusters_ind)
distribution = np.zeros((10, 10), dtype=int)
print(distribution)
for vector_index,cluster_nb in enumerate(clusters_ind):
label = dataset['test'][vector_index]['label']
distribution[cluster_nb][label]+=1
print(distribution)
row_sums = np.sum(distribution, axis=1)
print("Number of images per cluster:")
print(row_sums)
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
import matplotlib.pyplot as plt
Certainly! Below is an advanced, professional, and optimized version of your initial script adhering to PEP-8 standards. The code leverages Plotly for interactive and high-quality visualizations, includes comprehensive error handling, uses type hints for clarity, and is structured for scalability and maintainability.
Key Enhancements:
PEP-8 Compliance: The code follows Python’s style guidelines for enhanced readability.
Type Hints & Modular Design: Functions are type-annotated, and the code is modularized for better maintainability.
Optimized Processing: Batch processing is implemented to handle large datasets efficiently.
Comprehensive Error Handling: Try-except blocks ensure robustness against unexpected issues.
Plotly Visualizations: Interactive and professional visualizations are created and saved as HTML files.
Logging: Integrated logging for better traceability and debugging.
Enhanced Code:
python
import logging
import time
from typing import Any, Dict, List, Tuple
import faiss
import numpy as np
import torch
from datasets import Dataset, load_dataset
from plotly import graph_objects as go
from plotly.subplots import make_subplots
from sklearn.metrics import confusion_matrix
from transformers import CLIPModel, AutoProcessor
# Configure logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[logging.StreamHandler()],
)
def get_device() -> torch.device:
"""Determine the available device (GPU if available, else CPU)."""
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
logging.info(f"Using device: {device}")
return device
def load_clip_model(device: torch.device) -> Tuple[AutoProcessor, CLIPModel]:
"""Load the CLIP model and processor."""
try:
processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32").to(device)
logging.info("CLIP model and processor loaded successfully.")
return processor, model
except Exception as e:
logging.error(f"Error loading CLIP model: {e}")
raise
def load_cifar10_dataset() -> Dataset:
"""Load the CIFAR-10 dataset."""
try:
dataset = load_dataset("cifar10")
logging.info("CIFAR-10 dataset loaded successfully.")
return dataset
except Exception as e:
logging.error(f"Error loading CIFAR-10 dataset: {e}")
raise
def extract_features(
images: List[Any],
processor: AutoProcessor,
model: CLIPModel,
device: torch.device,
) -> np.ndarray:
"""
Extract image features using CLIP model.
Args:
images (List[Any]): List of images.
processor (AutoProcessor): CLIP processor.
model (CLIPModel): CLIP model.
device (torch.device): Device to perform computation.
Returns:
np.ndarray: Extracted features.
"""
try:
inputs = processor(images=images, return_tensors="pt", padding=True).to(device)
with torch.no_grad():
image_features = model.get_image_features(**inputs)
features = image_features.cpu().numpy().astype("float32")
faiss.normalize_L2(features)
return features
except Exception as e:
logging.error(f"Error extracting features: {e}")
raise
def build_faiss_index(
data: np.ndarray, dimension: int = 512
) -> faiss.IndexFlatL2:
"""
Build a FAISS index.
Args:
data (np.ndarray): Data to index.
dimension (int, optional): Dimension of the vectors. Defaults to 512.
Returns:
faiss.IndexFlatL2: FAISS index.
"""
try:
index = faiss.IndexFlatL2(dimension)
index.add(data)
logging.info(f"FAISS index built with {index.ntotal} vectors.")
return index
except Exception as e:
logging.error(f"Error building FAISS index: {e}")
raise
def perform_clustering(
vectors: np.ndarray,
ncentroids: int = 10,
niter: int = 50,
verbose: bool = True,
) -> faiss.Clustering:
"""
Perform K-Means clustering using FAISS.
Args:
vectors (np.ndarray): Vectors to cluster.
ncentroids (int, optional): Number of clusters. Defaults to 10.
niter (int, optional): Number of iterations. Defaults to 50.
verbose (bool, optional): Verbosity flag. Defaults to True.
Returns:
faiss.Kmeans: Trained K-Means model.
"""
try:
d = vectors.shape[1]
kmeans = faiss.Kmeans(d, ncentroids, niter=niter, verbose=verbose)
start_time = time.time()
kmeans.train(vectors)
elapsed_time = time.time() - start_time
logging.info(f"Clustering completed in {elapsed_time:.2f} seconds.")
return kmeans
except Exception as e:
logging.error(f"Error during clustering: {e}")
raise
def assign_clusters(
kmeans: faiss.Kmeans, vectors: np.ndarray
) -> Tuple[np.ndarray, np.ndarray]:
"""
Assign vectors to clusters.
Args:
kmeans (faiss.Kmeans): Trained K-Means model.
vectors (np.ndarray): Vectors to assign.
Returns:
Tuple[np.ndarray, np.ndarray]: Cluster assignments and distances.
"""
try:
distances, assignments = kmeans.index.search(vectors, 1)
logging.info("Cluster assignments completed.")
return assignments.flatten(), distances.flatten()
except Exception as e:
logging.error(f"Error assigning clusters: {e}")
raise
def compute_distribution(
assignments: np.ndarray, labels: List[int], n_clusters: int = 10
) -> np.ndarray:
"""
Compute the distribution of labels per cluster.
Args:
assignments (np.ndarray): Cluster assignments.
labels (List[int]): True labels of the data.
n_clusters (int, optional): Number of clusters. Defaults to 10.
Returns:
np.ndarray: Distribution matrix.
"""
try:
distribution = np.zeros((n_clusters, 10), dtype=int)
for cluster_id, label in zip(assignments, labels):
distribution[cluster_id][label] += 1
logging.info("Distribution matrix computed.")
return distribution
except Exception as e:
logging.error(f"Error computing distribution: {e}")
raise
def create_interactive_confusion_matrix(
distribution: np.ndarray,
class_labels: List[str],
output_file: str = "confusion_matrix.html",
) -> None:
"""
Create and save an interactive confusion matrix using Plotly.
Args:
distribution (np.ndarray): Distribution matrix.
class_labels (List[str]): List of class names.
output_file (str, optional): Output HTML file. Defaults to "confusion_matrix.html".
"""
try:
fig = go.Figure(
data=go.Heatmap(
z=distribution,
x=class_labels,
y=[f"Cluster {i}" for i in range(distribution.shape[0])],
colorscale='Viridis'
)
)
fig.update_layout(
title="Distribution of CIFAR-10 Classes Across Clusters",
xaxis_title="CIFAR-10 Classes",
yaxis_title="Cluster ID",
autosize=False,
width=800,
height=600,
)
fig.write_html(output_file)
logging.info(f"Confusion matrix saved to {output_file}.")
except Exception as e:
logging.error(f"Error creating confusion matrix: {e}")
raise
def create_cluster_distribution_bar_chart(
distribution: np.ndarray,
class_labels: List[str],
output_file: str = "cluster_distribution.html",
) -> None:
"""
Create and save an interactive bar chart showing the number of images per cluster.
Args:
distribution (np.ndarray): Distribution matrix.
class_labels (List[str]): List of class names.
output_file (str, optional): Output HTML file. Defaults to "cluster_distribution.html".
"""
try:
cluster_sums = distribution.sum(axis=1)
fig = go.Figure(
data=[
go.Bar(
x=[f"Cluster {i}" for i in range(distribution.shape[0])],
y=cluster_sums,
text=cluster_sums,
textposition='auto',
)
]
)
fig.update_layout(
title="Number of Images per Cluster",
xaxis_title="Cluster ID",
yaxis_title="Number of Images",
autosize=False,
width=800,
height=600,
)
fig.write_html(output_file)
logging.info(f"Cluster distribution bar chart saved to {output_file}.")
except Exception as e:
logging.error(f"Error creating cluster distribution bar chart: {e}")
raise
def main() -> None:
"""Main function to execute the workflow."""
try:
device = get_device()
processor, model = load_clip_model(device)
dataset = load_cifar10_dataset()
# Parameters
batch_size = 64
n_clusters = 10
n_iterations = 50
# Extract features in batches for efficiency
test_dataset = dataset["test"]
labels = test_dataset["label"]
num_samples = len(test_dataset)
all_features = np.empty((num_samples, 512), dtype="float32")
logging.info("Starting feature extraction...")
for i in range(0, num_samples, batch_size):
batch_images = test_dataset[i : i + batch_size]["img"]
features = extract_features(batch_images, processor, model, device)
all_features[i : i + batch_size] = features
if (i // batch_size) % 10 == 0:
logging.info(f"Processed {i} / {num_samples} images.")
logging.info("Feature extraction completed.")
# Build FAISS index
index = build_faiss_index(all_features)
# Perform clustering
kmeans = perform_clustering(
vectors=all_features, ncentroids=n_clusters, niter=n_iterations, verbose=True
)
# Assign clusters
assignments, _ = assign_clusters(kmeans, all_features)
# Compute distribution
distribution = compute_distribution(assignments, labels, n_clusters=n_clusters)
# Get class labels
class_labels = test_dataset.features["label"].names
# Create and save visualizations
create_interactive_confusion_matrix(distribution, class_labels)
create_cluster_distribution_bar_chart(distribution, class_labels)
# Optionally, save the FAISS index for future use
faiss.write_index(index, "clip_faiss_index.index")
logging.info("FAISS index saved as 'clip_faiss_index.index'.")
except Exception as e:
logging.critical(f"An unexpected error occurred: {e}")
if __name__ == "__main__":
main()
Explanation of Enhancements:
Modular Functions with Type Hints:
Each major step is encapsulated within its own function, making the code easier to test and maintain.
Type hints provide clarity on expected input and output types.
Batch Processing for Feature Extraction:
Processing images in batches (batch_size = 64) optimizes memory usage and speeds up feature extraction, especially for larger datasets.
Comprehensive Error Handling:
Try-except blocks are used in each function to gracefully handle and log errors without crashing the entire program.
Logging:
The logging module provides real-time feedback on the program's progress and helps in debugging if issues arise.
Plotly Visualizations:
Confusion Matrix: An interactive heatmap showcasing the distribution of CIFAR-10 classes across different clusters.
Cluster Distribution Bar Chart: An interactive bar chart displaying the number of images in each cluster.
Both visualizations are saved as HTML files (confusion_matrix.html and cluster_distribution.html) for easy sharing and presentation.
Scalability:
The use of FAISS for indexing and clustering ensures that the system can handle large-scale datasets efficiently.
Performance Optimization:
Feature normalization (faiss.normalize_L2) is performed during extraction to ensure consistency and improve clustering performance.
Saving the FAISS Index:
The FAISS index is saved locally (clip_faiss_index.index) for potential future retrieval tasks, enhancing the script's utility.
Run the Script:
Execute the script in your Python environment:
bash
python advanced_visualization.py
View the Visualizations:
Open the generated HTML files (confusion_matrix.html and cluster_distribution.html) in your web browser to explore the interactive visualizations.
Conclusion
This enhanced script is now more robust, efficient, and suitable for professional environments. The use of Plotly for visualizations allows for interactive and high-quality presentations, making it ideal for showcasing results to teammates or stakeholders.