神经网络训练代码

Posted hkkeryu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了神经网络训练代码相关的知识,希望对你有一定的参考价值。

# 2019/2/7


# In[2]:


import numpy
# scipy.special for the sigmoid function expit()
import scipy.special
# library for plotting arrays
import matplotlib.pyplot
# ensure the plots are inside this notebook, not an external window
get_ipython().magic(‘matplotlib inline‘)


# In[3]:


# neural network class definition
class neuralNetwork:
    
    
    # initialise the neural network
    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
        
        # link weight matrices, wih and who
        # weights inside the arrays are w_i_j, where link is from node i to node j in the next layer
        # w11 w21
        # w12 w22 etc 
        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))

        # learning rate
        self.lr = learningrate
        
        # activation function is the sigmoid function
        self.activation_function = lambda x: scipy.special.expit(x)
        
        pass

    
    # train the neural network
    def train(self, inputs_list, targets_list):
        # convert inputs list to 2d array
        inputs = numpy.array(inputs_list, ndmin=2).T
        targets = numpy.array(targets_list, ndmin=2).T
        
        # calculate signals into hidden layer
        hidden_inputs = numpy.dot(self.wih, inputs)
        # calculate the signals emerging from hidden layer
        hidden_outputs = self.activation_function(hidden_inputs)
        
        # calculate signals into final output layer
        final_inputs = numpy.dot(self.who, hidden_outputs)
        # calculate the signals emerging from final output layer
        final_outputs = self.activation_function(final_inputs)
        
        # output layer error is the (target - actual)
        output_errors = targets - final_outputs
        # hidden layer error is the output_errors, split by weights, recombined at hidden nodes
        hidden_errors = numpy.dot(self.who.T, output_errors) 
        
        # update the weights for the links between the hidden and output layers
        self.who += self.lr * numpy.dot((output_errors * final_outputs * (1.0 - final_outputs)), numpy.transpose(hidden_outputs))
        
        # update the weights for the links between the input and hidden layers
        self.wih += self.lr * numpy.dot((hidden_errors * hidden_outputs * (1.0 - hidden_outputs)), numpy.transpose(inputs))
        
        pass

    
    # query the neural network
    def query(self, inputs_list):
        # convert inputs list to 2d array
        inputs = numpy.array(inputs_list, ndmin=2).T
        
        # calculate signals into hidden layer
        hidden_inputs = numpy.dot(self.wih, inputs)
        # calculate the signals emerging from hidden layer
        hidden_outputs = self.activation_function(hidden_inputs)
        
        # calculate signals into final output layer
        final_inputs = numpy.dot(self.who, hidden_outputs)
        # calculate the signals emerging from final output layer
        final_outputs = self.activation_function(final_inputs)
        
        return final_outputs


# In[4]:


# number of input, hidden and output nodes
input_nodes = 400
hidden_nodes = 800
output_nodes = 13

# learning rate
learning_rate = 0.1

# create instance of neural network
n = neuralNetwork(input_nodes,hidden_nodes,output_nodes, learning_rate)


# In[ ]:


# load the mnist training data CSV file into a list
training_data_file = open("data_sheet/train.csv", ‘r‘)
training_data_list = training_data_file.readlines()
training_data_file.close()
print(training_data_list)


# In[ ]:


# train the neural network

# epochs is the number of times the training data set is used for training
epochs =500

for e in range(epochs):
    # go through all records in the training data set
    for record in training_data_list:
        # split the record by the ‘,‘ commas
        all_values = record.split(‘,‘)
        # scale and shift the inputs
        inputs = (numpy.asfarray(all_values[1:]) / 1.0 * 0.99) + 0.01
        # create the target output values (all 0.01, except the desired label which is 0.99)
        targets = numpy.zeros(output_nodes) + 0.01
     
        # all_values[0] is the target label for this record
        targets[int(all_values[0])-1] = 0.99
        #+++ 
        #print(targets)    right
        n.train(inputs, targets)
        pass
    pass


# In[ ]:


# load the mnist test data CSV file into a list
test_data_file = open("data_sheet/test.csv", ‘r‘)
test_data_list = test_data_file.readlines()
test_data_file.close()


# In[ ]:


# test the neural network

# scorecard for how well the network performs, initially empty
scorecard = []

# go through all the records in the test data set
for record in test_data_list:
    # split the record by the ‘,‘ commas
    all_values = record.split(‘,‘)
    # correct answer is first value
    correct_label = int(all_values[0])
    #++++++++
    #print(correct_label)    right
    #++++++++
    # scale and shift the inputs
    inputs = (numpy.asfarray(all_values[1:]) / 1.0 * 0.99) + 0.01
    
    # query the network
    outputs = n.query(inputs)
    print(outputs)
    
    # the index of the highest value corresponds to the label
    label = numpy.argmax(outputs)+1
   # print(label)
    # append correct or incorrect to list
    if (label == correct_label):
        # network‘s answer matches correct answer, add 1 to scorecard
        scorecard.append(1)
    else:
        # network‘s answer doesn‘t match correct answer, add 0 to scorecard
        scorecard.append(0)
        pass
    
    pass


# In[ ]:





# In[ ]:


print(scorecard)


# In[ ]:


# calculate the performance score, the fraction of correct answers
scorecard_array = numpy.asarray(scorecard)
print ("performance = ", scorecard_array.sum() / scorecard_array.size)

  

以上是关于神经网络训练代码的主要内容,如果未能解决你的问题,请参考以下文章

VSCode自定义代码片段14——Vue的axios网络请求封装

神经网络训练代码

matlab BP神经网络的训练算法中训练函数(traingdm 、trainlm、trainbr)的实现过程及相应的VC源代码

片段和活动之间的核心区别是啥?哪些代码可以写成片段?

DDIM代码详细解读:分类器classifier的网络设计训练推理

《计算机视觉和图像处理简介 - 中英双语 + 代码实践版》:使用动量优化 Momentum 训练神经网络