【问题标题】:Isomap Cant Reshape reshape array of size 72 into shape (8,8)Isomap Cant Reshape 将大小为 72 的数组重塑为形状 (8,8)
【发布时间】:2024-08-26 12:20:01
【问题描述】:

我正在编写使用 Isomap 进行图像识别的教程,代码如下:

主要错误是 def Plot2D 中的 reshape 函数,ValueError: cannot reshape array of size 72 into shape (8,8).

二维绘图功能:

def Plot2D(T, title, x, y, num_to_plot=40):
# This method picks a bunch of random samples (images in your case)
# to plot onto the chart:
fig = plt.figure()

ax = fig.add_subplot(111)
ax.set_title(title)
ax.set_xlabel('Component: {0}'.format(x))
ax.set_ylabel('Component: {0}'.format(y))

x_size = (max(T[:,x]) - min(T[:,x])) * 0.08
y_size = (max(T[:,y]) - min(T[:,y])) * 0.08

for i in range(num_to_plot):
    img_num = int(random.random() * num_images)
    x0, y0 = T[img_num,x]-x_size/2., T[img_num,y]-y_size/2.
    x1, y1 = T[img_num,x]+x_size/2., T[img_num,y]+y_size/2.
    img = df.iloc[img_num,:].reshape(num_pixels, num_pixels)
    ax.imshow(img, aspect='auto', cmap=plt.cm.gray, interpolation='nearest', zorder=100000, extent=(x0, x1, y0, y1))

图片上传处理功能:

  df = []
  for image_path in glob.glob("path/*.png"):
      image= misc.imread(image_path)
      df.append((image[::2, ::2] / 255.0).reshape(-1))
      df = pd.DataFrame(df).T
      iso = Isomap(n_neighbors=3,n_components=3).fit(df)
      T = iso.transform(df)

绘图功能:

     num_images, num_pixels = df.shape
     num_pixels = int(math.sqrt(num_pixels))
     Plot2D(T, "test", 0, 1, num_to_plot=40)

错误信息:

<ipython-input-30-e9aeee7b57c9> in Plot2D(T, title, x, y, num_to_plot)
 16         x0, y0 = T[img_num,x]-x_size/2., T[img_num,y]-y_size/2.
 17         x1, y1 = T[img_num,x]+x_size/2., T[img_num,y]+y_size/2.
 -> 18         img = df.iloc[img_num,:].reshape(num_pixels, num_pixels)
 19         ax.imshow(img, aspect='auto', cmap=plt.cm.gray, 
 interpolation='nearest', zorder=100000, extent=(x0, x1, y0, y1))

 ValueError: cannot reshape array of size 72 into shape (8,8)

【问题讨论】:

    标签: image machine-learning reshape


    【解决方案1】:

    我知道这对您来说可能为时已晚,但希望使用本课程的人不会将时间浪费在如此简单的事情上(就像我今天早上所做的那样)。该课程不再更新,我相信自第一次发布以来,一些 pandas 和 numpy 功能发生了变化。

    img = df.iloc[img_num,:].reshape(num_pixels, num_pixels)
    

    需要改成:

    img = df.iloc[img_num,:].values.reshape(num_pixels, num_pixels)
    

    与他们转换 MATLAB 文件的代码相同:

    for i in range(num_images):
        df.loc[i,:] = df.loc[i,:].reshape(num_pixels, num_pixels).T.reshape(-1)
    

    改为:

    for i in range(num_images):
        df.loc[i,:] = df.loc[i,:].values.reshape(num_pixels, num_pixels).T.reshape(-1)
    

    【讨论】: