简体   繁体   English

计算验证损失与训练损失同时进行

[英]Compute validation loss in parallel with training loss

I am trying to compute the validation loss on each iteration after the weights are computed (on the train set). 我正在尝试在权重计算后(在火车上)计算每次迭代的验证损失。 How can I use the resulted weight tensor to predict the values on the validation set? 如何使用得到的权重张量来预测验证集中的值?

I tried using two arrays to store the loss values at each step of the session. 我尝试使用两个数组在会话的每个步骤中存储损失值。

X_tr, X_val, y_tr, y_val = train_test_split(train_set, y_train, test_size=0.2, random_state=42)

x = tf.placeholder(tf.float32, X_tr.shape, name = 'data')
y = tf.placeholder(tf.float32, y_tr.shape, name = 'labels')
W = tf.Variable(tf.zeros([len(train_set.columns),1]), dtype = tf.float32, name = 'weights')
b = tf.Variable(0, dtype = tf.float32, name = 'bias')
y_pred = tf.matmul(x, W) + b

loss = tf.reduce_mean(tf.square(y - y_pred), name = 'loss')
optimizer = tf.train.MomentumOptimizer(learning_rate = 0.0006, momentum = 0.90)
train_op = optimizer.minimize(loss)

losses_t, losses_v = [], []
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    for i in range(1000):
        _, loss_t = sess.run([train_op, loss], feed_dict = {x: X_tr, y: y_tr})
        losses_t.append(loss_t)
        loss_v = sess.run(loss, feed_dict = {x: X_val, y: y_val})
        losses_v.append(loss_v)
        if(i % 20 == 0):
            print('Training loss is: ', loss_t)
            print('Validation loss is: ', loss_v)

    W_value, b_value = sess.run([W, b])

The error: 错误:

ValueError: Cannot feed value of shape (292, 220) for Tensor 'data_6:0', which has shape '(1166, 220)'

The problem was that I was giving the same parameters to both sess.run functions. 问题是我给两个sess.run函数都赋予了相同的参数。 I created instead new placeholders (to fit the shape of the input X_val and y_val) and a loss function for the validation loss specific to its test set (X_val, y_val). 我改而创建了新的占位符(以适应输入X_val和y_val的形状)和一个损失函数,用于特定于其测试集的验证损失(X_val,y_val)。

losses_t = []
losses_v = []
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    for i in range(3000):
        _, loss_t = sess.run([train_op, loss], feed_dict = {x: X_tr, y: y_tr})
        losses_t.append(loss_t)
        loss_v = sess.run(lossv, feed_dict = {xv: X_val, yv: y_val})
        losses_v.append(loss_v)
        if(i % 20 == 0):
            print('Training loss is: ', loss_t)
            print('Validation loss is: ', loss_v)

    W_value, b_value = sess.run([W, b])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM