2015-02-09 2 views
0

Я хочу получить доступ к значению my_classifier.y_binary. Моя цель - вычислить my_classifier.error.Как получить доступ к значению символической переменной anano внутри класса?

Я знаю, как получить значение my_classifier.y_hat с помощью eval, но я не знаю, как его использовать, когда вход является параметром self.

Благодаря

# imports 
 
import theano 
 
import theano.tensor as T 
 
import numpy as np 
 
import matplotlib.pyplot as plt 
 
import os, subprocess 
 

 
class Perceptron(object): 
 
    """Perceptron for the last layer 
 
    """ 
 
    def __init__(self, input, targets, n_features): 
 
     """ Initialize parameters for Perceptron 
 
     
 
     :type input:theano.tensor.TensorType 
 
     :param input:symbolic variable that describes the 
 
        input of the architecture 
 
         
 
     :type targets:theano.tensor.TensorType 
 
     :param targets:symbolic variable that describes the 
 
         targets of the architecture 
 
         
 
     :type n_features:int 
 
     :param n_features:number of features 
 
          (including "1" for bias term) 
 
          
 
     """ 
 
     
 
     # initilialize with 0 the weights W as a matrix of shape 
 
     # n_features x n_targets 
 
     
 
     self.w = theano.shared(value=np.zeros((n_features), dtype=theano.config.floatX), 
 
           name='w', 
 
           borrow=True 
 
           ) 
 
           
 
     self.y_hat = T.nnet.sigmoid(T.dot(input,self.w)) 
 
     self.y_binary = self.y_hat>0.5 
 
     self.binary_crossentropy = T.mean(T.nnet.binary_crossentropy(self.y_hat,targets)) 
 
     self.error= T.mean(T.neq(self.y_binary, targets))  
 

 
# create training data 
 
features = np.array([[1., 0., 0],[1., 0., 1.], [1.,1.,0.], [1., 1., 1.]]) 
 
targets = np.array([0., 1., 1., 1]) 
 
n_targets = features.shape[0] 
 
n_features = features.shape[1] 
 
       
 
# Symbolic variable initialization 
 
X = T.matrix("X") 
 
y = T.vector("y") 
 

 
my_classifier = Perceptron(input=X, targets=y,n_features=n_features) 
 
cost = my_classifier.binary_crossentropy 
 
error = my_classifier.error 
 
gradient = T.grad(cost=cost, wrt=my_classifier.w) 
 
updates = [[my_classifier.w, my_classifier.w-gradient*0.05]] 
 
# compiling to a theano function 
 
train = theano.function(inputs = [X,y], outputs=cost, updates=updates, allow_input_downcast=True) 
 

 
# iterate through data 
 
# Iterate through data 
 
l = np.linspace(-1.1,1.1) 
 
cost_list = [] 
 
for idx in range(500): 
 
    cost = train(features, targets) 
 
    if my_classifier.error==0: 
 
     break 
 
    
 

 

 
     
 
         
 
     
 
                        
 
                                           
 
                                                              
 
                                                                                                  

ответ

0

Если вы хотите, значение узла в графе вам необходимо составить функцию, чтобы получить его. Я думаю, что-то вроде

y_binary = theano.function(inputs = [X,], outputs=my_classifier.y_binary, allow_input_downcast=True) 

должно дать вам функцию y_binary() и вызов y_binary(features) должно направить распространить сеть и дает двоичный выход.

0

Скомпилированный функция является гораздо лучшим выбором, но в то время как вы настраиваете вещи вверх быстрый и грязный способ, как это:

так:

while (epoch < n_epochs):  
     epoch = epoch + 1  
     for minibatch_index in range(n_train_batches): 
      minibatch_avg_cost = train_model(minibatch_index) 
      iter = (epoch - 1) * n_train_batches + minibatch_index 
      print("**********************************") 
      print(classifier.hiddenLayer.W.get_value()) 

полный код здесь: https://github.com/timestocome/MiscDeepLearning/blob/master/MLP_iris2.py

Я думаю, что в вашем примере вы бы использовали 'my_classifier.w.get_value()'

Смежные вопросы