日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > windows >内容正文

windows

【theano-windows】学习笔记九——softmax手写数字分类

發布時間:2023/12/13 windows 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【theano-windows】学习笔记九——softmax手写数字分类 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

前言

上一篇博客折騰了數據集的預備知識, 接下來按照官方的Deep learning 0.1 documentation一步步走, 先折騰softmax, 關于softmax和logistic回歸分類的聯系, 我在之前寫過一個小博客

國際慣例, 參考博客走一波:

Classifying MNIST digits using Logistic Regression

softmax理論及代碼解讀——UFLDL

softmax簡介

直接碼公式了,理論就不說了:

各標簽概率:

P(y(i)=1|x(i);W,b)=ewi?x(i)+biki=1ewi?x(i)+bi
其實每個單元值得計算就是 ewi?x+bi,其中 wi就是連接輸入神經元和第 i個神經元的權重,bi就是第 i個神經元的偏置, 最后為了保證概率和為1, 進行了歸一化而已.

獲取當前預測值,也就是概率最大的那個標簽, 可以用它來計算準確率
ypred=argmaxiP(Y=i|xi;W,b)

代價函數為負對數似然:

J(θ)=?1m??i=1mj=1k1{y(i)=j}logP(y(i)=1|x(i);W,b)??
梯度就不求了,直接用 theano的自動梯度函數 grad()

算法實現

【PS】官方代碼加上注釋竟然能達到五百多行,這是有多么生猛。

導入包

導入包就不用說了,需要用到處理文件路徑, 和解壓以及讀取數據的模塊

import theano import theano.tensor as T import numpy as np import cPickle,gzip#讀取數據解壓用的 import os#路徑相關操作需要 import timeit#時間

讀取數據

#讀取數據集 def load_data(dataset):data_dir,data_file=os.path.split(dataset)if os.path.isfile(dataset):with gzip.open(dataset,'rb') as f:train_set,valid_set,test_set=cPickle.load(f)#共享數據集def shared_dataset(data_xy,borrow=True):data_x,data_y=data_xyshared_x=theano.shared(np.asarray(data_x,dtype=theano.config.floatX),borrow=borrow)shared_y=theano.shared(np.asarray(data_y,dtype=theano.config.floatX),borrow=borrow)return shared_x,T.cast(shared_y,'int32')#定義三個元組分別返回訓練集,驗證集,測試集train_set_x,train_set_y=shared_dataset(train_set)valid_set_x,valid_set_y=shared_dataset(valid_set)test_set_x,test_set_y=shared_dataset(test_set)rval=[(train_set_x,train_set_y),(valid_set_x,valid_set_y),(test_set_x,test_set_y)]return rval

分類器函數

定義一個分類器類, 用于存儲模型參數以及實現負對數似然和模型當前預測誤差的計算, 以及負對數似然就是上面那個帶有log的式子, 將當前樣本所應屬的類別的概率相加求均值即可. 誤差就是當前樣本有多少個識別錯誤了, 看看當前樣本所屬的最大概率類別是不是它所應屬的類別, 然后求均值就得到了誤差

#定義分類器相關操作 class LogisticRegression(object):def __init__(self,input,n_in,n_out):#共享權重self.W=theano.shared(value=np.zeros((n_in,n_out),dtype=theano.config.floatX),name='W',borrow=True)#共享偏置self.b=theano.shared(value=np.zeros((n_out,),dtype=theano.config.floatX),name='b',borrow=True)#softmax函數self.p_y_given_x=T.nnet.softmax(T.dot(input,self.W)+self.b)#預測值self.y_pred=T.argmax(self.p_y_given_x,axis=1)self.params=[self.W,self.b]#模型參數self.input=input#模型輸入#定義負對數似然def negative_log_likelihood(self,y):return -T.mean(T.log(self.p_y_given_x)[T.arange(y.shape[0]),y])#定義誤差def errors(self, y):if y.ndim != self.y_pred.ndim:#查看維度是不是一樣raise TypeError('y should have the same shape as self.y_pred',('y', y.type, 'y_pred', self.y_pred.type))if y.dtype.startswith('int'):#查看y的類型是不是正確的return T.mean(T.neq(self.y_pred, y))#neq是判斷相等(0)和不等(1)else:raise NotImplementedError()

訓練

以下操作都放在一個函數sgd_mnist中

def sgd_mnist(learning_rate=0.13,n_epochs=1000,dataset='mnist.pkl.gz',batch_size=600):

