python - 教科书示例中的索引超出范围
问题描述
我正在尝试按照教科书示例来训练感知,但我一直遇到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}')
这就是错误的样子。
我完全按照教科书的显示方式编写了代码,但我不断收到此错误。当我尝试单独运行该生产线时,它工作正常。
我不完全确定我做错了什么。
谢谢你
解决方案
这是问题所在:
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)
. 它已经是一个数组。
推荐阅读
- php - 嵌套循环头痛 PHP
- r - 简化基于另一个数据帧中的值对一个数据帧执行操作的函数
- google-bigquery - 如何快速将数据从 Google bigquery 迁移到 Snowflake?
- r - 视图中的错误:无法将类 'c("gg", "ggplot")' 强制转换为 data.frame
- python - 如果我在不同时间运行程序后在不同的地方得到一个 IndexError 是什么意思?
- proxy - 支持 TLS-PSK 的透明代理
- javascript - 从 url-string 读取参数并执行正确的函数
- c# - 设置 WPF DataGridCell ControlTemplate 后无法编辑
- express - 如何将所有以字符串 api 开头的调用路由到快速中间件中的处理程序
- c++ - 通过引用传递结构数组