我收到一个错误提示说’tuple’对象没有属性’train’。我无法理解这个错误(我在使用Google Colab)。请帮助我,并尽可能详细地解释(训练部分)。我的代码如下。非常感谢您的帮助
%tensorflow_version 1.x## 加载必要的函数和CIFAR10数据集 from __future__ import print_functionimport tensorflow as tffrom tensorflow.keras.datasets import cifar10tf.__version__((train_X, train_y), (test_X, test_y)) = cifar10.load_data()print(f"train_X: {train_X.shape}, test_X = {test_X.shape}")cifar10 = cifar10.load_data()# 定义网络输入的占位符X = tf.placeholder(tf.float32, [None, 3072])/255.0 # 32x32x3Y = tf.placeholder(tf.float32, [None, 10])keep_prob = tf.placeholder(tf.float32)learning_rate = 0.001training_epochs =10batch_size = 30# 神经网络层的权重和偏置W = tf.Variable(tf.random_normal([3072, 10]))b = tf.Variable(tf.random_normal([10]))hypothesis = tf.matmul(X, W) + b# 定义成本/损失和优化器cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=hypothesis, labels=Y))optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)# 初始化sess = tf.Session()sess.run(tf.global_variables_initializer())# 训练我的模型for epoch in range(training_epochs): avg_cost = 0 num_examples = 50000 total_batch = int(num_examples / batch_size)
我的问题在这里
for i in range(total_batch): batch_xs, batch_ys = cifar10.train.next_batch(batch_size) feed_dict = {X: batch_xs, Y: batch_ys} c, _ = sess.run([cost, optimizer], feed_dict=feed_dict) avg_cost += c / total_batch print('Epoch:', '%04d' % (epoch + 1), 'cost =', '{:.9f}'.format(avg_cost))print('Learning Finished!')# 测试模型并检查准确率correct_prediction = tf.equal(tf.argmax(hypothesis, 1), tf.argmax(Y, 1))accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))print('Accuracy:', sess.run(accuracy, feed_dict={X: cifar10.test.images, Y: cifar10.test.labels}))
回答:
您试图从cifar10.load_data()
返回的元组中访问train
属性。您已经在前面的步骤中正确地加载了数据:
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
cifar10.load_data()
是一个数据加载器,它返回数据集的训练和测试集。
如果您想实现next_batch
方法来执行上述操作,您需要定义一个自定义的辅助类,这是一种非常常见的做法。这里有一个示例案例。