【问题标题】:How to derive the output from Keras model using its layers' weight and biases?如何使用 Keras 模型的层权重和偏差导出输出?
【发布时间】:2020-02-01 07:31:28
【问题描述】:

我的模型试图预测 y = 2x + 5 之后的线性回归中的值。因此,我的训练数据类似于以下内容:

x_train = [0, 1, 2, 3, 4, ...] and y_train = [5, 7, 9, 11, 13, ...]   

我的 Keras 模型如下所示:

`model = tf.keras.Sequential([
    tf.keras.layers.Dense(16, activation='relu', input_dim=1),
    tf.keras.layers.Dense(1, activation='linear')
])
model.compile(loss='mean_squared_error', optimizer='adam', metrics=['mse'])
model.fit(x_train, y_train, epochs=1000, batch_size=10)`

在获得良好的验证准确度后,我希望查看模型的权重和偏差来计算给定输入的输出,因为我希望了解简单的神经网络是如何工作的。我在跑步时实现了以下权重和偏差

for l in model.layers: print(l.get_weights())

[array([[-0.10382611,  0.48899287, -0.36912352, -0.11604425,  0.03658517,
     0.546786  , -0.0094437 ,  0.5393126 , -0.36325318, -0.20389882,
    -0.00112574, -0.39811927, -0.25433052, -0.16315842,  0.6172162 ,
    -0.47300738]], dtype=float32), array([ 0.        ,  1.1705374 ,  
     0.        ,  0.        , -0.41323203, 0.97515434, 0.        , 
     0.99699414,  0.        ,  0.        ,-0.2316811 , 0.        ,
     0.        ,  0.        ,  1.4638424 , 0.       ], dtype=float32)]
[array([[-0.30404267],
   [ 0.91265625],
   [ 0.3578334 ],
   [-0.23462006],
   [-0.33843294],
   [ 1.080244  ],
   [-0.5933689 ],
   [ 1.0348322 ],
   [ 0.47716653],
   [ 0.18852347],
   [-0.21219982],
   [ 0.45529807],
   [ 0.39576346],
   [-0.05013525],
   [ 0.67550814],
   [-0.19761673]], dtype=float32), array([0.7426254], dtype=float32)]

我的印象是,如果我输入 10 的值,我应该期望 25 的值作为输出(或非常接近)。然而,当我尝试自己做数学时,我并没有那么接近。我目前对这应该如何工作的理解是:

  1. 将权重数组的第 n 个元素乘以 10 并添加偏置数组的第 n 个元素
  2. 取第 n 个结果并乘以第二个权重数组的第 n 个元素,然后加上第二个偏置数组的第 n 个元素
  3. 结果应该是 25(或非常接近)

我不明白这应该如何工作吗?

【问题讨论】:

  • 你考虑relu激活吗?第一步之后,你应该应用 relu 非线性函数。
  • 是的。我忘了在我的 Excel 表中使用我的激活功能。谢谢你。 @zihaozhihao

标签: python tensorflow keras


【解决方案1】:

如果我们观察每一层的权重和偏差数组,我们可以看到错误的结果是由于缺乏训练造成的。模型无法使用这些参数学习模式,但我们可以说它正在改进,因为权重和偏差被认为在增加,这是必需的,因为我们已经有了模式背后的逻辑。如果您的训练数据很小,我建议您增加迭代次数并更改批量大小。

【讨论】:

    猜你喜欢
    • 2018-08-03
    • 1970-01-01
    • 2019-11-18
    • 1970-01-01
    • 2017-05-25
    • 1970-01-01
    • 1970-01-01
    • 2017-01-26
    相关资源
    最近更新 更多