Tuesday, April 15, 2025

उन्नत मल्टी-हेड अव्यक्त ध्यान और ठीक-ठीक दाने वाले विशेषज्ञ विभाजन के लिए एक कोडिंग कार्यान्वयन – Gadgets Solutions

-

इस ट्यूटोरियल में, हम एक उपन्यास डीप लर्निंग एप्रोच का पता लगाते हैं, जो ठीक-ठीक दाने वाले विशेषज्ञ विभाजन के साथ मल्टी-हेड अव्यक्त ध्यान को जोड़ती है। अव्यक्त ध्यान की शक्ति का उपयोग करके, मॉडल परिष्कृत विशेषज्ञ सुविधाओं का एक सेट सीखता है जो उच्च-स्तरीय संदर्भ और स्थानिक विवरणों को पकड़ते हैं, अंततः सटीक प्रति-पिक्सेल विभाजन को सक्षम करते हैं। इस कार्यान्वयन के दौरान, हम आपको Google Colab पर Pytorch का उपयोग करके एंड-टू-एंड कार्यान्वयन के माध्यम से चलेंगे, प्रमुख बिल्डिंग ब्लॉकों का प्रदर्शन करेंगे, एक साधारण कन्व्यूशनल एनकोडर से ध्यान तंत्र के लिए जो विभाजन के लिए महत्वपूर्ण सुविधाओं को एकत्र करते हैं। यह हैंड्स-ऑन गाइड आपको एक प्रारंभिक बिंदु के रूप में सिंथेटिक डेटा का उपयोग करके उन्नत विभाजन तकनीकों के साथ समझने और प्रयोग करने में मदद करने के लिए डिज़ाइन किया गया है।

import torch
import torch.nn as nn
import torch.nn.functional as F
import matplotlib.pyplot as plt
import numpy as np


torch.manual_seed(42)

हम आवश्यक पुस्तकालयों जैसे कि गहरी सीखने के लिए पिटोरच, संख्यात्मक संगणना के लिए संख्या, और विज़ुअलाइज़ेशन के लिए मैटप्लोटलिब आयात करते हैं, तंत्रिका नेटवर्क के निर्माण के लिए एक मजबूत वातावरण स्थापित करते हैं। Aldo, Torch.manual_seed (42) सभी मशाल-आधारित यादृच्छिक संख्या जनरेटर के लिए यादृच्छिक बीज को ठीक करके प्रतिलिपि प्रस्तुत करने योग्य परिणाम सुनिश्चित करता है।

class SimpleEncoder(nn.Module):
    """
    A basic CNN encoder that extracts feature maps from an input image.
    Two convolutional layers with ReLU activations and max-pooling are used
    to reduce spatial dimensions.
    """
    def __init__(self, in_channels=3, feature_dim=64):
        super().__init__()
        self.conv1 = nn.Conv2d(in_channels, 32, kernel_size=3, padding=1)
        self.conv2 = nn.Conv2d(32, feature_dim, kernel_size=3, padding=1)
        self.pool = nn.MaxPool2d(2, 2)
       
    def forward(self, x):
        x = F.relu(self.conv1(x))
        x = self.pool(x)  
        x = F.relu(self.conv2(x))
        x = self.pool(x)  
        return x

SIMPLENCODER वर्ग एक बुनियादी कन्व्यूशनल न्यूरल नेटवर्क को लागू करता है जो एक इनपुट छवि से मैप्स को निकालता है। यह रिले सक्रियणों और अधिकतम-पूलिंग के साथ संयुक्त रूप से स्थानिक आयामों को कम करने के लिए दो कन्व्यूशनल परतों को नियुक्त करता है, इस प्रकार बाद के प्रसंस्करण के लिए छवि प्रतिनिधित्व को सरल बनाता है।

