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.
TASK :
we have tensor with dim (batch_size , channel, height, weight) , patches (height,weight)
lets assume when we convert into patches we have x numbers of pathches created , out of that 5% of x patches we should add Gaussian_noise with eps of 5%
return tensor(b,c,H,W)
Assistant
python
import torch
import torch.nn.functional as F
from typing import Tuple
import math
def add_random_gaussian_noise_to_patches(
input_tensor: torch.Tensor,
patch_size: Tuple[int, int],
noise_eps: float = 0.05,
noise_fraction: float = 0.05,
seed: int = None
) -> torch.Tensor:
"""
Adds Gaussian noise to a random subset of patches in the input tensor.
Args:
input_tensor (torch.Tensor): A tensor of shape (batch_size, channels, height, width).
patch_size (Tuple[int, int]): The size of each patch as (patch_height, patch_width).
noise_eps (float, optional): The standard deviation of the Gaussian noise. Defaults to 0.05.
noise_fraction (float, optional): The fraction of patches to which noise will be added. Defaults to 0.05.
seed (int, optional): Random seed for reproducibility. Defaults to None.
Returns:
torch.Tensor: The tensor with Gaussian noise added to a subset of patches, maintaining the original shape.
Raises:
ValueError: If the input tensor dimensions are incompatible with the patch size.
TypeError: If the input tensor is not a 4-dimensional torch.Tensor.
"""
if not isinstance(input_tensor, torch.Tensor):
raise TypeError("input_tensor must be a torch.Tensor.")
if input_tensor.dim() != 4:
raise ValueError("input_tensor must be a 4-dimensional tensor (batch_size, channels, height, width).")
batch_size, channels, height, width = input_tensor.shape
patch_height, patch_width = patch_size
if height % patch_height != 0 or width % patch_width != 0:
raise ValueError(
"Height and width of the input tensor must be divisible by the patch size."
)
num_patches_h = height // patch_height
num_patches_w = width // patch_width
total_patches = batch_size * num_patches_h * num_patches_w
# Set random seed if provided for reproducibility
if seed is not None:
torch.manual_seed(seed)
# Determine number of patches to add noise to
num_noisy_patches = math.ceil(total_patches * noise_fraction)
# Generate unique random indices for patches to add noise
noisy_patch_indices = torch.randperm(total_patches)[:num_noisy_patches]
# Reshape input tensor to extract patches
patches = input_tensor.unfold(2, patch_height, patch_height).unfold(3, patch_width, patch_width)
# patches shape: (batch_size, channels, num_patches_h, num_patches_w, patch_height, patch_width)
patches = patches.contiguous().view(batch_size, channels, -1, patch_height, patch_width)
# patches shape: (batch_size, channels, total_patches_per_batch, patch_height, patch_width)
# Reshape to (batch_size * total_patches_per_batch, channels, patch_height, patch_width)
patches = patches.view(-1, channels, patch_height, patch_width)
# Create a mask for patches to add noise
noise_mask = torch.zeros(patches.size(0), dtype=torch.bool)
noise_mask[noisy_patch_indices] = True
# Generate Gaussian noise
noise = torch.randn_like(patches) * noise_eps
# Add noise to selected patches
patches[noise_mask] += noise[noise_mask]
# Reshape patches back to original tensor shape
patches = patches.view(batch_size, num_patches_h, num_patches_w, channels, patch_height, patch_width)
patches = patches.permute(0, 3, 1, 4, 2, 5).contiguous()
# patches shape: (batch_size, channels, num_patches_h, patch_height, num_patches_w, patch_width)
# Fold patches back into the original tensor shape
output_tensor = patches.view(
batch_size,
channels,
num_patches_h * patch_height,
num_patches_w * patch_width
)
return output_tensor
Example Usage
python
def main():
# Example tensor with shape (batch_size=2, channels=3, height=8, width=8)
batch_size = 2
channels = 3
height = 8
width = 8
patch_size = (4, 4) # Each patch is 4x4
noise_eps = 0.05
noise_fraction = 0.05
seed = 42
input_tensor = torch.ones((batch_size, channels, height, width))
try:
output_tensor = add_random_gaussian_noise_to_patches(
input_tensor=input_tensor,
patch_size=patch_size,
noise_eps=noise_eps,
noise_fraction=noise_fraction,
seed=seed
)
print("Original Tensor:\n", input_tensor)
print("\nOutput Tensor with Noise added to 5% of patches:\n", output_tensor)
except (ValueError, TypeError) as e:
print(f"Error: {e}")
if __name__ == "__main__":
main()
Explanation
Function Definition:
The function add_random_gaussian_noise_to_patches takes an input tensor and adds Gaussian noise to a specified fraction of its patches.
Parameters:
input_tensor: The input tensor with shape (batch_size, channels, height, width).
patch_size: A tuple specifying the height and width of each patch.
noise_eps: The standard deviation of the Gaussian noise to be added.
noise_fraction: The fraction of total patches to which noise will be added.
seed: An optional parameter to set the random seed for reproducibility.
Error Handling:
The function checks if the input tensor is a 4-dimensional torch.Tensor.
It verifies that the height and width of the tensor are divisible by the patch size. If not, it raises a ValueError.
If the input does not meet the required conditions, appropriate exceptions are raised with meaningful error messages.
Processing Steps:
Patch Extraction: The tensor is unfolded to extract patches based on the provided patch_size. This is achieved using the unfold method, which creates overlapping windows. The patches are then reshaped to a suitable format for processing.
Selecting Patches for Noise: Using torch.randperm, a random permutation of patch indices is generated, and the top num_noisy_patches indices are selected to receive noise.
Adding Gaussian Noise: Gaussian noise with standard deviation noise_eps is generated and added to the selected patches.
Reconstructing the Tensor: After adding noise, the patches are reshaped and permuted to their original spatial arrangement using view and permute. The final tensor maintains the original shape (batch_size, channels, height, width).
Example Usage:
An example is provided in the main function to demonstrate how to use the add_random_gaussian_noise_to_patches function.
A sample tensor of ones is created, and the function is called to add Gaussian noise to 5% of its patches.