ValueError:“顺序”的输入0;与该层不兼容:预期形状=(无,32、32、3),发现形状=(32、32、3)

发布于 2025-01-24 06:40:26 字数 4277 浏览 0 评论 0原文

这是我收到的错误,有些帮助将很棒:我粘贴了代码的错误和部分,我认为可能出了点问题。 如果您能帮助我解决这个问题,那将是很棒的。 ValueError:在用户代码中: ----------------------------------------------------------------------------- -------------------------------------- ValueError Trackback(最近的最新电话) 在 27返回图 28 ---> 29显示(plotImages(x_test,data_test_picture,y_test,n_images = 10))

<command-3924510788207782> in plotImages(x_test, images_arr, labels_arr, n_images)
     16         ax.set_yticks(())
     17 
---> 18         predict_x=model2000.predict([[x_test[rand]]])
     19         label=categoriesList[predictions[0]]
     20 

/databricks/python/lib/python3.8/site-packages/keras/utils/traceback_utils.py in error_handler(*args, **kwargs)
     65     except Exception as e:  # pylint: disable=broad-except
     66       filtered_tb = _process_traceback_frames(e.__traceback__)
---> 67       raise e.with_traceback(filtered_tb) from None
     68     finally:
     69       del filtered_tb

/databricks/python/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in autograph_handler(*args, **kwargs)
   1127           except Exception as e:  # pylint:disable=broad-except
   1128             if hasattr(e, "ag_error_metadata"):
-> 1129               raise e.ag_error_metadata.to_exception(e)
   1130             else:
   1131               raise

ValueError: in user code:

    File "/databricks/python/lib/python3.8/site-packages/keras/engine/training.py", line 1621, in predict_function  *
        return step_function(self, iterator)
    File "/databricks/python/lib/python3.8/site-packages/keras/engine/training.py", line 1611, in step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "/databricks/python/lib/python3.8/site-packages/keras/engine/training.py", line 1604, in run_step  **
        outputs = model.predict_step(data)
    File "/databricks/python/lib/python3.8/site-packages/keras/engine/training.py", line 1572, in predict_step
        return self(x, training=False)
    File "/databricks/python/lib/python3.8/site-packages/keras/utils/traceback_utils.py", line 67, in error_handler
        raise e.with_traceback(filtered_tb) from None
    File "/databricks/python/lib/python3.8/site-packages/keras/engine/input_spec.py", line 263, in assert_input_compatibility
        raise ValueError(f'Input {input_index} of layer "{layer_name}" is '

    ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 32, 32, 3), found shape=(32, 32, 3)

以下是代码的一部分,我认为可能很有用:

def initializeModel():
  model = Sequential()

  model.add(Conv2D(32, (3, 3), padding='same',
                   input_shape=x_train.shape[1:]))
  model.add(Activation('relu'))
  model.add(Conv2D(32, (3, 3)))
  model.add(Activation('relu'))
  model.add(MaxPooling2D(pool_size=(2, 2)))
  model.add(Dropout(0.25))

  model.add(Conv2D(64, (3, 3), padding='same'))
  model.add(Activation('relu'))
  model.add(Conv2D(64, (3, 3)))
  model.add(Activation('relu'))
  model.add(MaxPooling2D(pool_size=(2, 2)))
  model.add(Dropout(0.25))

  model.add(Flatten())
  model.add(Dense(512))
  model.add(Activation('relu'))
  model.add(Dropout(0.5))
  model.add(Dense(num_classes))
  model.add(Activation('softmax'))
  return model

categoriesList=["airplane","automobile","bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck"]

import matplotlib.pyplot as plt
import random
def plotImages(x_test, images_arr, labels_arr, n_images=8):
    fig, axes = plt.subplots(n_images, n_images, figsize=(9,9))
    axes = axes.flatten()
    
    for i in range(100):
        rand = random.randint(0, x_test.shape[0] -1)
        img = images_arr[rand]
        ax = axes[i]
    
        ax.imshow( img, cmap="Greys_r")
        ax.set_xticks(())
        ax.set_yticks(())
        
        predict_x=model2000.predict([[x_test[rand]]])
        label=categoriesList[predictions[0]]  
        
        if labels_arr[rand][predictions[0]] == 0:
            ax.set_title(label, fontsize=18 - n_images, color="red")
        else:
            ax.set_title(label, fontsize=18 - n_images) 
        
    plot = plt.tight_layout()
    return plot
  
display (plotImages(x_test, data_test_picture, y_test, n_images=10))

