为何无法用TensorFlow预测三次方程?如何修改代码解决?
如何用TensorFlow拟合三次方程3x³+5x²+10
你之前使用的单层Dense模型是线性模型,只能学习输入与输出之间的线性映射关系,而三次方程属于高度非线性函数,因此无法准确拟合。以下两种方案可解决该问题:
方案1:构建带非线性激活的深层神经网络
通过添加隐藏层并引入非线性激活函数,让模型具备学习复杂非线性关系的能力,同时优化训练数据和优化器提升效果:
import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense import numpy as np # 扩充训练数据范围与数量,覆盖正负区间,让模型学习完整函数趋势 xs = np.array([-5.0, -4.0, -3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0], dtype=float) # 直接用公式生成标签,避免手动输入误差 ys = 3 * xs**3 + 5 * xs**2 + 10 # 构建带隐藏层的非线性模型 model = Sequential([ Dense(units=16, input_shape=[1], activation='relu'), # 第一隐藏层,ReLU激活引入非线性 Dense(units=16, activation='relu'), # 第二隐藏层,增强模型表达能力 Dense(units=1) # 输出层,回归任务用线性激活 ]) # 使用Adam优化器,自适应学习率比SGD更适合复杂模型的收敛 model.compile(optimizer='adam', loss='mean_squared_error') # 训练模型,verbose=1可查看训练过程 model.fit(xs, ys, epochs=1000, verbose=1) # 测试预测 print("x=11的预测结果:", model.predict([11.0])) print("x=0的预测结果:", model.predict([0.0]))
关键改动说明
- 扩充训练数据:原数据仅覆盖小范围正数值,补充负数和更多样本后,模型能学习到完整的三次函数曲线特征
- 添加非线性隐藏层:ReLU激活函数打破线性限制,多层结构提升模型对复杂关系的拟合能力
- 更换优化器:Adam优化器自带自适应学习率调整,比SGD更快收敛到最优解
- 自动生成标签:通过公式计算
ys,避免手动输入数据错误
方案2:手动构造多项式特征
三次方程本质是x、x²、x³的线性组合,因此可手动将输入扩展为多项式特征,再用线性模型拟合:
import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense import numpy as np # 准备基础输入数据 xs = np.array([-5.0, -4.0, -3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0], dtype=float) # 构造多项式特征:合并x、x²、x³为3维输入 xs_poly = np.column_stack([xs, xs**2, xs**3]) # 生成标签数据 ys = 3 * xs**3 + 5 * xs**2 + 10 # 用线性模型拟合多项式特征(此时问题已转化为线性回归) model = Sequential([ Dense(units=1, input_shape=[3]) # 输入维度对应3个多项式特征 ]) model.compile(optimizer='sgd', loss='mean_squared_error') model.fit(xs_poly, ys, epochs=400, verbose=1) # 预测时需构造对应多项式特征 test_x = 11.0 test_feature = np.array([[test_x, test_x**2, test_x**3]]) print("x=11的预测结果:", model.predict(test_feature)) test_x_0 = 0.0 test_feature_0 = np.array([[test_x_0, test_x_0**2, test_x_0**3]]) print("x=0的预测结果:", model.predict(test_feature_0))
方案优势
模型结构简单,训练速度快,适合明确知道函数形式的场景,直接通过特征工程将非线性问题转化为线性问题解决。
内容的提问来源于stack exchange,提问作者Aminadav Glickshtein
相关产品推荐
相关产品推荐

