0

이미지의 레이블을 예측하기위한 CNN을 만들었습니다. 나는 그것을 훈련했다. 이제 새 모델의 레이블을 예측하는 데 내 모델을 사용하고 싶습니다. CNN 코드는 다음과 같습니다. -Tensorflow에서 InvalidArgumentError 받기

def LeNet(x):  
    # Arguments used for tf.truncated_normal, randomly defines variables for the weights and biases for each layer 
    mu = 0 
    sigma = 0.1 

    # SOLUTION: Layer 1: Convolutional. Input = 32x32x3. Output = 28x28x6. 
    conv1_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 3, 6), mean = mu, stddev = sigma)) 
    conv1_b = tf.Variable(tf.zeros(6)) 
    conv1 = tf.nn.conv2d(x, conv1_W, strides=[1, 1, 1, 1], padding='VALID') + conv1_b 

    # SOLUTION: Activation. 
    conv1 = tf.nn.relu(conv1) 


    # SOLUTION: Pooling. Input = 28x28x6. Output = 14x14x6. 
    conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID') 

    # SOLUTION: Layer 2: Convolutional. Output = 10x10x16. 
    conv2_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 6, 16), mean = mu, stddev = sigma)) 
    conv2_b = tf.Variable(tf.zeros(16)) 
    conv2 = tf.nn.conv2d(conv1, conv2_W, strides=[1, 1, 1, 1], padding='VALID') + conv2_b 

    # SOLUTION: Activation. 
    conv2 = tf.nn.relu(conv2) 



    # SOLUTION: Pooling. Input = 10x10x16. Output = 5x5x16. 
    conv2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID') 

    # SOLUTION: Flatten. Input = 5x5x16. Output = 400. 
    fc0 = flatten(conv2) 

    # SOLUTION: Layer 3: Fully Connected. Input = 400. Output = 120. 
    fc1_W = tf.Variable(tf.truncated_normal(shape=(400, 120), mean = mu, stddev = sigma)) 
    fc1_b = tf.Variable(tf.zeros(120)) 
    fc1 = tf.matmul(fc0, fc1_W) + fc1_b 

    # SOLUTION: Activation. 
    fc1 = tf.nn.relu(fc1) 
    fc1 = tf.nn.dropout(fc1,0.6) 

    # SOLUTION: Layer 4: Fully Connected. Input = 120. Output = 84. 
    fc2_W = tf.Variable(tf.truncated_normal(shape=(120, 84), mean = mu, stddev = sigma)) 
    fc2_b = tf.Variable(tf.zeros(84)) 
    fc2 = tf.matmul(fc1, fc2_W) + fc2_b 

    # SOLUTION: Activation. 
    fc2 = tf.nn.relu(fc2) 
    fc2 = tf.nn.dropout(fc2,0.7) 


    # SOLUTION: Layer 5: Fully Connected. Input = 84. Output = 43. 
    fc3_W = tf.Variable(tf.truncated_normal(shape=(84, 43), mean = mu, stddev =  sigma)) 
    fc3_b = tf.Variable(tf.zeros(43)) 

    logits = tf.matmul(fc2, fc3_W) + fc3_b 

    return logits 

    x = tf.placeholder(tf.float32, (None, 32, 32, 3)) 
    y = tf.placeholder(tf.int32, (None)) 
    one_hot_y = tf.one_hot(y, 43) 

    rate = 0.001 
    logits = LeNet(x) 
    cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits,      labels=one_hot_y) 
    loss_operation = tf.reduce_mean(cross_entropy) 
    optimizer = tf.train.AdamOptimizer(learning_rate = rate) 
    training_operation = optimizer.minimize(loss_operation) 

    correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1)) 
accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) 
saver = tf.train.Saver() 

def evaluate(X_data, y_data): 
    num_examples = len(X_data) 
    total_accuracy = 0 
    sess = tf.get_default_session() 
    for offset in range(0, num_examples, BATCH_SIZE): 
     batch_x, batch_y = X_data[offset:offset+BATCH_SIZE],  y_data[offset:offset+BATCH_SIZE] 
     accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y}) 
     total_accuracy += (accuracy * len(batch_x)) 
    return total_accuracy/num_examples 

with tf.Session() as sess: 
sess.run(tf.global_variables_initializer()) 
num_examples = len(X_train) 

print("Training...") 
print() 
for i in range(EPOCHS): 
    X_train, y_train = shuffle(X_train, y_train) 
    for offset in range(0, num_examples, BATCH_SIZE): 
     end = offset + BATCH_SIZE 
     batch_x, batch_y = X_train[offset:end], y_train[offset:end] 
     sess.run(training_operation, feed_dict={x: batch_x, y: batch_y}) 

    training_accuracy = evaluate(X_train,y_train) 
    validation_accuracy = evaluate(X_valid, y_valid) 
    print("EPOCH {} ...".format(i+1)) 
    print("training Accuracy = {:.3f}".format(training_accuracy)) 
    print("Validation Accuracy = {:.3f}".format(validation_accuracy)) 
    print() 

saver.save(sess, './lenet') 
print("Model saved") 

이제 인터넷에서 일부 이미지를 다운로드하고 레이블을 예측하고 싶습니다. 다음과 같이 numpy.ndarray하도록 이미지를 처리하고 변환하는 코드는 다음과 같습니다 -

from os import listdir 
from PIL import Image as PImage 
from matplotlib import pyplot as plt 

def loadImages(path): 
    # return array of images 

    imagesList = listdir(path) 
    loadedImages = [] 
    basewidth = 32 
    hsize = 32 
    for image in imagesList: 
     img = PImage.open(path + image) 
     img = img.resize((basewidth,hsize),PIL.Image.ANTIALIAS) 
     loadedImages.append(img) 

    return loadedImages 

    path = "C:\\Users\\che\\CarND-Traffic-Sign-Classifier-Project\\images\\" 

    image_in_pixels = [] 

for image in imgs: 
    image = np.array(image.getdata(),np.float32).reshape(32, 32, 3) 
    image_in_pixels.append(image) 

    print(type(image_in_pixels)) 
    test_images = np.array(image_in_pixels) 
    print(test_images.shape) 
    print(type(test_images[0])) 

지금 여기에 내가 저장 한 모델을 사용하여 이러한 이미지를 레이블을 예측해야합니다. 다음과 같은에 대한 나의 코드는 : - feed_dict에 대한

x = tf.placeholder(dtype=tf.float32,shape=(None,32,32,3)) 
    keep_prob = tf.placeholder(dtype=tf.float32) 

    with tf.Session() as sess: 
     saver.restore(sess, tf.train.latest_checkpoint('.')) 
     vals = sess.run(logits,feed_dict={x:test_images,keep_prob: 1.}) 
     print (vals) 

I am getting the following error. 

    InvalidArgumentError      Traceback (most recent call last) 
C:\ProgramData\Anaconda3\envs\carnd-term1\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args) 
    1021  try: 
-> 1022  return fn(*args) 
    1023  except errors.OpError as e: 

C:\ProgramData\Anaconda3\envs\carnd-term1\lib\site-packages\tensorflow\python\client\session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata) 
    1003         feed_dict, fetch_list, target_list, 
-> 1004         status, run_metadata) 
    1005 

C:\ProgramData\Anaconda3\envs\carnd-term1\lib\contextlib.py in __exit__(self, type, value, traceback) 
    65    try: 
---> 66     next(self.gen) 
    67    except StopIteration: 

C:\ProgramData\Anaconda3\envs\carnd-term1\lib\site-packages\tensorflow\python\framework\errors_impl.py in raise_exception_on_not_ok_status() 
    465   compat.as_text(pywrap_tensorflow.TF_Message(status)), 
--> 466   pywrap_tensorflow.TF_GetCode(status)) 
    467 finally: 

InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder_2' with dtype float 
    [[Node: Placeholder_2 = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]] 

During handling of the above exception, another exception occurred: 

InvalidArgumentError      Traceback (most recent call last) 
<ipython-input-213-6e880af91901> in <module>() 
     4 with tf.Session() as sess: 
     5 saver.restore(sess, tf.train.latest_checkpoint('.')) 
----> 6 vals = sess.run(logits,feed_dict={x:test_images,keep_prob: 1.}) 
     7 print (vals) 

