1

theanoscan 기능을 더 잘 이해하려고 노력하고 있습니다. 제 생각에이 코드는 document에 기반한 for 루프처럼 동작합니다. 선형 회귀를 수행 할 때 무게와 편향을 찾기 위해 아주 간단한 작업 예제를 만들었습니다.Theano 선형 회귀에서`for` 루프 대신에`scan`을 사용합니다

#### Libraries 
# Third Party Libraries 
import numpy as np 
import theano 
import theano.tensor as T 

# not intended for mini-batch 
def gen_data(num_points=50, slope=1, bias=10, x_max=50): 
    f = lambda z: slope * z + bias 
    x = np.zeros(shape=(num_points), dtype=theano.config.floatX) 
    y = np.zeros(shape=(num_points), dtype=theano.config.floatX) 

    for i in range(num_points): 
     x_temp = np.random.uniform()*x_max 
     x[i] = x_temp 
     y[i] = f(x_temp) + np.random.normal(scale=3.0) 

    return (x, y) 

############################################################# 
############################################################# 
train_x, train_y = gen_data(num_points=50, slope=2, bias=5) 
epochs = 50 

# Declaring variable 
learn_rate = T.scalar(name='learn_rate', dtype=theano.config.floatX) 
x = T.vector(name='x', dtype=theano.config.floatX) 
y = T.vector(name='y', dtype=theano.config.floatX) 
# Variables that will be updated 
theta = theano.shared(np.random.rand(), name='theta') 
bias = theano.shared(np.random.rand(), name='bias') 

hyp = T.dot(theta, x) + bias 
cost = T.mean((hyp - y)**2)/2 
f_cost = theano.function(inputs=[x, y], outputs=cost) 

grad_t, grad_b = T.grad(cost, [theta, bias]) 

train = theano.function(inputs=[x, y, learn_rate], outputs=cost, 
         updates=((theta, theta-learn_rate*grad_t), 
           (bias, bias-learn_rate*grad_b))) 

print('weight: {}, bias: {}'.format(theta.get_value(), bias.get_value())) 

for i in range(epochs): # Try changing this to a `scan` 
    train(train_x, train_y, 0.001) 

print('------------------------------') 
print('weight: {}, bias: {}'.format(theta.get_value(), bias.get_value())) 

나는 theano.scan 기능이 for 루프를 변경하려면,하지만이 만든 모든 시도는 다음 후 1 오류 메시지가 나왔고.

답변

1

theano.scan을 사용하려면 collection에서 OrderedDict을 가져와 공유 변수에 사용하십시오. dict를 사용하면 다음과 같은 오류 메시지가 발생할 것이다

Expected OrderedDict or OrderedUpdates, got <class 'dict'>. This can make your script non-deterministic. 

둘째, I는 손실 및 기울기를 계산한다 함수를 정의. 이 함수는 lossOrderedDict()을 반환합니다. 기능

def cost(inputs, outputs, learn_rate, theta, bias): 
    hyp = T.dot(theta, inputs) + bias 
    loss = T.mean((hyp - outputs)**2)/2 

    grad_t, grad_b = T.grad(loss, [theta, bias]) 

    return loss, OrderedDict([(theta, theta-learn_rate*grad_t), 
           (bias, bias-learn_rate*grad_b)]) 

는 같은 theano.scan()를 정의 하였다 :

results, updates = theano.scan(fn=cost, 
           non_sequences=[x, y, learn_rate, theta, bias], 
           n_steps=epochs) 

I 인해이 장난감 예의 대하여 작은 크기 및이 회 약하므로 non_sequences 같은 xy을 포함하도록 선택한 그 (것)들을 통과하는 것과 비교하여 빨리 sequences.

마지막으로는, theano.function()는 우리가 가진 모든 toghether을 퍼팅 theano.scan()

train = theano.function(inputs=[x, y, learn_rate, epochs], outputs=results, 
         updates=updates) 

에서 results, updates을 사용하여 정의되었다 :

#### Libraries 
# Standard Libraries 
from collections import OrderedDict 

# Third Party Libraries 
# import matplotlib.pyplot as plt 
import numpy as np 
# from sklearn import linear_model 
import theano 
import theano.tensor as T 

# def gen_data(num_points=50, slope=1, bias=10, x_max=50): 
#  pass # Use the code in the above post to generate sample points 

######################################################################## 
# Generate Data 
train_x, train_y = gen_data(num_points=50, slope=2) 

# Declaring variable 
x = T.vector(name='x', dtype=theano.config.floatX) 
y = T.vector(name='y', dtype=theano.config.floatX) 

learn_rate = T.scalar(name='learn_rate', dtype=theano.config.floatX) 
epochs = T.iscalar(name='epochs') 

# Variables that will be updated, hence are declared as `theano.share` 
theta = theano.shared(np.random.rand(), name='theta') 
bias = theano.shared(np.random.rand(), name='bias') 

def cost(inputs, outputs, learn_rate, theta, bias): 
    hyp = T.dot(theta, inputs) + bias 
    loss = T.mean((hyp - outputs)**2)/2 

    grad_t, grad_b = T.grad(loss, [theta, bias]) 

    return loss, OrderedDict([(theta, theta-learn_rate*grad_t), 
           (bias, bias-learn_rate*grad_b)]) 

results, updates = theano.scan(fn=cost, 
           non_sequences=[x, y, learn_rate, theta, bias], 
           n_steps=epochs) 

# results, updates = theano.scan(fn=cost, 
#        sequences=[x, y], 
#        non_sequences = [learn_rate, theta, bias], 
#        n_steps=epochs) 

train = theano.function(inputs=[x, y, learn_rate, epochs], outputs=results, 
         updates=updates) 

print('weight: {}, bias: {}'.format(theta.get_value(), bias.get_value())) 
train(train_x, train_y, 0.001, 30) 
print('------------------------------') 
print('weight: {}, bias: {}'.format(theta.get_value(), bias.get_value())) 

나는 완전성에 대한 sequencesxy를 전달하는 코드를 포함 시켰습니다. 코드의 해당 부분의 주석을 제거하고 theano.scan()의 다른 인스턴스를 주석 처리합니다.

관련 문제