IndexError: list assignment index out of range for CNN program from scratch
IndexError: list assignment index out of range for CNN program from scratch
当我的数组维度与我的循环限制匹配时,我一直收到此错误,我应该更改什么。
本程序旨在从头开始使用神经网络对 32*32p 黑白图像进行分类。
import numpy as np
import matplotlib.pyplot as plt
import pickle
from math import exp
from random import seed
from random import random
def unpickle(file):
with open(file, 'rb') as fo:
data = pickle.load(fo, encoding='bytes')
return data
def load_data(data_dir, negatives=False):
meta_data_dict = unpickle("batches.meta")
data_label_names = meta_data_dict[b'label_names']
data_label_names = np.array(data_label_names)
# training data
train_data = None
train_filenames = []
train_labels = []
train_data_dict = unpickle("data_batch_1")
train_data = train_data_dict[b'data']
train_filenames += train_data_dict[b'filenames']
train_labels += train_data_dict[b'labels']
train_data = train_data.reshape((len(train_data), 1, 32, 32))
if negatives:
train_data = train_data.transpose(0, 2, 3, 1).astype(np.float32)
else:
train_data = np.rollaxis(train_data, 1, 4)
train_filenames = np.array(train_filenames)
train_labels = np.array(train_labels)
return train_data, train_filenames, train_labels, data_label_names
data_dir = 'data-batches-py'
x_train, x_train_filenames, y_train_labels, y_label_names =load_cifar_10_data(data_dir)
print (x_train.shape)
print (len(x_train))
# Initialize a network
def initialize_network(n_hidden):
network = list()
hidden_layer = [{'weights':[random() for i in range(len(x_train) + 1)]} for i in range(n_hidden)]
network.append(hidden_layer)
output_layer = [{'weights':[random() for i in range(n_hidden +1)]} for i in range(10)]
network.append(output_layer)
return network
def sum(inputs):
sum_row=[]
for i in range(len(x_train)):
for a in range(32):
for b in range(32):
sum_row[i]=0
sum_row[i]+= inputs[i][a][b][1]
return sum_row
# Calculate neuron activation for an input
def activate(weights, inputs):
flattened= sum(inputs)
activation = weights[-1]
for i in range(len(weights)-1):
activation += weights[i] * flattened[i]
return activation
# Transfer neuron activation
def transfer(activation):
return 1.0 / (1.0 + exp(-activation))
# Forward propagate input to a network output
def forward_propagate(network, row):
inputs = row
for layer in network:
new_inputs = []
for neuron in layer:
activation = activate(neuron['weights'], inputs)
neuron['output'] = transfer(activation)
new_inputs.append(neuron['output'])
inputs = new_inputs
return inputs
network = initialize_network(1)
row = x_train
output = forward_propagate(network, row)
print(output)
在 运行 这段代码之后我得到以下输出
(10000, 32, 32, 1)
10000
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
/var/folders/gm/z9_jyr1s5k1232zgf4xf7cxc0000gn/T/ipykernel_15670/2752672525.py in <module>
153 network = initialize_network(1)
154 row = x_train
--> 155 output = forward_propagate(network, row)
156 print(output)
/var/folders/gm/z9_jyr1s5k1232zgf4xf7cxc0000gn/T/ipykernel_15670/2752672525.py in forward_propagate(network, row)
78 new_inputs = []
79 for neuron in layer:
---> 80 activation = activate(neuron['weights'], inputs)
81 neuron['output'] = transfer(activation)
82 new_inputs.append(neuron['output'])
/var/folders/gm/z9_jyr1s5k1232zgf4xf7cxc0000gn/T/ipykernel_15670/2752672525.py in activate(weights, inputs)
62 # Calculate neuron activation for an input
63 def activate(weights, inputs):
---> 64 flattened= sum(inputs)
65 activation = weights[-1]
66 for i in range(len(weights)-1):
/var/folders/gm/z9_jyr1s5k1232zgf4xf7cxc0000gn/T/ipykernel_15670/2752672525.py in sum(inputs)
57 for a in range(32):
58 for b in range(32):
---> 59 sum_row[i]=0
60 sum_row[i]+= inputs[i][a][b][1]
61 return sum_row
IndexError: list assignment index out of range
可以看到输入的维度是100003232*1,那为什么会报错呢?
错误在
def sum(inputs):
sum_row=[]
for i in range(len(x_train)):
for a in range(32):
for b in range(32):
sum_row[i]=0
sum_row[i]+= inputs[i][a][b][1]
return sum_row
错误的原因是您试图访问 sum_row 的元素,但 sum_row 中没有任何元素(因为您在 sum_row 之前将其设置为 [] for 循环)。在 for 循环中,您尝试访问它没有的成员。而不是做 sum_row[i] = 0
你应该做 sum_row.append(0) 向该列表添加一个元素。然后你可以通过 sum_row[-1] += inputs[i][a][b][1]
访问它
当我的数组维度与我的循环限制匹配时,我一直收到此错误,我应该更改什么。
本程序旨在从头开始使用神经网络对 32*32p 黑白图像进行分类。
import numpy as np
import matplotlib.pyplot as plt
import pickle
from math import exp
from random import seed
from random import random
def unpickle(file):
with open(file, 'rb') as fo:
data = pickle.load(fo, encoding='bytes')
return data
def load_data(data_dir, negatives=False):
meta_data_dict = unpickle("batches.meta")
data_label_names = meta_data_dict[b'label_names']
data_label_names = np.array(data_label_names)
# training data
train_data = None
train_filenames = []
train_labels = []
train_data_dict = unpickle("data_batch_1")
train_data = train_data_dict[b'data']
train_filenames += train_data_dict[b'filenames']
train_labels += train_data_dict[b'labels']
train_data = train_data.reshape((len(train_data), 1, 32, 32))
if negatives:
train_data = train_data.transpose(0, 2, 3, 1).astype(np.float32)
else:
train_data = np.rollaxis(train_data, 1, 4)
train_filenames = np.array(train_filenames)
train_labels = np.array(train_labels)
return train_data, train_filenames, train_labels, data_label_names
data_dir = 'data-batches-py'
x_train, x_train_filenames, y_train_labels, y_label_names =load_cifar_10_data(data_dir)
print (x_train.shape)
print (len(x_train))
# Initialize a network
def initialize_network(n_hidden):
network = list()
hidden_layer = [{'weights':[random() for i in range(len(x_train) + 1)]} for i in range(n_hidden)]
network.append(hidden_layer)
output_layer = [{'weights':[random() for i in range(n_hidden +1)]} for i in range(10)]
network.append(output_layer)
return network
def sum(inputs):
sum_row=[]
for i in range(len(x_train)):
for a in range(32):
for b in range(32):
sum_row[i]=0
sum_row[i]+= inputs[i][a][b][1]
return sum_row
# Calculate neuron activation for an input
def activate(weights, inputs):
flattened= sum(inputs)
activation = weights[-1]
for i in range(len(weights)-1):
activation += weights[i] * flattened[i]
return activation
# Transfer neuron activation
def transfer(activation):
return 1.0 / (1.0 + exp(-activation))
# Forward propagate input to a network output
def forward_propagate(network, row):
inputs = row
for layer in network:
new_inputs = []
for neuron in layer:
activation = activate(neuron['weights'], inputs)
neuron['output'] = transfer(activation)
new_inputs.append(neuron['output'])
inputs = new_inputs
return inputs
network = initialize_network(1)
row = x_train
output = forward_propagate(network, row)
print(output)
在 运行 这段代码之后我得到以下输出
(10000, 32, 32, 1)
10000
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
/var/folders/gm/z9_jyr1s5k1232zgf4xf7cxc0000gn/T/ipykernel_15670/2752672525.py in <module>
153 network = initialize_network(1)
154 row = x_train
--> 155 output = forward_propagate(network, row)
156 print(output)
/var/folders/gm/z9_jyr1s5k1232zgf4xf7cxc0000gn/T/ipykernel_15670/2752672525.py in forward_propagate(network, row)
78 new_inputs = []
79 for neuron in layer:
---> 80 activation = activate(neuron['weights'], inputs)
81 neuron['output'] = transfer(activation)
82 new_inputs.append(neuron['output'])
/var/folders/gm/z9_jyr1s5k1232zgf4xf7cxc0000gn/T/ipykernel_15670/2752672525.py in activate(weights, inputs)
62 # Calculate neuron activation for an input
63 def activate(weights, inputs):
---> 64 flattened= sum(inputs)
65 activation = weights[-1]
66 for i in range(len(weights)-1):
/var/folders/gm/z9_jyr1s5k1232zgf4xf7cxc0000gn/T/ipykernel_15670/2752672525.py in sum(inputs)
57 for a in range(32):
58 for b in range(32):
---> 59 sum_row[i]=0
60 sum_row[i]+= inputs[i][a][b][1]
61 return sum_row
IndexError: list assignment index out of range
可以看到输入的维度是100003232*1,那为什么会报错呢?
错误在
def sum(inputs):
sum_row=[]
for i in range(len(x_train)):
for a in range(32):
for b in range(32):
sum_row[i]=0
sum_row[i]+= inputs[i][a][b][1]
return sum_row
错误的原因是您试图访问 sum_row 的元素,但 sum_row 中没有任何元素(因为您在 sum_row 之前将其设置为 [] for 循环)。在 for 循环中,您尝试访问它没有的成员。而不是做 sum_row[i] = 0
你应该做 sum_row.append(0) 向该列表添加一个元素。然后你可以通过 sum_row[-1] += inputs[i][a][b][1]