用numpy写神经网络

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)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容