首先通過讀取函數load_data讀取數據, 并且建立好分批索引

#處理數據集datasets=load_data(dataset)#讀取數據集train_set_x,train_set_y=datasets[0]#訓練集valid_set_x,valid_set_y=datasets[1]#驗證集test_set_x,test_set_y=datasets[2]#測試集print '驗證集大小',valid_set_x.get_value().shape#看看是否讀取成功#總共多少批數據,注意共享變量數據用get_value獲取n_train_batches=train_set_x.get_value(borrow=True).shape[0]//batch_sizen_valid_batches=valid_set_x.get_value(borrow=True).shape[0]//batch_sizen_test_batches=test_set_x.get_value(borrow=True).shape[0]//batch_size

然后建立兩個容器去存儲每批輸入的數據, 順便想象一下, 我們后面每次在function中迭代計算就用givens去不斷替換這個容器里面的數據就能實現每次迭代都是不同批次的數據, 注意數據是包含圖片和標簽的, 所以需要矩陣和向量存儲

#建立模型print '建立模型'index=T.lscalar()#索引數據所屬批次x=T.matrix('x')#柵格化圖片數據y=T.ivector('y')#數據標簽,不要直接使用vector

然后把分類器初始化一下,其實就是權重和偏置初始化一下

#初始化分類器:輸入,輸入大小,輸出大小classifier=LogisticRegression(input=x,n_in=28*28,n_out=10)cost=classifier.negative_log_likelihood(y)

權重和偏置的更新梯度, 以及放到function去編譯

#權重和偏置更新g_W=T.grad(cost=cost,wrt=classifier.W)#損失對權重的導數g_b=T.grad(cost=cost,wrt=classifier.b)#損失對偏置的導數#更新偏置和梯度,注意每次迭代要在givens中替換批數據updates=[(classifier.W,classifier.W-learning_rate*g_W),(classifier.b,classifier.b-learning_rate*g_b)]train_mode=theano.function(inputs=[index],outputs=cost,updates=updates,givens={x:train_set_x[index*batch_size:(index+1)*batch_size],y:train_set_y[index*batch_size:(index+1)*batch_size]})

當然我們機器學習中還有兩個數據集:驗證集和測試集, 都有各自的作用, 我們定義一下模型的測試函數

#驗證集測試模型valid_mode=theano.function(inputs=[index],outputs=classifier.errors(y),givens={x:valid_set_x[index*batch_size:(index+1)*batch_size],y:valid_set_y[index*batch_size:(index+1)*batch_size]})#測試集誤差test_mode=theano.function(inputs=[index],outputs=classifier.errors(y),givens={x:test_set_x[index*batch_size:(index+1)*batch_size],y:test_set_y[index*batch_size:(index+1)*batch_size]

接下來就是利用上一篇博客中所說的提前終止算法進行訓練了

#訓練開始, 使用提前終止法訓練print '訓練開始'patience=5000#初始patiencepatience_increase=2#增量improvement_threshold=0.995#性能提升閾值validation_frequency=min(n_train_batches,patience//2)#至少每個patience預測兩次best_validation_loss=np.inf#最好的預測值test_score=0start_time=timeit.default_timer()done_looping=False#是否停止循環epoch=0#初始迭代次數while (epoch<n_epochs) and (not done_looping):epoch=epoch+1for minibatch_index in range(n_train_batches):minibatch_avg_cost=train_mode(minibatch_index)#對數似然目標函數值iter=(epoch-1)*n_train_batches+minibatch_index#當前迭代批次數#驗證集誤差if (iter+1)%validation_frequency==0:validation_loss=[valid_mode(i) for i in range(n_valid_batches)]this_validation_loss=np.mean(validation_loss)print 'epoch %i, minibatch %i/%i, validation error: %f %%' %\(epoch,minibatch_index+1,n_train_batches,this_validation_loss*100.)#閾值判斷性能提升if this_validation_loss<best_validation_loss:if this_validation_loss<best_validation_loss*improvement_threshold:patience=max(patience,iter*patience_increase)best_validation_loss=this_validation_loss#如果性能提升,就重新記錄最優值test_loss=[test_mode(i) for i in range(n_test_batches)]test_score=np.mean(test_loss)print 'epoch %i minibatch %i/%i,test error of best model %f%%' %\(epoch,minibatch_index+1,n_train_batches,test_score*100.)#存儲最好的模型參數with open('best_model.pkl','wb') as f:cPickle.dump(classifier,f)if patience<=iter:done_looping=Truebreakend_time=timeit.default_timer()print 'Optimization complete with best validation score of %f %%,'\'with test performance %f %%'\% (best_validation_loss * 100., test_score * 100.)print 'The code run for %d epochs,with %f epochs/sec'\%(epoch,1.*epoch/(end_time-start_time))

執行主函數進行訓練

#開始訓練 sgd_mnist()

結果

驗證集大小 (10000L, 784L) 建立模型 訓練開始 epoch 1, minibatch 83/83, validation error: 12.458333 % epoch 1 minibatch 83/83,test error of best model 12.375000% epoch 2, minibatch 83/83, validation error: 11.010417 % epoch 2 minibatch 83/83,test error of best model 10.958333% epoch 3, minibatch 83/83, validation error: 10.312500 % epoch 3 minibatch 83/83,test error of best model 10.312500% epoch 4, minibatch 83/83, validation error: 9.875000 % epoch 4 minibatch 83/83,test error of best model 9.833333% epoch 5, minibatch 83/83, validation error: 9.562500 % epoch 5 minibatch 83/83,test error of best model 9.479167% epoch 6, minibatch 83/83, validation error: 9.322917 % epoch 6 minibatch 83/83,test error of best model 9.291667% epoch 7, minibatch 83/83, validation error: 9.187500 % epoch 7 minibatch 83/83,test error of best model 9.000000% epoch 8, minibatch 83/83, validation error: 8.989583 % epoch 8 minibatch 83/83,test error of best model 8.958333% epoch 9, minibatch 83/83, validation error: 8.937500 % epoch 9 minibatch 83/83,test error of best model 8.812500% epoch 10, minibatch 83/83, validation error: 8.750000 % epoch 10 minibatch 83/83,test error of best model 8.666667% epoch 11, minibatch 83/83, validation error: 8.666667 % epoch 11 minibatch 83/83,test error of best model 8.520833% epoch 12, minibatch 83/83, validation error: 8.583333 % epoch 12 minibatch 83/83,test error of best model 8.416667% epoch 13, minibatch 83/83, validation error: 8.489583 % epoch 13 minibatch 83/83,test error of best model 8.291667% epoch 14, minibatch 83/83, validation error: 8.427083 % epoch 14 minibatch 83/83,test error of best model 8.281250% epoch 15, minibatch 83/83, validation error: 8.354167 % epoch 15 minibatch 83/83,test error of best model 8.270833% epoch 16, minibatch 83/83, validation error: 8.302083 % epoch 16 minibatch 83/83,test error of best model 8.239583% epoch 17, minibatch 83/83, validation error: 8.250000 % epoch 17 minibatch 83/83,test error of best model 8.177083% epoch 18, minibatch 83/83, validation error: 8.229167 % epoch 18 minibatch 83/83,test error of best model 8.062500% epoch 19, minibatch 83/83, validation error: 8.260417 % epoch 20, minibatch 83/83, validation error: 8.260417 % epoch 21, minibatch 83/83, validation error: 8.208333 % epoch 21 minibatch 83/83,test error of best model 7.947917% epoch 22, minibatch 83/83, validation error: 8.187500 % epoch 22 minibatch 83/83,test error of best model 7.927083% epoch 23, minibatch 83/83, validation error: 8.156250 % epoch 23 minibatch 83/83,test error of best model 7.958333% epoch 24, minibatch 83/83, validation error: 8.114583 % epoch 24 minibatch 83/83,test error of best model 7.947917% epoch 25, minibatch 83/83, validation error: 8.093750 % epoch 25 minibatch 83/83,test error of best model 7.947917% epoch 26, minibatch 83/83, validation error: 8.104167 % epoch 27, minibatch 83/83, validation error: 8.104167 % epoch 28, minibatch 83/83, validation error: 8.052083 % epoch 28 minibatch 83/83,test error of best model 7.843750% epoch 29, minibatch 83/83, validation error: 8.052083 % epoch 30, minibatch 83/83, validation error: 8.031250 % epoch 30 minibatch 83/83,test error of best model 7.843750% epoch 31, minibatch 83/83, validation error: 8.010417 % epoch 31 minibatch 83/83,test error of best model 7.833333% epoch 32, minibatch 83/83, validation error: 7.979167 % epoch 32 minibatch 83/83,test error of best model 7.812500% epoch 33, minibatch 83/83, validation error: 7.947917 % epoch 33 minibatch 83/83,test error of best model 7.739583% epoch 34, minibatch 83/83, validation error: 7.875000 % epoch 34 minibatch 83/83,test error of best model 7.729167% epoch 35, minibatch 83/83, validation error: 7.885417 % epoch 36, minibatch 83/83, validation error: 7.843750 % epoch 36 minibatch 83/83,test error of best model 7.697917% epoch 37, minibatch 83/83, validation error: 7.802083 % epoch 37 minibatch 83/83,test error of best model 7.635417% epoch 38, minibatch 83/83, validation error: 7.812500 % epoch 39, minibatch 83/83, validation error: 7.812500 % epoch 40, minibatch 83/83, validation error: 7.822917 % epoch 41, minibatch 83/83, validation error: 7.791667 % epoch 41 minibatch 83/83,test error of best model 7.625000% epoch 42, minibatch 83/83, validation error: 7.770833 % epoch 42 minibatch 83/83,test error of best model 7.614583% epoch 43, minibatch 83/83, validation error: 7.750000 % epoch 43 minibatch 83/83,test error of best model 7.593750% epoch 44, minibatch 83/83, validation error: 7.739583 % epoch 44 minibatch 83/83,test error of best model 7.593750% epoch 45, minibatch 83/83, validation error: 7.739583 % epoch 46, minibatch 83/83, validation error: 7.739583 % epoch 47, minibatch 83/83, validation error: 7.739583 % epoch 48, minibatch 83/83, validation error: 7.708333 % epoch 48 minibatch 83/83,test error of best model 7.583333% epoch 49, minibatch 83/83, validation error: 7.677083 % epoch 49 minibatch 83/83,test error of best model 7.572917% epoch 50, minibatch 83/83, validation error: 7.677083 % epoch 51, minibatch 83/83, validation error: 7.677083 % epoch 52, minibatch 83/83, validation error: 7.656250 % epoch 52 minibatch 83/83,test error of best model 7.541667% epoch 53, minibatch 83/83, validation error: 7.656250 % epoch 54, minibatch 83/83, validation error: 7.635417 % epoch 54 minibatch 83/83,test error of best model 7.520833% epoch 55, minibatch 83/83, validation error: 7.635417 % epoch 56, minibatch 83/83, validation error: 7.635417 % epoch 57, minibatch 83/83, validation error: 7.604167 % epoch 57 minibatch 83/83,test error of best model 7.489583% epoch 58, minibatch 83/83, validation error: 7.583333 % epoch 58 minibatch 83/83,test error of best model 7.458333% epoch 59, minibatch 83/83, validation error: 7.572917 % epoch 59 minibatch 83/83,test error of best model 7.468750% epoch 60, minibatch 83/83, validation error: 7.572917 % epoch 61, minibatch 83/83, validation error: 7.583333 % epoch 62, minibatch 83/83, validation error: 7.572917 % epoch 62 minibatch 83/83,test error of best model 7.520833% epoch 63, minibatch 83/83, validation error: 7.562500 % epoch 63 minibatch 83/83,test error of best model 7.510417% epoch 64, minibatch 83/83, validation error: 7.572917 % epoch 65, minibatch 83/83, validation error: 7.562500 % epoch 66, minibatch 83/83, validation error: 7.552083 % epoch 66 minibatch 83/83,test error of best model 7.520833% epoch 67, minibatch 83/83, validation error: 7.552083 % epoch 68, minibatch 83/83, validation error: 7.531250 % epoch 68 minibatch 83/83,test error of best model 7.520833% epoch 69, minibatch 83/83, validation error: 7.531250 % epoch 70, minibatch 83/83, validation error: 7.510417 % epoch 70 minibatch 83/83,test error of best model 7.500000% epoch 71, minibatch 83/83, validation error: 7.520833 % epoch 72, minibatch 83/83, validation error: 7.510417 % epoch 73, minibatch 83/83, validation error: 7.500000 % epoch 73 minibatch 83/83,test error of best model 7.489583% Optimization complete with best validation score of 7.500000 %,with test performance 7.489583 % The code run for 74 epochs,with 6.870845 epochs/sec

