TensorFlow搭建sigmoid回归网络拟合函数输出始终为线性问题求解
问题排查与解决方案
核心问题原因
- 接口导入不规范:代码中调用
keras.models.Sequential()但未单独导入keras模块,应统一使用tf.keras系列接口,避免版本不匹配导致的隐性异常。 - 优化器参数不合理:sigmoid激活函数存在梯度饱和特性,当输入偏离0点时梯度会快速衰减,你设置的SGD学习率
0.001过小,会导致参数更新幅度极小,短时间训练完全无法拟合非线性特征。 - 训练轮次不足:即使调大学习率,个位数轮次的训练也不足以让100个神经元的隐藏层学到目标函数的分段特征。
修改后可正常运行的代码
import numpy as np import tensorflow as tf from tensorflow.keras import layers import matplotlib.pyplot as plt f1 = lambda x: ((x < .5) * np.power(x, 2) + (x > .5) * x) * 2 -1 x = np.linspace(-1, 1, 180).reshape(-1,1) y = f1(x).reshape(-1, 1) # 统一使用tf.keras接口,避免导入冲突 model = tf.keras.models.Sequential() model.add(layers.Dense(100, activation=tf.keras.activations.sigmoid, input_shape=(1,))) model.add(layers.Dense(1, activation=tf.keras.activations.linear)) # 调大SGD学习率,可根据训练效果在0.05~0.2区间调整 model.compile(loss=tf.keras.losses.mean_squared_error, optimizer=tf.keras.optimizers.SGD(learning_rate=0.1), metrics=[tf.keras.losses.mean_squared_error]) # 增加训练轮次,调整batch_size降低训练波动,verbose=0可关闭训练日志 model.fit(x, y, batch_size=8, epochs=600, verbose=0) xtest = np.linspace(-1, 1, 100).reshape(-1, 1) ytest = model.predict(xtest, verbose=0) plt.scatter(x, y, label='目标函数值') plt.plot(xtest, ytest, c='r', label='模型预测值') plt.legend() plt.show()
效果说明
运行上述代码后,模型可以正常拟合目标函数的分段非线性特征,不会再输出线性结果,在保持你要求的100个sigmoid神经元隐藏层+线性输出层的结构不变的前提下,可达到和Matlab一致的拟合效果。
内容的提问来源于stack exchange,提问作者yanniknelson
相关产品推荐
相关产品推荐

