簡體   English   中英

如何減輕神經網絡的權重

[英]How to save weights of a neural network

我在將經過訓練的神經網絡的權重保存在文本文件中時遇到問題。 這是我的代碼

 def nNetwork(trainingData,filename): lamda = 1 input_layer = 1200 output_layer = 10 hidden_layer = 25 X=trainingData[0] y=trainingData[1] theta1 = randInitializeWeights(1200,25) theta2 = randInitializeWeights(25,10) m,n = np.shape(X) yk = recodeLabel(y,output_layer) theta = np.r_[theta1.T.flatten(), theta2.T.flatten()] X_bias = np.r_[np.ones((1,X.shape[0])), XT] #conjugate gradient algo result = scipy.optimize.fmin_cg(computeCost,fprime=computeGradient,x0=theta,args=(input_layer,hidden_layer,output_layer,X,y,lamda,yk,X_bias),maxiter=100,disp=True,full_output=True ) print result[1] #min value theta1,theta2 = paramUnroll(result[0],input_layer,hidden_layer,output_layer) counter = 0 for i in range(m): prediction = predict(X[i],theta1,theta2) actual = y[i] if(prediction == actual): counter+=1 print str(counter *100/m) + '% accuracy' data = {"Theta1":[theta1], "Theta2":[theta2]} op=open(filename,'w') json.dump(data,op) op.close() 

 def paramUnroll(params,input_layer,hidden_layer,labels): theta1_elems = (input_layer+1)*hidden_layer theta1_size = (input_layer+1,hidden_layer) theta2_size = (hidden_layer+1,labels) theta1 = params[:theta1_elems].T.reshape(theta1_size).T theta2 = params[theta1_elems:].T.reshape(theta2_size).T return theta1, theta2 

我收到以下錯誤,引發TypeError(repr(o)+“不是JSON可序列化”)

請提供解決方案或任何其他方式來保存權重,以便我可以輕松地將它們加載到其他代碼中。

將numpy數組保存為純文本的最簡單方法是執行numpy.savetxt (並使用numpy.loadtxt加載)。 但是,如果要使用JSON格式保存這兩個文件,則可以使用StringIO實例寫入文件:

with StringIO as theta1IO:
    numpy.savetxt(theta1IO, theta1)
    data = {"theta1": theta1IO.getvalue() }
    # write as JSON as usual

您也可以使用其他參數來執行此操作。

要檢索數據,您可以執行以下操作:

# read data from JSON
with StringIO as theta1IO:
    theta1IO.write(data['theta1'])
    theta1 = numpy.loadtxt(theta1IO)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM