TensorFlow 是一个广泛应用的开源深度学习框架,支持多种机器学习任务,如深度学习、神经网络、强化学习等。以下是 TensorFlow 的详细教程,涵盖基础使用方法和示例代码。
1. 安装与导入
安装 TensorFlow:
pip install tensorflow
导入 TensorFlow:
import tensorflow as tf
import numpy as np
验证安装:
print(tf.__version__) # 查看 TensorFlow 版本
2. TensorFlow 基础
2.1 张量(Tensor)
TensorFlow 的核心数据结构是张量,它是一个多维数组。
# 创建张量
a = tf.constant([1, 2, 3], dtype=tf.float32) # 常量张量
b = tf.Variable([4, 5, 6], dtype=tf.float32) # 可变张量
# 基本运算
c = a + b
print(c.numpy()) # 转换为 NumPy 数组输出
输出结果
[5. 7. 9.]
2.2 自动求导
TensorFlow 支持自动计算梯度。
x = tf.Variable(3.0)
with tf.GradientTape() as tape:
y = x**2 # 定义目标函数
dy_dx = tape.gradient(y, x) # 自动求导
print(dy_dx.numpy())
输出结果
6.0
3. 构建模型
3.1 使用 Sequential API
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense
# 构建简单神经网络
model = Sequential([
Dense(64, activation='relu', input_shape=(10,)),
Dense(32, activation='relu'),
Dense(1, activation='sigmoid')
])
# 查看模型结构
model.summary()
输出结果
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense (Dense) (None, 64) 704
dense_1 (Dense) (None, 32) 2080
dense_2 (Dense) (None, 1) 33
=================================================================
Total params: 2,817
Trainable params: 2,817
Non-trainable params: 0
_________________________________________________________________
3.2 自定义模型
import tensorflow as tf
from tensorflow.keras.layers import Dense
class MyModel(tf.keras.Model):
def __init__(self):
super(MyModel, self).__init__()
self.dense1 = Dense(64, activation='relu')
self.dense2 = Dense(32, activation='relu')
self.output_layer = Dense(1, activat