Opens in a new window Opens an external website Opens an external website in a new window
<!---->Close this dialog<!---->
This website utilizes technologies such as cookies to enable essential site functionality, as well as for analytics, personalization, and targeted advertising. To learn more, view the following link:  [Privacy Policy](https://lfprojects.org/policies/privacy-policy/)
Manage Preferences 
<!---->Close Cookie Preferences<!---->
[Skip to main content](https://docs.pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html#main-content)
Back to top
`Ctrl`+`K`
[ ![PyTorch Tutorials - Home](../images/body-71378417393ef1821ab7.svg) ![PyTorch Tutorials - Home](../images/body-0e3f4966f818379ca30a.svg) ](https://docs.pytorch.org/tutorials/index.html)
[ ![PyTorch Tutorials - Home](../images/body-71378417393ef1821ab7.svg) ![PyTorch Tutorials - Home](../images/body-0e3f4966f818379ca30a.svg) ](https://docs.pytorch.org/tutorials/index.html)
[v2.14.0+cu130](https://docs.pytorch.org/tutorials/index.html)
  * [ Intro ](https://docs.pytorch.org/tutorials/intro.html)
    * [ Learn the Basics ](https://docs.pytorch.org/tutorials/beginner/basics/intro.html)
    * [ Introduction to PyTorch - YouTube Series ](https://docs.pytorch.org/tutorials/beginner/introyt/introyt_index.html)
    * [ Deep Learning with PyTorch: A 60 Minute Blitz ](https://docs.pytorch.org/tutorials/beginner/deep_learning_60min_blitz.html)
    * [ Learning PyTorch with Examples ](https://docs.pytorch.org/tutorials/beginner/pytorch_with_examples.html)
    * [ What is torch.nn really? ](https://docs.pytorch.org/tutorials/beginner/nn_tutorial.html)
    * [ Understanding requires_grad, retain_grad, Leaf, and Non-leaf Tensors ](https://docs.pytorch.org/tutorials/beginner/understanding_leaf_vs_nonleaf_tutorial.html)
    * [ NLP from Scratch ](https://docs.pytorch.org/tutorials/intermediate/nlp_from_scratch_index.html)
    * [ Visualizing Models, Data, and Training with TensorBoard ](https://docs.pytorch.org/tutorials/intermediate/tensorboard_tutorial.html)
    * [ A guide on good usage of non_blocking and pin_memory() in PyTorch ](https://docs.pytorch.org/tutorials/intermediate/pinmem_nonblock.html)
    * [ Data Loading Optimization in PyTorch ](https://docs.pytorch.org/tutorials/intermediate/intermediate_data_loading_tutorial.html)
    * [ Visualizing Gradients ](https://docs.pytorch.org/tutorials/intermediate/visualizing_gradients_tutorial.html)
  * [ Compilers ](https://docs.pytorch.org/tutorials/compilers_index.html)
    * [ Introduction to torch.compile ](https://docs.pytorch.org/tutorials/intermediate/torch_compile_tutorial.html)
    * [ torch.compile End-to-End Tutorial ](https://docs.pytorch.org/tutorials/intermediate/torch_compile_full_example.html)
    * [ Compiled Autograd: Capturing a larger backward graph for torch.compile ](https://docs.pytorch.org/tutorials/intermediate/compiled_autograd_tutorial.html)
    * [ Inductor CPU backend debugging and profiling ](https://docs.pytorch.org/tutorials/intermediate/inductor_debug_cpu.html)
    * [ Dynamic Compilation Control with torch.compiler.set_stance ](https://docs.pytorch.org/tutorials/recipes/torch_compiler_set_stance_tutorial.html)
    * [ Demonstration of torch.export flow, common challenges and the solutions to address them ](https://docs.pytorch.org/tutorials/recipes/torch_export_challenges_solutions.html)
    * [ (beta) Compiling the optimizer with torch.compile ](https://docs.pytorch.org/tutorials/recipes/compiling_optimizer.html)
    * [ (beta) Running the compiled optimizer with an LR Scheduler ](https://docs.pytorch.org/tutorials/recipes/compiling_optimizer_lr_scheduler.html)
    * [ Using Variable Length Attention in PyTorch ](https://docs.pytorch.org/tutorials/intermediate/variable_length_attention_tutorial.html)
    * [ Using User-Defined Triton Kernels with torch.compile ](https://docs.pytorch.org/tutorials/recipes/torch_compile_user_defined_triton_kernel_tutorial.html)
    * [ Compile Time Caching in torch.compile ](https://docs.pytorch.org/tutorials/recipes/torch_compile_caching_tutorial.html)
    * [ Reducing torch.compile cold start compilation time with regional compilation ](https://docs.pytorch.org/tutorials/recipes/regional_compilation.html)
    * [ torch.export Tutorial ](https://docs.pytorch.org/tutorials/intermediate/torch_export_tutorial.html)
    * [ torch.export AOTInductor Tutorial for Python runtime (Beta) ](https://docs.pytorch.org/tutorials/recipes/torch_export_aoti_python.html)
    * [ Demonstration of torch.export flow, common challenges and the solutions to address them ](https://docs.pytorch.org/tutorials/recipes/torch_export_challenges_solutions.html)
    * [ Introduction to ONNX ](https://docs.pytorch.org/tutorials/beginner/onnx/intro_onnx.html)
    * [ Export a PyTorch model to ONNX ](https://docs.pytorch.org/tutorials/beginner/onnx/export_simple_model_to_onnx_tutorial.html)
    * [ Extending the ONNX Exporter Operator Support ](https://docs.pytorch.org/tutorials/beginner/onnx/onnx_registry_tutorial.html)
    * [ Export a model with control flow to ONNX ](https://docs.pytorch.org/tutorials/beginner/onnx/export_control_flow_model_to_onnx_tutorial.html)
    * [ Building a Convolution/Batch Norm fuser with torch.compile ](https://docs.pytorch.org/tutorials/intermediate/torch_compile_conv_bn_fuser.html)
    * [ (beta) Building a Simple CPU Performance Profiler with FX ](https://docs.pytorch.org/tutorials/intermediate/fx_profiling_tutorial.html)
  * [ Domains ](https://docs.pytorch.org/tutorials/domains.html)
    * [ TorchVision Object Detection Finetuning Tutorial ](https://docs.pytorch.org/tutorials/intermediate/torchvision_tutorial.html)
    * [ Transfer Learning for Computer Vision Tutorial ](https://docs.pytorch.org/tutorials/beginner/transfer_learning_tutorial.html)
    * [ Adversarial Example Generation ](https://docs.pytorch.org/tutorials/beginner/fgsm_tutorial.html)
    * [ DCGAN Tutorial ](https://docs.pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html)
    * [ Spatial Transformer Networks Tutorial ](https://docs.pytorch.org/tutorials/intermediate/spatial_transformer_tutorial.html)
    * [ Reinforcement Learning (DQN) Tutorial ](https://docs.pytorch.org/tutorials/intermediate/reinforcement_q_learning.html)
    * [ Reinforcement Learning (PPO) with TorchRL Tutorial ](https://docs.pytorch.org/tutorials/intermediate/reinforcement_ppo.html)
    * [ Train a Mario-playing RL Agent ](https://docs.pytorch.org/tutorials/intermediate/mario_rl_tutorial.html)
    * [ Pendulum: Writing your environment and transforms with TorchRL ](https://docs.pytorch.org/tutorials/advanced/pendulum.html)
    * [ Introduction to TorchRec ](https://docs.pytorch.org/tutorials/intermediate/torchrec_intro_tutorial.html)
    * [ Exploring TorchRec sharding ](https://docs.pytorch.org/tutorials/advanced/sharding.html)
  * [ Distributed ](https://docs.pytorch.org/tutorials/distributed.html)
    * [ PyTorch Distributed Overview ](https://docs.pytorch.org/tutorials/beginner/dist_overview.html)
    * [ Distributed Data Parallel in PyTorch - Video Tutorials ](https://docs.pytorch.org/tutorials/beginner/ddp_series_intro.html)
    * [ Getting Started with Distributed Data Parallel ](https://docs.pytorch.org/tutorials/intermediate/ddp_tutorial.html)
    * [ Writing Distributed Applications with PyTorch ](https://docs.pytorch.org/tutorials/intermediate/dist_tuto.html)
    * [ Getting Started with Fully Sharded Data Parallel (FSDP2) ](https://docs.pytorch.org/tutorials/intermediate/FSDP_tutorial.html)
    * [ Introduction to Libuv TCPStore Backend ](https://docs.pytorch.org/tutorials/intermediate/TCPStore_libuv_backend.html)
    * [ Large Scale Transformer model training with Tensor Parallel (TP) ](https://docs.pytorch.org/tutorials/intermediate/TP_tutorial.html)
    * [ Introduction to Distributed Pipeline Parallelism ](https://docs.pytorch.org/tutorials/intermediate/pipelining_tutorial.html)
    * [ Customize Process Group Backends Using Cpp Extensions ](https://docs.pytorch.org/tutorials/intermediate/process_group_cpp_extension_tutorial.html)
    * [ Getting Started with Distributed RPC Framework ](https://docs.pytorch.org/tutorials/intermediate/rpc_tutorial.html)
    * [ Implementing a Parameter Server Using Distributed RPC Framework ](https://docs.pytorch.org/tutorials/intermediate/rpc_param_server_tutorial.html)
    * [ Implementing Batch RPC Processing Using Asynchronous Executions ](https://docs.pytorch.org/tutorials/intermediate/rpc_async_execution.html)
    * [ Interactive Distributed Applications with Monarch ](https://docs.pytorch.org/tutorials/intermediate/monarch_distributed_tutorial.html)
    * [ Debugging Hangs with Flight Recorder Using TorchComms and Debug Server ](https://docs.pytorch.org/tutorials/intermediate/debug_hangs_with_flight_recorder.html)
    * [ Combining Distributed DataParallel with Distributed RPC Framework ](https://docs.pytorch.org/tutorials/advanced/rpc_ddp_tutorial.html)
    * [ Distributed Training with Uneven Inputs Using the Join Context Manager ](https://docs.pytorch.org/tutorials/advanced/generic_join.html)
    * [ Distributed training at scale with PyTorch and Ray Train ](https://docs.pytorch.org/tutorials/beginner/distributed_training_with_ray_tutorial.html)
  * [ Deep Dive ](https://docs.pytorch.org/tutorials/deep-dive.html)
    * [ Profiling your PyTorch Module ](https://docs.pytorch.org/tutorials/beginner/profiler.html)
    * [ CUDA Graph Kernel Annotations and Profiling ](https://docs.pytorch.org/tutorials/advanced/cuda_graph_annotations_tutorial.html)
    * [ Parametrizations Tutorial ](https://docs.pytorch.org/tutorials/intermediate/parametrizations.html)
    * [ Pruning Tutorial ](https://docs.pytorch.org/tutorials/intermediate/pruning_tutorial.html)
    * [ Inductor CPU backend debugging and profiling ](https://docs.pytorch.org/tutorials/intermediate/inductor_debug_cpu.html)
    * [ (Beta) Implementing High-Performance Transformers with Scaled Dot Product Attention (SDPA) ](https://docs.pytorch.org/tutorials/intermediate/scaled_dot_product_attention_tutorial.html)
    * [ Knowledge Distillation Tutorial ](https://docs.pytorch.org/tutorials/beginner/knowledge_distillation_tutorial.html)
    * [ Channels Last Memory Format in PyTorch ](https://docs.pytorch.org/tutorials/intermediate/memory_format_tutorial.html)
    * [ Forward-mode Automatic Differentiation (Beta) ](https://docs.pytorch.org/tutorials/intermediate/forward_ad_usage.html)
    * [ Jacobians, Hessians, hvp, vhp, and more: composing function transforms ](https://docs.pytorch.org/tutorials/intermediate/jacobians_hessians.html)
    * [ Model ensembling ](https://docs.pytorch.org/tutorials/intermediate/ensembling.html)
    * [ Per-sample-gradients ](https://docs.pytorch.org/tutorials/intermediate/per_sample_grads.html)
    * [ Using the PyTorch C++ Frontend ](https://docs.pytorch.org/tutorials/advanced/cpp_frontend.html)
    * [ Autograd in C++ Frontend ](https://docs.pytorch.org/tutorials/advanced/cpp_autograd.html)
  * [ Extension ](https://docs.pytorch.org/tutorials/extension.html)
    * [ PyTorch Custom Operators ](https://docs.pytorch.org/tutorials/advanced/custom_ops_landing_page.html)
    * [ Double Backward with Custom Functions ](https://docs.pytorch.org/tutorials/intermediate/custom_function_double_backward_tutorial.html)
    * [ Fusing Convolution and Batch Norm using Custom Function ](https://docs.pytorch.org/tutorials/intermediate/custom_function_conv_bn_tutorial.html)
    * [ Registering a Dispatched Operator in C++ ](https://docs.pytorch.org/tutorials/advanced/dispatcher.html)
    * [ Extending dispatcher for a new backend in C++ ](https://docs.pytorch.org/tutorials/advanced/extend_dispatcher.html)
    * [ Facilitating New Backend Integration by PrivateUse1 ](https://docs.pytorch.org/tutorials/advanced/privateuseone.html)
  * [ Ecosystem ](https://docs.pytorch.org/tutorials/ecosystem.html)
    * [ Hyperparameter tuning using Ray Tune ](https://docs.pytorch.org/tutorials/beginner/hyperparameter_tuning_tutorial.html)
    * [ Serve PyTorch models at scale with Ray Serve ](https://docs.pytorch.org/tutorials/beginner/serving_tutorial.html)
    * [ Multi-Objective NAS with Ax ](https://docs.pytorch.org/tutorials/intermediate/ax_multiobjective_nas_tutorial.html)
    * [ Real Time Inference on Raspberry Pi 4 and 5 (40 fps!) ](https://docs.pytorch.org/tutorials/intermediate/realtime_rpi.html)
    * [ Mosaic: Memory Profiling for PyTorch ](https://docs.pytorch.org/tutorials/beginner/mosaic_memory_profiling_tutorial.html)
    * [ Distributed training at scale with PyTorch and Ray Train ](https://docs.pytorch.org/tutorials/beginner/distributed_training_with_ray_tutorial.html)
  * More 
    * [ Recipes ](https://docs.pytorch.org/tutorials/recipes_index.html)
    * [ Unstable ](https://docs.pytorch.org/tutorials/unstable_index.html)


[ Go to pytorch.org  ](https://pytorch.org)
`Ctrl`+`K`  
|   
 |   | [×](javascript:void\(0\) "Clear search box")  |  
| --- | --- |  
| search  |   |  
Custom Search  
|   |  Sort by Relevance Date  |  
| --- | --- |  
  * [ X](https://x.com/PyTorch)
  * [ GitHub](https://github.com/pytorch/tutorials)
  * [ Discourse](https://dev-discuss.pytorch.org/)
  * [ PyPi](https://pypi.org/project/torch/)


[v2.14.0+cu130](https://docs.pytorch.org/tutorials/index.html)
  * [ Intro ](https://docs.pytorch.org/tutorials/intro.html)
    * [ Learn the Basics ](https://docs.pytorch.org/tutorials/beginner/basics/intro.html)
    * [ Introduction to PyTorch - YouTube Series ](https://docs.pytorch.org/tutorials/beginner/introyt/introyt_index.html)
    * [ Deep Learning with PyTorch: A 60 Minute Blitz ](https://docs.pytorch.org/tutorials/beginner/deep_learning_60min_blitz.html)
    * [ Learning PyTorch with Examples ](https://docs.pytorch.org/tutorials/beginner/pytorch_with_examples.html)
    * [ What is torch.nn really? ](https://docs.pytorch.org/tutorials/beginner/nn_tutorial.html)
    * [ Understanding requires_grad, retain_grad, Leaf, and Non-leaf Tensors ](https://docs.pytorch.org/tutorials/beginner/understanding_leaf_vs_nonleaf_tutorial.html)
    * [ NLP from Scratch ](https://docs.pytorch.org/tutorials/intermediate/nlp_from_scratch_index.html)
    * [ Visualizing Models, Data, and Training with TensorBoard ](https://docs.pytorch.org/tutorials/intermediate/tensorboard_tutorial.html)
    * [ A guide on good usage of non_blocking and pin_memory() in PyTorch ](https://docs.pytorch.org/tutorials/intermediate/pinmem_nonblock.html)
    * [ Data Loading Optimization in PyTorch ](https://docs.pytorch.org/tutorials/intermediate/intermediate_data_loading_tutorial.html)
    * [ Visualizing Gradients ](https://docs.pytorch.org/tutorials/intermediate/visualizing_gradients_tutorial.html)
  * [ Compilers ](https://docs.pytorch.org/tutorials/compilers_index.html)
    * [ Introduction to torch.compile ](https://docs.pytorch.org/tutorials/intermediate/torch_compile_tutorial.html)
    * [ torch.compile End-to-End Tutorial ](https://docs.pytorch.org/tutorials/intermediate/torch_compile_full_example.html)
    * [ Compiled Autograd: Capturing a larger backward graph for torch.compile ](https://docs.pytorch.org/tutorials/intermediate/compiled_autograd_tutorial.html)
    * [ Inductor CPU backend debugging and profiling ](https://docs.pytorch.org/tutorials/intermediate/inductor_debug_cpu.html)
    * [ Dynamic Compilation Control with torch.compiler.set_stance ](https://docs.pytorch.org/tutorials/recipes/torch_compiler_set_stance_tutorial.html)
    * [ Demonstration of torch.export flow, common challenges and the solutions to address them ](https://docs.pytorch.org/tutorials/recipes/torch_export_challenges_solutions.html)
    * [ (beta) Compiling the optimizer with torch.compile ](https://docs.pytorch.org/tutorials/recipes/compiling_optimizer.html)
    * [ (beta) Running the compiled optimizer with an LR Scheduler ](https://docs.pytorch.org/tutorials/recipes/compiling_optimizer_lr_scheduler.html)
    * [ Using Variable Length Attention in PyTorch ](https://docs.pytorch.org/tutorials/intermediate/variable_length_attention_tutorial.html)
    * [ Using User-Defined Triton Kernels with torch.compile ](https://docs.pytorch.org/tutorials/recipes/torch_compile_user_defined_triton_kernel_tutorial.html)
    * [ Compile Time Caching in torch.compile ](https://docs.pytorch.org/tutorials/recipes/torch_compile_caching_tutorial.html)
    * [ Reducing torch.compile cold start compilation time with regional compilation ](https://docs.pytorch.org/tutorials/recipes/regional_compilation.html)
    * [ torch.export Tutorial ](https://docs.pytorch.org/tutorials/intermediate/torch_export_tutorial.html)
    * [ torch.export AOTInductor Tutorial for Python runtime (Beta) ](https://docs.pytorch.org/tutorials/recipes/torch_export_aoti_python.html)
    * [ Demonstration of torch.export flow, common challenges and the solutions to address them ](https://docs.pytorch.org/tutorials/recipes/torch_export_challenges_solutions.html)
    * [ Introduction to ONNX ](https://docs.pytorch.org/tutorials/beginner/onnx/intro_onnx.html)
    * [ Export a PyTorch model to ONNX ](https://docs.pytorch.org/tutorials/beginner/onnx/export_simple_model_to_onnx_tutorial.html)
    * [ Extending the ONNX Exporter Operator Support ](https://docs.pytorch.org/tutorials/beginner/onnx/onnx_registry_tutorial.html)
    * [ Export a model with control flow to ONNX ](https://docs.pytorch.org/tutorials/beginner/onnx/export_control_flow_model_to_onnx_tutorial.html)
    * [ Building a Convolution/Batch Norm fuser with torch.compile ](https://docs.pytorch.org/tutorials/intermediate/torch_compile_conv_bn_fuser.html)
    * [ (beta) Building a Simple CPU Performance Profiler with FX ](https://docs.pytorch.org/tutorials/intermediate/fx_profiling_tutorial.html)
  * [ Domains ](https://docs.pytorch.org/tutorials/domains.html)
    * [ TorchVision Object Detection Finetuning Tutorial ](https://docs.pytorch.org/tutorials/intermediate/torchvision_tutorial.html)
    * [ Transfer Learning for Computer Vision Tutorial ](https://docs.pytorch.org/tutorials/beginner/transfer_learning_tutorial.html)
    * [ Adversarial Example Generation ](https://docs.pytorch.org/tutorials/beginner/fgsm_tutorial.html)
    * [ DCGAN Tutorial ](https://docs.pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html)
    * [ Spatial Transformer Networks Tutorial ](https://docs.pytorch.org/tutorials/intermediate/spatial_transformer_tutorial.html)
    * [ Reinforcement Learning (DQN) Tutorial ](https://docs.pytorch.org/tutorials/intermediate/reinforcement_q_learning.html)
    * [ Reinforcement Learning (PPO) with TorchRL Tutorial ](https://docs.pytorch.org/tutorials/intermediate/reinforcement_ppo.html)
    * [ Train a Mario-playing RL Agent ](https://docs.pytorch.org/tutorials/intermediate/mario_rl_tutorial.html)
    * [ Pendulum: Writing your environment and transforms with TorchRL ](https://docs.pytorch.org/tutorials/advanced/pendulum.html)
    * [ Introduction to TorchRec ](https://docs.pytorch.org/tutorials/intermediate/torchrec_intro_tutorial.html)
    * [ Exploring TorchRec sharding ](https://docs.pytorch.org/tutorials/advanced/sharding.html)
  * [ Distributed ](https://docs.pytorch.org/tutorials/distributed.html)
    * [ PyTorch Distributed Overview ](https://docs.pytorch.org/tutorials/beginner/dist_overview.html)
    * [ Distributed Data Parallel in PyTorch - Video Tutorials ](https://docs.pytorch.org/tutorials/beginner/ddp_series_intro.html)
    * [ Getting Started with Distributed Data Parallel ](https://docs.pytorch.org/tutorials/intermediate/ddp_tutorial.html)
    * [ Writing Distributed Applications with PyTorch ](https://docs.pytorch.org/tutorials/intermediate/dist_tuto.html)
    * [ Getting Started with Fully Sharded Data Parallel (FSDP2) ](https://docs.pytorch.org/tutorials/intermediate/FSDP_tutorial.html)
    * [ Introduction to Libuv TCPStore Backend ](https://docs.pytorch.org/tutorials/intermediate/TCPStore_libuv_backend.html)
    * [ Large Scale Transformer model training with Tensor Parallel (TP) ](https://docs.pytorch.org/tutorials/intermediate/TP_tutorial.html)
    * [ Introduction to Distributed Pipeline Parallelism ](https://docs.pytorch.org/tutorials/intermediate/pipelining_tutorial.html)
    * [ Customize Process Group Backends Using Cpp Extensions ](https://docs.pytorch.org/tutorials/intermediate/process_group_cpp_extension_tutorial.html)
    * [ Getting Started with Distributed RPC Framework ](https://docs.pytorch.org/tutorials/intermediate/rpc_tutorial.html)
    * [ Implementing a Parameter Server Using Distributed RPC Framework ](https://docs.pytorch.org/tutorials/intermediate/rpc_param_server_tutorial.html)
    * [ Implementing Batch RPC Processing Using Asynchronous Executions ](https://docs.pytorch.org/tutorials/intermediate/rpc_async_execution.html)
    * [ Interactive Distributed Applications with Monarch ](https://docs.pytorch.org/tutorials/intermediate/monarch_distributed_tutorial.html)
    * [ Debugging Hangs with Flight Recorder Using TorchComms and Debug Server ](https://docs.pytorch.org/tutorials/intermediate/debug_hangs_with_flight_recorder.html)
    * [ Combining Distributed DataParallel with Distributed RPC Framework ](https://docs.pytorch.org/tutorials/advanced/rpc_ddp_tutorial.html)
    * [ Distributed Training with Uneven Inputs Using the Join Context Manager ](https://docs.pytorch.org/tutorials/advanced/generic_join.html)
    * [ Distributed training at scale with PyTorch and Ray Train ](https://docs.pytorch.org/tutorials/beginner/distributed_training_with_ray_tutorial.html)
  * [ Deep Dive ](https://docs.pytorch.org/tutorials/deep-dive.html)
    * [ Profiling your PyTorch Module ](https://docs.pytorch.org/tutorials/beginner/profiler.html)
    * [ CUDA Graph Kernel Annotations and Profiling ](https://docs.pytorch.org/tutorials/advanced/cuda_graph_annotations_tutorial.html)
    * [ Parametrizations Tutorial ](https://docs.pytorch.org/tutorials/intermediate/parametrizations.html)
    * [ Pruning Tutorial ](https://docs.pytorch.org/tutorials/intermediate/pruning_tutorial.html)
    * [ Inductor CPU backend debugging and profiling ](https://docs.pytorch.org/tutorials/intermediate/inductor_debug_cpu.html)
    * [ (Beta) Implementing High-Performance Transformers with Scaled Dot Product Attention (SDPA) ](https://docs.pytorch.org/tutorials/intermediate/scaled_dot_product_attention_tutorial.html)
    * [ Knowledge Distillation Tutorial ](https://docs.pytorch.org/tutorials/beginner/knowledge_distillation_tutorial.html)
    * [ Channels Last Memory Format in PyTorch ](https://docs.pytorch.org/tutorials/intermediate/memory_format_tutorial.html)
    * [ Forward-mode Automatic Differentiation (Beta) ](https://docs.pytorch.org/tutorials/intermediate/forward_ad_usage.html)
    * [ Jacobians, Hessians, hvp, vhp, and more: composing function transforms ](https://docs.pytorch.org/tutorials/intermediate/jacobians_hessians.html)
    * [ Model ensembling ](https://docs.pytorch.org/tutorials/intermediate/ensembling.html)
    * [ Per-sample-gradients ](https://docs.pytorch.org/tutorials/intermediate/per_sample_grads.html)
    * [ Using the PyTorch C++ Frontend ](https://docs.pytorch.org/tutorials/advanced/cpp_frontend.html)
    * [ Autograd in C++ Frontend ](https://docs.pytorch.org/tutorials/advanced/cpp_autograd.html)
  * [ Extension ](https://docs.pytorch.org/tutorials/extension.html)
    * [ PyTorch Custom Operators ](https://docs.pytorch.org/tutorials/advanced/custom_ops_landing_page.html)
    * [ Double Backward with Custom Functions ](https://docs.pytorch.org/tutorials/intermediate/custom_function_double_backward_tutorial.html)
    * [ Fusing Convolution and Batch Norm using Custom Function ](https://docs.pytorch.org/tutorials/intermediate/custom_function_conv_bn_tutorial.html)
    * [ Registering a Dispatched Operator in C++ ](https://docs.pytorch.org/tutorials/advanced/dispatcher.html)
    * [ Extending dispatcher for a new backend in C++ ](https://docs.pytorch.org/tutorials/advanced/extend_dispatcher.html)
    * [ Facilitating New Backend Integration by PrivateUse1 ](https://docs.pytorch.org/tutorials/advanced/privateuseone.html)
  * [ Ecosystem ](https://docs.pytorch.org/tutorials/ecosystem.html)
    * [ Hyperparameter tuning using Ray Tune ](https://docs.pytorch.org/tutorials/beginner/hyperparameter_tuning_tutorial.html)
    * [ Serve PyTorch models at scale with Ray Serve ](https://docs.pytorch.org/tutorials/beginner/serving_tutorial.html)
    * [ Multi-Objective NAS with Ax ](https://docs.pytorch.org/tutorials/intermediate/ax_multiobjective_nas_tutorial.html)
    * [ Real Time Inference on Raspberry Pi 4 and 5 (40 fps!) ](https://docs.pytorch.org/tutorials/intermediate/realtime_rpi.html)
    * [ Mosaic: Memory Profiling for PyTorch ](https://docs.pytorch.org/tutorials/beginner/mosaic_memory_profiling_tutorial.html)
    * [ Distributed training at scale with PyTorch and Ray Train ](https://docs.pytorch.org/tutorials/beginner/distributed_training_with_ray_tutorial.html)
  * [ Recipes ](https://docs.pytorch.org/tutorials/recipes_index.html)
    * [ Defining a Neural Network in PyTorch ](https://docs.pytorch.org/tutorials/recipes/recipes/defining_a_neural_network.html)
    * [ (beta) Using TORCH_LOGS python API with torch.compile ](https://docs.pytorch.org/tutorials/recipes/torch_logs.html)
    * [ What is a state_dict in PyTorch ](https://docs.pytorch.org/tutorials/recipes/recipes/what_is_state_dict.html)
    * [ Warmstarting model using parameters from a different model in PyTorch ](https://docs.pytorch.org/tutorials/recipes/recipes/warmstarting_model_using_parameters_from_a_different_model.html)
    * [ Zeroing out gradients in PyTorch ](https://docs.pytorch.org/tutorials/recipes/recipes/zeroing_out_gradients.html)
    * [ PyTorch Profiler ](https://docs.pytorch.org/tutorials/recipes/recipes/profiler_recipe.html)
    * [ Model Interpretability using Captum ](https://docs.pytorch.org/tutorials/recipes/recipes/Captum_Recipe.html)
    * [ How to use TensorBoard with PyTorch ](https://docs.pytorch.org/tutorials/recipes/recipes/tensorboard_with_pytorch.html)
    * [ Automatic Mixed Precision ](https://docs.pytorch.org/tutorials/recipes/recipes/amp_recipe.html)
    * [ Performance Tuning Guide ](https://docs.pytorch.org/tutorials/recipes/recipes/tuning_guide.html)
    * [ (beta) Compiling the optimizer with torch.compile ](https://docs.pytorch.org/tutorials/recipes/compiling_optimizer.html)
    * [ Timer quick start ](https://docs.pytorch.org/tutorials/recipes/recipes/timer_quick_start.html)
    * [ Shard Optimizer States with ZeroRedundancyOptimizer ](https://docs.pytorch.org/tutorials/recipes/zero_redundancy_optimizer.html)
    * [ Getting Started with CommDebugMode ](https://docs.pytorch.org/tutorials/recipes/distributed_comm_debug_mode.html)
    * [ Demonstration of torch.export flow, common challenges and the solutions to address them ](https://docs.pytorch.org/tutorials/recipes/torch_export_challenges_solutions.html)
    * [ SyntaxError ](https://docs.pytorch.org/tutorials/recipes/recipes/benchmark.html)
    * [ Tips for Loading an nn.Module from a Checkpoint ](https://docs.pytorch.org/tutorials/recipes/recipes/module_load_state_dict_tips.html)
    * [ Reasoning about Shapes in PyTorch ](https://docs.pytorch.org/tutorials/recipes/recipes/reasoning_about_shapes.html)
    * [ Extension points in nn.Module for load_state_dict and tensor subclasses ](https://docs.pytorch.org/tutorials/recipes/recipes/swap_tensors.html)
    * [ torch.export AOTInductor Tutorial for Python runtime (Beta) ](https://docs.pytorch.org/tutorials/recipes/torch_export_aoti_python.html)
    * [ How to use TensorBoard with PyTorch ](https://docs.pytorch.org/tutorials/recipes/recipes/tensorboard_with_pytorch.html)
    * [ (beta) Utilizing Torch Function modes with torch.compile ](https://docs.pytorch.org/tutorials/recipes/torch_compile_torch_function_modes.html)
    * [ (beta) Running the compiled optimizer with an LR Scheduler ](https://docs.pytorch.org/tutorials/recipes/compiling_optimizer_lr_scheduler.html)
    * [ Explicit horizontal fusion with foreach_map and torch.compile ](https://docs.pytorch.org/tutorials/recipes/foreach_map.html)
    * [ Using User-Defined Triton Kernels with torch.compile ](https://docs.pytorch.org/tutorials/recipes/torch_compile_user_defined_triton_kernel_tutorial.html)
    * [ Compile Time Caching in torch.compile ](https://docs.pytorch.org/tutorials/recipes/torch_compile_caching_tutorial.html)
    * [ Compile Time Caching Configuration ](https://docs.pytorch.org/tutorials/recipes/torch_compile_caching_configuration_tutorial.html)
    * [ Reducing torch.compile cold start compilation time with regional compilation ](https://docs.pytorch.org/tutorials/recipes/regional_compilation.html)
    * [ Reducing AoT cold start compilation time with regional compilation ](https://docs.pytorch.org/tutorials/recipes/regional_aot.html)
    * [ Ease-of-use quantization for PyTorch with Intel® Neural Compressor ](https://docs.pytorch.org/tutorials/recipes/intel_neural_compressor_for_pytorch.html)
    * [ Getting Started with DeviceMesh ](https://docs.pytorch.org/tutorials/recipes/distributed_device_mesh.html)
    * [ Getting Started with Distributed Checkpoint (DCP) ](https://docs.pytorch.org/tutorials/recipes/distributed_checkpoint_recipe.html)
    * [ Asynchronous Saving with Distributed Checkpoint (DCP) ](https://docs.pytorch.org/tutorials/recipes/distributed_async_checkpoint_recipe.html)
    * [ DebugMode: Recording Dispatched Operations and Numerical Debugging ](https://docs.pytorch.org/tutorials/recipes/debug_mode_tutorial.html)
  * [ Unstable ](https://docs.pytorch.org/tutorials/unstable_index.html)
    * [ Introduction to Context Parallel ](https://docs.pytorch.org/tutorials/unstable/context_parallel.html)
    * [ Flight Recorder for Debugging Stuck Jobs ](https://docs.pytorch.org/tutorials/unstable/flight_recorder_tutorial.html)
    * [ TorchInductor C++ Wrapper Tutorial ](https://docs.pytorch.org/tutorials/unstable/inductor_cpp_wrapper_tutorial.html)
    * [ How to use torch.compile on Windows CPU/XPU ](https://docs.pytorch.org/tutorials/unstable/inductor_windows.html)
    * [ torch.vmap ](https://docs.pytorch.org/tutorials/unstable/vmap_recipe.html)
    * [ Getting Started with Nested Tensors ](https://docs.pytorch.org/tutorials/unstable/nestedtensor.html)
    * [ MaskedTensor Overview ](https://docs.pytorch.org/tutorials/unstable/maskedtensor_overview.html)
    * [ MaskedTensor Sparsity ](https://docs.pytorch.org/tutorials/unstable/maskedtensor_sparsity.html)
    * [ MaskedTensor Advanced Semantics ](https://docs.pytorch.org/tutorials/unstable/maskedtensor_advanced_semantics.html)
    * [ Efficiently writing “sparse” semantics for Adagrad with MaskedTensor ](https://docs.pytorch.org/tutorials/unstable/maskedtensor_adagrad.html)
    * [ Autoloading Out-of-Tree Extension ](https://docs.pytorch.org/tutorials/unstable/python_extension_autoload.html)
    * [ Using Max-Autotune Compilation on CPU for Better Performance ](https://docs.pytorch.org/tutorials/unstable/max_autotune_on_CPU_tutorial.html)


[ Go to pytorch.org  ](https://pytorch.org)
`Ctrl`+`K`  
|   
 |   | [×](javascript:void\(0\) "Clear search box")  |  
| --- | --- |  
| search  |   |  
Custom Search  
|   |  Sort by Relevance Date  |  
| --- | --- |  
  * [ X](https://x.com/PyTorch)
  * [ GitHub](https://github.com/pytorch/tutorials)
  * [ Discourse](https://dev-discuss.pytorch.org/)
  * [ PyPi](https://pypi.org/project/torch/)


Section Navigation
Image and Video
  * [TorchVision Object Detection Finetuning Tutorial](https://docs.pytorch.org/tutorials/intermediate/torchvision_tutorial.html)
  * [Transfer Learning for Computer Vision Tutorial](https://docs.pytorch.org/tutorials/beginner/transfer_learning_tutorial.html)
  * [Adversarial Example Generation](https://docs.pytorch.org/tutorials/beginner/fgsm_tutorial.html)
  * [DCGAN Tutorial](https://docs.pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html)
  * [Spatial Transformer Networks Tutorial](https://docs.pytorch.org/tutorials/intermediate/spatial_transformer_tutorial.html)


Reinforcement Learning
  * [Reinforcement Learning (DQN) Tutorial](https://docs.pytorch.org/tutorials/intermediate/reinforcement_q_learning.html)
  * [Reinforcement Learning (PPO) with TorchRL Tutorial](https://docs.pytorch.org/tutorials/intermediate/reinforcement_ppo.html)
  * [Train a Mario-playing RL Agent](https://docs.pytorch.org/tutorials/intermediate/mario_rl_tutorial.html)
  * [Pendulum: Writing your environment and transforms with TorchRL](https://docs.pytorch.org/tutorials/advanced/pendulum.html)


Recommendation Systems
  * [Introduction to TorchRec](https://docs.pytorch.org/tutorials/intermediate/torchrec_intro_tutorial.html)
  * [Exploring TorchRec sharding](https://docs.pytorch.org/tutorials/advanced/sharding.html)


Other Domains
  * [See Audio tutorials on the audio website](https://pytorch.org/audio/stable/index.html)
  * [See ExecuTorch tutorials on the ExecuTorch website](https://pytorch.org/executorch/stable/index.html)


  * [ ](https://docs.pytorch.org/tutorials/index.html)
  * [Domains](https://docs.pytorch.org/tutorials/domains.html)
  * DCGAN Tutorial


Rate this Page 
★ ★ ★ ★ ★
beginner/dcgan_faces_tutorial
[ ![](../images/body-167dd8ecb5441f36da47.svg) Run in Google Colab Colab ](https://colab.research.google.com/github/pytorch/tutorials/blob/gh-pages/_downloads/5f81194dd43910d586578638f83205a3/dcgan_faces_tutorial.ipynb) [ ![](../images/body-1f5c68da75ef5177f5c6.svg) Download Notebook Notebook ](https://docs.pytorch.org/tutorials/_downloads/5f81194dd43910d586578638f83205a3/dcgan_faces_tutorial.ipynb) [ ![](../images/body-03bd3502e12b535c8012.svg) View on GitHub GitHub ](https://github.com/pytorch/tutorials/blob/main/beginner_source/dcgan_faces_tutorial.py)
Note
[Go to the end](https://docs.pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html#sphx-glr-download-beginner-dcgan-faces-tutorial-py) to download the full example code.
# DCGAN Tutorial[#](https://docs.pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html#dcgan-tutorial "Link to this heading")
Created On: Jul 31, 2018 | Last Updated: Jan 19, 2024 | Last Verified: Nov 05, 2024
**Author** : [Nathan Inkawhich](https://github.com/inkawhich)
## Introduction[#](https://docs.pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html#introduction "Link to this heading")
This tutorial will give an introduction to DCGANs through an example. We will train a generative adversarial network (GAN) to generate new celebrities after showing it pictures of many real celebrities. Most of the code here is from the DCGAN implementation in [pytorch/examples](https://github.com/pytorch/examples), and this document will give a thorough explanation of the implementation and shed light on how and why this model works. But don’t worry, no prior knowledge of GANs is required, but it may require a first-timer to spend some time reasoning about what is actually happening under the hood. Also, for the sake of time it will help to have a GPU, or two. Lets start from the beginning.
## Generative Adversarial Networks[#](https://docs.pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html#generative-adversarial-networks "Link to this heading")
### What is a GAN?[#](https://docs.pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html#what-is-a-gan "Link to this heading")
GANs are a framework for teaching a deep learning model to capture the training data distribution so we can generate new data from that same distribution. GANs were invented by Ian Goodfellow in 2014 and first described in the paper [Generative Adversarial Nets](https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf). They are made of two distinct models, a _generator_ and a _discriminator_. The job of the generator is to spawn ‘fake’ images that look like the training images. The job of the discriminator is to look at an image and output whether or not it is a real training image or a fake image from the generator. During training, the generator is constantly trying to outsmart the discriminator by generating better and better fakes, while the discriminator is working to become a better detective and correctly classify the real and fake images. The equilibrium of this game is when the generator is generating perfect fakes that look as if they came directly from the training data, and the discriminator is left to always guess at 50% confidence that the generator output is real or fake.
Now, lets define some notation to be used throughout tutorial starting with the discriminator. Let xxx be data representing an image. D(x)D(x)D(x) is the discriminator network which outputs the (scalar) probability that xxx came from training data rather than the generator. Here, since we are dealing with images, the input to D(x)D(x)D(x) is an image of CHW size 3x64x64. Intuitively, D(x)D(x)D(x) should be HIGH when xxx comes from training data and LOW when xxx comes from the generator. D(x)D(x)D(x) can also be thought of as a traditional binary classifier.
For the generator’s notation, let zzz be a latent space vector sampled from a standard normal distribution. G(z)G(z)G(z) represents the generator function which maps the latent vector zzz to data-space. The goal of GGG is to estimate the distribution that the training data comes from (pdatap_{data}pdata​) so it can generate fake samples from that estimated distribution (pgp_gpg​).
So, D(G(z))D(G(z))D(G(z)) is the probability (scalar) that the output of the generator GGG is a real image. As described in [Goodfellow’s paper](https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf), DDD and GGG play a minimax game in which DDD tries to maximize the probability it correctly classifies reals and fakes (logD(x)logD(x)logD(x)), and GGG tries to minimize the probability that DDD will predict its outputs are fake (log(1−D(G(z)))log(1-D(G(z)))log(1−D(G(z)))). From the paper, the GAN loss function is
minGmaxDV(D,G)=Ex∼pdata(x)[logD(x)]+Ez∼pz(z)[log(1−D(G(z)))]\underset{G}{\text{min}} \underset{D}{\text{max}}V(D,G) = \mathbb{E}_{x\sim p_{data}(x)}\big[logD(x)\big] + \mathbb{E}_{z\sim p_{z}(z)}\big[log(1-D(G(z)))\big] Gmin​Dmax​V(D,G)=Ex∼pdata​(x)​[logD(x)]+Ez∼pz​(z)​[log(1−D(G(z)))]
In theory, the solution to this minimax game is where pg=pdatap_g = p_{data}pg​=pdata​, and the discriminator guesses randomly if the inputs are real or fake. However, the convergence theory of GANs is still being actively researched and in reality models do not always train to this point.
### What is a DCGAN?[#](https://docs.pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html#what-is-a-dcgan "Link to this heading")
A DCGAN is a direct extension of the GAN described above, except that it explicitly uses convolutional and convolutional-transpose layers in the discriminator and generator, respectively. It was first described by Radford et. al. in the paper [Unsupervised Representation Learning With Deep Convolutional Generative Adversarial Networks](https://arxiv.org/pdf/1511.06434.pdf). The discriminator is made up of strided [convolution](https://pytorch.org/docs/stable/nn.html#torch.nn.Conv2d) layers, [batch norm](https://pytorch.org/docs/stable/nn.html#torch.nn.BatchNorm2d) layers, and [LeakyReLU](https://pytorch.org/docs/stable/nn.html#torch.nn.LeakyReLU) activations. The input is a 3x64x64 input image and the output is a scalar probability that the input is from the real data distribution. The generator is comprised of [convolutional-transpose](https://pytorch.org/docs/stable/nn.html#torch.nn.ConvTranspose2d) layers, batch norm layers, and [ReLU](https://pytorch.org/docs/stable/nn.html#relu) activations. The input is a latent vector, zzz, that is drawn from a standard normal distribution and the output is a 3x64x64 RGB image. The strided conv-transpose layers allow the latent vector to be transformed into a volume with the same shape as an image. In the paper, the authors also give some tips about how to setup the optimizers, how to calculate the loss functions, and how to initialize the model weights, all of which will be explained in the coming sections.

```
#%matplotlib inline
import argparse
import os
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim as optim
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.utils as vutils
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from IPython.display import HTML

# Set random seed for reproducibility
manualSeed = 999
#manualSeed = random.randint(1, 10000) # use if you want new results
print("Random Seed: ", manualSeed)
random.seed(manualSeed)
[torch.manual_seed](https://docs.pytorch.org/docs/stable/generated/torch.manual_seed.html#torch.manual_seed "torch.manual_seed")(manualSeed)
[torch.use_deterministic_algorithms](https://docs.pytorch.org/docs/stable/generated/torch.use_deterministic_algorithms.html#torch.use_deterministic_algorithms "torch.use_deterministic_algorithms")(True) # Needed for reproducible results

```
Copy to clipboard

```
Random Seed:  999

```
Copy to clipboard
## Inputs[#](https://docs.pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html#inputs "Link to this heading")
Let’s define some inputs for the run:
  * `dataroot` - the path to the root of the dataset folder. We will talk more about the dataset in the next section.
  * `workers` - the number of worker threads for loading the data with the `DataLoader`.
  * `batch_size` - the batch size used in training. The DCGAN paper uses a batch size of 128.
  * `image_size` - the spatial size of the images used for training. This implementation defaults to 64x64. If another size is desired, the structures of D and G must be changed. See [here](https://github.com/pytorch/examples/issues/70) for more details.
  * `nc` - number of color channels in the input images. For color images this is 3.
  * `nz` - length of latent vector.
  * `ngf` - relates to the depth of feature maps carried through the generator.
  * `ndf` - sets the depth of feature maps propagated through the discriminator.
  * `num_epochs` - number of training epochs to run. Training for longer will probably lead to better results but will also take much longer.
  * `lr` - learning rate for training. As described in the DCGAN paper, this number should be 0.0002.
  * `beta1` - beta1 hyperparameter for Adam optimizers. As described in paper, this number should be 0.5.
  * `ngpu` - number of GPUs available. If this is 0, code will run in CPU mode. If this number is greater than 0 it will run on that number of GPUs.



```
# Root directory for dataset
dataroot = "data/celeba"

# Number of workers for dataloader
workers = 2

# Batch size during training
batch_size = 128

# Spatial size of training images. All images will be resized to this
#   size using a transformer.
image_size = 64

# Number of channels in the training images. For color images this is 3
nc = 3

# Size of z latent vector (i.e. size of generator input)
nz = 100

# Size of feature maps in generator
ngf = 64

# Size of feature maps in discriminator
ndf = 64

# Number of training epochs
num_epochs = 5

# Learning rate for optimizers
lr = 0.0002

# Beta1 hyperparameter for Adam optimizers
beta1 = 0.5

# Number of GPUs available. Use 0 for CPU mode.
ngpu = 1

```
Copy to clipboard
## Data[#](https://docs.pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html#data "Link to this heading")
In this tutorial we will use the [Celeb-A Faces dataset](http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html) which can be downloaded at the linked site, or in [Google Drive](https://drive.google.com/drive/folders/0B7EVK8r0v71pTUZsaXdaSnZBZzg). The dataset will download as a file named `img_align_celeba.zip`. Once downloaded, create a directory named `celeba` and extract the zip file into that directory. Then, set the `dataroot` input for this notebook to the `celeba` directory you just created. The resulting directory structure should be:

```
/path/to/celeba
    -> img_align_celeba
        -> 188242.jpg
        -> 173822.jpg
        -> 284702.jpg
        -> 537394.jpg
           ...

```
Copy to clipboard
This is an important step because we will be using the `ImageFolder` dataset class, which requires there to be subdirectories in the dataset root folder. Now, we can create the dataset, create the dataloader, set the device to run on, and finally visualize some of the training data.

```
# We can use an image folder dataset the way we have it setup.
# Create the dataset
[dataset](https://docs.pytorch.org/vision/stable/generated/torchvision.datasets.ImageFolder.html#torchvision.datasets.ImageFolder "torchvision.datasets.ImageFolder") = [dset.ImageFolder](https://docs.pytorch.org/vision/stable/generated/torchvision.datasets.ImageFolder.html#torchvision.datasets.ImageFolder "torchvision.datasets.ImageFolder")(root=dataroot,
                           transform=[transforms.Compose](https://docs.pytorch.org/vision/stable/generated/torchvision.transforms.Compose.html#torchvision.transforms.Compose "torchvision.transforms.Compose")([
                               [transforms.Resize](https://docs.pytorch.org/vision/stable/generated/torchvision.transforms.Resize.html#torchvision.transforms.Resize "torchvision.transforms.Resize")(image_size),
                               [transforms.CenterCrop](https://docs.pytorch.org/vision/stable/generated/torchvision.transforms.CenterCrop.html#torchvision.transforms.CenterCrop "torchvision.transforms.CenterCrop")(image_size),
                               [transforms.ToTensor](https://docs.pytorch.org/vision/stable/generated/torchvision.transforms.ToTensor.html#torchvision.transforms.ToTensor "torchvision.transforms.ToTensor")(),
                               [transforms.Normalize](https://docs.pytorch.org/vision/stable/generated/torchvision.transforms.Normalize.html#torchvision.transforms.Normalize "torchvision.transforms.Normalize")((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
                           ]))
# Create the dataloader
[dataloader](https://docs.pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader "torch.utils.data.DataLoader") = [torch.utils.data.DataLoader](https://docs.pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader "torch.utils.data.DataLoader")([dataset](https://docs.pytorch.org/vision/stable/generated/torchvision.datasets.ImageFolder.html#torchvision.datasets.ImageFolder "torchvision.datasets.ImageFolder"), batch_size=batch_size,
                                         shuffle=True, num_workers=workers)

# Decide which device we want to run on
[device](https://docs.pytorch.org/docs/stable/tensor_attributes.html#torch.device "torch.device") = [torch.device](https://docs.pytorch.org/docs/stable/tensor_attributes.html#torch.device "torch.device")("cuda:0" if ([torch.cuda.is_available](https://docs.pytorch.org/docs/stable/generated/torch.cuda.is_available.html#torch.cuda.is_available "torch.cuda.is_available")() and ngpu > 0) else "cpu")

# Plot some training images
real_batch = next(iter([dataloader](https://docs.pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader "torch.utils.data.DataLoader")))
plt.figure(figsize=(8,8))
plt.axis("off")
plt.title("Training Images")
plt.imshow(np.transpose([vutils.make_grid](https://docs.pytorch.org/vision/stable/generated/torchvision.utils.make_grid.html#torchvision.utils.make_grid "torchvision.utils.make_grid")(real_batch[0].to([device](https://docs.pytorch.org/docs/stable/tensor_attributes.html#torch.device "torch.device"))[:64], padding=2, normalize=True).cpu(),(1,2,0)))
plt.show()

```
Copy to clipboard
![Training Images](../images/body-8b33e1a329e5e2567e3f.png)
## Implementation[#](https://docs.pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html#implementation "Link to this heading")
With our input parameters set and the dataset prepared, we can now get into the implementation. We will start with the weight initialization strategy, then talk about the generator, discriminator, loss functions, and training loop in detail.
### Weight Initialization[#](https://docs.pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html#weight-initialization "Link to this heading")
From the DCGAN paper, the authors specify that all model weights shall be randomly initialized from a Normal distribution with `mean=0`, `stdev=0.02`. The `weights_init` function takes an initialized model as input and reinitializes all convolutional, convolutional-transpose, and batch normalization layers to meet this criteria. This function is applied to the models immediately after initialization.

```
# custom weights initialization called on ``netG`` and ``netD``
def weights_init(m):
    classname = m.__class__.__name__
    if classname.find('Conv') != -1:
        [nn.init.normal_](https://docs.pytorch.org/docs/stable/nn.init.html#torch.nn.init.normal_ "torch.nn.init.normal_")(m.weight.data, 0.0, 0.02)
    elif classname.find('BatchNorm') != -1:
        [nn.init.normal_](https://docs.pytorch.org/docs/stable/nn.init.html#torch.nn.init.normal_ "torch.nn.init.normal_")(m.weight.data, 1.0, 0.02)
        [nn.init.constant_](https://docs.pytorch.org/docs/stable/nn.init.html#torch.nn.init.constant_ "torch.nn.init.constant_")(m.bias.data, 0)

```
Copy to clipboard
### Generator[#](https://docs.pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html#generator "Link to this heading")
The generator, GGG, is designed to map the latent space vector (zzz) to data-space. Since our data are images, converting zzz to data-space means ultimately creating a RGB image with the same size as the training images (i.e. 3x64x64). In practice, this is accomplished through a series of strided two dimensional convolutional transpose layers, each paired with a 2d batch norm layer and a relu activation. The output of the generator is fed through a tanh function to return it to the input data range of [−1,1][-1,1][−1,1]. It is worth noting the existence of the batch norm functions after the conv-transpose layers, as this is a critical contribution of the DCGAN paper. These layers help with the flow of gradients during training. An image of the generator from the DCGAN paper is shown below.
![dcgan_generator](../images/body-5ee9f4797137fdc5a5e6.png)
Notice, how the inputs we set in the input section (`nz`, `ngf`, and `nc`) influence the generator architecture in code. `nz` is the length of the z input vector, `ngf` relates to the size of the feature maps that are propagated through the generator, and `nc` is the number of channels in the output image (set to 3 for RGB images). Below is the code for the generator.

```
# Generator Code

class Generator([nn.Module](https://docs.pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module "torch.nn.Module")):
    def __init__(self, ngpu):
        super([Generator](https://docs.pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module "torch.nn.Module"), self).__init__()
        self.ngpu = ngpu
        self.main = [nn.Sequential](https://docs.pytorch.org/docs/stable/generated/torch.nn.Sequential.html#torch.nn.Sequential "torch.nn.Sequential")(
            # input is Z, going into a convolution
            [nn.ConvTranspose2d](https://docs.pytorch.org/docs/stable/generated/torch.nn.ConvTranspose2d.html#torch.nn.ConvTranspose2d "torch.nn.ConvTranspose2d")( nz, ngf * 8, 4, 1, 0, bias=False),
            [nn.BatchNorm2d](https://docs.pytorch.org/docs/stable/generated/torch.nn.BatchNorm2d.html#torch.nn.BatchNorm2d "torch.nn.BatchNorm2d")(ngf * 8),
            [nn.ReLU](https://docs.pytorch.org/docs/stable/generated/torch.nn.ReLU.html#torch.nn.ReLU "torch.nn.ReLU")(True),
            # state size. ``(ngf*8) x 4 x 4``
            [nn.ConvTranspose2d](https://docs.pytorch.org/docs/stable/generated/torch.nn.ConvTranspose2d.html#torch.nn.ConvTranspose2d "torch.nn.ConvTranspose2d")(ngf * 8, ngf * 4, 4, 2, 1, bias=False),
            [nn.BatchNorm2d](https://docs.pytorch.org/docs/stable/generated/torch.nn.BatchNorm2d.html#torch.nn.BatchNorm2d "torch.nn.BatchNorm2d")(ngf * 4),
            [nn.ReLU](https://docs.pytorch.org/docs/stable/generated/torch.nn.ReLU.html#torch.nn.ReLU "torch.nn.ReLU")(True),
            # state size. ``(ngf*4) x 8 x 8``
            [nn.ConvTranspose2d](https://docs.pytorch.org/docs/stable/generated/torch.nn.ConvTranspose2d.html#torch.nn.ConvTranspose2d "torch.nn.ConvTranspose2d")( ngf * 4, ngf * 2, 4, 2, 1, bias=False),
            [nn.BatchNorm2d](https://docs.pytorch.org/docs/stable/generated/torch.nn.BatchNorm2d.html#torch.nn.BatchNorm2d "torch.nn.BatchNorm2d")(ngf * 2),
            [nn.ReLU](https://docs.pytorch.org/docs/stable/generated/torch.nn.ReLU.html#torch.nn.ReLU "torch.nn.ReLU")(True),
            # state size. ``(ngf*2) x 16 x 16``
            [nn.ConvTranspose2d](https://docs.pytorch.org/docs/stable/generated/torch.nn.ConvTranspose2d.html#torch.nn.ConvTranspose2d "torch.nn.ConvTranspose2d")( ngf * 2, ngf, 4, 2, 1, bias=False),
            [nn.BatchNorm2d](https://docs.pytorch.org/docs/stable/generated/torch.nn.BatchNorm2d.html#torch.nn.BatchNorm2d "torch.nn.BatchNorm2d")(ngf),
            [nn.ReLU](https://docs.pytorch.org/docs/stable/generated/torch.nn.ReLU.html#torch.nn.ReLU "torch.nn.ReLU")(True),
            # state size. ``(ngf) x 32 x 32``
            [nn.ConvTranspose2d](https://docs.pytorch.org/docs/stable/generated/torch.nn.ConvTranspose2d.html#torch.nn.ConvTranspose2d "torch.nn.ConvTranspose2d")( ngf, nc, 4, 2, 1, bias=False),
            [nn.Tanh](https://docs.pytorch.org/docs/stable/generated/torch.nn.Tanh.html#torch.nn.Tanh "torch.nn.Tanh")()
            # state size. ``(nc) x 64 x 64``
        )

    def forward(self, input):
        return self.main(input)

```
Copy to clipboard
Now, we can instantiate the generator and apply the `weights_init` function. Check out the printed model to see how the generator object is structured.

```
# Create the generator
netG = [Generator](https://docs.pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module "torch.nn.Module")(ngpu).to([device](https://docs.pytorch.org/docs/stable/tensor_attributes.html#torch.device "torch.device"))

# Handle multi-GPU if desired
if ([device](https://docs.pytorch.org/docs/stable/tensor_attributes.html#torch.device "torch.device").type == 'cuda') and (ngpu > 1):
    netG = [nn.DataParallel](https://docs.pytorch.org/docs/stable/generated/torch.nn.DataParallel.html#torch.nn.DataParallel "torch.nn.DataParallel")(netG, list(range(ngpu)))

# Apply the ``weights_init`` function to randomly initialize all weights
#  to ``mean=0``, ``stdev=0.02``.
[netG.apply](https://docs.pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.apply "torch.nn.Module.apply")(weights_init)

# Print the model
print(netG)

```
Copy to clipboard

```
Generator(
  (main): Sequential(
    (0): ConvTranspose2d(100, 512, kernel_size=(4, 4), stride=(1, 1), bias=False)
    (1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, bias=True, track_running_stats=True)
    (2): ReLU(inplace=True)
    (3): ConvTranspose2d(512, 256, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
    (4): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, bias=True, track_running_stats=True)
    (5): ReLU(inplace=True)
    (6): ConvTranspose2d(256, 128, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
    (7): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, bias=True, track_running_stats=True)
    (8): ReLU(inplace=True)
    (9): ConvTranspose2d(128, 64, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
    (10): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, bias=True, track_running_stats=True)
    (11): ReLU(inplace=True)
    (12): ConvTranspose2d(64, 3, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
    (13): Tanh()
  )
)

```
Copy to clipboard
### Discriminator[#](https://docs.pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html#discriminator "Link to this heading")
As mentioned, the discriminator, DDD, is a binary classification network that takes an image as input and outputs a scalar probability that the input image is real (as opposed to fake). Here, DDD takes a 3x64x64 input image, processes it through a series of Conv2d, BatchNorm2d, and LeakyReLU layers, and outputs the final probability through a Sigmoid activation function. This architecture can be extended with more layers if necessary for the problem, but there is significance to the use of the strided convolution, BatchNorm, and LeakyReLUs. The DCGAN paper mentions it is a good practice to use strided convolution rather than pooling to downsample because it lets the network learn its own pooling function. Also batch norm and leaky relu functions promote healthy gradient flow which is critical for the learning process of both GGG and DDD.
Discriminator Code

```
class Discriminator([nn.Module](https://docs.pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module "torch.nn.Module")):
    def __init__(self, ngpu):
        super([Discriminator](https://docs.pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module "torch.nn.Module"), self).__init__()
        self.ngpu = ngpu
        self.main = [nn.Sequential](https://docs.pytorch.org/docs/stable/generated/torch.nn.Sequential.html#torch.nn.Sequential "torch.nn.Sequential")(
            # input is ``(nc) x 64 x 64``
            [nn.Conv2d](https://docs.pytorch.org/docs/stable/generated/torch.nn.Conv2d.html#torch.nn.Conv2d "torch.nn.Conv2d")(nc, ndf, 4, 2, 1, bias=False),
            [nn.LeakyReLU](https://docs.pytorch.org/docs/stable/generated/torch.nn.LeakyReLU.html#torch.nn.LeakyReLU "torch.nn.LeakyReLU")(0.2, inplace=True),
            # state size. ``(ndf) x 32 x 32``
            [nn.Conv2d](https://docs.pytorch.org/docs/stable/generated/torch.nn.Conv2d.html#torch.nn.Conv2d "torch.nn.Conv2d")(ndf, ndf * 2, 4, 2, 1, bias=False),
            [nn.BatchNorm2d](https://docs.pytorch.org/docs/stable/generated/torch.nn.BatchNorm2d.html#torch.nn.BatchNorm2d "torch.nn.BatchNorm2d")(ndf * 2),
            [nn.LeakyReLU](https://docs.pytorch.org/docs/stable/generated/torch.nn.LeakyReLU.html#torch.nn.LeakyReLU "torch.nn.LeakyReLU")(0.2, inplace=True),
            # state size. ``(ndf*2) x 16 x 16``
            [nn.Conv2d](https://docs.pytorch.org/docs/stable/generated/torch.nn.Conv2d.html#torch.nn.Conv2d "torch.nn.Conv2d")(ndf * 2, ndf * 4, 4, 2, 1, bias=False),
            [nn.BatchNorm2d](https://docs.pytorch.org/docs/stable/generated/torch.nn.BatchNorm2d.html#torch.nn.BatchNorm2d "torch.nn.BatchNorm2d")(ndf * 4),
            [nn.LeakyReLU](https://docs.pytorch.org/docs/stable/generated/torch.nn.LeakyReLU.html#torch.nn.LeakyReLU "torch.nn.LeakyReLU")(0.2, inplace=True),
            # state size. ``(ndf*4) x 8 x 8``
            [nn.Conv2d](https://docs.pytorch.org/docs/stable/generated/torch.nn.Conv2d.html#torch.nn.Conv2d "torch.nn.Conv2d")(ndf * 4, ndf * 8, 4, 2, 1, bias=False),
            [nn.BatchNorm2d](https://docs.pytorch.org/docs/stable/generated/torch.nn.BatchNorm2d.html#torch.nn.BatchNorm2d "torch.nn.BatchNorm2d")(ndf * 8),
            [nn.LeakyReLU](https://docs.pytorch.org/docs/stable/generated/torch.nn.LeakyReLU.html#torch.nn.LeakyReLU "torch.nn.LeakyReLU")(0.2, inplace=True),
            # state size. ``(ndf*8) x 4 x 4``
            [nn.Conv2d](https://docs.pytorch.org/docs/stable/generated/torch.nn.Conv2d.html#torch.nn.Conv2d "torch.nn.Conv2d")(ndf * 8, 1, 4, 1, 0, bias=False),
            [nn.Sigmoid](https://docs.pytorch.org/docs/stable/generated/torch.nn.Sigmoid.html#torch.nn.Sigmoid "torch.nn.Sigmoid")()
        )

    def forward(self, input):
        return self.main(input)

```
Copy to clipboard
Now, as with the generator, we can create the discriminator, apply the `weights_init` function, and print the model’s structure.

```
# Create the Discriminator
netD = [Discriminator](https://docs.pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module "torch.nn.Module")(ngpu).to([device](https://docs.pytorch.org/docs/stable/tensor_attributes.html#torch.device "torch.device"))

# Handle multi-GPU if desired
if ([device](https://docs.pytorch.org/docs/stable/tensor_attributes.html#torch.device "torch.device").type == 'cuda') and (ngpu > 1):
    netD = [nn.DataParallel](https://docs.pytorch.org/docs/stable/generated/torch.nn.DataParallel.html#torch.nn.DataParallel "torch.nn.DataParallel")(netD, list(range(ngpu)))

# Apply the ``weights_init`` function to randomly initialize all weights
# like this: ``to mean=0, stdev=0.2``.
[netD.apply](https://docs.pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.apply "torch.nn.Module.apply")(weights_init)

# Print the model
print(netD)

```
Copy to clipboard

```
Discriminator(
  (main): Sequential(
    (0): Conv2d(3, 64, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
    (1): LeakyReLU(negative_slope=0.2, inplace=True)
    (2): Conv2d(64, 128, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
    (3): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, bias=True, track_running_stats=True)
    (4): LeakyReLU(negative_slope=0.2, inplace=True)
    (5): Conv2d(128, 256, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
    (6): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, bias=True, track_running_stats=True)
    (7): LeakyReLU(negative_slope=0.2, inplace=True)
    (8): Conv2d(256, 512, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
    (9): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, bias=True, track_running_stats=True)
    (10): LeakyReLU(negative_slope=0.2, inplace=True)
    (11): Conv2d(512, 1, kernel_size=(4, 4), stride=(1, 1), bias=False)
    (12): Sigmoid()
  )
)

```
Copy to clipboard
### Loss Functions and Optimizers[#](https://docs.pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html#loss-functions-and-optimizers "Link to this heading")
With DDD and GGG setup, we can specify how they learn through the loss functions and optimizers. We will use the Binary Cross Entropy loss ([BCELoss](https://pytorch.org/docs/stable/generated/torch.nn.BCELoss.html#torch.nn.BCELoss)) function which is defined in PyTorch as:
ℓ(x,y)=L={l1,…,lN}⊤,ln=−[yn⋅log⁡xn+(1−yn)⋅log⁡(1−xn)]\ell(x, y) = L = \\{l_1,\dots,l_N\\}^\top, \quad l_n = - \left[ y_n \cdot \log x_n + (1 - y_n) \cdot \log (1 - x_n) \right] ℓ(x,y)=L={l1​,…,lN​}⊤,ln​=−[yn​⋅logxn​+(1−yn​)⋅log(1−xn​)]
Notice how this function provides the calculation of both log components in the objective function (i.e. log(D(x))log(D(x))log(D(x)) and log(1−D(G(z)))log(1-D(G(z)))log(1−D(G(z)))). We can specify what part of the BCE equation to use with the yyy input. This is accomplished in the training loop which is coming up soon, but it is important to understand how we can choose which component we wish to calculate just by changing yyy (i.e. GT labels).
Next, we define our real label as 1 and the fake label as 0. These labels will be used when calculating the losses of DDD and GGG, and this is also the convention used in the original GAN paper. Finally, we set up two separate optimizers, one for DDD and one for GGG. As specified in the DCGAN paper, both are Adam optimizers with learning rate 0.0002 and Beta1 = 0.5. For keeping track of the generator’s learning progression, we will generate a fixed batch of latent vectors that are drawn from a Gaussian distribution (i.e. fixed_noise) . In the training loop, we will periodically input this fixed_noise into GGG, and over the iterations we will see images form out of the noise.

```
# Initialize the ``BCELoss`` function
[criterion](https://docs.pytorch.org/docs/stable/generated/torch.nn.BCELoss.html#torch.nn.BCELoss "torch.nn.BCELoss") = [nn.BCELoss](https://docs.pytorch.org/docs/stable/generated/torch.nn.BCELoss.html#torch.nn.BCELoss "torch.nn.BCELoss")()

# Create batch of latent vectors that we will use to visualize
#  the progression of the generator
[fixed_noise](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor") = [torch.randn](https://docs.pytorch.org/docs/stable/generated/torch.randn.html#torch.randn "torch.randn")(64, nz, 1, 1, [device](https://docs.pytorch.org/docs/stable/tensor_attributes.html#torch.device "torch.device")=[device](https://docs.pytorch.org/docs/stable/tensor_attributes.html#torch.device "torch.device"))

# Establish convention for real and fake labels during training
real_label = 1.
fake_label = 0.

# Setup Adam optimizers for both G and D
[optimizerD](https://docs.pytorch.org/docs/stable/generated/torch.optim.Adam.html#torch.optim.Adam "torch.optim.Adam") = [optim.Adam](https://docs.pytorch.org/docs/stable/generated/torch.optim.Adam.html#torch.optim.Adam "torch.optim.Adam")([netD.parameters](https://docs.pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.parameters "torch.nn.Module.parameters")(), lr=lr, betas=(beta1, 0.999))
[optimizerG](https://docs.pytorch.org/docs/stable/generated/torch.optim.Adam.html#torch.optim.Adam "torch.optim.Adam") = [optim.Adam](https://docs.pytorch.org/docs/stable/generated/torch.optim.Adam.html#torch.optim.Adam "torch.optim.Adam")([netG.parameters](https://docs.pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.parameters "torch.nn.Module.parameters")(), lr=lr, betas=(beta1, 0.999))

```
Copy to clipboard
### Training[#](https://docs.pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html#training "Link to this heading")
Finally, now that we have all of the parts of the GAN framework defined, we can train it. Be mindful that training GANs is somewhat of an art form, as incorrect hyperparameter settings lead to mode collapse with little explanation of what went wrong. Here, we will closely follow Algorithm 1 from the [Goodfellow’s paper](https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf), while abiding by some of the best practices shown in [ganhacks](https://github.com/soumith/ganhacks). Namely, we will “construct different mini-batches for real and fake” images, and also adjust G’s objective function to maximize log(D(G(z)))log(D(G(z)))log(D(G(z))). Training is split up into two main parts. Part 1 updates the Discriminator and Part 2 updates the Generator.
**Part 1 - Train the Discriminator**
Recall, the goal of training the discriminator is to maximize the probability of correctly classifying a given input as real or fake. In terms of Goodfellow, we wish to “update the discriminator by ascending its stochastic gradient”. Practically, we want to maximize log(D(x))+log(1−D(G(z)))log(D(x)) + log(1-D(G(z)))log(D(x))+log(1−D(G(z))). Due to the separate mini-batch suggestion from [ganhacks](https://github.com/soumith/ganhacks), we will calculate this in two steps. First, we will construct a batch of real samples from the training set, forward pass through DDD, calculate the loss (log(D(x))log(D(x))log(D(x))), then calculate the gradients in a backward pass. Secondly, we will construct a batch of fake samples with the current generator, forward pass this batch through DDD, calculate the loss (log(1−D(G(z)))log(1-D(G(z)))log(1−D(G(z)))), and _accumulate_ the gradients with a backward pass. Now, with the gradients accumulated from both the all-real and all-fake batches, we call a step of the Discriminator’s optimizer.
**Part 2 - Train the Generator**
As stated in the original paper, we want to train the Generator by minimizing log(1−D(G(z)))log(1-D(G(z)))log(1−D(G(z))) in an effort to generate better fakes. As mentioned, this was shown by Goodfellow to not provide sufficient gradients, especially early in the learning process. As a fix, we instead wish to maximize log(D(G(z)))log(D(G(z)))log(D(G(z))). In the code we accomplish this by: classifying the Generator output from Part 1 with the Discriminator, computing G’s loss _using real labels as GT_ , computing G’s gradients in a backward pass, and finally updating G’s parameters with an optimizer step. It may seem counter-intuitive to use the real labels as GT labels for the loss function, but this allows us to use the log(x)log(x)log(x) part of the `BCELoss` (rather than the log(1−x)log(1-x)log(1−x) part) which is exactly what we want.
Finally, we will do some statistic reporting and at the end of each epoch we will push our fixed_noise batch through the generator to visually track the progress of G’s training. The training statistics reported are:
  * **Loss_D** - discriminator loss calculated as the sum of losses for the all real and all fake batches (log(D(x))+log(1−D(G(z)))log(D(x)) + log(1 - D(G(z)))log(D(x))+log(1−D(G(z)))).
  * **Loss_G** - generator loss calculated as log(D(G(z)))log(D(G(z)))log(D(G(z)))
  * **D(x)** - the average output (across the batch) of the discriminator for the all real batch. This should start close to 1 then theoretically converge to 0.5 when G gets better. Think about why this is.
  * **D(G(z))** - average discriminator outputs for the all fake batch. The first number is before D is updated and the second number is after D is updated. These numbers should start near 0 and converge to 0.5 as G gets better. Think about why this is.


**Note:** This step might take a while, depending on how many epochs you run and if you removed some data from the dataset.

```
# Training Loop

# Lists to keep track of progress
img_list = []
G_losses = []
D_losses = []
iters = 0

print("Starting Training Loop...")
# For each epoch
for epoch in range(num_epochs):
    # For each batch in the dataloader
    for i, data in enumerate([dataloader](https://docs.pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader "torch.utils.data.DataLoader"), 0):

        ############################
        # (1) Update D network: maximize log(D(x)) + log(1 - D(G(z)))
        ###########################
        ## Train with all-real batch
        [netD.zero_grad](https://docs.pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.zero_grad "torch.nn.Module.zero_grad")()
        # Format batch
        [real_cpu](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor") = data[0].to([device](https://docs.pytorch.org/docs/stable/tensor_attributes.html#torch.device "torch.device"))
        b_size = [real_cpu](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor").size(0)
        [label](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor") = [torch.full](https://docs.pytorch.org/docs/stable/generated/torch.full.html#torch.full "torch.full")((b_size,), real_label, dtype=[torch.float](https://docs.pytorch.org/docs/stable/tensor_attributes.html#torch.dtype "torch.dtype"), [device](https://docs.pytorch.org/docs/stable/tensor_attributes.html#torch.device "torch.device")=[device](https://docs.pytorch.org/docs/stable/tensor_attributes.html#torch.device "torch.device"))
        # Forward pass real batch through D
        [output](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor") = netD([real_cpu](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor")).view(-1)
        # Calculate loss on all-real batch
        [errD_real](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor") = [criterion](https://docs.pytorch.org/docs/stable/generated/torch.nn.BCELoss.html#torch.nn.BCELoss "torch.nn.BCELoss")([output](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor"), [label](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor"))
        # Calculate gradients for D in backward pass
        [errD_real.backward](https://docs.pytorch.org/docs/stable/generated/torch.Tensor.backward.html#torch.Tensor.backward "torch.Tensor.backward")()
        D_x = [output](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor").mean().item()

        ## Train with all-fake batch
        # Generate batch of latent vectors
        [noise](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor") = [torch.randn](https://docs.pytorch.org/docs/stable/generated/torch.randn.html#torch.randn "torch.randn")(b_size, nz, 1, 1, [device](https://docs.pytorch.org/docs/stable/tensor_attributes.html#torch.device "torch.device")=[device](https://docs.pytorch.org/docs/stable/tensor_attributes.html#torch.device "torch.device"))
        # Generate fake image batch with G
        [fake](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor") = netG([noise](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor"))
        [label](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor").fill_(fake_label)
        # Classify all fake batch with D
        [output](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor") = netD([fake](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor").detach()).view(-1)
        # Calculate D's loss on the all-fake batch
        [errD_fake](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor") = [criterion](https://docs.pytorch.org/docs/stable/generated/torch.nn.BCELoss.html#torch.nn.BCELoss "torch.nn.BCELoss")([output](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor"), [label](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor"))
        # Calculate the gradients for this batch, accumulated (summed) with previous gradients
        [errD_fake.backward](https://docs.pytorch.org/docs/stable/generated/torch.Tensor.backward.html#torch.Tensor.backward "torch.Tensor.backward")()
        D_G_z1 = [output](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor").mean().item()
        # Compute error of D as sum over the fake and the real batches
        [errD](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor") = [errD_real](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor") + [errD_fake](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor")
        # Update D
        [optimizerD.step](https://docs.pytorch.org/docs/stable/generated/torch.optim.Adam.html#torch.optim.Adam.step "torch.optim.Adam.step")()

        ############################
        # (2) Update G network: maximize log(D(G(z)))
        ###########################
        [netG.zero_grad](https://docs.pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.zero_grad "torch.nn.Module.zero_grad")()
        [label](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor").fill_(real_label)  # fake labels are real for generator cost
        # Since we just updated D, perform another forward pass of all-fake batch through D
        [output](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor") = netD([fake](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor")).view(-1)
        # Calculate G's loss based on this output
        [errG](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor") = [criterion](https://docs.pytorch.org/docs/stable/generated/torch.nn.BCELoss.html#torch.nn.BCELoss "torch.nn.BCELoss")([output](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor"), [label](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor"))
        # Calculate gradients for G
        [errG.backward](https://docs.pytorch.org/docs/stable/generated/torch.Tensor.backward.html#torch.Tensor.backward "torch.Tensor.backward")()
        D_G_z2 = [output](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor").mean().item()
        # Update G
        [optimizerG.step](https://docs.pytorch.org/docs/stable/generated/torch.optim.Adam.html#torch.optim.Adam.step "torch.optim.Adam.step")()

        # Output training stats
        if i % 50 == 0:
            print('[%d/%d][%d/%d]\tLoss_D: %.4f\tLoss_G: %.4f\tD(x): %.4f\tD(G(z)): %.4f / %.4f'
                  % (epoch, num_epochs, i, len([dataloader](https://docs.pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader "torch.utils.data.DataLoader")),
                     [errD](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor").item(), [errG](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor").item(), D_x, D_G_z1, D_G_z2))

        # Save Losses for plotting later
        G_losses.append([errG](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor").item())
        D_losses.append([errD](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor").item())

        # Check how the generator is doing by saving G's output on fixed_noise
        if (iters % 500 == 0) or ((epoch == num_epochs-1) and (i == len([dataloader](https://docs.pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader "torch.utils.data.DataLoader"))-1)):
            with [torch.no_grad](https://docs.pytorch.org/docs/stable/generated/torch.no_grad.html#torch.no_grad "torch.no_grad")():
                [fake](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor") = netG([fixed_noise](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor")).detach().cpu()
            img_list.append([vutils.make_grid](https://docs.pytorch.org/vision/stable/generated/torchvision.utils.make_grid.html#torchvision.utils.make_grid "torchvision.utils.make_grid")([fake](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor"), padding=2, normalize=True))

        iters += 1

```
Copy to clipboard

```
Starting Training Loop...
[0/5][0/1583]   Loss_D: 1.4639  Loss_G: 6.9363  D(x): 0.7143    D(G(z)): 0.5877 / 0.0017
[0/5][50/1583]  Loss_D: 0.0335  Loss_G: 16.0282 D(x): 0.9813    D(G(z)): 0.0000 / 0.0000
[0/5][100/1583] Loss_D: 0.4136  Loss_G: 3.8454  D(x): 0.8426    D(G(z)): 0.1067 / 0.0408
[0/5][150/1583] Loss_D: 0.5206  Loss_G: 4.0907  D(x): 0.7922    D(G(z)): 0.1732 / 0.0333
[0/5][200/1583] Loss_D: 2.3379  Loss_G: 13.0434 D(x): 0.9244    D(G(z)): 0.8178 / 0.0000
[0/5][250/1583] Loss_D: 0.3563  Loss_G: 5.1989  D(x): 0.8698    D(G(z)): 0.1518 / 0.0089
[0/5][300/1583] Loss_D: 1.0709  Loss_G: 1.6531  D(x): 0.4849    D(G(z)): 0.0507 / 0.2972
[0/5][350/1583] Loss_D: 0.4713  Loss_G: 6.0641  D(x): 0.9406    D(G(z)): 0.2967 / 0.0053
[0/5][400/1583] Loss_D: 0.8053  Loss_G: 7.5662  D(x): 0.9341    D(G(z)): 0.4660 / 0.0016
[0/5][450/1583] Loss_D: 0.5695  Loss_G: 4.7134  D(x): 0.8291    D(G(z)): 0.2157 / 0.0217
[0/5][500/1583] Loss_D: 1.0662  Loss_G: 2.7778  D(x): 0.4828    D(G(z)): 0.0906 / 0.1134
[0/5][550/1583] Loss_D: 0.3802  Loss_G: 4.1184  D(x): 0.7979    D(G(z)): 0.0655 / 0.0302
[0/5][600/1583] Loss_D: 0.3569  Loss_G: 5.8982  D(x): 0.8807    D(G(z)): 0.1630 / 0.0052
[0/5][650/1583] Loss_D: 0.6227  Loss_G: 5.1058  D(x): 0.6387    D(G(z)): 0.0158 / 0.0134
[0/5][700/1583] Loss_D: 0.5803  Loss_G: 7.0945  D(x): 0.9065    D(G(z)): 0.3245 / 0.0021
[0/5][750/1583] Loss_D: 0.2599  Loss_G: 8.5842  D(x): 0.8288    D(G(z)): 0.0063 / 0.0011
[0/5][800/1583] Loss_D: 0.8226  Loss_G: 8.1796  D(x): 0.9771    D(G(z)): 0.4773 / 0.0007
[0/5][850/1583] Loss_D: 0.6746  Loss_G: 4.8579  D(x): 0.8342    D(G(z)): 0.2834 / 0.0246
[0/5][900/1583] Loss_D: 0.4721  Loss_G: 3.1009  D(x): 0.7903    D(G(z)): 0.1481 / 0.0659
[0/5][950/1583] Loss_D: 0.8599  Loss_G: 1.6909  D(x): 0.6047    D(G(z)): 0.1094 / 0.2435
[0/5][1000/1583]        Loss_D: 0.6415  Loss_G: 4.8156  D(x): 0.8288    D(G(z)): 0.2918 / 0.0197
[0/5][1050/1583]        Loss_D: 0.4587  Loss_G: 3.6132  D(x): 0.8037    D(G(z)): 0.1277 / 0.0458
[0/5][1100/1583]        Loss_D: 0.8629  Loss_G: 6.4246  D(x): 0.9380    D(G(z)): 0.4683 / 0.0045
[0/5][1150/1583]        Loss_D: 0.4934  Loss_G: 6.4047  D(x): 0.9231    D(G(z)): 0.2861 / 0.0032
[0/5][1200/1583]        Loss_D: 0.4716  Loss_G: 3.6436  D(x): 0.8290    D(G(z)): 0.1614 / 0.0494
[0/5][1250/1583]        Loss_D: 0.4101  Loss_G: 3.6744  D(x): 0.7819    D(G(z)): 0.0860 / 0.0528
[0/5][1300/1583]        Loss_D: 1.0250  Loss_G: 2.1397  D(x): 0.5451    D(G(z)): 0.1394 / 0.1862
[0/5][1350/1583]        Loss_D: 0.7924  Loss_G: 2.7885  D(x): 0.7071    D(G(z)): 0.2612 / 0.0861
[0/5][1400/1583]        Loss_D: 0.3543  Loss_G: 2.2940  D(x): 0.8108    D(G(z)): 0.0950 / 0.1510
[0/5][1450/1583]        Loss_D: 1.6106  Loss_G: 1.8363  D(x): 0.2962    D(G(z)): 0.0046 / 0.2410
[0/5][1500/1583]        Loss_D: 0.6485  Loss_G: 5.9762  D(x): 0.8651    D(G(z)): 0.3407 / 0.0047
[0/5][1550/1583]        Loss_D: 0.4995  Loss_G: 4.7542  D(x): 0.8385    D(G(z)): 0.2170 / 0.0170
[1/5][0/1583]   Loss_D: 0.3602  Loss_G: 3.8552  D(x): 0.7658    D(G(z)): 0.0422 / 0.0393
[1/5][50/1583]  Loss_D: 1.0677  Loss_G: 2.4240  D(x): 0.4761    D(G(z)): 0.0200 / 0.1430
[1/5][100/1583] Loss_D: 1.6919  Loss_G: 1.2506  D(x): 0.2777    D(G(z)): 0.0131 / 0.3854
[1/5][150/1583] Loss_D: 0.8513  Loss_G: 6.0725  D(x): 0.9375    D(G(z)): 0.4965 / 0.0036
[1/5][200/1583] Loss_D: 0.4481  Loss_G: 3.6840  D(x): 0.8617    D(G(z)): 0.2120 / 0.0417
[1/5][250/1583] Loss_D: 0.4869  Loss_G: 2.3636  D(x): 0.7251    D(G(z)): 0.0814 / 0.1519
[1/5][300/1583] Loss_D: 0.8142  Loss_G: 6.4943  D(x): 0.9433    D(G(z)): 0.4643 / 0.0037
[1/5][350/1583] Loss_D: 0.3275  Loss_G: 4.3855  D(x): 0.9001    D(G(z)): 0.1706 / 0.0222
[1/5][400/1583] Loss_D: 1.0553  Loss_G: 5.4383  D(x): 0.9198    D(G(z)): 0.5340 / 0.0113
[1/5][450/1583] Loss_D: 0.5342  Loss_G: 3.4719  D(x): 0.6642    D(G(z)): 0.0172 / 0.0567
[1/5][500/1583] Loss_D: 0.3529  Loss_G: 4.2050  D(x): 0.7726    D(G(z)): 0.0433 / 0.0253
[1/5][550/1583] Loss_D: 0.3481  Loss_G: 4.0055  D(x): 0.8610    D(G(z)): 0.1469 / 0.0340
[1/5][600/1583] Loss_D: 0.5269  Loss_G: 2.7998  D(x): 0.7031    D(G(z)): 0.0880 / 0.0907
[1/5][650/1583] Loss_D: 0.4778  Loss_G: 3.2417  D(x): 0.8108    D(G(z)): 0.1782 / 0.0572
[1/5][700/1583] Loss_D: 0.8457  Loss_G: 5.6924  D(x): 0.9377    D(G(z)): 0.4784 / 0.0070
[1/5][750/1583] Loss_D: 1.6658  Loss_G: 5.8465  D(x): 0.9556    D(G(z)): 0.7095 / 0.0075
[1/5][800/1583] Loss_D: 0.4271  Loss_G: 4.4940  D(x): 0.9294    D(G(z)): 0.2713 / 0.0171
[1/5][850/1583] Loss_D: 0.5112  Loss_G: 2.2343  D(x): 0.7473    D(G(z)): 0.1261 / 0.1398
[1/5][900/1583] Loss_D: 0.5887  Loss_G: 4.0595  D(x): 0.8503    D(G(z)): 0.3015 / 0.0312
[1/5][950/1583] Loss_D: 0.8232  Loss_G: 1.7852  D(x): 0.5429    D(G(z)): 0.0224 / 0.2250
[1/5][1000/1583]        Loss_D: 0.5225  Loss_G: 2.9947  D(x): 0.7243    D(G(z)): 0.1102 / 0.0916
[1/5][1050/1583]        Loss_D: 0.4546  Loss_G: 2.7369  D(x): 0.7663    D(G(z)): 0.1208 / 0.0863
[1/5][1100/1583]        Loss_D: 0.5109  Loss_G: 2.0627  D(x): 0.7003    D(G(z)): 0.0734 / 0.1667
[1/5][1150/1583]        Loss_D: 0.5148  Loss_G: 1.9273  D(x): 0.7022    D(G(z)): 0.0851 / 0.1940
[1/5][1200/1583]        Loss_D: 0.4869  Loss_G: 3.4446  D(x): 0.9155    D(G(z)): 0.2814 / 0.0543
[1/5][1250/1583]        Loss_D: 2.1255  Loss_G: 8.5872  D(x): 0.9635    D(G(z)): 0.8007 / 0.0004
[1/5][1300/1583]        Loss_D: 0.5144  Loss_G: 3.7323  D(x): 0.9250    D(G(z)): 0.3080 / 0.0413
[1/5][1350/1583]        Loss_D: 0.4774  Loss_G: 2.0437  D(x): 0.7005    D(G(z)): 0.0573 / 0.1662
[1/5][1400/1583]        Loss_D: 0.6017  Loss_G: 3.7591  D(x): 0.8787    D(G(z)): 0.3448 / 0.0338
[1/5][1450/1583]        Loss_D: 0.3361  Loss_G: 2.5965  D(x): 0.8415    D(G(z)): 0.1248 / 0.1041
[1/5][1500/1583]        Loss_D: 0.6442  Loss_G: 3.5299  D(x): 0.8733    D(G(z)): 0.3358 / 0.0457
[1/5][1550/1583]        Loss_D: 0.5264  Loss_G: 3.3173  D(x): 0.8866    D(G(z)): 0.2955 / 0.0530
[2/5][0/1583]   Loss_D: 0.4355  Loss_G: 2.9453  D(x): 0.8170    D(G(z)): 0.1740 / 0.0790
[2/5][50/1583]  Loss_D: 0.5613  Loss_G: 2.2878  D(x): 0.7624    D(G(z)): 0.1989 / 0.1445
[2/5][100/1583] Loss_D: 0.4071  Loss_G: 2.8658  D(x): 0.8440    D(G(z)): 0.1788 / 0.0787
[2/5][150/1583] Loss_D: 0.7194  Loss_G: 2.3804  D(x): 0.6915    D(G(z)): 0.2386 / 0.1237
[2/5][200/1583] Loss_D: 0.7337  Loss_G: 3.2976  D(x): 0.8361    D(G(z)): 0.3657 / 0.0505
[2/5][250/1583] Loss_D: 0.6978  Loss_G: 1.1942  D(x): 0.5845    D(G(z)): 0.0600 / 0.3464
[2/5][300/1583] Loss_D: 1.8758  Loss_G: 0.1049  D(x): 0.2247    D(G(z)): 0.0231 / 0.9067
[2/5][350/1583] Loss_D: 0.7192  Loss_G: 1.6271  D(x): 0.7092    D(G(z)): 0.2432 / 0.2475
[2/5][400/1583] Loss_D: 0.9044  Loss_G: 4.5618  D(x): 0.9135    D(G(z)): 0.5016 / 0.0175
[2/5][450/1583] Loss_D: 0.4705  Loss_G: 2.6927  D(x): 0.8290    D(G(z)): 0.2166 / 0.0926
[2/5][500/1583] Loss_D: 0.9481  Loss_G: 1.7050  D(x): 0.4741    D(G(z)): 0.0644 / 0.2479
[2/5][550/1583] Loss_D: 0.8897  Loss_G: 1.5763  D(x): 0.5010    D(G(z)): 0.0646 / 0.2718
[2/5][600/1583] Loss_D: 0.6414  Loss_G: 4.1424  D(x): 0.8967    D(G(z)): 0.3749 / 0.0225
[2/5][650/1583] Loss_D: 1.1566  Loss_G: 0.6323  D(x): 0.4067    D(G(z)): 0.0403 / 0.5921
[2/5][700/1583] Loss_D: 0.7189  Loss_G: 4.4080  D(x): 0.8873    D(G(z)): 0.4014 / 0.0205
[2/5][750/1583] Loss_D: 0.6507  Loss_G: 3.0001  D(x): 0.8545    D(G(z)): 0.3497 / 0.0659
[2/5][800/1583] Loss_D: 0.5050  Loss_G: 2.2567  D(x): 0.7411    D(G(z)): 0.1453 / 0.1463
[2/5][850/1583] Loss_D: 0.6416  Loss_G: 1.8507  D(x): 0.6685    D(G(z)): 0.1546 / 0.1972
[2/5][900/1583] Loss_D: 0.5452  Loss_G: 2.5952  D(x): 0.8675    D(G(z)): 0.2913 / 0.0956
[2/5][950/1583] Loss_D: 0.7234  Loss_G: 2.6786  D(x): 0.7113    D(G(z)): 0.2608 / 0.0905
[2/5][1000/1583]        Loss_D: 0.5062  Loss_G: 2.4790  D(x): 0.7909    D(G(z)): 0.2073 / 0.1052
[2/5][1050/1583]        Loss_D: 0.7153  Loss_G: 2.3895  D(x): 0.8569    D(G(z)): 0.3822 / 0.1211
[2/5][1100/1583]        Loss_D: 0.8595  Loss_G: 3.8420  D(x): 0.9298    D(G(z)): 0.5028 / 0.0325
[2/5][1150/1583]        Loss_D: 0.6264  Loss_G: 2.0854  D(x): 0.7232    D(G(z)): 0.2128 / 0.1611
[2/5][1200/1583]        Loss_D: 0.7019  Loss_G: 3.6000  D(x): 0.8918    D(G(z)): 0.3990 / 0.0429
[2/5][1250/1583]        Loss_D: 0.5670  Loss_G: 2.2590  D(x): 0.7721    D(G(z)): 0.2216 / 0.1288
[2/5][1300/1583]        Loss_D: 0.5370  Loss_G: 2.5245  D(x): 0.7748    D(G(z)): 0.2041 / 0.1076
[2/5][1350/1583]        Loss_D: 1.2343  Loss_G: 5.6195  D(x): 0.9171    D(G(z)): 0.6329 / 0.0070
[2/5][1400/1583]        Loss_D: 0.7298  Loss_G: 3.7086  D(x): 0.8529    D(G(z)): 0.3842 / 0.0335
[2/5][1450/1583]        Loss_D: 0.5449  Loss_G: 3.5281  D(x): 0.8691    D(G(z)): 0.3028 / 0.0389
[2/5][1500/1583]        Loss_D: 0.6057  Loss_G: 1.9677  D(x): 0.6187    D(G(z)): 0.0668 / 0.1777
[2/5][1550/1583]        Loss_D: 0.4917  Loss_G: 3.4132  D(x): 0.8972    D(G(z)): 0.2894 / 0.0423
[3/5][0/1583]   Loss_D: 0.5575  Loss_G: 1.8105  D(x): 0.7082    D(G(z)): 0.1537 / 0.2037
[3/5][50/1583]  Loss_D: 1.7413  Loss_G: 5.1448  D(x): 0.9646    D(G(z)): 0.7700 / 0.0103
[3/5][100/1583] Loss_D: 1.1206  Loss_G: 1.3007  D(x): 0.4276    D(G(z)): 0.0554 / 0.3365
[3/5][150/1583] Loss_D: 0.5955  Loss_G: 1.7999  D(x): 0.7076    D(G(z)): 0.1747 / 0.2029
[3/5][200/1583] Loss_D: 0.6961  Loss_G: 3.7222  D(x): 0.8321    D(G(z)): 0.3667 / 0.0321
[3/5][250/1583] Loss_D: 0.4007  Loss_G: 2.8452  D(x): 0.7988    D(G(z)): 0.1379 / 0.0781
[3/5][300/1583] Loss_D: 0.6564  Loss_G: 2.0469  D(x): 0.7051    D(G(z)): 0.2095 / 0.1643
[3/5][350/1583] Loss_D: 0.6704  Loss_G: 1.3749  D(x): 0.6466    D(G(z)): 0.1634 / 0.2931
[3/5][400/1583] Loss_D: 0.6857  Loss_G: 2.0913  D(x): 0.5764    D(G(z)): 0.0540 / 0.1542
[3/5][450/1583] Loss_D: 0.6722  Loss_G: 3.6257  D(x): 0.8451    D(G(z)): 0.3591 / 0.0353
[3/5][500/1583] Loss_D: 1.2377  Loss_G: 0.6136  D(x): 0.3546    D(G(z)): 0.0484 / 0.5801
[3/5][550/1583] Loss_D: 0.4995  Loss_G: 2.5051  D(x): 0.8135    D(G(z)): 0.2210 / 0.1020
[3/5][600/1583] Loss_D: 0.7371  Loss_G: 1.3311  D(x): 0.5612    D(G(z)): 0.0663 / 0.3027
[3/5][650/1583] Loss_D: 0.5689  Loss_G: 1.7670  D(x): 0.6286    D(G(z)): 0.0547 / 0.2199
[3/5][700/1583] Loss_D: 0.5304  Loss_G: 2.7843  D(x): 0.8501    D(G(z)): 0.2718 / 0.0785
[3/5][750/1583] Loss_D: 0.4839  Loss_G: 2.3616  D(x): 0.8008    D(G(z)): 0.2041 / 0.1190
[3/5][800/1583] Loss_D: 0.5746  Loss_G: 2.0189  D(x): 0.6863    D(G(z)): 0.1333 / 0.1655
[3/5][850/1583] Loss_D: 0.8328  Loss_G: 3.7750  D(x): 0.8823    D(G(z)): 0.4617 / 0.0326
[3/5][900/1583] Loss_D: 0.5305  Loss_G: 2.9058  D(x): 0.8745    D(G(z)): 0.2987 / 0.0696
[3/5][950/1583] Loss_D: 0.5446  Loss_G: 2.5951  D(x): 0.8808    D(G(z)): 0.2981 / 0.1071
[3/5][1000/1583]        Loss_D: 0.5476  Loss_G: 2.1378  D(x): 0.6528    D(G(z)): 0.0669 / 0.1621
[3/5][1050/1583]        Loss_D: 0.9009  Loss_G: 1.1014  D(x): 0.5071    D(G(z)): 0.0916 / 0.3846
[3/5][1100/1583]        Loss_D: 0.5750  Loss_G: 2.9691  D(x): 0.8845    D(G(z)): 0.3302 / 0.0663
[3/5][1150/1583]        Loss_D: 0.8456  Loss_G: 1.7220  D(x): 0.6015    D(G(z)): 0.2135 / 0.2143
[3/5][1200/1583]        Loss_D: 0.5376  Loss_G: 1.9356  D(x): 0.7530    D(G(z)): 0.1877 / 0.1840
[3/5][1250/1583]        Loss_D: 0.9893  Loss_G: 3.8034  D(x): 0.9370    D(G(z)): 0.5492 / 0.0315
[3/5][1300/1583]        Loss_D: 0.8103  Loss_G: 1.5027  D(x): 0.5088    D(G(z)): 0.0404 / 0.2727
[3/5][1350/1583]        Loss_D: 0.5382  Loss_G: 1.4694  D(x): 0.7231    D(G(z)): 0.1599 / 0.2731
[3/5][1400/1583]        Loss_D: 1.0334  Loss_G: 1.0126  D(x): 0.4632    D(G(z)): 0.1031 / 0.4122
[3/5][1450/1583]        Loss_D: 0.4757  Loss_G: 1.9061  D(x): 0.7601    D(G(z)): 0.1547 / 0.1823
[3/5][1500/1583]        Loss_D: 0.6546  Loss_G: 3.2963  D(x): 0.8076    D(G(z)): 0.3076 / 0.0504
[3/5][1550/1583]        Loss_D: 0.7705  Loss_G: 3.2457  D(x): 0.8294    D(G(z)): 0.3949 / 0.0516
[4/5][0/1583]   Loss_D: 0.6028  Loss_G: 2.3475  D(x): 0.7754    D(G(z)): 0.2488 / 0.1262
[4/5][50/1583]  Loss_D: 0.7614  Loss_G: 3.9099  D(x): 0.9312    D(G(z)): 0.4557 / 0.0279
[4/5][100/1583] Loss_D: 1.3392  Loss_G: 0.6799  D(x): 0.3213    D(G(z)): 0.0230 / 0.5560
[4/5][150/1583] Loss_D: 0.5082  Loss_G: 3.0762  D(x): 0.8566    D(G(z)): 0.2760 / 0.0600
[4/5][200/1583] Loss_D: 0.8252  Loss_G: 4.0072  D(x): 0.9221    D(G(z)): 0.4694 / 0.0296
[4/5][250/1583] Loss_D: 0.4909  Loss_G: 2.6500  D(x): 0.7729    D(G(z)): 0.1818 / 0.0935
[4/5][300/1583] Loss_D: 0.6793  Loss_G: 3.8483  D(x): 0.8954    D(G(z)): 0.3954 / 0.0293
[4/5][350/1583] Loss_D: 0.5959  Loss_G: 3.2546  D(x): 0.8589    D(G(z)): 0.3267 / 0.0502
[4/5][400/1583] Loss_D: 0.7204  Loss_G: 1.8128  D(x): 0.5761    D(G(z)): 0.0747 / 0.2132
[4/5][450/1583] Loss_D: 0.6253  Loss_G: 3.8699  D(x): 0.9221    D(G(z)): 0.3843 / 0.0295
[4/5][500/1583] Loss_D: 0.5200  Loss_G: 2.4470  D(x): 0.7570    D(G(z)): 0.1796 / 0.1181
[4/5][550/1583] Loss_D: 0.9892  Loss_G: 4.7044  D(x): 0.8942    D(G(z)): 0.5066 / 0.0135
[4/5][600/1583] Loss_D: 0.4343  Loss_G: 2.9781  D(x): 0.8453    D(G(z)): 0.2101 / 0.0642
[4/5][650/1583] Loss_D: 1.5967  Loss_G: 4.2490  D(x): 0.9419    D(G(z)): 0.7255 / 0.0231
[4/5][700/1583] Loss_D: 0.5672  Loss_G: 3.5243  D(x): 0.8898    D(G(z)): 0.3383 / 0.0360
[4/5][750/1583] Loss_D: 0.5089  Loss_G: 3.1110  D(x): 0.8679    D(G(z)): 0.2821 / 0.0553
[4/5][800/1583] Loss_D: 0.6581  Loss_G: 3.1131  D(x): 0.7878    D(G(z)): 0.2940 / 0.0682
[4/5][850/1583] Loss_D: 1.3859  Loss_G: 0.6585  D(x): 0.3220    D(G(z)): 0.0369 / 0.6021
[4/5][900/1583] Loss_D: 0.5722  Loss_G: 3.0522  D(x): 0.8335    D(G(z)): 0.2775 / 0.0693
[4/5][950/1583] Loss_D: 0.4414  Loss_G: 2.5937  D(x): 0.8578    D(G(z)): 0.2228 / 0.1017
[4/5][1000/1583]        Loss_D: 0.5011  Loss_G: 2.4809  D(x): 0.8281    D(G(z)): 0.2443 / 0.0999
[4/5][1050/1583]        Loss_D: 0.7283  Loss_G: 1.9399  D(x): 0.6368    D(G(z)): 0.1740 / 0.1767
[4/5][1100/1583]        Loss_D: 0.4500  Loss_G: 3.4137  D(x): 0.9333    D(G(z)): 0.2733 / 0.0502
[4/5][1150/1583]        Loss_D: 0.7120  Loss_G: 3.4910  D(x): 0.8907    D(G(z)): 0.3977 / 0.0437
[4/5][1200/1583]        Loss_D: 0.5525  Loss_G: 2.6768  D(x): 0.8155    D(G(z)): 0.2422 / 0.0931
[4/5][1250/1583]        Loss_D: 0.6997  Loss_G: 1.5459  D(x): 0.5832    D(G(z)): 0.0603 / 0.2608
[4/5][1300/1583]        Loss_D: 0.4300  Loss_G: 2.2103  D(x): 0.7592    D(G(z)): 0.1148 / 0.1421
[4/5][1350/1583]        Loss_D: 2.4836  Loss_G: 5.5115  D(x): 0.9568    D(G(z)): 0.8612 / 0.0065
[4/5][1400/1583]        Loss_D: 0.9552  Loss_G: 3.1371  D(x): 0.8761    D(G(z)): 0.5150 / 0.0606
[4/5][1450/1583]        Loss_D: 0.5326  Loss_G: 1.7700  D(x): 0.7328    D(G(z)): 0.1584 / 0.2052
[4/5][1500/1583]        Loss_D: 0.7565  Loss_G: 3.8208  D(x): 0.8543    D(G(z)): 0.4054 / 0.0292
[4/5][1550/1583]        Loss_D: 0.5943  Loss_G: 2.3004  D(x): 0.7305    D(G(z)): 0.2107 / 0.1229

```
Copy to clipboard
## Results[#](https://docs.pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html#results "Link to this heading")
Finally, lets check out how we did. Here, we will look at three different results. First, we will see how D and G’s losses changed during training. Second, we will visualize G’s output on the fixed_noise batch for every epoch. And third, we will look at a batch of real data next to a batch of fake data from G.
**Loss versus training iteration**
Below is a plot of D & G’s losses versus training iterations.

```
plt.figure(figsize=(10,5))
plt.title("Generator and Discriminator Loss During Training")
plt.plot(G_losses,[label](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor")="G")
plt.plot(D_losses,[label](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor")="D")
plt.xlabel("iterations")
plt.ylabel("Loss")
plt.legend()
plt.show()

```
Copy to clipboard
![Generator and Discriminator Loss During Training](../images/body-b9388f8e452d33cce997.png)
**Visualization of G’s progression**
Remember how we saved the generator’s output on the fixed_noise batch after every epoch of training. Now, we can visualize the training progression of G with an animation. Press the play button to start the animation.

```
fig = plt.figure(figsize=(8,8))
plt.axis("off")
ims = [[plt.imshow(np.transpose(i,(1,2,0)), animated=True)] for i in img_list]
ani = animation.ArtistAnimation(fig, ims, interval=1000, repeat_delay=1000, blit=True)

HTML(ani.to_jshtml())

```
Copy to clipboard
![dcgan faces tutorial](../images/body-c7266476e6dd85c876db.png)
![](https://docs.pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html)
Once Loop Reflect
