简体   繁体   English

如何修复此错误:numpy.ndarray“对象没有属性” append”

[英]how to fix this error : numpy.ndarray “ object has no attribute ”append"

I hope that you are doing well. 我希望你一切都好。 I tried to run the below code. 我试图运行以下代码。 I am getting this error " numpy.ndarray object has no attribute append". 我收到此错误“ numpy.ndarray对象没有附加属性”。 I tried to used the solution recommended in other questions, like numpy.append() , numpy.concatenate() but I could not solve the problem. 我尝试使用其他问题中推荐的解决方案,例如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()

I am getting this 我得到这个

在此处输入图片说明

I would like that you help me to solve this problem. 我希望您能帮助我解决这个问题。 thanks in to all in advance 预先感谢大家

Numpy array instance doesn't have append function. Numpy数组实例没有附加功能。 Call 呼叫

numpy.append(your_arr, value_to_append)

which is class function. 这是类函数。

From the documentation : 文档中

You should be doing something like batchImages = np.append(batchImages, image) because "append" is not actually a defined function on numpy arrays, which is what the error message is saying. 您应该做类似batchImages = np.append(batchImages, image)因为“ append”实际上不是numpy数组上的已定义函数,这就是错误消息的意思。 If you want to insert somewhere specific in the array, np.insert(batchImages, index, image) works as well. 如果要在数组中的特定位置插入, np.insert(batchImages, index, image)可以工作。

You start with 你开始

batchImages = []

then successfully append to the list 然后成功附加到列表

batchImages.append(image)

then in the same iteration, you make an array and assign it to the same variable: 然后在同一迭代中,创建一个数组并将其分配给同一变量:

batchImages = np.vstack(batchImages)

next iteration, batchImages is no longer a list, so the append doesn't work! 在下一次迭代中, batchImages不再是列表,因此append不起作用!

I wonder if that vstack has the wrong indentation. 我想知道该vstack是否具有错误的缩进。 Is it supposed to happen in the j iteration, or the i one? 它应该发生在j迭代还是i迭代中?

Ignore the recommendations to use np.append . 忽略使用np.append的建议。 It should not be used iteratively, and is hard to use correctly. 不应迭代使用它,并且很难正确使用。 It's just a crude cover function for concatenate . 它只是用于concatenate的原始掩盖函数。 vstack is better. vstack更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何修复此错误 'numpy.ndarray' 对象在下面的代码中没有属性 'append' - how to fix this error 'numpy.ndarray' object has no attribute 'append' in the code below numpy.ndarray' object 没有属性 'append - numpy.ndarray' object has no attribute 'append 'numpy.ndarray' 对象没有属性 'append' - 'numpy.ndarray' object has no attribute 'append' AttributeError: 'numpy.ndarray' object 没有属性 'append' 错误 - AttributeError: 'numpy.ndarray' object has no attribute 'append' error 修复错误 'numpy.ndarray' object 没有属性 'convert' - To fix an error 'numpy.ndarray' object has no attribute 'convert' 如何修复此错误:AttributeError: 'numpy.ndarray' object has no attribute 'apply' - How to fix this error :AttributeError: 'numpy.ndarray' object has no attribute 'apply' AttributeError: 'numpy.ndarray' 对象没有属性 'append' - AttributeError: 'numpy.ndarray' object has no attribute 'append' Python - AttributeError:'numpy.ndarray'对象没有属性'append' - Python - AttributeError: 'numpy.ndarray' object has no attribute 'append' 保存到 csv - numpy.ndarray' object 没有属性“附加” - save to csv - numpy.ndarray' object has no attribute 'append' 为什么 python 抛出错误:AttributeError: 'numpy.ndarray' object has no attribute 'append'? - Why is python throwing error : AttributeError: 'numpy.ndarray' object has no attribute 'append'?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM