1 浅层神经网络
import numpy as np
import pandas as pd
from sklearn.metrics import mean_absolute_error
x = np.array([[0,1,0],[1,0,1],[1,1,0],[0,0,1]])
y = np.array([1,0,1,0])
class shallow_NN(object):
def __init__(self,x,y):
self.x = x
self.y = y
self.weight = np.random.rand(3) * 2 -1
def sigmoid(self,x):
out = 1/(1+np.exp(-x))
return out
def forward(self,x):
z = np.dot(x,self.weight)
a = self.sigmoid(z)
return a
def backward(self,a,x):
self.weight -= np.dot(x.T, (a - self.y ) * a * (1 - a)) #反向传播 #np.dot 默认把 (4,1) 视作 (4,)
return self
def train(self):
a = self.forward(self.x)
self.backward(a,self.x)
def predict(self,x):
print("Predicted data based on trained weights:")
return self.forward(x)
def mae(self):
y_pre = self.predict(self.x)
error = mean_absolute_error(self.y,y_pre)
print("Current mean absolute error: %s" % error)
return error
s1 = shallow_NN(x,y)
for i in range(1000):
print("Round %s" % i)
s1.train()
s1.mae()
s1.predict(x)
网友评论