无法访问numpy数组的索引

时间:2019-12-16 10:30:50

标签: python numpy machine-learning multidimensional-array

我的问题可能很琐碎,但我在任何地方都找不到解决方案,所以无论如何我都会问你。如您在此代码片段中所见,我创建了一个名为 index 的随机整数,然后我想访问该索引处的元素(test_res是一个2维的numpy数组)。我收到错误消息AttributeError: 'numpy.ndarray' object has no attribute 'index'。足够奇怪的是,当我在控制台中键入该内容时,它确实可以工作:

index=random.randrange(0,10000)
network.test_res[index]

正确返回array([1., 0., 0., 0., 0., 0., 0., 0., 0., 0.], dtype=float32) 但是在此功能中,我仅收到错误消息,而我不明白为什么。我做了什么不同的事情?我可能缺少明显的东西,所以请原谅,并先谢谢您。

这是我的代码段:

def test_predict(self):
        """ test some random numbers from the test part of the data set """
        index = random.randrange(0,10000) # there are 10000 images in the test part of the data set
        """ the actual result stored in the data set 
            It's represented as a list of 10 elements one of which being 1, the rest 0 """
        num_pixels = self.test_img.shape[0] * self.test_img.shape[1]
        correct_res = np.where(self.test_res[index] == 1) 
        predicted_res = np.argmax(self.model.predict(self.test_img[index].reshape(-1, num_pixels)), axis = 1)

        if correct_res != predicted_res:
            print("Error in predict ! \
                  index = ", index, " predicted result = ", predicted_res, " correct result = ", correct_res)
        else:
            print("alright")

编辑:这是完整的代码:

# import random for tests
import random

# import keras and the MNIST dataset
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from keras.utils import np_utils

# import matplotlib to show pictures
import matplotlib.pyplot as plt

# numpy is necessary since keras uses numpy arrays
import numpy as np

class mnist_network():
    def __init__(self):
        """ load data, create and train model """
        # load data
        (X_train, y_train), (X_test, y_test) = mnist.load_data()
        # flatten 28*28 images to a 784 vector for each image
        num_pixels = X_train.shape[1] * X_train.shape[2]
        X_train = X_train.reshape((X_train.shape[0], num_pixels)).astype('float32')
        X_test = X_test.reshape((X_test.shape[0], num_pixels)).astype('float32')
        # normalize inputs from 0-255 to 0-1
        X_train = X_train / 255
        X_test = X_test / 255
        # one hot encode outputs
        y_train = np_utils.to_categorical(y_train)
        y_test = np_utils.to_categorical(y_test)
        num_classes = y_test.shape[1]


        # create model
        self.model = Sequential()
        self.model.add(Dense(num_pixels, input_dim=num_pixels, kernel_initializer='normal', activation='relu'))
        self.model.add(Dense(num_classes, kernel_initializer='normal', activation='softmax'))
        # Compile model
        self.model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

        # train the model
        self.model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=200, verbose=2)

        self.train_img = X_train
        self.train_res = y_train
        self.test_img = X_test
        self.test_res = y_test


    def test_all(self):
        """ evaluates the success rate using all the test data """
        scores = self.model.evaluate(self.test_img, self.test_res, verbose=0)
        print("Baseline Error: %.2f%%" % (100-scores[1]*100))

    def predict(self, img, show=False):
        """ img has to be a 784 vector """
        """ predicts the number in a picture (vector) """
        if show:
            # show the picture
            plt.imshow(img, cmap='Greys')
            plt.show()

        num_pixels = img.shape[1] * img.shape[2]
        # the actual number
        res_number = np.argmax(self.model.predict(img.reshape(-1,num_pixels)), axis = 1)

        """ the probabilities """
        res_probabilities = self.model.predict(img.reshape(-1,num_pixels))

        return res_number[0]    # res_number is a list containing one element

    def test_predict(self):
        """ test some random numbers from the test part of the data set """
        index = random.randrange(0,10000) # there are 10000 images in the test part of the data set
        """ the actual result stored in the data set 
            It's represented as a list of 10 elements one of which being 1, the rest 0 """
        num_pixels = self.test_img.shape[0] * self.test_img.shape[1]
        correct_res = np.where(self.test_res[index] == 1) 
        predicted_res = np.argmax(self.model.predict(self.test_img[index].reshape(-1, num_pixels)), axis = 1)

        if correct_res != predicted_res:
            print("Error in predict ! \
                  index = ", index, " predicted result = ", predicted_res, " correct result = ", correct_res)
        else:
            print("alright")



network = mnist_network()
network.test_predict()

0 个答案:

没有答案