gpt4 book ai didi

python - TensorFlow 是否为其用户实现了交叉验证?

转载 作者:IT老高 更新时间:2023-10-28 20:55:13 26 4
gpt4 key购买 nike

我正在考虑尝试使用交叉验证来选择超参数(例如正则化),或者可能训练模型的多个初始化,然后选择具有最高交叉验证准确度的模型。实现 k-fold 或 CV 很简单,但很乏味/烦人(特别是如果我试图在不同的 CPU、GPU 甚至不同的计算机等中训练不同的模型)。我希望像 TensorFlow 这样的库能够为其用户实现类似的功能,这样我们就不必编写 100 次相同的东西。因此,TensorFlow 是否有库或可以帮助我进行交叉验证的东西?


作为更新,似乎可以使用 scikit learn 或其他东西来做到这一点。如果是这种情况,那么如果有人可以提供一个简单的 NN 训练示例并使用 scikit learn 进行交叉验证,那就太棒了!不确定这是否可以扩展到多个 cpu、gpus、集群等。

最佳答案

如前所述,tensorflow 没有提供自己的方法来交叉验证模型。推荐的方式是使用KFold .这有点乏味,但可行。这是一个使用 tensorflowKFold 交叉验证 MNIST 模型的完整示例:

from sklearn.model_selection import KFold
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

# Parameters
learning_rate = 0.01
batch_size = 500

# TF graph
x = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32, [None, 10])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
pred = tf.nn.softmax(tf.matmul(x, W) + b)
cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred), reduction_indices=1))
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
init = tf.global_variables_initializer()

mnist = input_data.read_data_sets("data/mnist-tf", one_hot=True)
train_x_all = mnist.train.images
train_y_all = mnist.train.labels
test_x = mnist.test.images
test_y = mnist.test.labels

def run_train(session, train_x, train_y):
print "\nStart training"
session.run(init)
for epoch in range(10):
total_batch = int(train_x.shape[0] / batch_size)
for i in range(total_batch):
batch_x = train_x[i*batch_size:(i+1)*batch_size]
batch_y = train_y[i*batch_size:(i+1)*batch_size]
_, c = session.run([optimizer, cost], feed_dict={x: batch_x, y: batch_y})
if i % 50 == 0:
print "Epoch #%d step=%d cost=%f" % (epoch, i, c)

def cross_validate(session, split_size=5):
results = []
kf = KFold(n_splits=split_size)
for train_idx, val_idx in kf.split(train_x_all, train_y_all):
train_x = train_x_all[train_idx]
train_y = train_y_all[train_idx]
val_x = train_x_all[val_idx]
val_y = train_y_all[val_idx]
run_train(session, train_x, train_y)
results.append(session.run(accuracy, feed_dict={x: val_x, y: val_y}))
return results

with tf.Session() as session:
result = cross_validate(session)
print "Cross-validation result: %s" % result
print "Test accuracy: %f" % session.run(accuracy, feed_dict={x: test_x, y: test_y})

关于python - TensorFlow 是否为其用户实现了交叉验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38164798/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com