### Install VisualTorch via pip Source: https://visualtorch.readthedocs.io/en/latest/_sources/markdown/get_started/installation.md Use this command to install the latest stable release of VisualTorch from PyPI. This command also installs all required dependencies. ```bash pip install visualtorch ``` -------------------------------- ### Install VisualTorch from Source Source: https://visualtorch.readthedocs.io/en/latest/_sources/markdown/get_started/installation.md Install the latest development version of VisualTorch directly from its GitHub repository. This method is recommended if you need the most up-to-date features. ```bash pip install git+https://github.com/Visual-OpenLLaMA/VisualTorch.git ``` -------------------------------- ### Install Development Requirements Source: https://visualtorch.readthedocs.io/en/latest/_sources/markdown/developer_guides/contributing.md Install the project's development dependencies using pip. The '-e .' flag installs the package in editable mode. ```bash pip install -e .[dev] ``` -------------------------------- ### VisualTorch Dependencies Source: https://visualtorch.readthedocs.io/en/latest/markdown/get_started/installation.html These are the core dependencies that will be automatically installed along with VisualTorch when installing from source or PyPI. ```bash pillow>=10.0.0 numpy>=1.18.1 aggdraw>=1.3.11 torch>=2.0.0 ``` -------------------------------- ### Install and Configure Pre-commit Hooks Source: https://visualtorch.readthedocs.io/en/latest/_sources/markdown/developer_guides/contributing.md Install the pre-commit framework to automatically run code quality checks on commit. This ensures code consistency. ```bash pre-commit install ``` -------------------------------- ### VisualTorch Dependencies Source: https://visualtorch.readthedocs.io/en/latest/_sources/markdown/get_started/installation.md This command lists the essential dependencies that will be automatically installed when you install VisualTorch using pip. ```bash pip install -r requirements.txt ``` -------------------------------- ### Visualize Basic Custom CNN Model Source: https://visualtorch.readthedocs.io/en/latest/usage_examples/layered/plot_basic_custom.html Defines a simple CNN, creates an instance, and visualizes its architecture using `visualtorch.layered_view`. Requires Matplotlib for display. Ensure PyTorch and VisualTorch are installed. ```python import matplotlib.pyplot as plt import torch import torch.nn.functional as func import visualtorch from torch import nn # Example of a simple CNN model class SimpleCNN(nn.Module): """Simple CNN Model.""" def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(3, 16, kernel_size=3, padding=1) self.conv2 = nn.Conv2d(16, 32, kernel_size=3, padding=1) self.conv3 = nn.Conv2d(32, 64, kernel_size=3, padding=1) self.fc1 = nn.Linear(64 * 28 * 28, 128) self.fc2 = nn.Linear(128, 10) def forward(self, x: torch.Tensor) -> torch.Tensor: """Define the forward pass.""" x = self.conv1(x) x = func.relu(x) x = func.max_pool2d(x, 2, 2) x = self.conv2(x) x = func.relu(x) x = func.max_pool2d(x, 2, 2) x = self.conv3(x) x = func.relu(x) x = func.max_pool2d(x, 2, 2) x = x.view(x.size(0), -1) x = self.fc1(x) x = func.relu(x) return self.fc2(x) # Create an instance of the SimpleCNN model = SimpleCNN() input_shape = (1, 3, 224, 224) img = visualtorch.layered_view(model, input_shape=input_shape, legend=True) plt.axis("off") plt.tight_layout() plt.imshow(img) plt.show() ``` -------------------------------- ### Visualize Basic Sequential Model Source: https://visualtorch.readthedocs.io/en/latest/_downloads/7d2feed9aadf11bc362f5ec33175be75/plot_basic_sequential.ipynb Visualize a PyTorch nn.Sequential model, such as a CNN, by providing the model and an example input shape. This helps in understanding the layer structure and data flow. ```python import matplotlib.pyplot as plt import visualtorch from torch import nn # Example of a simple CNN model using nn.Sequential model = nn.Sequential( nn.Conv2d(3, 16, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Conv2d(16, 32, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Conv2d(32, 64, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Flatten(), nn.Linear(64 * 28 * 28, 256), # Adjusted the input size for the Linear layer nn.ReLU(), nn.Linear(256, 10), # Assuming 10 output classes ) input_shape = (1, 3, 224, 224) img = visualtorch.layered_view(model, input_shape=input_shape, legend=True) plt.axis("off") plt.tight_layout() plt.imshow(img) plt.show() ``` -------------------------------- ### Define and Visualize a Simple CNN Source: https://visualtorch.readthedocs.io/en/latest/_downloads/9d92539c8858d8d4d6661cdabaf75845/plot_basic_custom.ipynb Define a simple CNN model and visualize its structure using visualtorch. Ensure matplotlib and torch are installed. This snippet requires a PyTorch model definition and then uses visualtorch.layered_view to generate the visualization. ```python import matplotlib.pyplot as plt import torch import torch.nn.functional as func import visualtorch from torch import nn # Example of a simple CNN model class SimpleCNN(nn.Module): """Simple CNN Model.""" def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(3, 16, kernel_size=3, padding=1) self.conv2 = nn.Conv2d(16, 32, kernel_size=3, padding=1) self.conv3 = nn.Conv2d(32, 64, kernel_size=3, padding=1) self.fc1 = nn.Linear(64 * 28 * 28, 128) self.fc2 = nn.Linear(128, 10) def forward(self, x: torch.Tensor) -> torch.Tensor: """Define the forward pass.""" x = self.conv1(x) x = func.relu(x) x = func.max_pool2d(x, 2, 2) x = self.conv2(x) x = func.relu(x) x = func.max_pool2d(x, 2, 2) x = self.conv3(x) x = func.relu(x) x = func.max_pool2d(x, 2, 2) x = x.view(x.size(0), -1) x = self.fc1(x) x = func.relu(x) return self.fc2(x) # Create an instance of the SimpleCNN model = SimpleCNN() input_shape = (1, 3, 224, 224) img = visualtorch.layered_view(model, input_shape=input_shape, legend=True) plt.axis("off") plt.tight_layout() plt.imshow(img) plt.show() ``` -------------------------------- ### Visualize CNN with Custom Spacing Source: https://visualtorch.readthedocs.io/en/latest/_downloads/4075b6ed79648c2db7f8e9346af90462/plot_custom_spacing.ipynb Visualizes a simple CNN model with custom spacing between layers using visualtorch.layered_view. Ensure matplotlib is installed for displaying the image. ```python import matplotlib.pyplot as plt import visualtorch from torch import nn # Example of a simple CNN model using nn.Sequential model = nn.Sequential( nn.Conv2d(3, 16, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Conv2d(16, 32, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Conv2d(32, 64, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Flatten(), nn.Linear(64 * 28 * 28, 256), # Adjusted the input size for the Linear layer nn.ReLU(), nn.Linear(256, 10), # Assuming 10 output classes ) input_shape = (1, 3, 224, 224) img = visualtorch.layered_view(model, input_shape=input_shape, spacing=50) plt.axis("off") plt.tight_layout() plt.imshow(img) plt.show() ``` -------------------------------- ### Visualize PyTorch Model in 2D Source: https://visualtorch.readthedocs.io/en/latest/_downloads/e285bd70253c5fcd2a79a42b0b3f81ed/plot_2d_view.ipynb Generates and displays a 2D layered view of a PyTorch model. Ensure matplotlib is installed for displaying the image. The `draw_volume=False` argument is used to create a 2D representation. ```python import matplotlib.pyplot as plt import visualtorch from torch import nn # Example of a simple CNN model using nn.Sequential model = nn.Sequential( nn.Conv2d(3, 16, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Conv2d(16, 32, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Conv2d(32, 64, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Flatten(), nn.Linear(64 * 28 * 28, 256), # Adjusted the input size for the Linear layer nn.ReLU(), nn.Linear(256, 10), # Assuming 10 output classes ) input_shape = (1, 3, 224, 224) img = visualtorch.layered_view(model, input_shape=input_shape, draw_volume=False) plt.axis("off") plt.tight_layout() plt.imshow(img) plt.show() ``` -------------------------------- ### Visualize PyTorch Model with Custom Layer Spacing Source: https://visualtorch.readthedocs.io/en/latest/_downloads/e7dda8933732e69cea3c6728de9158e5/plot_custom_spacing_layers.ipynb Define a simple PyTorch model and visualize its graph structure with custom spacing between layers. This is useful for improving the readability of complex or wide networks. Ensure matplotlib and visualtorch are installed. ```python import matplotlib.pyplot as plt import torch import visualtorch from torch import nn class SimpleDense(nn.Module): """Simple Dense Model.""" def __init__(self) -> None: super().__init__() self.h0 = nn.Linear(4, 8) self.h1 = nn.Linear(8, 8) self.h2 = nn.Linear(8, 4) self.out = nn.Linear(4, 2) def forward(self, x: torch.Tensor) -> torch.Tensor: """Define the forward pass.""" x = self.h0(x) x = self.h1(x) x = self.h2(x) return self.out(x) model = SimpleDense() input_shape = (1, 4) img = visualtorch.graph_view(model, input_shape, layer_spacing=500) plt.axis("off") plt.tight_layout() plt.imshow(img) plt.show() ``` -------------------------------- ### Visualize Basic Dense Model Source: https://visualtorch.readthedocs.io/en/latest/_downloads/af82a0cd0ebe397a58a94d3f62bca47d/plot_basic_dense.ipynb Define a simple dense model and visualize its architecture using visualtorch.graph_view. This is useful for understanding the structure of sequential models. ```python import matplotlib.pyplot as plt import torch import visualtorch from torch import nn class SimpleDense(nn.Module): """Simple Dense Model.""" def __init__(self) -> None: super().__init__() self.h0 = nn.Linear(4, 8) self.h1 = nn.Linear(8, 8) self.h2 = nn.Linear(8, 4) self.out = nn.Linear(4, 2) def forward(self, x: torch.Tensor) -> torch.Tensor: """Define the forward pass.""" x = self.h0(x) x = self.h1(x) x = self.h2(x) return self.out(x) model = SimpleDense() input_shape = (1, 4) img = visualtorch.graph_view(model, input_shape) plt.axis("off") plt.tight_layout() plt.imshow(img) plt.show() ``` -------------------------------- ### Run Tests and Quality Checks Source: https://visualtorch.readthedocs.io/en/latest/_sources/markdown/developer_guides/contributing.md Execute the test suite using pytest and run pre-commit checks on all files. This ensures code quality and test coverage. ```bash pre-commit run --all-files pytest tests/ ``` -------------------------------- ### Create and Activate Conda Environment Source: https://visualtorch.readthedocs.io/en/latest/_sources/markdown/developer_guides/contributing.md Use this command to create a new Conda environment named 'visualtorch_env' with Python 3.10 and then activate it. ```bash conda create -n visualtorch_env python=3.10 conda activate visualtorch_env ``` -------------------------------- ### graph_view() Source: https://visualtorch.readthedocs.io/en/latest/markdown/api_references/graph.html Generates an architecture visualization for a given linear PyTorch model in a graph style. ```APIDOC ## graph_view() ### Description Generates an architecture visualization for a given linear PyTorch model in a graph style. ### Parameters #### Path Parameters - **model** (_torch.nn.Module_) – A PyTorch model that will be visualized. - **input_shape** (_tuple_) – The shape of the input tensor. - **to_file** (_str_ _,__optional_) – Path to the file to write the created image to. If the image does not exist yet, it will be created, else overwritten. Image type is inferred from the file ending. Providing None will disable writing. - **color_map** (_dict_ _,__optional_) – Dict defining fill and outline for each layer by class type. Will fallback to default values for not specified classes. - **node_size** (_int_ _,__optional_) – Size in pixels each node will have. - **background_fill** (_Any_ _,__optional_) – Color for the image background. Can be str or (R,G,B,A). - **padding** (_int_ _,__optional_) – Distance in pixels before the first and after the last layer. - **layer_spacing** (_int_ _,__optional_) – Spacing in pixels between two layers. - **node_spacing** (_int_ _,__optional_) – Spacing in pixels between nodes. - **connector_fill** (_Any_ _,__optional_) – Color for the connectors. Can be str or (R,G,B,A). - **connector_width** (_int_ _,__optional_) – Line-width of the connectors in pixels. - **ellipsize_after** (_int_ _,__optional_) – Maximum number of neurons per layer to draw. If a layer is exceeding this, the remaining neurons will be drawn as ellipses. - **show_neurons** (_bool_ _,__optional_) – If True a node for each neuron in supported layers is created (constrained by ellipsize_after), else each layer is represented by a node. - **opacity** (_int_ _,__optional_) – Transparency of the color (0 ~ 255). ### Returns Generated architecture image. ### Return type Image.Image ``` -------------------------------- ### Run Tests with Pytest Source: https://visualtorch.readthedocs.io/en/latest/markdown/developer_guides/contributing.html Execute the project's test suite using pytest to verify the correctness of new or modified code. ```bash pytest tests/ ``` -------------------------------- ### lenet_view Source: https://visualtorch.readthedocs.io/en/latest/markdown/api_references/lenet_style.html Generates a LeNet style architecture visualization for a given PyTorch model. ```APIDOC ## lenet_view() ### Description Generate a LeNet style architecture visualization for a given torch model. TODO: remove unnecessary arguments for this LeNet style architecture. ### Parameters #### Path Parameters - **model** (torch.nn.Module) - A torch model that will be visualized. - **input_shape** (tuple) - The shape of the input tensor (default: (1, 3, 224, 224)). #### Query Parameters - **to_file** (str, optional) - Path to the file to write the created image. Overwrite if exist. Image type is inferred from the file extension. Providing None will disable writing. - **min_z** (int, optional) - Minimum size in pixels that a layer will have along the z-axis. - **min_xy** (int, optional) - Minimum size in pixels that a layer will have along the x and y axes. - **max_xy** (int, optional) - Maximum size in pixels that a layer will have along the x and y axes. - **scale_z** (float, optional) - Scalar multiplier for the size of each layer along the z-axis. - **scale_xy** (float, optional) - Scalar multiplier for the size of each layer along the x and y axes. - **type_ignore** (list, optional) - List of layer types in the torch model to ignore during drawing. - **index_ignore** (list, optional) - List of layer indexes in the torch model to ignore during drawing. - **color_map** (dict, optional) - Dictionary defining fill and outline colors for each layer by class type. Will fallback to default values for unspecified classes. - **one_dim_orientation** (str, optional) - Axis on which one-dim layers should be drawn. E.g., ‘x’, ‘y’, or ‘z’. - **background_fill** (str or tuple, optional) - Background color for the image. A string or a tuple (R, G, B, A). - **padding** (int, optional) - Distance in pixels before the first and after the last layer. - **spacing** (int, optional) - Spacing in pixels between two layers. - **draw_funnel** (bool, optional) - If True, a funnel will be drawn between consecutive layers. - **shade_step** (int, optional) - Deviation in lightness for drawing shades (only in volumetric view). - **font** (PIL.ImageFont, optional) - Font that will be used for the legend. If None, default font will be used. - **font_color** (str or tuple, optional) - Color for the font if used. Can be a string or a tuple (R, G, B, A). - **opacity** (int) - Transparency of the color (0 ~ 255). - **offset_z** (int) - control the offset of overlapping between channels. ### Response #### Success Response (200) - **Image** (PIL.Image) - An Image object representing the generated architecture visualization. ``` -------------------------------- ### Visualize CNN Model with Custom Opacity Source: https://visualtorch.readthedocs.io/en/latest/_downloads/5fcf96415a1f45629a473a7095b0fd7b/plot_custom_opacity.ipynb This snippet visualizes a simple CNN model with custom opacity. It requires matplotlib and visualtorch. Ensure your model and input shape are correctly defined. ```python import matplotlib.pyplot as plt import visualtorch from torch import nn # Example of a simple CNN model using nn.Sequential model = nn.Sequential( nn.Conv2d(3, 16, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Conv2d(16, 32, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Conv2d(32, 64, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Flatten(), nn.Linear(64 * 28 * 28, 256), # Adjusted the input size for the Linear layer nn.ReLU(), nn.Linear(256, 10), # Assuming 10 output classes ) input_shape = (1, 3, 224, 224) img = visualtorch.layered_view(model, input_shape=input_shape, opacity=100) plt.axis("off") plt.tight_layout() plt.imshow(img) plt.show() ``` -------------------------------- ### Visualize LeNet Style Sequential Model Source: https://visualtorch.readthedocs.io/en/latest/usage_examples/lenet_style/plot_basic_sequential_lenet_style.html Use visualtorch.lenet_view to visualize a PyTorch nn.Sequential model. Ensure matplotlib is imported for displaying the visualization. ```python import matplotlib.pyplot as plt import visualtorch from torch import nn # Example of a simple CNN model using nn.Sequential model = nn.Sequential( nn.Conv2d(3, 8, kernel_size=3, padding=1), nn.MaxPool2d(2, 2), nn.Conv2d(8, 16, kernel_size=3, padding=1), nn.MaxPool2d(2, 2), ) input_shape = (1, 3, 128, 128) img = visualtorch.lenet_view(model, input_shape=input_shape) plt.axis("off") plt.tight_layout() plt.imshow(img) plt.show() ``` -------------------------------- ### Visualize Model with Custom Node Colors Source: https://visualtorch.readthedocs.io/en/latest/_downloads/dc6dfac20b24f8522dfd4e4d45888f6f/plot_custom_node_color.ipynb Define a simple PyTorch model, create a color map to assign specific colors to layer types (e.g., nn.Linear), and then use visualtorch.graph_view to generate and display the visualization with the custom colors. Ensure matplotlib is used to display the generated image. ```python from collections import defaultdict import matplotlib.pyplot as plt import torch import visualtorch from torch import nn class SimpleDense(nn.Module): """Simple Dense Model.""" def __init__(self) -> None: super().__init__() self.h0 = nn.Linear(4, 8) self.h1 = nn.Linear(8, 8) self.h2 = nn.Linear(8, 4) self.out = nn.Linear(4, 2) def forward(self, x: torch.Tensor) -> torch.Tensor: """Define the forward pass.""" x = self.h0(x) x = self.h1(x) x = self.h2(x) return self.out(x) model = SimpleDense() input_shape = (1, 4) color_map: dict = defaultdict(dict) color_map[nn.Linear]["fill"] = "#98FB98" img = visualtorch.graph_view(model, input_shape, color_map=color_map) plt.axis("off") plt.tight_layout() plt.imshow(img) plt.show() ``` -------------------------------- ### Visualize Model with Custom Node Size Source: https://visualtorch.readthedocs.io/en/latest/_downloads/735f34eeb8a96454bb8d7f9c0cbb20ba/plot_custom_node_size.ipynb Define a simple PyTorch model and visualize its graph structure using visualtorch, specifying a custom node size. This is useful for highlighting specific layers or emphasizing the complexity of certain parts of the network. ```python import matplotlib.pyplot as plt import torch import visualtorch from torch import nn class SimpleDense(nn.Module): """Simple Dense Model.""" def __init__(self) -> None: super().__init__() self.h0 = nn.Linear(4, 8) self.h1 = nn.Linear(8, 8) self.h2 = nn.Linear(8, 4) self.out = nn.Linear(4, 2) def forward(self, x: torch.Tensor) -> torch.Tensor: """Define the forward pass.""" x = self.h0(x) x = self.h1(x) x = self.h2(x) return self.out(x) model = SimpleDense() input_shape = (1, 4) img = visualtorch.graph_view(model, input_shape, node_size=100) plt.axis("off") plt.tight_layout() plt.imshow(img) plt.show() ``` -------------------------------- ### Run Pre-commit Checks Manually Source: https://visualtorch.readthedocs.io/en/latest/_sources/markdown/developer_guides/contributing.md Manually execute all configured pre-commit checks across all files in the repository. This is useful for verifying code quality before committing. ```bash pre-commit run --all-files ``` -------------------------------- ### layered_view() Source: https://visualtorch.readthedocs.io/en/latest/markdown/api_references/layered.html Generates a layered architecture visualization for a given PyTorch model. ```APIDOC ## layered_view() ### Description Generate a layered architecture visualization for a given torch model. ### Parameters #### Parameters - **model** (_torch.nn.Module_) – A torch model that will be visualized. - **input_shape** (_tuple_) – The shape of the input tensor (default: (1, 3, 224, 224)). - **to_file** (_str_ _,__optional_) – Path to the file to write the created image. Overwrite if exist. Image type is inferred from the file extension. Providing None will disable writing. - **min_z** (_int_ _,__optional_) – Minimum size in pixels that a layer will have along the z-axis. - **min_xy** (_int_ _,__optional_) – Minimum size in pixels that a layer will have along the x and y axes. - **max_z** (_int_ _,__optional_) – Maximum size in pixels that a layer will have along the z-axis. - **max_xy** (_int_ _,__optional_) – Maximum size in pixels that a layer will have along the x and y axes. - **scale_z** (_float_ _,__optional_) – Scalar multiplier for the size of each layer along the z-axis. - **scale_xy** (_float_ _,__optional_) – Scalar multiplier for the size of each layer along the x and y axes. - **type_ignore** (_list_ _,__optional_) – List of layer types in the torch model to ignore during drawing. - **index_ignore** (_list_ _,__optional_) – List of layer indexes in the torch model to ignore during drawing. - **color_map** (_dict_ _,__optional_) – Dictionary defining fill and outline colors for each layer by class type. Will fallback to default values for unspecified classes. - **one_dim_orientation** (_str_ _,__optional_) – Axis on which one-dim layers should be drawn. E.g., ‘x’, ‘y’, or ‘z’. - **background_fill** (_str_ _or_ _tuple_ _,__optional_) – Background color for the image. A string or a tuple (R, G, B, A). - **draw_volume** (_bool_ _,__optional_) – Flag to switch between 3D volumetric view and 2D box view. - **padding** (_int_ _,__optional_) – Distance in pixels before the first and after the last layer. - **spacing** (_int_ _,__optional_) – Spacing in pixels between two layers. - **draw_funnel** (_bool_ _,__optional_) – If True, a funnel will be drawn between consecutive layers. - **shade_step** (_int_ _,__optional_) – Deviation in lightness for drawing shades (only in volumetric view). - **legend** (_bool_ _,__optional_) – Add a legend of the layers to the image. - **font** (_PIL.ImageFont_ _,__optional_) – Font that will be used for the legend. If None, default font will be used. - **font_color** (_str_ _or_ _tuple_ _,__optional_) – Color for the font if used. Can be a string or a tuple (R, G, B, A). - **opacity** (_int_) – Transparency of the color (0 ~ 255). ### Returns An Image object representing the generated architecture visualization. ### Return type PIL.Image ``` -------------------------------- ### Citation for VisualTorch Source: https://visualtorch.readthedocs.io/en/latest/_sources/index.md Use this BibTeX entry to cite VisualTorch in your publications. ```bibtex @misc{visualtorch, author = {VisualTorch Contributors}, title = {VisualTorch: Visualize PyTorch Neural Network Architectures}, year = {2023}, url = {https://github.com/visualtorch/visualtorch}, } ``` -------------------------------- ### Visualize LeNet Style CNN Model Source: https://visualtorch.readthedocs.io/en/latest/_downloads/5300b43087263131d1e95ba414032926/plot_basic_sequential_lenet_style.ipynb Visualize a simple CNN model defined using `nn.Sequential`. This snippet requires `matplotlib.pyplot`, `visualtorch`, and `torch.nn`. It defines a model, specifies an input shape, generates a visualization using `visualtorch.lenet_view`, and displays it using `matplotlib`. ```python import matplotlib.pyplot as plt import visualtorch from torch import nn # Example of a simple CNN model using nn.Sequential model = nn.Sequential( nn.Conv2d(3, 8, kernel_size=3, padding=1), nn.MaxPool2d(2, 2), nn.Conv2d(8, 16, kernel_size=3, padding=1), nn.MaxPool2d(2, 2), ) input_shape = (1, 3, 128, 128) img = visualtorch.lenet_view(model, input_shape=input_shape) plt.axis("off") plt.tight_layout() plt.imshow(img) plt.show() ``` -------------------------------- ### Visualize CNN with Custom Shading Source: https://visualtorch.readthedocs.io/en/latest/_downloads/1f8ad8231a762da579f0c5824143eca2/plot_custom_shading.ipynb Defines a simple CNN model and visualizes its layered structure with custom shading. Requires matplotlib and visualtorch. Ensure the input shape and model architecture are correctly defined. ```python import matplotlib.pyplot as plt import visualtorch from torch import nn # Example of a simple CNN model using nn.Sequential model = nn.Sequential( nn.Conv2d(3, 16, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Conv2d(16, 32, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Conv2d(32, 64, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Flatten(), nn.Linear(64 * 28 * 28, 256), # Adjusted the input size for the Linear layer nn.ReLU(), nn.Linear(256, 10), # Assuming 10 output classes ) input_shape = (1, 3, 224, 224) img = visualtorch.layered_view(model, input_shape=input_shape, shade_step=50) plt.axis("off") plt.tight_layout() plt.imshow(img) plt.show() ``` -------------------------------- ### Visualize CNN with Custom Orientation Source: https://visualtorch.readthedocs.io/en/latest/_downloads/294ec23be84a8fa57a71935f6e2b1651/plot_custom_orientation.ipynb Defines a CNN model and visualizes its layers with a custom 'x' orientation for 1D layers. Requires matplotlib and visualtorch. Ensure the input shape matches the model's expected input. ```python import matplotlib.pyplot as plt import visualtorch from torch import nn # Example of a simple CNN model using nn.Sequential model = nn.Sequential( nn.Conv2d(3, 16, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Conv2d(16, 32, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Conv2d(32, 64, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Flatten(), nn.Linear(64 * 28 * 28, 256), # Adjusted the input size for the Linear layer nn.ReLU(), nn.Linear(256, 10), # Assuming 10 output classes ) input_shape = (1, 3, 224, 224) img = visualtorch.layered_view( model, input_shape=input_shape, one_dim_orientation="x", spacing=40, ) plt.axis("off") plt.tight_layout() plt.imshow(img) plt.show() ``` -------------------------------- ### Visualize Model Ignoring Specific Layer Types Source: https://visualtorch.readthedocs.io/en/latest/_downloads/c16f2a3d22a43444aef19fa7ccfafae5/plot_ignore_layers.ipynb This snippet shows how to create a CNN model and then visualize it using `visualtorch.layered_view`, excluding layers of type `nn.ReLU` and `nn.Flatten`. Ensure `matplotlib` is imported for plotting. ```python import matplotlib.pyplot as plt import visualtorch from torch import nn # Example of a simple CNN model using nn.Sequential model = nn.Sequential( nn.Conv2d(3, 16, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Conv2d(16, 32, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Conv2d(32, 64, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Flatten(), nn.Linear(64 * 28 * 28, 256), # Adjusted the input size for the Linear layer nn.ReLU(), nn.Linear(256, 10), # Assuming 10 output classes ) ignored_layers = [nn.ReLU, nn.Flatten] input_shape = (1, 3, 224, 224) img = visualtorch.layered_view( model, input_shape=input_shape, type_ignore=ignored_layers, ) plt.axis("off") plt.tight_layout() plt.imshow(img) plt.show() ``` -------------------------------- ### Visualize PyTorch Model with Custom Colors Source: https://visualtorch.readthedocs.io/en/latest/_downloads/78b89eefc1c4b2792f591b1b313ea3fb/plot_custom_color.ipynb Define a custom color map to assign specific colors to different layer types (e.g., Conv2d, ReLU, Linear) in a PyTorch model visualization. This helps in distinguishing layers at a glance. Requires `matplotlib` and `visualtorch`. ```python from collections import defaultdict import matplotlib.pyplot as plt import visualtorch from torch import nn # Example of a simple CNN model using nn.Sequential model = nn.Sequential( nn.Conv2d(3, 16, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Conv2d(16, 32, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Conv2d(32, 64, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Flatten(), nn.Linear(64 * 28 * 28, 256), # Adjusted the input size for the Linear layer nn.ReLU(), nn.Linear(256, 10), # Assuming 10 output classes ) color_map: dict = defaultdict(dict) color_map[nn.Conv2d]["fill"] = "LightSlateGray" # Light Slate Gray color_map[nn.ReLU]["fill"] = "#87CEFA" # Light Sky Blue color_map[nn.MaxPool2d]["fill"] = "LightSeaGreen" # Light Sea Green color_map[nn.Flatten]["fill"] = "#98FB98" # Pale Green color_map[nn.Linear]["fill"] = "LightSteelBlue" # Light Steel Blue input_shape = (1, 3, 224, 224) img = visualtorch.layered_view(model, input_shape=input_shape, color_map=color_map) plt.axis("off") plt.tight_layout() plt.imshow(img) plt.show() ``` -------------------------------- ### Visualize Model Ignoring Specific Layers Source: https://visualtorch.readthedocs.io/en/latest/usage_examples/layered/plot_ignore_layers.html Use `type_ignore` parameter in `visualtorch.layered_view` to exclude layers like ReLU or Flatten from the visualization. This helps in focusing on the core computational layers of your model. ```python import matplotlib.pyplot as plt import visualtorch from torch import nn # Example of a simple CNN model using nn.Sequential model = nn.Sequential( nn.Conv2d(3, 16, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Conv2d(16, 32, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Conv2d(32, 64, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Flatten(), nn.Linear(64 * 28 * 28, 256), # Adjusted the input size for the Linear layer nn.ReLU(), nn.Linear(256, 10), # Assuming 10 output classes ) ignored_layers = [nn.ReLU, nn.Flatten] input_shape = (1, 3, 224, 224) img = visualtorch.layered_view( model, input_shape=input_shape, type_ignore=ignored_layers, ) plt.axis("off") plt.tight_layout() plt.imshow(img) plt.show() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.