C:\ProgramData\Anaconda3\envs\carnd-term1\lib\site-packages\tensorflow\python\client\session.py in run(self, fetches, feed_dict, options, run_metadata) 
    765  try: 
    766  result = self._run(None, fetches, feed_dict, options_ptr, 
--> 767       run_metadata_ptr) 
    768  if run_metadata: 
    769   proto_data = tf_session.TF_GetBuffer(run_metadata_ptr) 

C:\ProgramData\Anaconda3\envs\carnd-term1\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata) 
    963  if final_fetches or final_targets: 
    964  results = self._do_run(handle, final_targets, final_fetches, 
--> 965        feed_dict_string, options, run_metadata) 
    966  else: 
    967  results = [] 

C:\ProgramData\Anaconda3\envs\carnd-term1\lib\site-packages\tensorflow\python\client\session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata) 
    1013  if handle is None: 
    1014  return self._do_call(_run_fn, self._session, feed_dict, fetch_list, 
-> 1015       target_list, options, run_metadata) 
    1016  else: 
    1017  return self._do_call(_prun_fn, self._session, handle, feed_dict, 

C:\ProgramData\Anaconda3\envs\carnd-term1\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args) 
    1033   except KeyError: 
    1034   pass 
-> 1035  raise type(e)(node_def, op, message) 
    1036 
    1037 def _extend_graph(self): 

InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder_2' with dtype float 
    [[Node: Placeholder_2 = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]] 

Caused by op 'Placeholder_2', defined at: 
    File "C:\ProgramData\Anaconda3\envs\carnd-term1\lib\runpy.py", line 184, in _run_module_as_main 
    "__main__", mod_spec) 
    File "C:\ProgramData\Anaconda3\envs\carnd-term1\lib\runpy.py", line 85, in _run_code 
    exec(code, run_globals) 
    File "C:\ProgramData\Anaconda3\envs\carnd-term1\lib\site-packages\ipykernel\__main__.py", line 3, in <module> 
    app.launch_new_instance() 
    File "C:\ProgramData\Anaconda3\envs\carnd-term1\lib\site-packages\traitlets\config\application.py", line 658, in launch_instance 
    app.start() 
    File "C:\ProgramData\Anaconda3\envs\carnd-term1\lib\site-packages\ipykernel\kernelapp.py", line 474, in start 
    ioloop.IOLoop.instance().start() 
    File "C:\ProgramData\Anaconda3\envs\carnd-term1\lib\site-packages\zmq\eventloop\ioloop.py", line 177, in start 
    super(ZMQIOLoop, self).start() 
    File "C:\ProgramData\Anaconda3\envs\carnd-term1\lib\site-packages\tornado\ioloop.py", line 887, in start 
    handler_func(fd_obj, events) 
    File "C:\ProgramData\Anaconda3\envs\carnd-term1\lib\site-packages\tornado\stack_context.py", line 275, in null_wrapper 
    return fn(*args, **kwargs) 
    File "C:\ProgramData\Anaconda3\envs\carnd-term1\lib\site-packages\zmq\eventloop\zmqstream.py", line 440, in _handle_events 
    self._handle_recv() 
    File "C:\ProgramData\Anaconda3\envs\carnd-term1\lib\site-packages\zmq\eventloop\zmqstream.py", line 472, in _handle_recv 
    self._run_callback(callback, msg) 
    File "C:\ProgramData\Anaconda3\envs\carnd-term1\lib\site-packages\zmq\eventloop\zmqstream.py", line 414, in _run_callback 
    callback(*args, **kwargs) 
    File "C:\ProgramData\Anaconda3\envs\carnd-term1\lib\site-packages\tornado\stack_context.py", line 275, in null_wrapper 
    return fn(*args, **kwargs) 
    File "C:\ProgramData\Anaconda3\envs\carnd-term1\lib\site-packages\ipykernel\kernelbase.py", line 276, in dispatcher 
    return self.dispatch_shell(stream, msg) 
    File "C:\ProgramData\Anaconda3\envs\carnd-term1\lib\site-packages\ipykernel\kernelbase.py", line 228, in dispatch_shell 
    handler(stream, idents, msg) 
    File "C:\ProgramData\Anaconda3\envs\carnd-term1\lib\site-packages\ipykernel\kernelbase.py", line 390, in execute_request 
    user_expressions, allow_stdin) 
    File "C:\ProgramData\Anaconda3\envs\carnd-term1\lib\site-packages\ipykernel\ipkernel.py", line 196, in do_execute 
    res = shell.run_cell(code, store_history=store_history, silent=silent) 
    File "C:\ProgramData\Anaconda3\envs\carnd-term1\lib\site-packages\ipykernel\zmqshell.py", line 501, in run_cell 
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs) 
    File "C:\ProgramData\Anaconda3\envs\carnd-term1\lib\site-packages\IPython\core\interactiveshell.py", line 2717, in run_cell 
    interactivity=interactivity, compiler=compiler, result=result) 
    File "C:\ProgramData\Anaconda3\envs\carnd-term1\lib\site-packages\IPython\core\interactiveshell.py", line 2821, in run_ast_nodes 
    if self.run_code(code, result): 
    File "C:\ProgramData\Anaconda3\envs\carnd-term1\lib\site-packages\IPython\core\interactiveshell.py", line 2881, in run_code 
    exec(code_obj, self.user_global_ns, self.user_ns) 
    File "<ipython-input-17-55707f3825d1>", line 1, in <module> 
    x = tf.placeholder(tf.float32, (None, 32, 32, 3)) 
    File "C:\ProgramData\Anaconda3\envs\carnd-term1\lib\site-packages\tensorflow\python\ops\array_ops.py", line 1502, in placeholder 
    name=name) 
    File "C:\ProgramData\Anaconda3\envs\carnd-term1\lib\site-packages\tensorflow\python\ops\gen_array_ops.py", line 2149, in _placeholder 
    name=name) 
    File "C:\ProgramData\Anaconda3\envs\carnd-term1\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 763, in apply_op 
    op_def=op_def) 
    File "C:\ProgramData\Anaconda3\envs\carnd-term1\lib\site-packages\tensorflow\python\framework\ops.py", line 2327, in create_op 
    original_op=self._default_original_op, op_def=op_def) 
    File "C:\ProgramData\Anaconda3\envs\carnd-term1\lib\site-packages\tensorflow\python\framework\ops.py", line 1226, in __init__ 
    self._traceback = _extract_stack() 

InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Placeholder_2' with dtype float 
    [[Node: Placeholder_2 = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]] 

내 데이터 타입은 부동이다. 지난 3 일부터 나는 어떤 성공도없이 이것을 디버깅하는 데 어려움을 겪고있다. 귀하의 도움은 대단히 감사하겠습니다.

+0

위 코드에서 keep_prob을 사용하도록 드롭 아웃을 변경했습니다. - fc2 = tf.nn.dropout (fc2, keep_prob). 값은 하드 코딩되지 않습니다. –

답변

0

당신이 keep_prob

keep_prob = tf.placeholder(dtype=tf.float32, shape=(1)) 
+0

농담이 당신의 요점을 이해합니다. keep_prob는 float입니다. 그것을위한 모양을 정의하는 방법? –

+0

가끔은 저장하고 복원하는 동안 뭔가 일이 일어나는 것 같습니다. 어쩌면 가중치를 재정의하고 자리 표시자를 편향시킬 수 있습니다. 그리고 우리가 코스에서 가지고있는 것과 같은 이름을줍니다 : 'weights = tf.Variable (tf.truncated_normal ([2, 3]), name = 'weights_0')' 'bias = tf.Variable (tf.truncated_normal ([3]), name = 'bias_0')' 'saver = tf.train.Saver()' 'tf.reset_default_graph() ' 'bias = tf.Variable (tf.truncated_normal ([3]), 이름 = 'bias_0') ' '무게 = tf.Variable (이름, 'weights_0'), 이름 = 'weights_0') ' 세이버 = tf.train.Saver()' –

+0

체크 레슨 신경 네트워크, 섹션 14, Finetuning –

0

당신은 ValueError을 받고있는 모양을 정의합니다. tensorflow 문서에 따르면 "fetches 또는 feed_dict 키가 유효하지 않거나 존재하지 않는 Tensor를 참조하는 경우"오류가 발생합니다 (Tensorflow Session Documentation 참조).

필요하지 않은 텐서는 Tensorflow 세션 바로 전에 x = tf.placeholder(dtype=tf.float32,shape=(None,32,32,3))입니다. 그것을 제거하면 오류가 사라집니다.

관련 문제