You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用TensorFlow 2在Python中求解非线性最小二乘误差参数拟合问题

使用TensorFlow 2最小化误差函数SE恢复参数

问题背景

已知数据生成公式:

YL = YC + ZC*tan(theta + r) + noise

现在已获取N组(theta, YL)数据对,需要通过TensorFlow 2最小化平方误差函数SE,还原参数r、YC、ZC。

实现步骤与代码

1. 导入依赖并生成数据(沿用原生成逻辑)

保留原数据生成逻辑,同时导入TensorFlow库:

import math
import random
import tensorflow as tf

# 真实参数
YC_true = -0.25
ZC_true = 1.0
r_true = 4

theta = []
YL = []

# 生成带噪声的数据集
for theta_i in range(-10, 11):
    YL_i = math.tan(math.radians(r_true + theta_i)) + YC_true
    noise = random.uniform(-0.001, 0.001)
    YL_i += noise
    theta.append(theta_i)
    YL.append(YL_i)

2. 转换数据为TensorFlow张量

将列表格式的数据集转为tf.Tensor,适配TensorFlow的计算逻辑:

theta_tensor = tf.convert_to_tensor(theta, dtype=tf.float32)
YL_tensor = tf.convert_to_tensor(YL, dtype=tf.float32)

3. 定义可训练参数

用tf.Variable定义需要优化的参数,设置合理初始值:

# 初始化参数(可根据实际情况调整初始值)
r = tf.Variable(3.0, dtype=tf.float32)
YC = tf.Variable(0.0, dtype=tf.float32)
ZC = tf.Variable(0.5, dtype=tf.float32)

4. 定义TensorFlow版本的误差函数

使用TensorFlow的向量化运算替代循环,同时用TF内置函数保证自动求导:

def se_loss(r, YC, ZC, theta, YL):
    # 将角度转为弧度
    angle_rad = tf.math.radians(r + theta)
    # 计算预测值
    YL_pred = YC + ZC * tf.math.tan(angle_rad)
    # 计算平方误差和
    return tf.reduce_sum(tf.square(YL_pred - YL))

5. 选择优化器并执行训练循环

选择Adam优化器(自适应学习率,收敛更稳定),在循环中迭代更新参数:

# 选择优化器,设置学习率
optimizer = tf.optimizers.Adam(learning_rate=0.01)

# 训练迭代次数
epochs = 10000

for epoch in range(epochs):
    # 用GradientTape记录梯度
    with tf.GradientTape() as tape:
        loss = se_loss(r, YC, ZC, theta_tensor, YL_tensor)
    
    # 计算梯度
    gradients = tape.gradient(loss, [r, YC, ZC])
    
    # 更新参数
    optimizer.apply_gradients(zip(gradients, [r, YC, ZC]))
    
    # 每1000轮打印一次结果
    if epoch % 1000 == 0:
        print(f"Epoch {epoch}, Loss: {loss.numpy():.6f}")
        print(f"当前参数: r={r.numpy():.4f}, YC={YC.numpy():.4f}, ZC={ZC.numpy():.4f}")

# 最终结果
print("\n优化完成,最终参数:")
print(f"r: {r.numpy():.4f} (真实值: {r_true})")
print(f"YC: {YC.numpy():.4f} (真实值: {YC_true})")
print(f"ZC: {ZC.numpy():.4f} (真实值: {ZC_true})")

关键说明

  • 使用tf.GradientTape自动记录计算图的梯度,这是TensorFlow 2中自动求导的核心方式。
  • 用向量化运算替代原Python循环,既提升计算效率,又能兼容TensorFlow的自动求导机制。
  • 若收敛效果不佳,可尝试调整学习率、迭代次数,或更换为SGD等其他优化器。

内容的提问来源于stack exchange,提问作者Andy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 03:17:18