python - 无法访问numpy数组的索引
问题描述
我的问题可能很微不足道,但我在任何地方都找不到解决方案,所以我还是问你。正如您在此代码片段中看到的那样,我创建了一个名为index的随机整数,然后我想访问该索引处的元素(test_res 是一个 2-dim 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()
解决方案
推荐阅读
- sass - Browsersync 未检测到子文件夹中 sass 文件的更改
- sql - 如何使每月动态?下面的脚本是一月和二月的硬编码
- python - 在 Raspberry OS 上的 Python 中使用 OneWire
- jpa - 为什么 JPQL 忽略父字段?
- javascript - 单击按钮时未触发更改事件
- django - 如何使用通用 ListCreateAPIView 在嵌套序列化程序中创建用户?
- angular - 是否可以将 dotnet angular spa Ideneity API 与其他平台(例如移动应用程序)一起使用?
- node.js - 无法全局安装 npm 包
- redirect - IdentityServer4 版本 3.1.4 登录后重定向回客户端仅适用于 Firefox
- sql - 如何施加这种排除约束?