Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

TensorFlow Environment Setup

TensorFlow Environment Setup

TensorFlow 2.x has specific requirements for Python versions:

TensorFlow version Python version support
TensorFlow 2.15+ Python 3.9-3.12
TensorFlow 2.12-2.14 Python 3.8-3.11
TensorFlow 2.8-2.11 Python 3.7-3.10

Python 3.9-3.11 is recommended, these versions offer the best compatibility and stability.

Check the current Python version

# 检查 Python 版本

python --version

# 或

python3 --version



# Check pip version

pip --version

# 或

pip3 --version

Python Installation Options

Option 1: Official Python (recommended for beginners)

Option 2: Anaconda/Miniconda (recommended for data science)

Option 3: System package manager

# Ubuntu/Debian

sudo apt update

sudo apt install python3 python3-pip



# macOS (using Homebrew)

brew install python3



# Windows (using Chocolatey)

choco install python3


Virtual Environment Setup (Highly Recommended)

Why Use a Virtual Environment

Benefits:

Create a virtual environment with venv

# 创建虚拟环境

python -m venv tensorflow_env



# Activate virtual environment

# Windows:

tensorflow_env\Scripts\activate

# macOS/Linux:

source tensorflow_env/bin/activate



# Confirm activation (prompt will show environment name)

which python  # 应该指向虚拟环境中的 python



# 升级 pip

python -m pip install --upgrade pip

Create a virtual environment with Conda

# 创建新环境

conda create -n tensorflow_env python=3.10



# Activate environment

conda activate tensorflow_env



# List all environments

conda env list



# Install packages in the environment

conda install pip

Virtual environment management



# List installed packages

pip list



# Generate dependency files

pip freeze > requirements.txt



# Install dependencies from file

pip install -r requirements.txt



# exit virtual environment

deactivate  # venv

conda deactivate  # conda



# Delete virtual environment

rm -rf tensorflow_env  # venv

conda env remove -n tensorflow_env  # conda


TensorFlow Installation

CPU version installation (suitable for learning and lightweight tasks)



# Ensure in virtual environment

pip install tensorflow



# Verify installation

python -c "import tensorflow as tf; print('TensorFlow version:', tf.__version__)"

Features of the CPU version:

GPU version installation (suitable for large-scale training)

GPU acceleration can significantly improve training speed, especially for deep learning tasks.

3.2.1 NVIDIA GPU Requirements

Hardware requirements:

Check GPU information:



# Windows

nvidia-smi



# Linux

lspci | grep -i nvidia

CUDA and cuDNN Installation

TensorFlow 2.15+ and CUDA Version Correspondence:

TensorFlow CUDA cuDNN
2.15+ 12.2 8.9
2.12-2.14 11.8 8.6

