Keras 网络未训练

Keras network not training

我正在尝试学习 Keras 并创建了一个简单的网络。特征数据是 [1, 2, 3, 4, 5],标签是 [7, 9, 11, 13, 15] - 或者斜率为 2,截距为 5 的直线(Y = X * 2 + 5)。

这里是 Keras 网络:

# simple keras example
# 
# This solves for a line

import numpy as np
import keras

# configuration variables

samples = 5
base = 1

slope = 2
intercept = 5

# hyper-parameters

learning_rate = 0.01
epochs        = 2000

model = keras.Sequential()
model.add(keras.layers.Dense(1, input_dim=1, activation=keras.activations.linear))

sgd = keras.optimizers.SGD(learning_rate=learning_rate)

model.compile(loss='binary_crossentropy', optimizer=sgd, metrics=['mean_absolute_error'])

X = np.array(range(base, base+samples))
Y = X * slope + intercept

model.fit(X, Y, epochs=epochs, batch_size=samples)

loss, accuracy = model.evaluate(X, Y)

print('Loss: ', loss, ' Accuracy: ', accuracy)

k_slope = model.layers[0].get_weights()[0]
k_intercept = model.layers[0].get_weights()[1]

print('slope: ', k_slope, ' intercept: ', k_intercept)

第一个纪元的斜率最终为 -0.1879,并且没有进步。我怀疑我缺少参数或设置,或者可能是模型上的函数调用。但是我不知道它是什么。

这是我试图在 Keras 中重现的张量流网络。该网络在大约 1300 轮时收敛到正确答案:

#simple linear regression with tensorflow
# 
# This solves for a line
#

import tensorflow as tf
import numpy as np

# configuration variables

samples = 5
base = 1

slope = 2
intercept = 5

# hyper-parameters

learning_rate = 0.01
epochs        = 2000

x = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32)

m = tf.Variable(0.0)
b = tf.Variable(0.0)

pred = tf.add(tf.multiply(x, m), b)

cost = tf.reduce_mean(tf.abs(y - pred))

me_first = tf.global_variables_initializer()

optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
session = tf.Session()

session.run(me_first)

for i in range(epochs):

   X = np.array(range(base, base+samples))
   Y = X * slope + intercept

   t_slope, t_intercept, total_err, opt = session.run([m, b, cost, optimizer], feed_dict={x:X, y:Y})

print('iter: ', i, ' intercept: ', t_intercept, ' slope: ', t_slope, ' error: ', total_err)

奥林回答了问题。损失函数不适合网络。 "BinaryCrossentropy" 应在数据标签为 1 或 0 时使用。在我的例子中,标签是任意数字。要创建与我的 tensorflow 示例等效的网络,损失函数需要为 "mean_absolute_error",或简称为 "mae"。

我在 model.compile() 到 "mean_absolute_error" 的调用中确实设置了 "metrics" 字段,我错误地假设该指标将用作损失指标网络。事实上,"metrics" 被计算和报告,但根本没有被算法使用。指标可供开发人员查看训练数据集的其他损失函数值。

不幸的是,Keras 在这种情况下默默地失败了。如果当它看到 0 或 1 以外的标签时报告 "BinaryCrossentropy" 不应用作损失函数,这将很有用。