【问题标题】:python IndexError: index 3 is out of bounds for axis 0 with size 3python IndexError:索引3超出轴0的范围,大小为3
【发布时间】:2019-08-26 23:18:53
【问题描述】:

我正在 ipython 脚本下使用 python3.7 在我的 anaconda 中尝试神经网络前馈。

我不熟悉,还在学习python的问题,不知道如何调试。

import numpy as np
w1 = np.array([[11, 11, 9, 11, 7,13, 14, 6, 6, 12], [11, 11, 9, 11, 7,13, 14, 6, 6, 12], [11, 11, 9, 11, 7,13, 14, 6, 6, 12]])
w2 = np.zeros ((1,10))
b1 = np.array([0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8])
b2 = np.array([0.2])
def f(x):
        return 1 / (1 + np.exp(-x))
def simple_looped_nn_calc(n_layers, x,w,b):
  for l in range(n_layers-1):
    if l == 0:
         node_in = x
    else:
         node_in = h
    h = np.zeros((w[l].shape[0],))
    for i in range(w[l].shape[0]):
       f_sum = 0
       for j in range(w[l].shape[l]):
            f_sum += w[l][i][j]* node_in[j]
       f_sum += b[l][i]
       h[i] = f(f_sum)
  return h



w = [w1, w2]
b = [b1, b2]
x = [280, 0, 280, 280, 0, 0, 0, 0, 280, 0, 0, 0, 0, 0, 0, 0, 0, 280, 0]

当我运行我的代码时,我得到了错误,simple_looped_nn_calc(3, x, w, b) 像这样:

IndexError:索引 3 超出轴 0 的范围,大小为 3

【问题讨论】:

  • 知道错误出现在哪一行会有所帮助!

标签: python arrays numpy ipython python-3.7


【解决方案1】:

你确定要写吗:

for j in range(w[l].shape[l]):

而不是

for j in range(w[l].shape[1]):

希望我能帮上忙!

【讨论】:

    【解决方案2】:

    替换

    for j in range(w[l].shape[l])
    

    for j in range(w[l].shape[0]) 
    

    因为您分配的是node_in = h,所以这里是h = np.zeros((w[l].shape[0],)),所以如果您要分配for i in range(w[l].shape[l]),那么node_inw[l].shape[l] 的大小可能不匹配,会导致索引错误。

    【讨论】:

    • 感谢您的帮助。你能帮我吗?我想用 10 个权重做 10 个输入,我应该做 10 个偏差和 10 个隐藏层吗?我需要你的建议。
    • 您的预期输出是什么?在代码中,偏置层 = 'n_layers' ?和隐藏层 = 'h' ?
    • 先生,我的计划是我的输入是矩阵 19x10 可能是 x 值,矩阵 10x1 的权重和预期输出是 1。以上是一个练习,我的理解。需要您的建议什么是偏置层和隐藏层的最佳选择?
    • 在我的建议中,每个输入层有 1 个偏置节点,对于隐藏层,您可以点击并尝试 1,2,...10,这样可以获得更好的结果。隐藏层应该在您的输入和输出层之间。您可以查看此说明以更好地了解如何选择隐藏层stats.stackexchange.com/questions/181/…
    猜你喜欢
    • 2018-07-23
    • 1970-01-01
    • 1970-01-01
    • 2020-08-12
    • 1970-01-01
    • 2020-12-26
    • 2017-02-16
    • 2021-05-16
    • 2021-11-18
    相关资源
    最近更新 更多