TensorFlow深度学习教程

通俗易懂的交互式TensorFlow学习指南

1. TensorFlow简介 +

什么是TensorFlow

TensorFlow是由Google开发的深度学习框架,具有以下特点:

安装TensorFlow

# CPU版本 pip install tensorflow # GPU版本(需要CUDA) pip install tensorflow-gpu # 安装特定版本 pip install tensorflow==2.13.0
点击"运行命令"查看安装说明

2. 张量(Tensors)基础 +

创建张量

import tensorflow as tf # 从列表创建 data = [[1, 2], [3, 4]] x = tf.constant(data) print(x) # 特殊张量 zeros = tf.zeros([2, 3]) # 全0张量 ones = tf.ones([2, 3]) # 全1张量 rand = tf.random.normal([2, 3]) # 随机张量 # 变量(可训练参数) w = tf.Variable(tf.random.normal([3, 2]))
点击"运行代码"查看结果

张量操作

# 基本运算 x = tf.constant([1, 2, 3]) y = tf.constant([4, 5, 6]) add = tf.add(x, y) # 加法 sub = tf.subtract(x, y) # 减法 mul = tf.multiply(x, y) # 乘法 div = tf.divide(x, y) # 除法 # 矩阵乘法 A = tf.random.normal([3, 4]) B = tf.random.normal([4, 5]) C = tf.matmul(A, B) # 矩阵乘法
点击"运行代码"查看结果

3. 自动微分(GradientTape) +

梯度计算

# 使用GradientTape记录操作 x = tf.Variable(3.0) with tf.GradientTape() as tape: y = x ** 2 + 3 * x + 1 dy_dx = tape.gradient(y, x) print(dy_dx) # dy/dx = 2x + 3 = 9
点击"运行代码"查看结果

复杂梯度计算

w = tf.Variable(tf.random.normal([3, 2])) b = tf.Variable(tf.zeros([2])) with tf.GradientTape() as tape: y = tf.matmul(x, w) + b loss = tf.reduce_mean(y ** 2) grads = tape.gradient(loss, [w, b]) print(f"w梯度: {grads[0]}") print(f"b梯度: {grads[1]}")
点击"运行代码"查看结果

4. Keras API +

顺序模型(Sequential)

from tensorflow import keras from tensorflow.keras import layers # 创建顺序模型 model = keras.Sequential([ layers.Dense(64, activation='relu', input_shape=(10,)), layers.Dense(32, activation='relu'), layers.Dense(1, activation='sigmoid') ]) # 编译模型 model.compile( optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'] ) print(model.summary())
点击"运行代码"查看结果

函数式API

# 更灵活的模型定义 inputs = keras.Input(shape=(10,)) x = layers.Dense(64, activation='relu')(inputs) x = layers.Dense(32, activation='relu')(x) outputs = layers.Dense(1, activation='sigmoid')(x) model = keras.Model(inputs=inputs, outputs=outputs)
点击"运行代码"查看结果

5. 层类型 +

常用层

# 全连接层 dense = layers.Dense(units=64, activation='relu') # 卷积层 conv2d = layers.Conv2D(filters=32, kernel_size=3, activation='relu') # 池化层 max_pool = layers.MaxPooling2D(pool_size=2) avg_pool = layers.AveragePooling2D(pool_size=2) # 循环层 lstm = layers.LSTM(units=50, return_sequences=True) gru = layers.GRU(units=50) # 正则化 dropout = layers.Dropout(rate=0.5) batch_norm = layers.BatchNormalization()
点击"运行代码"查看结果

© 2025 AI框架教程 - 专为初学者设计的深度学习教程

武哥出品

返回主页