class LatentAttention(nn.Module):
    """
    This module learns a set of latent vectors (the experts) and refines them
    using multi-head attention on the input features.
   
    Input:
        x: A flattened feature tensor of shape (B, N, feature_dim),
           where N is the number of spatial tokens.
    Output:
        latent_output: The refined latent expert representations of shape (B, num_latents, latent_dim).
    """
    def __init__(self, feature_dim, latent_dim, num_latents, num_heads):
        super().__init__()
        self.num_latents = num_latents
        self.latent_dim = latent_dim
        self.latents = nn.Parameter(torch.randn(num_latents, latent_dim))
        self.key_proj = nn.Linear(feature_dim, latent_dim)
        self.value_proj = nn.Linear(feature_dim, latent_dim)
        self.query_proj = nn.Linear(latent_dim, latent_dim)
        self.attention = nn.MultiheadAttention(embed_dim=latent_dim, num_heads=num_heads, batch_first=True)
       
    def forward(self, x):
        B, N, _ = x.shape
        keys = self.key_proj(x)      
        values = self.value_proj(x)  
        queries = self.latents.unsqueeze(0).expand(B, -1, -1)  
        queries = self.query_proj(queries)
       
        latent_output, _ = self.attention(query=queries, key=keys, value=values)
        return latent_output 

अव्यक्तता मॉड्यूल एक अव्यक्त ध्यान तंत्र को लागू करता है जहां अव्यक्त विशेषज्ञ वैक्टर का एक निश्चित सेट कुंजियों और मूल्यों के रूप में अनुमानित इनपुट सुविधाओं का उपयोग करके मल्टी-हेड ध्यान के माध्यम से परिष्कृत किया जाता है। फॉरवर्ड पास में, ये अव्यक्त वैक्टर (क्वेरी) रूपांतरित इनपुट में भाग लेते हैं, जिसके परिणामस्वरूप परिष्कृत विशेषज्ञ अभ्यावेदन होते हैं जो अंतर्निहित सुविधा निर्भरता को कैप्चर करते हैं।

class ExpertSegmentation(nn.Module):
    """
    For fine-grained segmentation, each pixel (or patch) feature first projects into the latent space.
    Then, it attends over the latent experts (the output of the LatentAttention module) to obtain a refined representation.
    Finally, a segmentation head projects the attended features to per-pixel class logits.
   
    Input:
        x: Flattened pixel features from the encoder (B, N, feature_dim)
        latent_experts: Latent representations from the attention module (B, num_latents, latent_dim)
    Output:
        logits: Segmentation logits (B, N, num_classes)
    """
    def __init__(self, feature_dim, latent_dim, num_heads, num_classes):
        super().__init__()
        self.pixel_proj = nn.Linear(feature_dim, latent_dim)
        self.attention = nn.MultiheadAttention(embed_dim=latent_dim, num_heads=num_heads, batch_first=True)
        self.segmentation_head = nn.Linear(latent_dim, num_classes)
       
    def forward(self, x, latent_experts):
        queries = self.pixel_proj(x)  
        attn_output, _ = self.attention(query=queries, key=latent_experts, value=latent_experts)
        logits = self.segmentation_head(attn_output)  
        return logits

विशेषज्ञसेशन मॉड्यूल पहले अव्यक्त स्थान में उन्हें प्रोजेक्ट करके और फिर अव्यक्त विशेषज्ञ अभ्यावेदन का उपयोग करके बहु-सिर पर ध्यान देने के लिए विभाजन के लिए पिक्सेल-स्तरीय सुविधाओं को परिष्कृत करता है। अंत में, यह प्रति-पिक्सेल वर्ग लॉगिट उत्पन्न करने के लिए एक विभाजन सिर के माध्यम से इन परिष्कृत सुविधाओं को मैप करता है।

