2015-01-04 4 views
1

이것을 읽어 주셔서 감사합니다.Theano 내부 제품 3d 매트릭스

나는 theano 사용하여 멀티 라벨 로지스틱 회귀 분석을 구현하기 위해 노력하고있어 :

import numpy 
import theano 
import theano.tensor as T 
rng = numpy.random 

examples = 5 
features = 10 
labels = 2 
D = (rng.randn(examples, labels, features), rng.randint(size=(labels, examples), low=0, high=2)) 
training_steps = 10000 

# Declare Theano symbolic variables 
x = T.matrix("x") 
y = T.vector("y") 
w = theano.shared(rng.randn(1 , labels ,features), name="w") 
b = theano.shared(0., name="b") 
print "Initial model:" 
print w.get_value(), b.get_value() 

# Construct Theano expression graph 
p_1 = 1/(1 + T.exp(-T.dot(x, w) - b)) # Probability that target = 1 
prediction = p_1 > 0.5     # The prediction thresholded 
xent = -y * T.log(p_1) - (1-y) * T.log(1-p_1) # Cross-entropy loss function 
cost = xent.mean() + 0.01 * (w ** 2).sum()# The cost to minimize 
gw, gb = T.grad(cost, [w, b])    # Compute the gradient of the cost 
              # (we shall return to this in a 
              # following section of this tutorial) 

# Compile 
train = theano.function(
      inputs=[x,y], 
      outputs=[prediction, xent], 
      updates=((w, w - 0.1 * gw), (b, b - 0.1 * gb)), 
      name='train') 
predict = theano.function(inputs=[x], outputs=prediction , name='predict') 

# Train 
for i in range(training_steps): 
    pred, err = train(D[0], D[1]) 

print "Final model:" 
print w.get_value(), b.get_value() 
print "target values for D:", D[1] 
print "prediction on D:", predict(D[0]) 

을하지만 -T.dot (X, W) 제품이 오류와 함께 실패합니다

형식 오류 : (' 인덱스 0 (이름 기반)에 이름이 "train"인 잘못된 함수 인수가 잘못되었습니다. ','잘못된 차원 수 : 예상 2, 모양이 3 (5, 10, 2) 인 경우 '')

x has 모양 (5, 2, 10) 및 W (1, 2, 10). 내적 제품에는 모양이 있어야합니다 (5,2).

내 질문은 : 어쨌든이 제품을 할 수 있습니까? 다중 라벨 로지스틱 회귀를 달성하는 더 좋은 방법이 있다고 생각하십니까?

감사합니다.

---- 편집 ----- 그래서 여기

내가 NumPy와를 사용하고 싶으면 무엇의 구현입니다.

x = rng.randn(examples,labels,features) 
w = rng.randn (labels,features) 
dot = numpy.zeros((examples,labels)) 
for example in range(examples): 
    for label in range(labels): 
     dot[example,label] = x[example,label,:].dot(w[label,:]) 
print dot 

출력 :

[[-1.70321498 2.51088139] 
[-5.73608956 0.1066286 ] 
[ 2.31334531 3.31892284] 
[ 1.56301872 -0.56150922] 
[-1.98815855 -2.98866706]] 

하지만이 상징적으로 사용 Theano을 수행하는 방법을 모르겠어요.

내가 rng.randn (예, 기능, 라벨) 등의 입력을 가졌다 오류 대신 rng.randn했다 (예, 기능 :이 싸움의 몇 시간 후

+0

는 하나의 번호를 표시해야하는 내결하지 않습니까? https://en.wikipedia.org/wiki/Dot_product T.tensordot이 필요한가요? – Ashalynd

+0

이것이 theano의 단일 라벨 로지스틱 회귀 예제에서 내적 상품의 일반화일지도 모릅니다. 그들은 열 (features)을 train_x (예제, 피처)에 곱하고 내적 제품을 얻습니다 (예제) (5, 10) 내적 제품 (10,) = (5,) 다른 요소 별 작업 sigmod 함수를 생각해 내고 모양 (예,)이있는 예측 벡터로 끝나면 이것은 예제마다 하나의 예측입니다. 하지만 다중 레이블을 만들고 싶기 때문에 크기 (행렬의 수, 레이블 수)를 예측으로 사용하십시오 –

+0

저에게 표준 [행렬 x 벡터 제품] (http://en.wikipedia.org/)이 있습니다. 위키/Matrix_multiplication # Square_matrix_and_column_vector). –

답변

0

올바른 결과를 가져 오는 것 같습니다). 즉, 레이블이 더 많을뿐 아니라 입력이 같은 크기 여야합니다.

올바른 방법으로 dot product를 계산하는 방법은과 같은 theano.scan 메서드를 사용했습니다. updates = theano.scan (lambda label : T.dot (x, w [label ,:]) - b [label], sequences = T.arange (labels))

모두 도움을 주셔서 감사합니다.

import numpy as np 
import theano 
import theano.tensor as T 
rng = np.random 

examples = 5 
features = 10 
labels = 2 
D = (rng.randn(examples,features), rng.randint(size=(labels, examples), low=0, high=2)) 
training_steps = 10000 

# Declare Theano symbolic variables 
x = T.matrix("x") 
y = T.matrix("y") 
w = theano.shared(rng.randn(labels ,features), name="w") 
b = theano.shared(np.zeros(labels), name="b") 
print "Initial model:" 
print w.get_value(), b.get_value() 

results, updates = theano.scan(lambda label: T.dot(x, w[label,:]) - b[label], sequences=T.arange(labels)) 

# Construct Theano expression graph 
p_1 = 1/(1 + T.exp(- results)) # Probability that target = 1 
prediction = p_1 > .5       # The prediction thresholded 
xent = -y * T.log(p_1) - (1-y) * T.log(1-p_1) # Cross-entropy loss function 
cost = xent.mean() + 0.01 * (w ** 2).sum()# The cost to minimize 
gw, gb = T.grad(cost, [w, b])    # Compute the gradient of the cost 
              # (we shall return to this in a 
              # following section of this tutorial) 

# Compile 
train = theano.function(
      inputs=[x,y], 
      outputs=[prediction, xent], 
      updates=((w, w - 0.1 * gw), (b, b - 0.1 * gb)), 
      name='train') 
predict = theano.function(inputs=[x], outputs=prediction , name='predict') 

# Train 
for i in range(training_steps): 
    pred, err = train(D[0], D[1]) 

print "Final model:" 
print w.get_value(), b.get_value() 
print "target values for D:", D[1] 
print "prediction on D:", predict(D[0])