TensorFlow - 线性回归
TensorFlow - 线性回归
Section titled “TensorFlow - 线性回归”线性回归(Linear regression)是一种基础的监督学习(supervised machine learning)算法,用于通过将线性方程拟合到观测数据来模拟因变量(目标变量,target)与一个或多个自变量(特征,features)之间的关系。本章演示了如何使用 TensorFlow 及其 Keras API 实现一个简单的线性回归模型。
如果 ‘y’ 是因变量,‘x’ 是自变量,那么对于单个特征的线性回归方程为:
Y = W*x + b其中 ‘W’ 是权重(斜率,weight/slope),‘b’ 是偏置(截距,bias/intercept)。训练的目标是找到 ‘W’ 和 ‘b’ 的最优值,以最小化预测的 ‘Y’ 值与实际的 ‘Y’ 值之间的差异。这通常通过使用优化算法(optimization algorithm)最小化损失函数(cost function 或 loss function)来完成。
涉及的关键概念:
- 损失函数(Cost Function / Loss Function):衡量预测值与实际值之间误差的函数(例如,均方误差 - MSE)。
- 梯度下降(Gradient Descent):一种优化算法,通过迭代调整权重和偏置来最小化损失函数。
线性回归的一个简单表示是通过数据点的散点图找到最拟合的直线。
如果我们有数据点 (x, y),线性回归旨在找到一条最能代表这些点的直线 Y = Wx + b。
使用 TensorFlow Keras 实现线性回归的步骤
Section titled “使用 TensorFlow Keras 实现线性回归的步骤”我们将生成一些合成数据(synthetic data),然后构建一个模型来学习潜在的线性关系。
步骤 1:导入必要的库并生成数据
Section titled “步骤 1:导入必要的库并生成数据”我们将使用 NumPy 进行数值计算,使用 Matplotlib 进行绘图。
import tensorflow as tffrom tensorflow import kerasimport numpy as npimport matplotlib.pyplot as plt
# For reproducibilitynp.random.seed(42)tf.random.set_seed(42)
# Generate synthetic data# True parametersTRUE_W = 2.5TRUE_b = 0.8NUM_EXAMPLES = 500
X_data = np.random.rand(NUM_EXAMPLES) # Input feature (x values between 0 and 1)noise = np.random.randn(NUM_EXAMPLES) * 0.2 # Some noisey_data = TRUE_W * X_data + TRUE_b + noise # Target variable
# Reshape X_data to be (num_examples, 1) for Keras model inputX_data = X_data.reshape(-1, 1)步骤 2:可视化生成的数据
Section titled “步骤 2:可视化生成的数据”绘制数据有助于理解我们尝试建模的关系。
plt.figure(figsize=(8, 6))plt.scatter(X_data, y_data, label='Original data', alpha=0.6)plt.plot(X_data, TRUE_W * X_data + TRUE_b, label='True underlying relationship', color='red', linewidth=2)plt.xlabel('X')plt.ylabel('y')plt.title('Synthetic Data for Linear Regression')plt.legend()plt.grid(True)plt.show()该图将显示围绕真实线性关系的散点。
步骤 3:使用 Keras 定义线性回归模型
Section titled “步骤 3:使用 Keras 定义线性回归模型”具有一个输入特征和一个输出的线性回归模型可以用一个包含一个单元(unit)的 Dense 层来表示。
model = keras.Sequential([ layers.Dense(units=1, input_shape=[1]) # One unit, one input feature])
model.summary()Dense 层实现的操作是:output = activation(dot(input, kernel) + bias)。对于线性回归,使用了默认的线性激活函数。kernel 对应于 ‘W’,bias 对应于 ‘b’。
步骤 4:编译模型
Section titled “步骤 4:编译模型”指定优化器(optimizer)和损失函数(loss function)。
model.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=0.1), loss='mean_squared_error') # MSE is common for regression我们使用随机梯度下降(Stochastic Gradient Descent - SGD)作为优化器,使用均方误差(Mean Squared Error - MSE)作为损失函数。
步骤 5:训练模型
Section titled “步骤 5:训练模型”用我们的合成数据来拟合模型。
print("\nTraining the model...")epochs = 100history = model.fit(X_data, y_data, epochs=epochs, verbose=0) # verbose=0 to keep output clean
# Retrieve the learned weightslearned_W = model.layers[0].get_weights()[0][0][0]learned_b = model.layers[0].get_weights()[1][0]
print(f"Epochs run: {epochs}")print(f"Learned W: {learned_W:.4f}, Learned b: {learned_b:.4f}")print(f"True W: {TRUE_W}, True b: {TRUE_b}")训练后,学习到的权重 ‘W’ 和 ‘b’ 应该接近我们的 TRUE_W 和 TRUE_b。
步骤 6:可视化结果
Section titled “步骤 6:可视化结果”绘制原始数据以及学习到的回归线。
plt.figure(figsize=(8, 6))plt.scatter(X_data, y_data, label='Original data', alpha=0.6)plt.plot(X_data, TRUE_W * X_data + TRUE_b, label='True relationship', color='red', linewidth=2, linestyle='--')plt.plot(X_data, model.predict(X_data), label='Learned regression line', color='green', linewidth=2)plt.xlabel('X')plt.ylabel('y')plt.title('Linear Regression Fit')plt.legend()plt.grid(True)plt.show()完整的代码将生成数据,构建 Keras 模型,训练它,然后绘制学习到的直线与原始数据点,展示了 TensorFlow 如何学习线性关系。这展示了使用 TensorFlow 2.x 和 Keras 执行线性回归的一种现代、简洁的方式。
训练的预期输出(值可能略有不同):
Model: "sequential"_________________________________________________________________ Layer (type) Output Shape Param #================================================================= dense (Dense) (None, 1) 2
=================================================================Total params: 2Trainable params: 2Non-trainable params: 0_________________________________________________________________
Training the model...Epochs run: 100Learned W: 2.4878, Learned b: 0.8111True W: 2.5, True b: 0.8