首页 > 解决方案 > 教科书示例中的索引超出范围

问题描述

我正在尝试按照教科书示例来训练感知,但我一直遇到index out of bounds error. 我正在关注教科书“Hobson Lane、Cole Howard 和 Hannes Max Hapke 所著的“Natural Language Processing In Action”。

这是数据:

sample_data = [[0, 0], # False, False
[0, 1], # False, True
[1, 0], # True, False
[1, 1]] # True, True

# for toy example you can list out the expected outputs although in real life this is never the case
expected_results = [0, # (False OR False) gives False
1, # (False OR True ) gives True
1, # (True OR False) gives True
1] # (True OR True ) gives True
activation_threshold = 0.5

from random import random
import numpy as np

weights=np.random.random(2)/1000 # 2 small random floats divided by 1000 0<w<0.001
print(f'random weights:  {weights}')
bias_weight=np.random.random()/1000 #return 1 small random float divided by 1000
print(f'bias:{bias_weight}')
# f-strings allow you to insert values into string w/o type conversion

这是运行感知器的代码,但我一直在最后一个 for 循环下面的行中遇到错误new_weights.append(weights[i]+((expected_results[idx]-perceptron_output)*x))

for iteration_num in range(5):
    correct_answers=0
    for idx, sample in enumerate(sample_data):
        input_vector= np.array(sample)
        weights=np.array(weights)
        activation_level=np.dot(input_vector, weights)+(bias_weight)
        if activation_level>activation_threshold:
            perceptron_output=1
        else:
            perceptron_output==0
        if perceptron_output==expected_results[idx]:
            correct_answers+=1
        new_weights=[]
        for i, x in enumerate(sample):
            new_weights.append(weights[i]+((expected_results[idx]-perceptron_output)*x))
            bias_weight=bias_weight+((expected_results[idx]-perceptron_output)*1)
            weights=np.array(new_weights)
    print(f'{correct_answers} correct answers out of 5, for iteration {iteration_num}')

这就是错误的样子。

错误

我完全按照教科书的显示方式编写了代码,但我不断收到此错误。当我尝试单独运行该生产线时,它工作正常。

工作正常

我不完全确定我做错了什么。

谢谢你

标签: pythonnumpynlp

解决方案


这是问题所在:

        for i, x in enumerate(sample):
            new_weights.append(weights[i]+((expected_results[idx]-perceptron_output)*x))
            bias_weight=bias_weight+((expected_results[idx]-perceptron_output)*1)
            weights=np.array(new_weights)

weights每次通过循环时,您都会覆盖非常重要的数组。在第一次循环中,new_weights只会有一个元素,所以第二次通过循环,weights只有一个元素。

您需要缩进最后一行,使其位于循环之后,而不是循环的一部分。

顺便说一句,在那个函数的前面,你不需要weights = np.array(weights). 它已经是一个数组。


推荐阅读