import idx2numpy import numpy as np from functions import * from two_layer_network import * #导入训练集和训练集对应的标签并将其初始化 X_train,T_train=idx2numpy.convert_from_file('emnist/emnist-letters-train-images-idx3-ubyte'),idx2numpy.convert_from_file('emnist/emnist-letters-train-labels-idx1-ubyte') X_train,T_train=X_train.copy(),T_train.copy() X_train=X_train.reshape((X_train.shape[0],-1)) T_train=T_train-1 T_train=np.eye(26)[T_train] #导入测试集和测试集对应的标签标签并将其初始化 X_test,T_test=idx2numpy.convert_from_file('emnist/emnist-letters-test-images-idx3-ubyte'),idx2numpy.convert_from_file('emnist/emnist-letters-test-labels-idx1-ubyte') X_test,T_test=X_test.copy(),T_test.copy() X_test=X_test.reshape((X_test.shape[0],-1)) T_test=T_test-1 T_test=np.eye(26)[T_test] network=TwoLayerNet(input_size=784,hidden_size=45,output_size=26) train_size=X_train.shape[0] batch_size=100 iters_num=100000 learning_rate=0.01 train_loss_list=[] train_acc_list=[] test_acc_list=[] iter_per_epoch=max(train_size/batch_size,1) for i in range(iters_num): batch_mask=np.random.choice(train_size,batch_size) X_batch=X_train[batch_mask] T_batch=T_train[batch_mask] #从数据集里抽取batch_size笔数据 #grad=network.numerical_gradient(X_batch,T_batch)(跑不出来,卡在None None) grad=network.gradient(X_batch,T_batch) #计算梯度 for key in ('W1','b1','W2','b2') : network.params[key]-=learning_rate*grad[key] #误差反向传播法调整参数 loss=network.loss(X_batch,T_batch) train_loss_list.append(loss) #记录学习过程 if i % iter_per_epoch==0: train_acc=network.accuracy(X_train,T_train) test_acc=network.accuracy(X_test,T_test) train_acc_list.append(train_acc) test_acc_list.append(test_acc) print(train_acc,test_acc) #调整学习率 if i > 0 and i % 1000 == 0 and i<3000: learning_rate *= 0.1 print("learning rate reduced to " + str(learning_rate)) print(network.params) print(train_acc_list[-1],test_acc_list[-1])如果我想存储参数,该怎么做
时间: 2023-12-24 21:09:08 浏览: 76
numpy_class.7z
如果想要存储参数,可以使用Python内置的pickle模块。具体步骤如下:
1. 在代码中加入以下代码,将训练后的参数保存到文件中:
```
import pickle
with open("params.pkl", "wb") as f:
pickle.dump(network.params, f)
```
其中,"params.pkl"是你想要存储参数的文件名,network.params是你的神经网络的参数。
2. 在需要使用训练后的参数进行预测时,可以通过以下代码从文件中读取参数:
```
import pickle
with open("params.pkl", "rb") as f:
params = pickle.load(f)
network.params = params
```
其中,params是从文件中读取到的参数,将其赋给network.params即可。
阅读全文