简单的三层神经网络

aaJamesJones 2019-11-04

参照《Python神经网络编程》写一个简单的三层神经网络

#!/usr/bin/env python
# coding: utf-8
import numpy
# sigmoid  函数
import scipy.special

'''
简单的三层全连接网络,包括一个输入层,一个隐层和一个输出层
损失函数用sigmoid
'''
class neuralNetwork:
    # 初始化方法
    def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate):
        # set number of nodes in each input, hidden, output layer
        #输入层节点数
        self.inodes = inputnodes  
        #隐层节点数
        self.hnodes = hiddennodes
        #输出层节点数
        self.onodes = outputnodes
        
        
        #输入层和隐层的权重
        self.wih = numpy.random.normal(0.0, pow(self.inodes, -0.5), (self.hnodes, self.inodes))
        #隐层和输出层的权重
        self.who = numpy.random.normal(0.0, pow(self.hnodes, -0.5), (self.onodes, self.hnodes))
        
        # 学习率
        self.lr = learningrate
        
        # 损失函数用sigmoid
        self.activation_function = lambda x: scipy.special.expit(x)
        
        pass



    # 前馈网络
    def feedforward(self, inputs_list):
        inputs = numpy.array(inputs_list, ndmin=2).T

        # 点乘计算-输入层到隐层的权重 点乘 输入层输入 等于隐层输入
        hidden_inputs = numpy.dot(self.wih, inputs)
        #在隐层应用损失函数
        hidden_outputs = self.activation_function(hidden_inputs)

        # 点乘计算-隐层到输出层的权重 点乘 隐层输入 等于隐层输出
        final_inputs = numpy.dot(self.who, hidden_outputs)
        #在输出层应用损失函数
        final_outputs = self.activation_function(final_inputs)

        return hidden_outputs,final_outputs


    # In[ ]:


    # 训练神经网络
    def train(self, inputs_list, targets_list):
        #先正向进行前馈网络
        hidden_outputs,final_outputs = self.feedforward(self, inputs_list)

        inputs = numpy.array(inputs_list, ndmin=2).T
        targets = numpy.array(targets_list, ndmin=2).T
        #计算最终误差(目标值-实际值)
        output_errors = targets - final_outputs
        #更新隐层和输出层的权重
        self.who += self.lr * numpy.dot((output_errors * final_outputs * (1.0 - final_outputs)), numpy.transpose(hidden_outputs))


        # 隐藏层误差 = 输出层误差点乘 隐层到输出层的权重
        hidden_errors = numpy.dot(self.who.T, output_errors)
        #更新输入层和隐层间的权重
        self.wih += self.lr * numpy.dot((hidden_errors * hidden_outputs * (1.0 - hidden_outputs)), numpy.transpose(inputs))

        pass

    # 预测方法,预测方法很简单,直接进行前馈网络
    def fit(self, inputs_list):
         hidden_outputs,final_outputs = self.feedforward(inputs_list)
         return final_outputs



#测试方法
input_nodes = 3
hidden_nodes = 3
output_nodes = 3
learning_rate = 0.3
n = neuralNetwork(input_nodes, hidden_nodes, output_nodes, learning_rate)
inputs_list = [1.0, 0.5, -1.5]
final_outputs = n.fit(inputs_list)
print(final_outputs)

相关推荐