測試

一般測試分為兩種:

  • 批量測試: 一次性丟一堆數據進去, 測試這一堆數據的準確率
  • 單樣本測試: 自己手寫一個數字, 然后調用模型預測一下

批樣本測試

想一下, 我們訓練的時候是分批丟進去的, 那么批量測試是否可以復制相同部分的代碼進而減少代碼量呢?(答案是挺麻煩的, 繼續往下看)

  • 因為存儲的就是訓練好的LogisticRegression的值, 那么我們在測試的時候就可以直接調用它里面的函數, 而且跳過初始化__init__方法, 但是發現train_mode(),test_mode(),valid_mode()方法中的input都只是單純的索引, 而非索引的批數據, 而LogisticRegression中的輸入是真實數據而非索引, 那么是怎么將索引變成索引的數據而輸入到LogisticRegression中的呢?答案就是通過初始化classifier=LogisticRegression(input=x,n_in=28*28,n_out=10), 這就實現了theano.fuction中的givens中得到的數據x被傳遞給分類器了.

  • 然而調用訓練好的模型去做分類并不需要初始化, 那么我們也就不能使用批索引作為初始化inputs, 因為我們沒法從givens中將數據丟給x, 進而丟入到分類器中. 說白了也就是不能進行如下操作

    #由于缺少分類器初始化函數, 而無法將index得到的x丟入到分類器#無法通過此代碼實現批量準確率測試test_mode=theano.function(inputs=[index],outputs=classifier.errors(y),givens={x:test_set_x[index*batch_size:(index+1)*batch_size],y:test_set_y[index*batch_size:(index+1)*batch_size]

