【发布时间】:2021-07-14 09:14:32
【问题描述】:
我想只使用 numpy 为神经网络构建反向传播。配置使用 3 输入和“inp”变量的别名。隐藏层使用 4 个神经元,输出使用 2 个神经元。尽管如此,我在实现反向传播时遇到了一个错误,因为循环显示了索引错误。你能帮帮我吗?
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 19 02:28:04 2021
@author: hananta
"""
import numpy as np
inp = [1, 2, 0.5] # input
weightIW = [[0.5, 0.4, 0.2, 0.3],
[0.5, 0.3, 0.8, 0.7],
[0.6, 0.2, 0.9, 0.8]]
weightLW = [[0.5, 0.3],
[0.4, 0.5],
[0.2, 0.6],
[0.4, 0.7]]
biasIW = [0.5, 0.4, 0.3, 0.2]
biasLW = [0.3, 0.4]
T = [0, 1] # Target
def sigmoid(x):
return 1 / (1 + np.exp(-x)) #Sigmoid Func
def deriv_sigmoid(x):
return sigmoid(x) * (1-sigmoid(x))
print("Forward:")
Ziw = np.dot(inp, weightIW) + biasIW # Matrix Multiplication
print("Input : ", inp)
print("Bobot / Ziw : ", Ziw)
Yiw = sigmoid(Ziw)
print("Prediksi / Yiw : ", Yiw)
Zlw = np.dot(Yiw, weightLW) + biasLW
print("Bobot / Zlw : ", Zlw)
Ylw = sigmoid(Zlw)
print("prediksi / Ylw : ", Ylw)
E = 1/2 * sum((T-Ylw) ** 2) # MSE - Hasil dari Y dibandingkan dengan T
print("Error / E : ", E,'\n')
print("Backpropagation :")
alpha = 0.5
for c in range(2):
for r in range(4):
# turunan
delta = -1 * (T[c] - Ylw[c]) * deriv_sigmoid(Ylw[c]) * Yiw[r]
# update weight
weightLW[r][c] = weightLW[r][c] - alpha * delta
print("WeightLW : ", weightLW)
alpha = 0.5
for c in range(2):
delta = -1 * (T[c] - Ylw[c]) * deriv_sigmoid(Ylw[c])
biasLW[c] = biasLW[c] - alpha * (-1 * (T[c] - Ylw[c]) * deriv_sigmoid(Ylw[c]))
print("biasLW : ", biasLW, '\n')
alpha = 0.5
for c in range(4):
for r in range(3):
# turunan
delta = -1 * (Ylw[c] - Yiw[c]) * deriv_sigmoid(Yiw[c]) * inp[r]
# update weight
weightIW[r][c] = weightIW[r][c] - alpha * delta
print("WeightIW : ", weightIW)
alpha = 0.5
for c in range(4):
delta = -1 * (Ylw[c] - Yiw[c]) * deriv_sigmoid(Yiw[c])
biasIW[c] = biasIW[c] - alpha * (-1 * (Ylw[c] - Yiw[c]) * deriv_sigmoid(Yiw[c]))
print("biasIW : ", biasIW, '\n')
print("Forward Again:")
Ziw = np.dot(inp, weightIW) + biasIW # Matrix Multiplication
Yiw = sigmoid(Ziw)
Zlw = np.dot(Yiw, weightLW) + biasLW
Ylw = sigmoid(Zlw)
E = 1/2 * sum((T-Ylw) ** 2) # MSE - Hasil dari Y dibandingkan dengan T
print("Error / E : ", E,'\n')
迭代后显示“IndexError: index 2 is out of bounds for axis 0 with size 2”。我犯错了吗?感谢您的每一个回复。
【问题讨论】:
-
该错误基本上是在告诉您您正在索引一个超出其大小的数组。您的某些数组比您想象的要短,或者您的某些循环迭代的元素可能比合适的要多。
标签: python python-3.x numpy neural-network backpropagation