Installation Steps:

  1. Download and install CUDA Toolkit

  2. Access the NVIDIA CUDA Toolkit
  3. Select the corresponding version to download and install
  4. Add to system PATH
  5. - Visit [NVIDIA CUDA Toolkit](https://developer.nvidia.com/cuda-toolkit) - Select the corresponding version to download and install - Add to system PATH
    1. Download and install cuDNN

    2. Access the NVIDIA cuDNN
    3. Need to register an NVIDIA account
    4. Extract to the CUDA installation directory
    5. - Visit [NVIDIA cuDNN](https://developer.nvidia.com/cudnn) - Need to register an NVIDIA account - Extract to the CUDA installation directory
      1. Verify CUDA installation

        nvcc --version
        
        

      nvidia-smi

      Install the TensorFlow GPU version

      
      
      # TensorFlow 2.10+ unified package name
      
      pip install tensorflow
      
      
      
      # Verify GPU availability
      
      python -c "
      
      import tensorflow as tf
      
      print('TensorFlow version:', tf.__version__)
      
      print('GPU available:', tf.config.list_physical_devices('GPU'))
      
      print('Built with CUDA:', tf.test.is_built_with_cuda())
      
      "
      
      

      Install via Conda

      
      
      # CPU 版本
      
      conda install tensorflow
      
      
      
      # or from conda-forge
      
      conda install -c conda-forge tensorflow
      
      
      
      # GPU version (automatic CUDA installation)
      
      conda install tensorflow-gpu
      
      

      Install a specific version

      
      
      # Install specific version
      
      pip install tensorflow==2.14.0
      
      
      
      # Install pre-release version
      
      pip install tf-nightly
      
      
      
      # Upgrade to the latest version
      
      pip install --upgrade tensorflow
      
      

      Development tool installation

      upyter Notebook/Lab

      Jupyter is the standard development environment for data science and machine learning:

      
      
      # Install Jupyter Notebook
      
      pip install jupyter notebook
      
      
      
      # Or install JupyterLab (recommended)
      
      pip install jupyterlab
      
      
      
      # Start Jupyter
      
      jupyter notebook
      
      # 或
      
      jupyter lab
      
      

      Jupyter extensions:

      
      
      # Install useful extensions
      
      pip install jupyter_contrib_nbextensions
      
      jupyter contrib nbextension install --user
      
      
      
      # Variable Checker
      
      pip install nbextensions
      
      

      IDE selection

      Visual Studio Code (recommended):

      PyCharm:

      Google Colab (cloud option):

      Necessary Python packages

      
      
      # Data processing
      
      pip install numpy pandas matplotlib seaborn
      
      
      
      # Scientific Computing
      
      pip install scipy scikit-learn
      
      
      
      # Image processing
      
      pip install pillow opencv-python
      
      
      
      # Progress bar and utility tools
      
      pip install tqdm
      
      
      
      # Create a complete requirements file
      
      cat > requirements.txt << EOF
      
      tensorflow>=2.12.0
      
      numpy>=1.21.0
      
      pandas>=1.3.0
      
      matplotlib>=3.5.0
      
      seaborn>=0.11.0
      
      scikit-learn>=1.0.0
      
      jupyter>=1.0.0
      
      tqdm>=4.60.0
      
      pillow>=8.0.0
      
      EOF
      
      
      
      # Batch install
      
      pip install -r requirements.txt
      
      

      Configuration verification

      Complete installation verification script

      creation verify_installation.py File:

      Example

      #!/usr/bin/env python3

      """
      TensorFlow installation verification script
      """

      import

      sys

      print

      (

      "Python version:"

      ,

      sys

      .

      version

      )

      print

      (

      "-"

      50

      )

      Check TensorFlow

      try

      :

         

      import

      tensorflow

      as

      tf

         

      print

      (

      f

      "✓ TensorFlow version: {tf.version}"

      )

         

      print

      (

      f

      "✓ Keras version: {tf.keras.version}"

      )

         

         

      Check GPU support

          physical_devices

      =

      tf.

      config

      .

      list_physical_devices

      (

      'GPU'

      )

         

      if

      physical_devices:

             

      print

      (

      f

      "✓ GPU devices found: {len(physical_devices)}"

      )

             

      for

      i

      ,

      device

      in

      enumerate

      (

      physical_devices

      )

      :

                 

      print

      (

      f

      "  - GPU {i}: {device}"

      )

             

      print

      (

      f

      "✓ CUDA built: {tf.test.is_built_with_cuda()}"

      )

         

      else

      :

             

      print

      (

      "⚠ No GPU devices found (CPU only)"

      )

         

         

      Simple computation test

          a

      =

      tf.

      constant

      (

      [

      1

      ,

      2

      ,

      3

      ]

      )

          b

      =

      tf.

      constant

      (

      [

      4

      ,

      5

      ,

      6

      ]

      )

          c

      =

      tf.

      add

      (

      a

      ,

      b

      )

         

      print

      (

      f

      "✓ Basic computation test: {a.numpy()} + {b.numpy()} = {c.numpy()}"

      )

         

      except

      ImportError

      as

      e:

         

      print

      (

      f

      "✗ TensorFlow import failed: {e}"

      )

      print

      (

      "-"

      50

      )

      Check other important packages

      packages

      =

      [

      'numpy'

      ,

      'pandas'

      ,

      'matplotlib'

      ,

      'sklearn'

      ,

      'jupyter'

      ]

      for

      package

      in

      packages:

         

      try

      :

              module

      =

      import

      (

      package

      )

              version

      =

      getattr

      (

      module

      ,

      'version'

      ,

      'unknown'

      )

             

      print

      (

      f

      "✓ {package}: {version}"

      )

         

      except

      ImportError

      :

             

      print

      (

      f

      "✗ {package}: not installed"

      )

      print

      (

      "-"

      50

      )

      Memory and device information

      print

      (

      "System Information:"

      )

      if

      tf.

      config

      .

      list_physical_devices

      (

      'GPU'

      )

      :

         

      for

      gpu

      in

      tf.

      config

      .

      list_physical_devices

      (

      'GPU'

      )

      :

             

      try

      :

                  tf.

      config

      .

      experimental

      .

      set_memory_growth

      (

      gpu

      ,

      True

      )

                 

      print

      (

      f

      "✓ GPU memory growth enabled for {gpu}"

      )

             

      except

      :

                 

      print

      (

      f

      "⚠ Could not set memory growth for {gpu}"

      )

      print

      (

      "Installation verification complete!"

      )

      Run verification:

      python verify_installation.py
      
      

      Performance benchmarking

      Create a simple performance test:

      Example

      import

      tensorflow

      as

      tf

      import

      time

      print

      (

      "TensorFlow Performance Test"

      )

      print

      (

      "-"

      30

      )

      Matrix multiplication test

      def

      benchmark_matmul

      (

      device_name

      ,

      size

      =

      1000

      )

      :

         

      with

      tf.

      device

      (

      device_name

      )

      :

              a

      =

      tf.

      random

      .

      normal

      (

      [

      size

      ,

      size

      ]

      )

              b

      =

      tf.

      random

      .

      normal

      (

      [

      size

      ,

      size

      ]

      )

             

             

      Warm-up

             

      for

      _

      in

      range

      (

      5

      )

      :

                  c

      =

      tf.

      matmul

      (

      a

      ,

      b

      )

             

             

      Timing

              start_time

      =

      time

      .

      time

      (

      )

             

      for

      _

      in

      range

      (

      10

      )

      :

                  c

      =

      tf.

      matmul

      (

      a

      ,

      b

      )

              end_time

      =

      time

      .

      time

      (

      )

             

              avg_time

      =

      (

      end_time - start_time

      )

      /

      10

             

      return

      avg_time

      CPU test

      cpu_time

      =

      benchmark_matmul

      (

      '/CPU:0'

      )

      print

      (

      f

      "CPU ({1000}x{1000} matmul): {cpu_time:.4f} seconds"

      )

      GPU test (if available)

      if

      tf.

      config

      .

      list_physical_devices

      (

      'GPU'

      )

      :

          gpu_time

      =

      benchmark_matmul

      (

      '/GPU:0'

      )

         

      print

      (

      f

      "GPU ({1000}x{1000} matmul): {gpu_time:.4f} seconds"

      )

         

      print

      (

      f

      "GPU speedup: {cpu_time/gpu_time:.2f}x"

      )

      else

      :

         

      print

      (

      "No GPU available for testing"

      )


      Common problems and solutions

      Installation problems

      Problem 1: pip installation timeout

      
      
      pip install --user tensorflow
      
      

      Problem 2: Permission error

      
      
      # Create a new virtual environment
      
      python -m venv fresh_env
      
      source fresh_env/bin/activate  # Linux/Mac
      
      # or fresh_env\Scripts\activate  # Windows
      
      pip install tensorflow
      
      

      Problem 3: Version conflict

      
      
      # Create a new virtual environment
      
      python -m venv fresh_env
      
      source fresh_env/bin/activate  # Linux/Mac
      
      # or fresh_env\Scripts\activate  # Windows
      
      pip install tensorflow
      
      

      GPU-related problems

      Problem 1: CUDA version mismatch

      Problem 2: Insufficient GPU memory

      
      
      # Set GPU memory growth
      
      gpus = tf.config.experimental.list_physical_devices('GPU')
      
      if gpus:
      
          for gpu in gpus:
      
              tf.config.experimental.set_memory_growth(gpu, True)
      
      

      Problem 3: Cannot find GPU

      
      
      # Check NVIDIA driver
      
      nvidia-smi
      
      
      
      # Check CUDA installation
      
      nvcc --version
      
      
      
      # Reinstall GPU support
      
      pip uninstall tensorflow
      
      pip install tensorflow
      
      

      Jupyter-related problems

      Problem 1: Virtual environment not visible in Jupyter

      
      
      # Install ipykernel
      
      pip install ipykernel
      
      
      
      # Add virtual environment to Jupyter
      
      python -m ipykernel install --user --name tensorflow_env --display-name "Python (TensorFlow)"
      
      

      Problem 2: Jupyter fails to start

      
      
      # Reinstall Jupyter
      
      pip uninstall jupyter notebook
      
      pip install jupyter notebook
      
      
      
      # or use conda
      
      conda install jupyter
      
      

      Development environment optimization

      GPU memory management

      
      
      # GPU Configuration Optimization
      
      import tensorflow as tf
      
      
      
      # Method 1: Set memory growth
      
      gpus = tf.config.experimental.list_physical_devices('GPU')
      
      if gpus:
      
          try:
      
              for gpu in gpus:
      
                  tf.config.experimental.set_memory_growth(gpu, True)
      
          except RuntimeError as e:
      
              print(e)
      
      
      
      # Method 2: Limit memory usage
      
      if gpus:
      
          try:
      
              tf.config.experimental.set_memory_limit(gpus[0], 4096)  # 4GB
      
          except RuntimeError as e:
      
              print(e)
      
      

      Performance optimization settings

      # 启用混合精度训练(提升性能)
      
      from tensorflow.keras.mixed_precision import experimental as mixed_precision
      
      
      
      policy = mixed_precision.Policy('mixed_float16')
      
      mixed_precision.set_policy(policy)
      
      
      
      # Enable XLA compilation optimization
      
      tf.config.optimizer.set_jit(True)
      
      

      Development tool configuration

      VS Code configuration (.vscode/settings.json):

      {
      
          "python.defaultInterpreterPath": "./tensorflow_env/bin/python",
      
          "python.linting.enabled": true,
      
          "python.linting.pylintEnabled": true,
      
          "jupyter.defaultKernel": "tensorflow_env"
      
      }
      
      

      Environment maintenance

      Update regularly

      
      
      # Update TensorFlow
      
      pip install --upgrade tensorflow
      
      
      
      # Update all packages
      
      pip list --outdated
      
      pip install --upgrade package_name
      
      
      
      # or batch update
      
      pip freeze | grep -v "^-e" | cut -d = -f 1 | xargs pip install -U
      
      

      Environment backup and migration

      
      
      # Export environment
      
      pip freeze > requirements.txt
      
      conda env export > environment.yml
      
      
      
      # Restore environment on new machine
      
      pip install -r requirements.txt
      
      conda env create -f environment.yml