美文网首页
(6)神经网络算法(NN)

(6)神经网络算法(NN)

作者: 我的章鱼小丸子呢 | 来源:发表于2020-08-04 15:59 被阅读0次

1、关于非线性转化方程(non-linear transformation function)

sigmoid函数(S曲线)用来作为activation function:

sigmoid函数
  • 双曲函数(tanh)


    双曲函数
  • 逻辑函数(logistic function)


    逻辑函数

2、实现一个简单的神经网络算法

import numpy as np

def tanh(x):    #定义tan函数
    return np.tanh(x)

def tanh_deriv(x): #定义tan函数的导数
    return 1.0-np.tan(x)*np.tan(x)

def logistic(x):#定义逻辑回归函数
    return 1/(1+np.exp(-x))

def logistic_deriv(x):#定义逻辑回归函数的导数
    return logistic(x)*(1-logistic(x))

#定义一个名为神经网络的类
class NeuralNetwork:
    #init类似于构造函数 初始化一个类对象是默认调用
    def __init__(self,layers,activation='tanh'):
        
        #选择该神经网络所使用的损耗函数
        if activation == 'logistic':
            self.activation = logistic
            self.activation_deriv = logistic_deriv
        elif activation == 'tanh':
            self.activation = tanh
            self.activation_deriv = tanh_deriv
        
        self.weights = [] #初始化一个weigt权重容器
        #初始化权重 是随机的 还要加上偏差bias
        for i in range(0,len(layers)-1):
            self.weights.append((2*np.random.random((layers[i]+1,layers[i+1]+1))-1)*0.25)


    #参数说明
    def fit(self,x,y,learn_rate = 0.2,epochs = 100000):
        x = np.atleast_2d(x) #升到2维以上
        temp = np.ones([x.shape[0],x.shape[1]+1])  #增加的一类用于处理Bias 因此设置为1
        temp[:,0:-1] = x  #左闭右开  把X的值赋值给新的数组
        x = temp
        y = np.array(y)

        for k in range(epochs):  #采用抽样的方法进行训练
            i =  np.random.randint(x.shape[0])
            a = [x[i]]

            for l in range(len(self.weights)):
                a.append(self.activation(np.dot(a[l],self.weights[l])))  #矩阵求和 然后在用损耗函数处理 再放在数组后面  整个过程处理完毕

            error = y[i] - a[-1] #计算结果误差
            deltas = [ error*self.activation_deriv(a[-1])]  #计算输出层误差

            #现在开始反向走
            for i in range(len(a)-2,0,-1): #
                deltas.append(deltas[-1].dot(self.weights[i].T)*self.activation_deriv(a[i]))                
            deltas.reverse()

            for i in range(len(self.weights)):
                layer = np.atleast_2d(a[i])
                delta = np.atleast_2d(deltas[i])
                self.weights[i]+= learn_rate*layer.T.dot(delta)

    def predict(self,x):
        x = np.array(x)
        temp = np.ones(x.shape[0]+1)
        temp[0:-1] = x
        a = temp
        for i in range(0,len(self.weights)):
           a = self.activation(np.dot(a,self.weights[i]))
        return a[0]
from NeuralNetwork import NeuralNetwork
import numpy as np 

nn = NeuralNetwork([2,2,1],'tanh') 
#建立两层神经网络 输入层为2维  隐藏层为2维 输出层为1维
x = np.array([[0,0],[0,1],[1,0],[1,1]])
y = np.array([0,1,1,0])
nn.fit(x,y)

for i in [[0,0],[0,1],[1,0],[1,1]]:
   print(nn.predict(i))

相关文章

网友评论

      本文标题:(6)神经网络算法(NN)

      本文链接:https://www.haomeiwen.com/subject/cgewrktx.html