class SegmentationModel(nn.Module):
    """
    The final model that ties together the encoder, latent attention module,
    and the expert segmentation head into one end-to-end trainable architecture.
    """
    def __init__(self, in_channels=3, feature_dim=64, latent_dim=64, num_latents=16, num_heads=4, num_classes=2):
        super().__init__()
        self.encoder = SimpleEncoder(in_channels, feature_dim)
        self.latent_attn = LatentAttention(feature_dim=feature_dim, latent_dim=latent_dim,
                                           num_latents=num_latents, num_heads=num_heads)
        self.expert_seg = ExpertSegmentation(feature_dim=feature_dim, latent_dim=latent_dim,
                                             num_heads=num_heads, num_classes=num_classes)
       
    def forward(self, x):
        features = self.encoder(x)
        B, F, H, W = features.shape
        features_flat = features.view(B, F, H * W).permute(0, 2, 1)  
        latent_experts = self.latent_attn(features_flat)  
        logits_flat = self.expert_seg(features_flat, latent_experts)  
        logits = logits_flat.permute(0, 2, 1).view(B, -1, H, W)
        return logits

सेगमेंटमोडेल क्लास सीएनएन एनकोडर, अव्यक्त ध्यान मॉड्यूल और विशेषज्ञ विभाजन सिर को एकीकृत, एंड-टू-एंड ट्रेन करने योग्य नेटवर्क में एकीकृत करता है। फॉरवर्ड पास के दौरान, मॉडल इनपुट छवि को फ़ीचर मैप्स, फ्लैटेंस में एन्कोड करता है और इन सुविधाओं को अव्यक्त ध्यान प्रसंस्करण के लिए बदल देता है, और अंत में प्रति-पिक्सेल क्लास लॉगिट्स का उत्पादन करने के लिए विशेषज्ञ विभाजन का उपयोग करता है।

model = SegmentationModel()
x_dummy = torch.randn(2, 3, 128, 128)  
output = model(x_dummy)
print("Output shape:", output.shape)

हम विभाजन मॉडल को तत्काल करते हैं और इसके माध्यम से दो 128 × 128 आरजीबी छवियों के एक डमी बैच को पास करते हैं। मुद्रित आउटपुट आकार पुष्टि करता है कि मॉडल इनपुट को सही ढंग से संसाधित करता है और अपेक्षित आयामों के साथ विभाजन मानचित्रों का उत्पादन करता है।

def generate_synthetic_data(batch_size, channels, height, width, num_classes):
    """
    Generates a batch of synthetic images and corresponding segmentation targets.
    The segmentation targets have lower resolution reflecting the encoder’s output size.
    """
    x = torch.randn(batch_size, channels, height, width)
    target_h, target_w = height // 4, width // 4
    y = torch.randint(0, num_classes, (batch_size, target_h, target_w))
    return x, y


batch_size = 4
channels = 3
height = 128
width = 128
num_classes = 2


model = SegmentationModel(in_channels=channels, num_classes=num_classes)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)


num_iterations = 100
model.train()
for iteration in range(num_iterations):
    x_batch, y_batch = generate_synthetic_data(batch_size, channels, height, width, num_classes)
    optimizer.zero_grad()
    logits = model(x_batch)  # logits shape: (B, num_classes, H/4, W/4)
    loss = criterion(logits, y_batch)
    loss.backward()
    optimizer.step()
    if iteration % 10 == 0:
        print(f"Iteration {iteration}: Loss = {loss.item():.4f}")

हम एक सिंथेटिक डेटा जनरेटर को परिभाषित करते हैं जो एनकोडर के आउटपुट रिज़ॉल्यूशन से मेल खाने के लिए यादृच्छिक छवियों और इसी कम-रिज़ॉल्यूशन सेगमेंटेशन लक्ष्य का उत्पादन करता है। फिर, हम क्रॉस-एंट्रॉपी लॉस और एडम ऑप्टिमाइज़र का उपयोग करके 100 पुनरावृत्तियों के लिए विभाजन मॉडल को स्थापित और प्रशिक्षित करते हैं। प्रशिक्षण प्रगति की निगरानी के लिए नुकसान मूल्यों को हर 10 पुनरावृत्तियों को मुद्रित किया जाता है।

model.eval()
x_vis, y_vis = generate_synthetic_data(1, channels, height, width, num_classes)
with torch.no_grad():
    logits_vis = model(x_vis)
    pred = torch.argmax(logits_vis, dim=1)  # shape: (1, H/4, W/4)


