0

Мне нужно сохранить веса или саму модель для использования её в одном мини-проекте

Я пытался сохранять с помощью модулей shelve,pickle и joblib, но веса сохранялись не точно, а попытки сохранения самой модели вызывали ошибку Can't pickle <function NeuralNetwork.__init__.<locals>.<lambda> at 0x00000206B645C310>: it's not found as __main__.NeuralNetwork.__init__.<locals>.<lambda>

Вот код класса нейронной сети

import numpy
# scipy.special for the sigmoid function expit()
import scipy.special
# scipy.ndimage for rotating image arrays
import scipy.ndimage
# os.path for сheck file
from os import path
# joblib for save weights
import joblib

who_file = r"who.txt"
wih_file = r"wih.txt"


class NeuralNetwork:
 
 # initialise the neural network
 def __init__(self, inputnodes = 784, hiddennodes = 200, outputnodes = 10, learningrate = 0.01):
     # 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.dowl_weights()

     # 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)
     #print ("guess "+str(numpy.argmax(final_outputs)))
     #print ('true '+str(numpy.argmax(targets)))
     
     # output layer error is the (target - actual)
     output_errors = targets - final_outputs
     print (numpy.sum(abs(output_errors)))
     # 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))

     self.save_weights()
     
     pass
 # dowl weights
 def dowl_weights(self):
     
     if path.exists(who_file):
         if path.getsize(who_file) > 0: 
             self.who_file = joblib.load(who_file)
             
         else:self.who = numpy.random.normal(0.0, pow(self.hnodes, -0.5), (self.onodes, self.hnodes))
     else:self.who = numpy.random.normal(0.0, pow(self.hnodes, -0.5), (self.onodes, self.hnodes))
             
         
         
     if path.exists(wih_file):
         if path.getsize(wih_file) > 0: 
             self.wih = joblib.load(wih_file)
             
         else:self.wih = numpy.random.normal(0.0, pow(self.inodes, -0.5), (self.hnodes, self.inodes))
     else:self.wih = numpy.random.normal(0.0, pow(self.inodes, -0.5), (self.hnodes, self.inodes))


 def save_weights (self):
     joblib.dump(self.who,who_file)
     
     joblib.dump(self.wih,wih_file)




 
 # 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

A так же фрагмент, где можно увидеть потери весов

print (n.who,end = '\n' * 10)
a = NeuralNetwork()
print (a.who)

1 ответ 1

0

Стоило просто использовать встроенную функцию numpy.save(filename,array)

Только с файлами с расширением .npy

0

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.