2015-04-18 37 views
1

我在保存文本文件中訓練好的神經網絡的權重時遇到了問題。 這裏是我的代碼如何保存神經網絡的權重

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])), X.T] 
 
    #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

我收到以下錯誤 加薪類型錯誤(再版(O)+ 「是不是JSON序列化」)

請給出一個解決方案或任何ot她的方式來保存權重,以便我可以輕鬆地加載他們在其他一些代碼。

+0

無論theta1或theta2,或兩者兼而有之,是不是JSON序列化。它們是由函數paramUnroll返回的對象。那麼他們是什麼樣的對象? –

+0

@PaulCornelius theta1和theta2是numpy數組 –

+0

嘗試'theta1.tolist()'。請記住在從文件加載書寫列表後再次初始化'numpy.array' – jorgenkg

回答

1

將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) 
+0

我們是否可以使用numpy將這兩個數組作爲字典保存在單個文本文件中。 savetxt –

+0

@IshankGulati如果它們具有匹配的維度,文檔將顯示一種方法來執行此操作,但是您必須在np.loadtxt之後處理矩陣才能分離兩個矩陣。 – igordsm