img_np = x_vis(0).permute(1, 2, 0).numpy()
gt_np = y_vis(0).numpy()
pred_np = pred(0).numpy()


fig, axs = plt.subplots(1, 3, figsize=(12, 4))
axs(0).imshow((img_np - img_np.min()) / (img_np.max()-img_np.min()))
axs(0).set_title("Input Image")
axs(1).imshow(gt_np, cmap='jet')
axs(1).set_title("Ground Truth")
axs(2).imshow(pred_np, cmap='jet')
axs(2).set_title("Predicted Segmentation")
for ax in axs:
    ax.axis('off')
plt.tight_layout()
plt.show()

मूल्यांकन मोड में, हम एक सिंथेटिक नमूना उत्पन्न करते हैं, टॉर्च.नो_ग्राड () का उपयोग करके मॉडल के विभाजन की भविष्यवाणी की गणना करते हैं, और फिर टेन्सर को न्यूमपी सरणियों में परिवर्तित करते हैं। अंत में, यह इनपुट छवि, जमीनी सत्य, और पूर्वानुमानित विभाजन मानचित्रों को मैटप्लोटलिब का उपयोग करके साइड की कल्पना करता है।

अंत में, हमने ठीक-ठीक दाने वाले विशेषज्ञ विभाजन के साथ-साथ मल्टी-हेड लेटेंट ध्यान को लागू करने पर एक गहन नज़र डाली, यह दिखाते हुए कि कैसे ये घटक विभाजन के प्रदर्शन को बेहतर बनाने के लिए एक साथ काम कर सकते हैं। एक बुनियादी सीएनएन एनकोडर के निर्माण से शुरू, हम अव्यक्त ध्यान तंत्रों के एकीकरण के माध्यम से चले गए और पिक्सेल-स्तरीय वर्गीकरण के लिए सुविधा अभ्यावेदन को परिष्कृत करने में उनकी भूमिका का प्रदर्शन किया। हम आपको इस नींव पर निर्माण करने के लिए प्रोत्साहित करते हैं, वास्तविक दुनिया के डेटासेट पर मॉडल का परीक्षण करते हैं, और आगे विभाजन कार्यों के लिए गहन सीखने में ध्यान-आधारित दृष्टिकोण की क्षमता का पता लगाते हैं।


यह रहा कोलैब नोटबुक। इसके अलावा, हमें फॉलो करना न भूलें ट्विटर और हमारे साथ जुड़ें तार -चैनल और लिंक्डइन जीआरओयूपी। हमारे साथ जुड़ने के लिए मत भूलना 85K+ एमएल सबरेडिट


उन्नत मल्टी-हेड अव्यक्त ध्यान और ठीक-ठीक दाने वाले विशेषज्ञ विभाजन के लिए एक कोडिंग कार्यान्वयन
 – Gadgets Solutions

Asif Razzaq MarkTechPost Media Inc के सीईओ हैं .. एक दूरदर्शी उद्यमी और इंजीनियर के रूप में, ASIF सामाजिक अच्छे के लिए कृत्रिम बुद्धिमत्ता की क्षमता का उपयोग करने के लिए प्रतिबद्ध है। उनका सबसे हालिया प्रयास एक आर्टिफिशियल इंटेलिजेंस मीडिया प्लेटफॉर्म, मार्कटेकपोस्ट का शुभारंभ है, जो मशीन लर्निंग और डीप लर्निंग न्यूज के अपने गहन कवरेज के लिए खड़ा है, जो तकनीकी रूप से ध्वनि और आसानी से एक व्यापक दर्शकों द्वारा समझ में आता है। मंच 2 मिलियन से अधिक मासिक विचारों का दावा करता है, दर्शकों के बीच अपनी लोकप्रियता को दर्शाता है।

LEAVE A REPLY

Please enter your comment!
Please enter your name here

FOLLOW US

150,000FansLike
35,000FollowersFollow
100,000SubscribersSubscribe

Related Stories

Translate »