我正在Google Colab上的猫和狗之间运行一个二进制分类器。我执行了一次脚本,并且脚本没有错误地执行,但是当我在完全连接各层之后将Dropout层添加到网络后再次运行时,遇到了以下错误。我也尝试过重新启动运行时,仍然会引发错误。然后,在删除Dropout并再次重新启动运行时之后,仍然会引发错误。我不知道发生什么事了,为什么任何帮助将不胜感激。
# Preprocess Data
import random
import os
import numpy as np
import pickle
import cv2
from tqdm import tqdm
img_size = 28
DIR = "train/"
images = os.listdir(DIR)
random.shuffle(images)
image_data = []
image_classification = []
with tqdm(total=len(images)) as progress_bar:
for name in images:
img = cv2.imread(DIR + name, cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img, (img_size, img_size))
img = np.array(img)
name = name.split('.')[0]
if name == "dog":
classification = [1., 0.]
else:
classification = [0., 1.]
image_data.append(img)
image_classification.append(classification)
progress_bar.update(1)
testing_size = int(0.1*(len(images)))
train_x, train_y = image_data[testing_size:], image_classification[testing_size:]
test_x, test_y = image_data[:testing_size], image_classification[:testing_size]
with open('train.data', 'wb', buffering=1000) as f:
pickle.dump([train_x, train_y], f)
with open('test.data', 'wb', buffering=1000) as f:
pickle.dump([test_x, test_y], f)
型号:
import tensorflow as tf
class ConvNet:
def __init__(self):
pass
def generate_weight_bias(self, weight, bias):
weight = tf.Variable(tf.random_normal(weight), name="Filter")
bias = tf.Variable(tf.random_normal(bias), name="Bias")
return weight, bias
def conv2d(self, x, filter, bias):
return self.relu(tf.add(tf.nn.conv2d(x, filter=filter, strides=[1, 1, 1, 1], padding='SAME'), bias))
def max_pool(self, x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
def relu(self, x):
return tf.nn.relu(x)
def dropout(self, x, keep_prob):
return tf.nn.dropout(x, keep_prob)
def model(self, x):
w, b = self.generate_weight_bias([5, 5, 1, 32], [32])
layer1_1 = self.conv2d(x, w, b)
w, b = self.generate_weight_bias([5, 5, 32, 32], [32])
layer1_2 = self.conv2d(layer1_1, w, b)
layer1_3 = self.max_pool(layer1_2)
w, b = self.generate_weight_bias([5, 5, 32, 64], [64])
layer2_1 = self.conv2d(layer1_3, w, b)
w, b = self.generate_weight_bias([5, 5, 64, 64], [64])
layer2_2 = self.conv2d(layer2_1, w, b)
layer2_3 = self.max_pool(layer2_2)
layer3_1 = tf.reshape(layer2_3, shape=[-1, 7*7*64])
w, b = self.generate_weight_bias([7*7*64, 1024], [1024])
layer3_1 = self.relu(tf.add(tf.matmul(layer3_1, w), b))
w, b = self.generate_weight_bias([1024, 1024], [1024])
layer3_2 = self.relu(tf.add(tf.matmul(layer3_1, w), b))
w, b = self.generate_weight_bias([1024, 2], [2])
layer3_3 = (tf.add(tf.matmul(layer3_2, w), b))
return layer3_3
变量:
x = tf.placeholder('float', [None, 28, 28, 1], name="Input")
y = tf.placeholder('float', [None, 2], name="Label")
train_x = np.reshape(train_x, [-1, 28, 28, 1])
test_x = np.reshape(test_x, [-1, 28, 28, 1])
培训:
network = ConvNet()
total_epochs = 100
batch_size = 100
with tf.name_scope('Model'):
prediction = tf.nn.softmax(network.model(x))
with tf.name_scope('Loss'):
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=prediction, labels=y))
with tf.name_scope('AdamOptimizer'):
optimizer = tf.train.AdamOptimizer().minimize(cost)
with tf.name_scope('Accuracy'):
accuracy = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(accuracy, tf.float32))
tf.summary.scalar("loss", cost)
tf.summary.scalar("accuracy", accuracy)
marged_summary_op = tf.summary.merge_all()
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
summary_writer = tf.summary.FileWriter("logs/", graph=tf.get_default_graph())
for epoch in range(total_epochs):
avg_cost = 0
i = 0
while i < len(train_x):
start = i
end = i + batch_size
i = end
epoch_x, epoch_y = np.array(train_x[start:end]), np.array(train_y[start:end])
_, c, summary = sess.run([optimizer, cost, marged_summary_op], feed_dict={x: epoch_x, y:epoch_y})
summary_writer.add_summary(summary, epoch*len(train_x) + int(i/batch_size))
avg_cost += c/len(train_x)
print("Epoch {} of {} Finished. Average Cost {}.".format(epoch+1, total_epochs, avg_cost))
print("Accuracy: {}".format(accuracy.eval({x: test_x, y:test_y})))
这是错误:
---------------------------------------------------------------------------
InvalidArgumentError Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
1321 try:
-> 1322 return fn(*args)
1323 except errors.OpError as e:
/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in _run_fn(feed_dict, fetch_list, target_list, options, run_metadata)
1306 return self._call_tf_sessionrun(
-> 1307 options, feed_dict, fetch_list, target_list, run_metadata)
1308
/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in _call_tf_sessionrun(self, options, feed_dict, fetch_list, target_list, run_metadata)
1408 self._session, options, feed_dict, fetch_list, target_list,
-> 1409 run_metadata)
1410 else:
InvalidArgumentError: You must feed a value for placeholder tensor 'Input' with dtype float and shape [?,28,28,1]
[[Node: Input = Placeholder[dtype=DT_FLOAT, shape=[?,28,28,1], _device="/job:localhost/replica:0/task:0/device:GPU:0"]()]]
[[Node: Loss/Mean/_9 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_198_Loss/Mean", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]
During handling of the above exception, another exception occurred:
InvalidArgumentError Traceback (most recent call last)
<ipython-input-9-cd895cf45a86> in <module>()
38 epoch_x, epoch_y = np.array(train_x[start:end]), np.array(train_y[start:end])
39
---> 40 _, c, summary = sess.run([optimizer, cost, marged_summary_op], feed_dict={x: epoch_x, y:epoch_y})
41
42 summary_writer.add_summary(summary, epoch*len(train_x) + int(i/batch_size))
/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
898 try:
899 result = self._run(None, fetches, feed_dict, options_ptr,
--> 900 run_metadata_ptr)
901 if run_metadata:
902 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
1133 if final_fetches or final_targets or (handle and feed_dict_tensor):
1134 results = self._do_run(handle, final_targets, final_fetches,
-> 1135 feed_dict_tensor, options, run_metadata)
1136 else:
1137 results = []
/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
1314 if handle is None:
1315 return self._do_call(_run_fn, feeds, fetches, targets, options,
-> 1316 run_metadata)
1317 else:
1318 return self._do_call(_prun_fn, handle, feeds, fetches)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
1333 except KeyError:
1334 pass
-> 1335 raise type(e)(node_def, op, message)
1336
1337 def _extend_graph(self):
InvalidArgumentError: You must feed a value for placeholder tensor 'Input' with dtype float and shape [?,28,28,1]
[[Node: Input = Placeholder[dtype=DT_FLOAT, shape=[?,28,28,1], _device="/job:localhost/replica:0/task:0/device:GPU:0"]()]]
[[Node: Loss/Mean/_9 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_198_Loss/Mean", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]
Caused by op 'Input', defined at:
File "/usr/lib/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/usr/lib/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py", line 16, in <module>
app.launch_new_instance()
File "/usr/local/lib/python3.6/dist-packages/traitlets/config/application.py", line 658, in launch_instance
app.start()
File "/usr/local/lib/python3.6/dist-packages/ipykernel/kernelapp.py", line 477, in start
ioloop.IOLoop.instance().start()
File "/usr/local/lib/python3.6/dist-packages/zmq/eventloop/ioloop.py", line 177, in start
super(ZMQIOLoop, self).start()
File "/usr/local/lib/python3.6/dist-packages/tornado/ioloop.py", line 888, in start
handler_func(fd_obj, events)
File "/usr/local/lib/python3.6/dist-packages/tornado/stack_context.py", line 277, in null_wrapper
return fn(*args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events
self._handle_recv()
File "/usr/local/lib/python3.6/dist-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv
self._run_callback(callback, msg)
File "/usr/local/lib/python3.6/dist-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback
callback(*args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/tornado/stack_context.py", line 277, in null_wrapper
return fn(*args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/ipykernel/kernelbase.py", line 283, in dispatcher
return self.dispatch_shell(stream, msg)
File "/usr/local/lib/python3.6/dist-packages/ipykernel/kernelbase.py", line 235, in dispatch_shell
handler(stream, idents, msg)
File "/usr/local/lib/python3.6/dist-packages/ipykernel/kernelbase.py", line 399, in execute_request
user_expressions, allow_stdin)
File "/usr/local/lib/python3.6/dist-packages/ipykernel/ipkernel.py", line 196, in do_execute
res = shell.run_cell(code, store_history=store_history, silent=silent)
File "/usr/local/lib/python3.6/dist-packages/ipykernel/zmqshell.py", line 533, in run_cell
return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py", line 2718, in run_cell
interactivity=interactivity, compiler=compiler, result=result)
File "/usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py", line 2822, in run_ast_nodes
if self.run_code(code, result):
File "/usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py", line 2882, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-3-50881c3fb0dd>", line 1, in <module>
x = tf.placeholder('float', [None, 28, 28, 1], name="Input")
File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/array_ops.py", line 1734, in placeholder
return gen_array_ops.placeholder(dtype=dtype, shape=shape, name=name)
File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/gen_array_ops.py", line 4924, in placeholder
"Placeholder", dtype=dtype, shape=shape, name=name)
File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/op_def_library.py", line 787, in _apply_op_helper
op_def=op_def)
File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py", line 3414, in create_op
op_def=op_def)
File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py", line 1740, in __init__
self._traceback = self._graph._extract_stack() # pylint: disable=protected-access
InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Input' with dtype float and shape [?,28,28,1]
[[Node: Input = Placeholder[dtype=DT_FLOAT, shape=[?,28,28,1], _device="/job:localhost/replica:0/task:0/device:GPU:0"]()]]
[[Node: Loss/Mean/_9 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_198_Loss/Mean", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]