TensorFlow基础教程
TensorFlow基础教程
TensorFlow简介
TensorFlow是Google开发的开源深度学习框架,支持静态图和动态图,广泛应用于工业级部署。
张量操作
import tensorflow as tf
# 创建张量
a = tf.zeros((3, 4))
b = tf.ones((3, 4))
c = tf.random.normal((3, 4))
d = tf.constant([1, 2, 3], dtype=tf.float32)
print(f"零张量: {a.shape}")
print(f"随机张量: {c.shape}")
张量运算
# 基本运算
x = tf.random.normal((2, 3))
y = tf.random.normal((2, 3))
add = tf.add(x, y)
mul = tf.multiply(x, y)
matmul = tf.matmul(x, tf.transpose(y))
print(f"矩阵乘法: {matmul.shape}")
# 形状操作
reshape = tf.reshape(tf.random.normal((2, 6)), (2, 3, 2))
print(f"重塑后: {reshape.shape}")
# 聚合操作
x = tf.random.normal((3, 4))
print(f"求和: {tf.reduce_sum(x, axis=0).shape}")
print(f"均值: {tf.reduce_mean(x, axis=1).shape}")
自动微分
# GradientTape计算梯度
x = tf.Variable([2.0, 3.0])
with tf.GradientTape() as tape:
y = x ** 2 + 2 * x + 1
grads = tape.gradient(y, x)
print(f"梯度 dy/dx = 2x+2: {grads.numpy()}")
Keras Sequential模型
from tensorflow import keras
from tensorflow.keras import layers
# Sequential API
model = keras.Sequential([
layers.Dense(64, activation='relu', input_shape=(10,)),
layers.Dropout(0.2),
layers.Dense(32, activation='relu'),
layers.Dense(2, activation='softmax')
])
model.summary()
Keras Functional API
# Functional API(支持多输入多输出)
inputs = keras.Input(shape=(10,))
x = layers.Dense(64, activation='relu')(inputs)
x = layers.Dense(32, activation='relu')(x)
outputs = layers.Dense(2, activation='softmax')(x)
model = keras.Model(inputs=inputs, outputs=outputs)
model.summary()
完整训练流程
import numpy as np
# 1. 准备数据
X_train = np.random.randn(500, 10).astype(np.float32)
y_train = np.random.randint(0, 2, (500,))
# 2. 创建模型
model = keras.Sequential([
layers.Dense(32, activation='relu', input_shape=(10,)),
layers.Dense(16, activation='relu'),
layers.Dense(2, activation='softmax')
])
# 3. 编译模型
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
# 4. 训练模型
history = model.fit(
X_train, y_train,
epochs=10,
batch_size=32,
validation_split=0.2,
verbose=1
)
# 5. 评估模型
loss, accuracy = model.evaluate(X_train, y_train)
print(f"训练准确率: {accuracy:.4f}")
回调函数
# 使用回调函数
callbacks = [
keras.callbacks.EarlyStopping(patience=3, restore_best_weights=True),
keras.callbacks.ReduceLROnPlateau(factor=0.5, patience=2),
keras.callbacks.ModelCheckpoint('best_model.keras', save_best_only=True)
]
model.fit(X_train, y_train, epochs=20, callbacks=callbacks, validation_split=0.2)
保存与加载
# 保存完整模型
model.save('my_model.keras')
# 加载模型
loaded_model = keras.models.load_model('my_model.keras')
总结
TensorFlow配合Keras API提供了从研究到部署的完整解决方案。