This is the error I'm receiving, some help would be great: I have pasted the error and parts of the code where I believe something might be wrong.
It would be wonderful if you could help me out witht this.
ValueError: in user code:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
in
27 return plot
28
---> 29 display (plotImages(x_test, data_test_picture, y_test, n_images=10))

<command-3924510788207782> in plotImages(x_test, images_arr, labels_arr, n_images)
     16         ax.set_yticks(())
     17 
---> 18         predict_x=model2000.predict([[x_test[rand]]])
     19         label=categoriesList[predictions[0]]
     20 

/databricks/python/lib/python3.8/site-packages/keras/utils/traceback_utils.py in error_handler(*args, **kwargs)
     65     except Exception as e:  # pylint: disable=broad-except
     66       filtered_tb = _process_traceback_frames(e.__traceback__)
---> 67       raise e.with_traceback(filtered_tb) from None
     68     finally:
     69       del filtered_tb

/databricks/python/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in autograph_handler(*args, **kwargs)
   1127           except Exception as e:  # pylint:disable=broad-except
   1128             if hasattr(e, "ag_error_metadata"):
-> 1129               raise e.ag_error_metadata.to_exception(e)
   1130             else:
   1131               raise

ValueError: in user code:

    File "/databricks/python/lib/python3.8/site-packages/keras/engine/training.py", line 1621, in predict_function  *
        return step_function(self, iterator)
    File "/databricks/python/lib/python3.8/site-packages/keras/engine/training.py", line 1611, in step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "/databricks/python/lib/python3.8/site-packages/keras/engine/training.py", line 1604, in run_step  **
        outputs = model.predict_step(data)
    File "/databricks/python/lib/python3.8/site-packages/keras/engine/training.py", line 1572, in predict_step
        return self(x, training=False)
    File "/databricks/python/lib/python3.8/site-packages/keras/utils/traceback_utils.py", line 67, in error_handler
        raise e.with_traceback(filtered_tb) from None
    File "/databricks/python/lib/python3.8/site-packages/keras/engine/input_spec.py", line 263, in assert_input_compatibility
        raise ValueError(f'Input {input_index} of layer "{layer_name}" is '

    ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 32, 32, 3), found shape=(32, 32, 3)

Here are parts of the code that i think might be usefull:

def initializeModel():
  model = Sequential()

  model.add(Conv2D(32, (3, 3), padding='same',
                   input_shape=x_train.shape[1:]))
  model.add(Activation('relu'))
  model.add(Conv2D(32, (3, 3)))
  model.add(Activation('relu'))
  model.add(MaxPooling2D(pool_size=(2, 2)))
  model.add(Dropout(0.25))

  model.add(Conv2D(64, (3, 3), padding='same'))
  model.add(Activation('relu'))
  model.add(Conv2D(64, (3, 3)))
  model.add(Activation('relu'))
  model.add(MaxPooling2D(pool_size=(2, 2)))
  model.add(Dropout(0.25))

  model.add(Flatten())
  model.add(Dense(512))
  model.add(Activation('relu'))
  model.add(Dropout(0.5))
  model.add(Dense(num_classes))
  model.add(Activation('softmax'))
  return model

categoriesList=["airplane","automobile","bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck"]

import matplotlib.pyplot as plt
import random
def plotImages(x_test, images_arr, labels_arr, n_images=8):
    fig, axes = plt.subplots(n_images, n_images, figsize=(9,9))
    axes = axes.flatten()
    
    for i in range(100):
        rand = random.randint(0, x_test.shape[0] -1)
        img = images_arr[rand]
        ax = axes[i]
    
        ax.imshow( img, cmap="Greys_r")
        ax.set_xticks(())
        ax.set_yticks(())
        
        predict_x=model2000.predict([[x_test[rand]]])
        label=categoriesList[predictions[0]]  
        
        if labels_arr[rand][predictions[0]] == 0:
            ax.set_title(label, fontsize=18 - n_images, color="red")
        else:
            ax.set_title(label, fontsize=18 - n_images) 
        
    plot = plt.tight_layout()
    return plot
  
display (plotImages(x_test, data_test_picture, y_test, n_images=10))

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

沒落の蓅哖 2025-01-31 06:40:26

问题

predict_x = model2000.predict([[x_test[rand]]])

sample = X_test[rand].reshape((1,32,32,3))
predict_x = model2000.predict(sample)

和问题替换。

replace the line

predict_x = model2000.predict([[x_test[rand]]])

with

sample = X_test[rand].reshape((1,32,32,3))
predict_x = model2000.predict(sample)

and problem may be solved.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文