解決方法:

  • 第一個方法是對于python學得好的同學, 如果知道如何對classifier進行初始化以后, 再將權重替換給classifier即可, 操作類似下面幾句話

    classifier=LogisticRegression(input=x,n_in=28*28,n_out=10) classifier.W=訓練好的模型.W classifier.b=訓練好的模型.b

    當然我嘗試過上面這個代碼, 暫時無法賦值成功, 可能我python功底不到家o(╯□╰)o(更新日志:之前忘記要使用set_value()才能設置共享參數的值了, 這里就不試了,在下一章節多層感知器可能會用到這個方法)

  • 第二個方法就是不使用LogisticRegression中的errors函數, 直接使用y_pred預測一下, 然后再與真實標簽作對比, 類似于這樣

    ## 批量預測準確率#讀取數據集dataset='mnist.pkl.gz' datasets=load_data(dataset) test_set_x,test_set_y=datasets[2] test_set_x=test_set_x.get_value()#定義存儲圖片和標簽的容器x=T.matrix('x') y=T.ivector('y')#定義批量測試參數batch_size=1000 n_test_batches=test_set_x.shape[0]//batch_size#度量準確率的函數a=T.ivector('a') b=T.ivector('b') z=T.mean(T.eq(a,b)) true_per=theano.function([a,b],z)#讀取模型classifier=cPickle.load(open('best_model.pkl'))#編譯函數predict_model=theano.function(inputs=[classifier.input],outputs=classifier.y_pred)#預測值for index in range(n_test_batches):x=test_set_x[index*batch_size:(index+1)*batch_size]y=test_set_y[index*batch_size:(index+1)*batch_size]predicted_values=predict_model(x)predicted_values=predicted_values.astype(np.int32)correct=true_per(predicted_values,y.eval())print 'Batch %d\'s correct ratio is %f %%' %(index,correct)

    結果

    Batch 0's correct ratio is 0.911000 % Batch 1's correct ratio is 0.886000 % Batch 2's correct ratio is 0.902000 % Batch 3's correct ratio is 0.905000 % Batch 4's correct ratio is 0.902000 % Batch 5's correct ratio is 0.941000 % Batch 6's correct ratio is 0.937000 % Batch 7's correct ratio is 0.955000 % Batch 8's correct ratio is 0.972000 % Batch 9's correct ratio is 0.914000 %

    我后來又想, 上述代碼如果使用for循環去調用LogisticRegression的errors()函數去獲取每批數據的準確率, 那就在每個for循環中使用一次

    predict_model=theano.function(inputs=[classifier.input],outputs=classifier.errors(test_set_y))

    每次的inputs是不同的數據, 后來發現這個test_set_y的標簽并不是作為errors函數的輸入, 也就是說即使你丟入一批數據, 這個標簽也是一股腦丟進去的, 那么就會出現預測標簽維度(批數據集)小于真實輸入的標簽維度(整個數據集), 那么解決方法就是改errors這個函數, 但是改完也得折騰訓練之類的, 所以我就偷懶不改了, 此想法作廢

    但是呢, 如果你的測試集不大, 那就一股腦全丟進去, 代碼更簡單,直接使用error函數

    #讀取數據集dataset='mnist.pkl.gz' datasets=load_data(dataset) test_set_x,test_set_y=datasets[2] test_set_x=test_set_x.get_value()#讀取模型classifier=cPickle.load(open('best_model.pkl'))#編譯函數predict_model=theano.function(inputs=[classifier.input],outputs=classifier.errors(test_set_y))#預測值predicted_values=predict_model(test_set_x) print "Predicted values for the first 10 examples in test set:",1-predicted_values#Predicted values for the first 10 examples in test set: 0.9225

