2017-11-21 1 views
3

저는 TensorFlow가 놀라운 것을하고있는 이유를 알아 내려고하고 있습니다. 나는 두 개의 입력을 함께 추가하는 사소한 문제에 대해 선형 회귀를 시도하면서 테스트 케이스로 압축했습니다. 가중치는 1.0으로 수렴하고 바이어스는 0.0으로 수렴합니다. 훈련 출력이 버전약간 다른 모양이 잘못된 숫자로 수렴됩니다 - 왜?

:

train_y = [2., 3., 4.] 

예상대로 비용이 0.0로 수렴하지만,이 버전 :

train_y = [[2.], [3.], [4.]] 

비용이 4.0로 수렴. 두 번째 버전에서 오류 메시지가 표시되면 너무 놀라지 않을 것입니다. 놀라운 것은 조용히 잘못된 대답을 준다는 것입니다. 왜이 일을하는거야? 테스트 케이스에 대한

전체 코드 :

import tensorflow as tf 
sess = tf.InteractiveSession() 
tf.set_random_seed(1) 

# Parameters 
epochs = 10000 
learning_rate = 0.01 

# Data 
train_x = [[1., 1.], [1., 2.], [2., 2.]] 

# It works with this version 
train_y = [2., 3., 4.] 

# But converges on cost 4.0 with this version 
#train_y = [[2.], [3.], [4.]] 

# Number of samples 
n_samples = len(train_x) 

# Inputs and outputs 
x = tf.placeholder(tf.float32, name='x') 
y = tf.placeholder(tf.float32, name='y') 

# Weights 
w = tf.Variable(tf.random_normal([2]), name='weight') 
b = tf.Variable(tf.random_normal([]), name='bias') 

# Model 
pred = tf.tensordot(x, w, 1) + b 
cost = tf.reduce_sum((pred-y)**2/n_samples) 
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) 

# Train 
tf.global_variables_initializer().run() 
for epoch in range(epochs): 
    # Print update at successive doublings of time 
    if epoch&(epoch-1)==0 or epoch==epochs-1: 
     print('{:6}'.format(epoch), end=' ') 
     print('{:12.6f}'.format(cost.eval({x: train_x, y: train_y})), end=' ') 
     print(' ['+', '.join('{:8.6f}'.format(z) for z in w.eval())+']', end=' ') 
     print('{:12.6f}'.format(b.eval())) 
    for (x1, y1) in zip(train_x, train_y): 
     optimizer.run({x: x1, y: y1}) 

답변

3

이유는 무엇입니까?

다른 모양의 장력을 공급할 때 비용 함수 계산이 문제입니다. 보다 구체적으로는 pred - y입니다.

하는 것은 혼란을 피하는 것은, 내가 같은 모양으로 상수를 사용하는 동안이 특정 예에서 잘못하고 위에서 언급 한 값 무엇을 표시하려면

이제
y0 = tf.constant([2., 3., 4.]) 
y1 = tf.constant([[2.], [3.], [4.]]) 
pred = tf.constant([2., 3., 4.]) 

,의는 표현의 모양을 보자 pred - y0pred - y1 :

res0 = pred - y0 
res1 = pred - y1 

print(res0.shape) 
print(res1.shape) 
는 출력은

:

(3,) 
(3, 3) 
,

(3, 3)pred - y1 모양을 (3,)(3, 1)으로 계산할 때 (3, 3)으로 방송하는 것을 보여줍니다.

res1_fixed = pred - tf.transpose(y1) 
print(res1_fixed.shape) 

출력 지금 : 이 또한 tf.reduce_sum() 호는 3 × 3 = 9 개 엘리먼트보다는 단지 3

(1, 3)y1를 전조하여이 경우이 작업을 해결 tf.transpose() 사용은 합산을 의미 :

(1, 3) 

해결 방법 :

cost = tf.reduce_sum((pred-y)**2/n_samples) 

하려면 : 846,510,403,210 지금, 다시 코드에 ... 간단하게 다음 식을 변경

cost = tf.reduce_sum((pred-tf.transpose(y))**2/n_samples) 

를 그리고 두 경우 모두 예상대로 0으로 수렴을 얻을 것이다.

관련 문제