{"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/CLIP_cluster.ipynb","timestamp":1760363231133}],"authorship_tag":"ABX9TyNVlcOb40q1uuP5+S31hMRN"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"}},"cells":[{"cell_type":"code","execution_count":null,"metadata":{"id":"G9yAxL_ViF7y"},"outputs":[],"source":["from google.colab import drive\n","drive.mount('/content/drive')"]},{"cell_type":"markdown","source":["Install Required Libraries\n","Run this cell to install the necessary packages. CLIP requires PyTorch, and we'll use scikit-learn for clustering, along with Pillow for image loading and matplotlib for visualization."],"metadata":{"id":"ji2qFha2icZi"}},{"cell_type":"code","source":["!pip install ftfy regex tqdm\n","!pip install git+https://github.com/openai/CLIP.git\n","!pip install scikit-learn matplotlib pillow umap-learn # UMAP is optional for 2D visualization"],"metadata":{"id":"WncaEzzGiaO2"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["Load Images and Extract CLIP Embeddings\n","Replace `/path/to/your/images` with your image directory (e.g., `/content/uploaded_images` for uploaded files or `/content/drive/MyDrive/images` for Drive).\n","\n","This code loads all images (supports JPG, PNG, etc.), preprocesses them, and extracts 512-dimensional embeddings using the ViT-B/32 CLIP model."],"metadata":{"id":"EnqyKHcOilVA"}},{"cell_type":"code","source":["!pip install open_clip_torch # Install if needed\n","\n","import open_clip\n","import torch\n","from PIL import Image\n","import numpy as np\n","import os\n","\n","# Configuration\n","image_dir = '/content/'\n","device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n","model_name = \"ViT-B-32-quickgelu\" # Or \"laion2b_s34b_b79k\" for fine-tuned\n","\n","# Load OpenCLIP model\n","model, _, preprocess = open_clip.create_model_and_transforms(model_name, pretrained=\"laion400m_e32\") # Use 'laion2b_s34b_b88k' for fine-tune\n","model.to(device)\n","\n","# Load images and extract embeddings\n","embeddings = []\n","image_names = []\n","for filename in os.listdir(image_dir):\n"," if filename.lower().endswith(('.png', '.jpg', '.jpeg')):\n"," img_path = os.path.join(image_dir, filename)\n"," try:\n"," image = preprocess(Image.open(img_path)).unsqueeze(0).to(device)\n"," with torch.no_grad():\n"," embedding = model.encode_image(image)\n"," embeddings.append(embedding.cpu().numpy().flatten())\n"," image_names.append(filename)\n"," print(f\"Processed: {filename}\")\n"," except Exception as e:\n"," print(f\"Error: {e}\")\n","\n","embeddings = np.array(embeddings)\n","print(f\"Extracted embeddings for {len(embeddings)} images. Shape: {embeddings.shape}\")"],"metadata":{"id":"LgNEcAlwx_T-"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["Perform Clustering\n","We'll use K-Means clustering on the embeddings. You can choose the number of clusters (`n_clusters`) based on your dataset size (e.g., try 5-10). We'll also compute the silhouette score to evaluate cluster quality (higher is better).\n","\n","For visualization, we'll optionally reduce dimensions to 2D using UMAP."],"metadata":{"id":"HQsc2r-ii6cK"}},{"cell_type":"code","source":["from umap import UMAP # For 2D projection (optional)\n","import os\n","import numpy as np\n","import torch\n","import clip\n","from PIL import Image\n","import matplotlib.pyplot as plt\n","from sklearn.cluster import KMeans\n","from sklearn.metrics import silhouette_score\n","import warnings\n","warnings.filterwarnings('ignore')\n","# Choose number of clusters (experiment with this)\n","n_clusters = 5 # Adjust based on your data\n","\n","# Perform K-Means clustering\n","kmeans = KMeans(n_clusters=n_clusters, random_state=42, n_init=10)\n","cluster_labels = kmeans.fit_predict(embeddings)\n","\n","# Evaluate clustering quality\n","sil_score = silhouette_score(embeddings, cluster_labels)\n","print(f\"Silhouette Score: {sil_score:.3f} (closer to 1 is better)\")\n","\n","# Optional: 2D visualization with UMAP\n","reducer = UMAP(random_state=42, n_components=2)\n","embed_2d = reducer.fit_transform(embeddings)\n","\n","plt.figure(figsize=(10, 8))\n","scatter = plt.scatter(embed_2d[:, 0], embed_2d[:, 1], c=cluster_labels, cmap='tab10', s=50)\n","plt.colorbar(scatter)\n","plt.title(f'2D UMAP Projection of CLIP Embeddings (K={n_clusters} Clusters)')\n","plt.xlabel('UMAP 1')\n","plt.ylabel('UMAP 2')\n","plt.show()"],"metadata":{"id":"WM9wug70jCtR"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["Sort Images into Clusters\n","This creates subdirectories for each cluster and moves/copies the images there. Set `move_files=True` to move (or False to copy)."],"metadata":{"id":"aWSOgPj5jLLI"}},{"cell_type":"code","source":["import shutil\n","\n","# Create cluster directories\n","output_dir = '/content/clusters' # Output base directory (change if needed)\n","os.makedirs(output_dir, exist_ok=True)\n","\n","move_files = False # Set to True to move files, False to copy\n","\n","for i in range(n_clusters):\n"," cluster_dir = os.path.join(output_dir, f'cluster_{i}')\n"," os.makedirs(cluster_dir, exist_ok=True)\n","\n","# Assign and sort images\n","for idx, label in enumerate(cluster_labels):\n"," src_path = image_names[idx]\n"," dst_path = os.path.join(output_dir, f'cluster_{label}', image_names[idx])\n"," if move_files:\n"," shutil.move(src_path, dst_path)\n"," else:\n"," shutil.copy2(src_path, dst_path)\n"," print(f\"Assigned {image_names[idx]} to cluster_{label}\")\n","\n","print(f\"Images sorted into {n_clusters} clusters in '{output_dir}'\")"],"metadata":{"id":"93e1ba60jQw2"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["Visualize Sample Images per Cluster\n","Display a few sample images from each cluster to inspect the results."],"metadata":{"id":"Tg_q68KnjUb5"}},{"cell_type":"code","source":["def display_cluster_samples(cluster_dir, n_samples=3):\n"," images = [f for f in os.listdir(cluster_dir) if f.lower().endswith(('.png', '.jpg', '.jpeg'))][:n_samples]\n"," if not images:\n"," print(f\"No images in {cluster_dir}\")\n"," return\n","\n"," fig, axs = plt.subplots(1, len(images), figsize=(5 * len(images), 5))\n"," if len(images) == 1:\n"," axs = [axs]\n"," for j, img_file in enumerate(images):\n"," img_path = os.path.join(cluster_dir, img_file)\n"," img = Image.open(img_path)\n"," axs[j].imshow(img)\n"," axs[j].set_title(img_file)\n"," axs[j].axis('off')\n"," plt.show()\n","\n","# Display samples from each cluster\n","for i in range(n_clusters):\n"," cluster_dir = os.path.join(output_dir, f'cluster_{i}')\n"," print(f\"\\nSamples from Cluster {i}:\")\n"," display_cluster_samples(cluster_dir)"],"metadata":{"id":"uByZnmR5ja8T"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#@markdown Upload to Google Drive as .zip folder (Be mindful of Google Drive Terms of Service)\n","drive_folder_name = 'my_zip_folder' # @param {type:'string'}\n","\n","%cd /content/\n","!zip -r /content/drive/MyDrive/{drive_folder_name}.zip /content/clusters\n","\n"],"metadata":{"id":"w2Gzortz0NuD"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["Tips and Next Steps\n","- **Choosing `n_clusters`**: Run the clustering cell multiple times with different values and pick the one with the highest silhouette score. Alternatively, use elbow method or silhouette analysis for more advanced selection.\n","- **Alternative Clustering**: For density-based clustering (handles varying cluster sizes better), replace K-Means with HDBSCAN: `!pip install hdbscan` and use `from hdbscan import HDBSCAN; clusterer = HDBSCAN(min_cluster_size=5); cluster_labels = clusterer.fit_predict(embeddings)`.\n","- **Larger Datasets**: If you have thousands of images, batch the embedding extraction to avoid memory issues.\n","- **Custom Prompts**: CLIP is multimodal— you could refine clusters by comparing image embeddings to text prompts (e.g., `model.encode_text(clip.tokenize([\"a photo of a dog\", \"a photo of a car\"]))`).\n","- **Download Results**: Right-click the `/content/clusters` folder in the Colab file browser and download as ZIP."],"metadata":{"id":"YHzdjp6sjeUH"}}]}