單樣本測試

  • 如果是測試集的某個樣本想取出來看看, 比如想看看第九個樣本的預測值和真實值, 那么

    #讀取數據集dataset='mnist.pkl.gz' datasets=load_data(dataset) test_set_x,test_set_y=datasets[2] test_set_x=test_set_x.get_value()#讀取模型classifier=cPickle.load(open('best_model.pkl'))#編譯函數predict_model=theano.function(inputs=[classifier.input],outputs=classifier.y_pred)#預測值predicted_values=predict_model(test_set_x[9:10]) print "Predicted values for the first 10 examples in test set:",predicted_values print "Real values for the first 10 examples in test set:",test_set_y[9:10].eval() ''' Predicted values for the first 10 examples in test set: [9] Real values for the first 10 examples in test set: [9] '''

    當然上述代碼如果改成predicted_values=predict_model(test_set_x[:10])就是測試前十個樣本0-9的標簽啦.

  • 如果是自己的手寫數字圖片, 比如我之前寫的博客【caffe-Windows】mnist實例編譯之model的使用-classification中的手寫數字樣本(密碼bead).
    吸取當時在caffe中識別自己手寫數字的教訓, 我們需要核對的有:

  • 讀取通道順序(高*寬*通道?寬*高*通道?)
  • 數據是否需要被歸一化(一般都是一定的)
  • 因為是python和theano, 數據類型和維度一定要統一
  • 第一點就不說了(因為我不想測試, 咳咳); 第二點歸一化(除以255), 第三點要注意了:

    dataset='mnist.pkl.gz' datasets=load_data(dataset) test_set_x,test_set_y=datasets[2] test_set_x=test_set_x.get_value() print test_set_x[9:10].dtype#float32 print type(test_set_x[9:10])#<type 'numpy.ndarray'> print test_set_x[9:10].shape#(1L, 784L)

    好了,接下來我們把自己的圖片轉換一波, 在丟到模型中

    from skimage import io import matplotlib.pyplot as plt mnist_data=io.imread('./binarybmp/3.bmp') io.imshow(mnist_data) plt.show()img_mnist=np.array([mnist_data.reshape(1,28*28)],dtype=np.float32) img_mnist=img_mnist/255.0#讀取模型classifier=cPickle.load(open('best_model.pkl'))#編譯函數predict_model=theano.function(inputs=[classifier.input],outputs=classifier.y_pred) print img_mnist[0].dtype#預測值predicted_values=predict_model(img_mnist[0]) print "Predicted values for our example:",predicted_values

結語

本次學習遇到的主要有有很多, 前面的坑忘記了,但是最后一個坑是如何取出theano.tensor.cast后的數據, 答案是eval()函數, 還有一個坑是經常出現這個錯誤:

theano.compile.function_module.UnusedInputError: theano.function was asked to create a function computing outputs given certain inputs, but the provided input variable at index 0 is not part of the computational graph needed to compute the outputs: X. To make this error into a warning, you can pass the parameter on_unused_input='warn' to theano.function. To disable it completely, use on_unused_input='ignore'.

雖然我忘記怎么解決的了,但是一定是代碼出現了錯誤, 不要嘗試什么warn或者ignore之類的, 仔細核對代碼, 認真查看每一個變量類型即可, 說的輕松, 這個softmax手寫數字折騰了 我兩天, 好懷念matlab咳咳咳咳咳咳

因為是初學python, 而且theano也是現學現賣, 所以整個歷程很可能出現各種錯誤, 希望看到這篇學習記錄的新手多多一起討論,也希望大佬們可以多多給出建議, 非常感謝.

code地址:

官方代碼:鏈接: https://pan.baidu.com/s/1jIL0M0m 密碼: h2dt

本文代碼:鏈接: https://pan.baidu.com/s/1catYii 密碼: 693s

總結

以上是生活随笔為你收集整理的【theano-windows】学习笔记九——softmax手写数字分类的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。