Quantcast
Channel: Data Science, Analytics and Big Data discussions - Latest topics
Viewing all articles
Browse latest Browse all 4448

Implement neural network using tensorflow: UnboundLocalError

$
0
0

@haiyang wrote:

I got lost what is wrong with this:
Error:

UnboundLocalError: local variable ‘batch_y’ referenced before assignment

here is the tf.Session

with tf.Session() as sess:
sess.run(init)

for epoch in range(epochs):
    avg_cost = 0
    total_batch = int(train_data.shape[0]//batch_size)
    for i in range(total_batch):
        batch_x, batch_y = batch_creator(batch_size, train_x.shape[0], 'train')
        #batch_x, batch_y = train_data.next_batch(batch_size)
        _,c = sess.run([optimizer, cost], feed_dict = {x: batch_x, y: batch_y})
        avg_cost += c/total_batch
    print("Epoch: ", (epoch+1), "cost: ", "{:.5f}".format(avg_cost))
print("Training complete")

and related batch_creator function:

def dense_to_one_hot(labels_dense, num_class = 10):
   """ Convert class label from scalr to one-hot vector """
   num_labels = labels_dense.shape[0]
   index_offset = np.arrange(num_labels)*num_classes
   labels_one_hot = np.zeros(num_labels, num_classes)
   labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
   return labels_one_hot
def preproc(unclean_batch_x):
   """ Convert values to range 0-1 """
   temp_batch = unclean_batch_x / unclean_batch_x.max()
   return temp_batch
def batch_creator(batch_size, dataset_length, dataset_name):
   """ Create batch with random samples and return appropiate format"""
   batch_mask = rng.choice(dataset_length, batch_size)
  if dataset_name == "train_data":
    batch_y = eval(dataset_name).ix[batch_mask, 'label'].values
    batch_y = dense_to_one_hot(batch_y)
    
return batch_x, batch_y

full code:

thanks in advance

Posts: 1

Participants: 1

Read full topic


Viewing all articles
Browse latest Browse all 4448

Trending Articles