Tensorflow Keras网络不是培训
我正在努力学习Keras,并创建了一个简单的网络。特征数据为[1,2,3,4,5],标签为[7,9,11,13,15]-或斜率为2、截距为5(Y=X*2+5)的直线 以下是Keras网络:Tensorflow Keras网络不是培训,tensorflow,machine-learning,keras,machine-learning-model,Tensorflow,Machine Learning,Keras,Machine Learning Model,我正在努力学习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 =
# 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,并且没有进展。我怀疑我缺少一个参数或设置,或者可能缺少对模型的函数调用。但我不知道是什么
这是一个tensorflow网络,我正试图在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)
奥林回答了这个问题。损失函数不适用于网络。当数据的标签为1或0时,应使用“BinaryCrossentropy”。在我的情况下,标签是任意数量的。为了制作与tensorflow示例等效的网络,损耗函数需要是“平均绝对误差”,或者简称为“mae” 在调用model.compile()时,我确实将“metrics”字段设置为“mean_absolute_error”,并且我错误地认为该度量将用作网络的损失度量。事实上,“度量”是计算和报告的,但算法根本不使用。开发人员可以查看培训数据集的其他损失函数值
不幸的是,在这种情况下,Keras默默地失败了。当它看到0或1以外的标签时,如果报告“BinaryCrossentropy”不应用作损失函数,这将非常有用。将损失函数从
binary\u crossentropy
切换到mae
(这是您的TensorFlow示例所使用的),将修复它。这是有效的。谢谢虽然我不知道为什么任何损失函数都不能产生正确答案的进展。Keras网站对损失函数的解释非常简单。