【问题标题】:how to fix this error : numpy.ndarray " object has no attribute "append"如何修复此错误:numpy.ndarray“对象没有属性”附加“
【发布时间】:2019-06-29 23:53:53
【问题描述】:

我希望你一切都好。我试图运行下面的代码。我收到此错误“numpy.ndarray 对象没有附加属性”。我尝试使用其他问题中推荐的解决方案,例如numpy.append()numpy.concatenate(),但我无法解决问题。

from keras.applications import VGG16
from keras.applications import imagenet_utils
from keras.preprocessing.image import img_to_array
from keras.preprocessing.image import load_img
from sklearn.preprocessing import LabelEncoder
from hdf5datasetwriter import HDF5DatasetWriter
from imutils import paths
import progressbar
import argparse
import random
import numpy as np
import os


# construct the argument parser and parse the arguments

ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", required= True,
                help=" path to the input dataset ")
ap.add_argument("-o", "--output", required= True,
                help=" path to output HDF5 file ")
ap.add_argument("-b","--batch_size", type= int, default=32,
                help =" batch size of images to be passed through network ")
ap.add_argument("-s","--buffer_size", type =int, default=1000,
                help=" size of feature extraction buffer")

args= vars(ap.parse_args())

# store the batch size in a convenience variable
bs = args["batch_size"]

# grab the list of images that we will be describing then randomly shuffle them to
# allow for easy training and testing splits via array slicing during training time

print ("[INFO] loading images ...")
imagePaths= list(paths.list_images(args["dataset"]))
random.shuffle(imagePaths)

# extract the class labels from the images paths then encode the labels

labels = [p.split(os.path.sep)[-2] for p in imagePaths]
le= LabelEncoder()
labels= le.fit_transform(labels)

# load the VGG16 network

print("[INFO] loading network ...")

model= VGG16(weights="imagenet", include_top=False)

# initialize the HDF5 dataset writer then store the class label names in the
# dataset
dataset = HDF5DatasetWriter((len(imagePaths), 512*7*7), args["output"], dataKey="features",
                            bufSize= args["buffer_size"])
dataset.storeClassLabels(le.classes_)

# initialize the prograss bar
widgets = [" extracting features:", progressbar.Percentage(), " " , progressbar.Bar(),
           " " , progressbar.ETA()]
pbar= progressbar.ProgressBar(maxval=len(imagePaths), widgets= widgets ).start()

# loop over the image patches

for i in np.arange(0, len(imagePaths),bs):
    # extract the batch of images and labels, then initalize the
    # list of actualimages that will be passed through the network for feature
    # extraction

    batchPaths= imagePaths[i:i + bs]
    batchLabels = labels[i:i+bs]
    batchImages = []

    for (j, imagePath) in enumerate(batchPaths):
        # load the input image using the keras helper utility
        # while ensuring the image is resized to 224x224 pixels

        image = load_img(imagePath, target_size = (224,224))
        image = img_to_array(image)

        # preprocess the image by (1) expanding the dimensions and
        # (2) substracting the mean RGB pixel intensity from the imagenet dataset

        image = np.expand_dims(image, axis =0)
        #image = imagenet_utils.preprocess_input(image)

        # add the image to the batch
        batchImages.append(image)

        # pass the images through the network and use the outputs as our
        # actual featues

        batchImages = np.vstack(batchImages)
        features = model.predict(batchImages, batch_size = bs)

        # reshape the features so that each image is represented by a flattened feature vector of the maxPooling2D outputs
        features = features.reshape((features.shape[0], 512*7*7))
        # add the features and the labels to HDF5 dataset
        dataset.add(features, batchLabels)
        pbar.update(i)


dataset.close()
pbar.finish()

我收到了

我希望您能帮我解决这个问题。在此先感谢大家

【问题讨论】:

    标签: python python-3.x numpy


    【解决方案1】:

    来自documentation

    您应该执行batchImages = np.append(batchImages, image) 之类的操作,因为“append”实际上不是 numpy 数组上定义的函数,这就是错误消息所说的。如果您想在数组中的某个特定位置插入,np.insert(batchImages, index, image) 也可以。

    【讨论】:

    • 谢谢,我试过了,但又遇到了一个错误。 “检查输入时出错:预期 input_1 有 4 个维度,但得到了形状为 (150528, 1) 的数组”。错误发生在这里“ features = model.predict(batchImages, batch_size = bs)”。似乎提供的输入没有预期的形状。 @tchainzzz
    • 这令人放心——意味着我们可能已经克服了这个错误并找到了另一个错误!我对 VGG16 不是特别熟悉,因为我自己没有使用过它,但在我看来,错误是说 batchImages 的尺寸错误。查看模型的文档以了解预期的输入类型以及如何确保输入与该类型一致。
    【解决方案2】:

    Numpy 数组实例没有附加功能。 打电话

    numpy.append(your_arr, value_to_append)
    

    这是类函数。

    【讨论】:

      【解决方案3】:

      你开始

      batchImages = []
      

      然后成功追加到列表中

      batchImages.append(image)
      

      然后在同一次迭代中,创建一个数组并将其分配给同一个变量:

      batchImages = np.vstack(batchImages)
      

      下一次迭代,batchImages 不再是一个列表,所以append 不起作用!

      我想知道vstack 是否有错误的缩进。它应该发生在j 迭代中还是i 迭代中?

      忽略使用np.append 的建议。它不应该被迭代使用,并且很难正确使用。这只是concatenate 的粗略覆盖功能。 vstack 更好。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-01-14
        • 2019-09-10
        • 1970-01-01
        • 2021-12-10
        • 1970-01-01
        • 2020-10-11
        • 1970-01-01
        相关资源
        最近更新 更多