tensorflow-gpu 安装

windows

在 wsl2 上 使用 tensorflow-gpu

  • 参考

  • windows 端:

  • wsl2 端:

    • 安装 cuda

      1
      2
      3
      4
      5
      6
      7
      
      # * 注意 ubuntu 版本
      apt-key adv --fetch-keys http://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/7fa2af80.pub
      sh -c 'echo "deb http://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64 /" > /etc/apt/sources.list.d/cuda.list'
      
      sudo apt-key adv --fetch-keys http://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64/7fa2af80.pub
      sudo sh -c 'echo "deb http://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64 /" > /etc/apt/sources.list.d/cuda.list'
      sudo apt-get update && sudo apt-get install -y cuda-toolkit-11-0
    • 运行程序

      • 普通 cuda 支持的程序
      • 在 docker 中 运行

测试是否安装成功

  • 即,是否能够使用 gpu

    1
    
    import tensorflow as tf; tf.test.gpu_device_name()

python + tensorflow

1
conda install cudatoolkit cudnn tensorflow

创建变量

  • 构建张量

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    
    tf.zeros([2,3])
    
    # * 1 维: 2
    # * 2 维: [2, 3]
    # * ...
    
    tf.ones()
    tf.fill()
    
    tf.random.normal()
    tf.random.truncated_normal()  # 2sigma
    
    
    # * 类型转换
    tf.cast()
    # * 计算最值
    tf.reduce_min()
    tf.reduce_max()
    # * 求和
    tf.sum()
  • 标记变量

    • tf.Variable()

      • 标记为可训练,以实现可以被训练更新

axis 指定

  • 0 –> 不同行,即:同一列
  • 1 –> 不同列,即:同一行

    1
    
    tf.reduce_max(name, axis=0)

数学运算

  • 四则运算

    • 加:tf.add
    • 减:tf.substract
    • 乘:tf.multiply
    • 除:tf.divide
    • 注意

      • 需要变量的维度相同
    • tf.square
    • tf.pow
    • tf.sqrt
  • 矩阵乘法

    • tf.matmul
  • 特殊功能

    • i–

      • tf.assign_sub
    • 注意:必须是 tf.Variable 标记了的变量
    • argmax

      • tf.argmax
      • 类似 numpy argmax

        • 指定维度最值

特征—-标签配对

1
tf.data.Dataset.from_tensor_slices((features, labels))

求导

1
2
3
4
5
6
with tf.GradientTap() as tap:
    # ... 计算过程(损失函数)
    pass
    grad = tap.gradient(loss, w)
    # loss --> 损失函数
    # w --> 对谁求导

独热码

  • tf.one_hot(labels, deps=分类数)

    1
    2
    3
    4
    5
    6
    7
    
    classes = 3
    labels = tf.Contant([1, 0, 2])
    output = tf.one_hot(labels, deps=classes)
    # output:
    [[0, 1, 0],
     [1, 0, 0],
     [0, 0, 1]]
  • 作用

    • 原来—> 一个数,不同数值表示不同分类
    • 转换成 –> 一个向量,表示使用 0 和 1 分类

输出函数

  • tf.nn.softmax
  • 作用

    • 转换成概率分布

      1
      
      e^y_given / sum(e^y_i)

训练集

  • 从 sklearn.dataset 获取

    1
    2
    3
    
    from sklearn.datasets import load_iris
    x_data = load_iris().data  # feature
    y_data = load_iris().target # label