2017-11-24 15 views
1

저는 선형 회귀를 수행하기 위해 아주 단순한 2 층 인공 신경망을 만들기 위해 텐서 흐름 라이브러리를 사용하고 있습니다. 제 문제는 결과가 예상보다 멀어진 것 같습니다. 나는 몇 시간 동안 실수를 저 지르려고 노력했지만 희망은 없었다. 나는 텐서 흐름과 신경 네트워크에 익숙하지 않으므로 사소한 실수 일 수 있습니다. 누구든지 내가 뭘 잘못하고 있는지 생각할 수 있을까?회귀 분석을위한 Tensorflow 신경망

from __future__ import print_function 

import tensorflow as tf 
import numpy as np 
# Python optimisation variables 
learning_rate = 0.02 

data_size=100000 
data_length=100 
train_input=10* np.random.rand(data_size,data_length); 
train_label=train_input.sum(axis=1); 
train_label=np.reshape(train_label,(data_size,1)); 

test_input= np.random.rand(data_size,data_length); 
test_label=test_input.sum(axis=1); 
test_label=np.reshape(test_label,(data_size,1)); 

x = tf.placeholder(tf.float32, [data_size, data_length]) 
y = tf.placeholder(tf.float32, [data_size, 1]) 

W1 = tf.Variable(tf.random_normal([data_length, 1], stddev=0.03), name='W1') 
b1 = tf.Variable(tf.random_normal([data_size, 1]), name='b1') 

y_ = tf.add(tf.matmul(x, W1), b1) 


cost = tf.reduce_mean(tf.square(y-y_))     
optimiser=tf.train.GradientDescentOptimizer(learning_rate=learning_rate) 
.minimize(cost) 

init_op = tf.global_variables_initializer() 

correct_prediction = tf.reduce_mean(tf.square(y-y_))  
accuracy = tf.cast(correct_prediction, tf.float32) 


with tf.Session() as sess: 
    sess.run(init_op) 
    _, c = sess.run([optimiser, cost], 
        feed_dict={x:train_input , y:train_label}) 
    k=sess.run(b1) 
    print(k)     
    print(sess.run(accuracy, feed_dict={x: test_input, y: test_label})) 

도움 주셔서 감사합니다.

+0

어떤 데이터를 교육하고 있습니까? RMSE와 RMSE를 간단한 회귀 분석 (아마 scikit-learn의 구현을 사용)과 비교해 보았습니까? 학습 속도를 다양하게 시도 했습니까? 당신은 당신의 데이터에 대해 단 한번의 패스 (신기원)를하고있는 것처럼 보입니다 : 아마도 당신은 여러 신기원을 위해 훈련해야합니까? – valentin

답변

1

코드에는 여러 가지 변경 사항이 있습니다.

먼저 에포크 수에 대한 교육을 수행하고 최적화 도구 교육 데이터를 일괄 적으로 입력해야합니다. 학습률이 매우 높았습니다. 바이어스는 모든 밀집된 (완전히 연결된) 레이어에 대해 하나의 입력으로만 사용됩니다. 비용 (손실) 값을 플롯하여 네트워크가 어떻게 수렴되는지 확인할 수 있습니다. 데이터를 일괄 적으로 입력하기 위해 자리 표시 자도 변경했습니다. 전체 수정 된 코드 확인 :

from __future__ import print_function 

import tensorflow as tf 
import numpy as np 
import matplotlib.pyplot as plt 
# Python optimisation variables 
learning_rate = 0.001 

data_size=1000 # Had to change these value to fit in my memory 
data_length=10 
train_input=10* np.random.rand(data_size,data_length); 
train_label=train_input.sum(axis=1); 
train_label=np.reshape(train_label,(data_size,1)); 

test_input= np.random.rand(data_size,data_length); 
test_label=test_input.sum(axis=1); 
test_label=np.reshape(test_label,(data_size,1)); 

tf.reset_default_graph() 
x = tf.placeholder(tf.float32, [None, data_length]) 
y = tf.placeholder(tf.float32, [None, 1]) 

W1 = tf.Variable(tf.random_normal([data_length, 1], stddev=0.03), name='W1') 
b1 = tf.Variable(tf.random_normal([1, 1]), name='b1') 

y_ = tf.add(tf.matmul(x, W1), b1) 


cost = tf.reduce_mean(tf.square(y-y_))     
optimiser=tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cost) 

init_op = tf.global_variables_initializer() 

EPOCHS = 500 
BATCH_SIZE = 32 
with tf.Session() as sess: 
    sess.run(init_op) 

    loss_history = [] 
    for epoch_no in range(EPOCHS): 
     for offset in range(0, data_size, BATCH_SIZE): 
      batch_x = train_input[offset: offset + BATCH_SIZE] 
      batch_y = train_label[offset: offset + BATCH_SIZE] 

      _, c = sess.run([optimiser, cost], 
        feed_dict={x:batch_x , y:batch_y}) 
      loss_history.append(c) 


    plt.plot(range(len(loss_history)), loss_history) 
    plt.show() 

    # For running test dataset 
    results, test_cost = sess.run([y_, cost], feed_dict={x: test_input, y: test_label}) 
    print('test cost: {:.3f}'.format(test_cost)) 
    for t1, t2 in zip(results, test_label): 
     print('Prediction: {:.3f}, actual: {:.3f}'.format(t1[0], t2[0]))