Trying to add CNN to an MLP Siamese - tensorflow

I'm getting an incompatible shape error when trying trying to add a CNN to a ready siamese code that I got from github : here is the link :
https://github.com/ywpkwon/siamese_tf_mnist
here is the code for running the session:
""" Siamese implementation using Tensorflow with MNIST example.
This siamese network embeds a 28x28 image (a point in 784D)
into a point in 2D.
By Youngwook Paul Kwon (young at berkeley.edu)
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
#import system things
from tensorflow.examples.tutorials.mnist import input_data # for data
import tensorflow as tf
import numpy as np
import os
#import helpers
import inference
import visualize
# prepare data and tf.session
mnist = input_data.read_data_sets('MNIST_data', one_hot=False)
sess = tf.InteractiveSession()
# setup siamese network
siamese = inference.siamese();
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(siamese.loss)
saver = tf.train.Saver()
tf.initialize_all_variables().run()
# start training
if new:
for step in range(1000):
batch_x1, batch_y1 = mnist.train.next_batch(128)
batch_x2, batch_y2 = mnist.train.next_batch(128)
batch_y = (batch_y1 == batch_y2).astype('float')
_, loss_v = sess.run([train_step, siamese.loss], feed_dict={
siamese.x1: batch_x1,
siamese.x2: batch_x2,
siamese.y_: batch_y})
if step % 10 == 0:
print ('step %d: loss' % (step))
print (loss_v)
here is the code for creating the Siamese model.
import tensorflow as tf
class siamese:
# Create model
def __init__(self):
self.x1 = tf.placeholder(tf.float32, [None, 784])
self.x2 = tf.placeholder(tf.float32, [None, 784])
with tf.variable_scope("siamese") as scope:
self.o1 = self.network(self.x1)
scope.reuse_variables()
self.o2 = self.network(self.x2)
# Create loss
self.y_ = tf.placeholder(tf.float32, [None])
self.loss = self.loss_with_step()
def network(self, x):
weights = []
fc1 = self.fc_layer(x, 1024, "fc1" , [5, 5, 1, 32])
return fc1
def fc_layer(self, bottom, n_weight, name,kernel_shape ): #[5, 5, 1, 32]
assert len(bottom.get_shape()) == 2
#n_prev_weight = bottom.get_shape()[1]
initer = tf.truncated_normal_initializer(stddev=0.01)
weights_for_convolution = tf.get_variable(name+"weights_for_convolution", kernel_shape,
initializer=tf.random_normal_initializer())
bias_shape = kernel_shape[-1]
biases_for_convolution = tf.get_variable(name+"biases_for_convolution", [bias_shape],
initializer=tf.constant_initializer(0.1))
biases_for_connected_layer = tf.get_variable(name+"biases_for_connected_layer", [1024],
initializer=tf.constant_initializer(0.1))
weights_for_connected_layer = tf.get_variable(name+"weights_for_connected_layer", [7*7*64,1024],
initializer=tf.random_normal_initializer())
W = tf.get_variable(name+'W', dtype=tf.float32, shape=[1024,2], initializer=initer)
b = tf.get_variable(name+'b', dtype=tf.float32, initializer=tf.constant(0.01, shape=[2], dtype=tf.float32))
#weights_for_readout_layer = tf.get_variable("weights_for_readout_layer", [1024,2],
#initializer=tf.random_normal_initializer())
#biases_for_readout_layer = tf.get_variable("biases_for_readout_layer", [2],
#initializer=tf.constant_initializer(0.1))
bottom1 = tf.reshape(bottom,[-1,28,28,1]) ##
c2 = tf.nn.conv2d(bottom1, weights_for_convolution, strides=[1, 1, 1, 1], padding='SAME')
conv = tf.nn.bias_add(c2, biases_for_convolution)
relu = tf.nn.relu(conv)
out = tf.nn.max_pool(relu, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='SAME')
#print tf.shape(out)
h_out_flat = tf.reshape(out ,[-1,7*7*64])
h_fc1 = tf.nn.relu(tf.matmul(h_out_flat, weights_for_connected_layer) + biases_for_connected_layer)
#compute model output
final_output = tf.matmul(h_fc1,W) + b
#fc = tf.nn.bias_add(tf.matmul(bottom, W), b)
return final_output
def loss_with_spring(self):
margin = 5.0
labels_t = self.y_
labels_f = tf.subtract(1.0, self.y_, name="1-yi") # labels_ = !labels;
eucd2 = tf.pow(tf.subtract(self.o1, self.o2), 2)
print tf.shape(eucd2)
eucd2 = tf.reduce_sum(eucd2, 1)
eucd = tf.sqrt(eucd2+1e-6, name="eucd")
C = tf.constant(margin, name="C")
# yi*||CNN(p1i)-CNN(p2i)||^2 + (1-yi)*max(0, C-||CNN(p1i)-CNN(p2i)||^2)
pos = tf.multiply(labels_t, eucd2, name="yi_x_eucd2")
# neg = tf.multiply(labels_f, tf.subtract(0.0,eucd2), name="yi_x_eucd2")
# neg = tf.multiply(labels_f, tf.maximum(0.0, tf.subtract(C,eucd2)), name="Nyi_x_C-eucd_xx_2")
neg = tf.multiply(labels_f, tf.pow(tf.maximum(tf.subtract(C, eucd), 0), 2), name="Nyi_x_C-eucd_xx_2")
losses = tf.add(pos, neg, name="losses")
loss = tf.reduce_mean(losses, name="loss")
return loss
def loss_with_step(self):
margin = 5.0
labels_t = self.y_ #128
labels_f = tf.subtract(1.0, self.y_, name="1-yi") # labels_ = !labels;
eucd2 = tf.pow(tf.subtract(self.o1, self.o2), 2)
eucd2 = tf.reduce_sum(eucd2, 1)
eucd = tf.sqrt(eucd2+1e-6, name="eucd")
C = tf.constant(margin, name="C")
pos = tf.multiply(labels_t, eucd, name="y_x_eucd")
neg = tf.multiply(labels_f, tf.maximum(0.0, tf.subtract(C, eucd)), name="Ny_C-eucd")
losses = tf.add(pos, neg, name="losses")
loss = tf.reduce_mean(losses, name="loss")
return loss
Actually as the batch size is 128 label-t is 128,
the problem here is that the euclidean distance in the loss_with_step function,
as well as in the loss_with_spring function is of size 256 and not 128 I don't really know why!
here is the error I get.
Traceback (most recent call last):
File "run1.py", line 56, in <module>
siamese.y_: batch_y})
File "/home/sudonuma/anaconda2/envs/tensorflow/lib/python2.7/site- packages/tensorflow/python/client/session.py", line 789, in run
run_metadata_ptr)
File "/home/sudonuma/anaconda2/envs/tensorflow/lib/python2.7/site- packages/tensorflow/python/client/session.py", line 997, in _run
feed_dict_string, options, run_metadata)
File "/home/sudonuma/anaconda2/envs/tensorflow/lib/python2.7/site- packages/tensorflow/python/client/session.py", line 1132, in _do_run
target_list, options, run_metadata)
File "/home/sudonuma/anaconda2/envs/tensorflow/lib/python2.7/site- packages/tensorflow/python/client/session.py", line 1152, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InvalidArgumentError: Incompatible shapes: [128] vs. [256]
[[Node: y_x_eucd = Mul[T=DT_FLOAT, _device="/job:localhost/ replica:0/task:0/cpu:0"](_arg_Placeholder_2_0_2, eucd)]]
Caused by op u'y_x_eucd', defined at:
File "run1.py", line 28, in <module>
siamese = inference1.siamese();
File "/home/sudonuma/Documents/siamese for mnist/siamese_tf_mnist-master /inference1.py", line 18, in __init__
self.loss = self.loss_with_step()
File "/home/sudonuma/Documents/siamese for mnist/siamese_tf_mnist-master /inference1.py", line 110, in loss_with_step
pos = tf.multiply(labels_t, eucd, name="y_x_eucd")
File "/home/sudonuma/anaconda2/envs/tensorflow/lib/python2.7/site- packages/tensorflow/python/ops/math_ops.py", line 286, in multiply
return gen_math_ops._mul(x, y, name)
File "/home/sudonuma/anaconda2/envs/tensorflow/lib/python2.7/site- packages/tensorflow/python/ops/gen_math_ops.py", line 1377, in _mul
result = _op_def_lib.apply_op("Mul", x=x, y=y, name=name)
File "/home/sudonuma/anaconda2/envs/tensorflow/lib/python2.7/site- packages/tensorflow/python/framework/op_def_library.py", line 767, in apply
_op
op_def=op_def)
File "/home/sudonuma/anaconda2/envs/tensorflow/lib/python2.7/site- packages/tensorflow/python/framework/ops.py", line 2506, in create_op
original_op=self._default_original_op, op_def=op_def)
File "/home/sudonuma/anaconda2/envs/tensorflow/lib/python2.7/site- packages/tensorflow/python/framework/ops.py", line 1269, in __init__
self._traceback = _extract_stack()
InvalidArgumentError (see above for traceback): Incompatible shapes: [128] vs. [256]
[[Node: y_x_eucd = Mul[T=DT_FLOAT, _device="/job:localhost /replica:0/task:0/cpu:0"](_arg_Placeholder_2_0_2, eucd)]]
can anyone help?

Looks like your reshaping after the convolution is wrong. The output of the convolution layer would be 14x14x32 for a 28x28x1 input passed through conv(stride=1)-maxpool(stride 2). So you need to change the flatten layer to :
h_out_flat = tf.reshape(out ,[-1,14*14*32])
and also the weights_for_connected_layer appropriately.

Related

InvalidArgumentError: Matrix size-incompatible: In[0]: [256,2048], In[1]: [256,1024]

I have been getting this error and i cant figure out the reason. if anyone could help would be great.
this is my code:
import numpy as np
import pickle
import os
import download
#from dataset import one_hot_encoded
#from sklearn.preprocessing import OneHotEncoder
import tensorflow as tf
from random import shuffle
data_path = "D:/Personal details/Internship/"
# Width and height of each image.
img_size = 32
# Number of channels in each image, 3 channels: Red, Green, Blue.
num_channels = 3
# Length of an image when flattened to a 1-dim array.
img_size_flat = img_size * img_size * num_channels
# Number of classes.
num_classes = 10
# Number of files for the training-set.
_num_files_train = 5
# Number of images for each batch-file in the training-set.
_images_per_file = 10000
def _get_file_path(filename=""):
return os.path.join(data_path, "cifar-10-batches-py/", filename)
def _unpickle(filename):
file_path = _get_file_path(filename)
print("Loading data: " + file_path)
with open(file_path, mode='rb') as file:
# In Python 3.X it is important to set the encoding,
# otherwise an exception is raised here.
data = pickle.load(file, encoding='bytes')
return data
def _convert_images(raw):
# Convert the raw images from the data-files to floating-points.
raw_float = np.array(raw, dtype=float) / 255.0
# Reshape the array to 4-dimensions.
images = raw_float.reshape([-1, num_channels, img_size, img_size])
# Reorder the indices of the array.
images = images.transpose([0, 2, 3, 1])
return images
def _load_data(filename):
# Load the pickled data-file.
data = _unpickle(filename)
# Get the raw images.
raw_images = data[b'data']
# Get the class-numbers for each image. Convert to numpy-array.
cls = np.array(data[b'labels'])
# Convert the images.
images = _convert_images(raw_images)
return images, cls
def load_class_names():
# Load the class-names from the pickled file.
raw = _unpickle(filename="batches.meta")[b'label_names']
# Convert from binary strings.
names = [x.decode('utf-8') for x in raw]
return names
def load_training_data():
images = np.zeros(shape=[_num_images_train, img_size, img_size, num_channels], dtype=float)
cls = np.zeros(shape=[_num_images_train], dtype=int)
# Begin-index for the current batch.
begin = 0
# For each data-file.
for i in range(_num_files_train):
# Load the images and class-numbers from the data-file.
images_batch, cls_batch = _load_data(filename="data_batch_" + str(i + 1))
# Number of images in this batch.
num_images = len(images_batch)
# End-index for the current batch.
end = begin + num_images
# Store the images into the array.
images[begin:end, :] = images_batch
# Store the class-numbers into the array.
cls[begin:end] = cls_batch
# The begin-index for the next batch is the current end-index.
begin = end
return images, cls, one_hot_encoded(class_numbers=cls, num_classes=num_classes)
def load_test_data():
images, cls = _load_data(filename="test_batch")
return images, cls, one_hot_encoded(class_numbers=cls, num_classes=num_classes)
########################################################################
def one_hot_encoded(class_numbers, num_classes=None):
if num_classes is None:
num_classes = np.max(class_numbers) + 1
return np.eye(num_classes, dtype=float)[class_numbers]
class_names = load_class_names()
images_train, cls_train, labels_train = load_training_data()
images_test, cls_test, labels_test = load_test_data()
images_train_train = images_train[0:45000]
validation_train = images_train[45000:50000]
labels_train_train = labels_train[0:45000]
validation_labels = labels_train[45000:]
print(len(images_train_train))
print(len(validation_train))
##print(class_names)
##print(len(images_train))
##print(cls_train)
##print(labels_train)
##print(cls_test)
##print(labels_test)
n_classes = len(class_names)
batch_size = 128
x = tf.placeholder(tf.float32, shape=[None, 32, 32, 3], name='x')
y = tf.placeholder(tf.float32, shape=[None, n_classes], name='y_true')
def conv2d(x,W):
return tf.nn.conv2d(x, W, strides=[1,1,1,1], padding='SAME')
def maxpool2d(x):
return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')
def convolutional_neural_network(x):
weights = {'W_conv1': tf.Variable(tf.random_normal([3,3,3,64])),
'W_conv2': tf.Variable(tf.random_normal([3,3,64,128])),
'W_conv3': tf.Variable(tf.random_normal([3,3,128,256])),
'W_conv4': tf.Variable(tf.random_normal([3,3,256,256])),
'W_fc1': tf.Variable(tf.random_normal([256,1024])),
'W_fc2': tf.Variable(tf.random_normal([1024,1024])),
'soft_max': tf.Variable(tf.random_normal([1024, n_classes]))}
biases = {'b_conv1': tf.Variable(tf.random_normal([64])),
'b_conv2': tf.Variable(tf.random_normal([128])),
'b_conv3': tf.Variable(tf.random_normal([256])),
'b_conv4': tf.Variable(tf.random_normal([256])),
'b_fc1': tf.Variable(tf.random_normal([1024])),
'b_fc2': tf.Variable(tf.random_normal([1024])),
'soft_max': tf.Variable(tf.random_normal([n_classes]))}
conv1 = tf.nn.relu(conv2d(x, weights['W_conv1']) + biases['b_conv1'])
conv1 = maxpool2d(conv1)
conv2 = tf.nn.relu(conv2d(conv1, weights['W_conv2']) + biases['b_conv2'])
conv2 = maxpool2d(conv2)
conv3 = tf.nn.relu(conv2d(conv2, weights['W_conv3']) + biases['b_conv3'])
conv4 = tf.nn.relu(conv2d(conv3, weights['W_conv4']) + biases['b_conv4'])
conv4 = maxpool2d(conv4)
fc1 = tf.reshape(conv4,[256,-1])
fc1 = tf.nn.relu(tf.matmul(fc1, weights['W_fc1']) + biases['b_fc1'])
fc2 = tf.nn.relu(tf.matmul(fc1, weights['W_fc2'] + biases['b_fc2']))
soft_max = tf.matmul(fc2, weights['soft_max']) + biases['soft_max']
return soft_max
def train_neural_network(x):
prediction = convolutional_neural_network(x)
cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(logits = prediction,labels = y) )
optimizer = tf.train.AdamOptimizer().minimize(cost)
hm_epochs = 3
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
for epoch in range(hm_epochs):
epoch_loss = 0
i = 0
while i < len(images_train_train):
start = i
end = i+batch_size
batch_x = np.array(images_train_train[start:end])
batch_y = np.array(labels_train_train[start:end])
_, c = sess.run([optimizer, cost], feed_dict={x: batch_x, y: batch_y})
epoch_loss += c
print('Epoch', epoch, 'completed out of',hm_epochs,'loss:',epoch_loss)
correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
print('Accuracy:',accuracy.eval({x:validation_train, y:validation_labels}))
train_neural_network(x)
Ans this is the error i have been getting.
WARNING:tensorflow:From D:/Personal details/Internship/cifar-10v1.0.py:310: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Future major versions of TensorFlow will allow gradients to flow
into the labels input on backprop by default.
See #{tf.nn.softmax_cross_entropy_with_logits_v2}.
WARNING:tensorflow:From C:\Python35\lib\site-packages\tensorflow\python\util\tf_should_use.py:118: initialize_all_variables (from tensorflow.python.ops.variables) is deprecated and will be removed after 2017-03-02.
Instructions for updating:
Use `tf.global_variables_initializer` instead.
Traceback (most recent call last):
File "C:\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1322, in _do_call
return fn(*args)
File "C:\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1307, in _run_fn
options, feed_dict, fetch_list, target_list, run_metadata)
File "C:\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1409, in _call_tf_sessionrun
run_metadata)
tensorflow.python.framework.errors_impl.InvalidArgumentError: Matrix size-incompatible: In[0]: [256,2048], In[1]: [256,1024]
[[Node: MatMul = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false, _device="/job:localhost/replica:0/task:0/device:CPU:0"](Reshape, Variable_4/read)]]
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:/Personal details/Internship/cifar-10v1.0.py", line 344, in <module>
train_neural_network(x)
File "D:/Personal details/Internship/cifar-10v1.0.py", line 327, in train_neural_network
_, c = sess.run([optimizer, cost], feed_dict={x: batch_x, y: batch_y})
File "C:\Python35\lib\site-packages\tensorflow\python\client\session.py", line 900, in run
run_metadata_ptr)
File "C:\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1135, in _run
feed_dict_tensor, options, run_metadata)
File "C:\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1316, in _do_run
run_metadata)
File "C:\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1335, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InvalidArgumentError: Matrix size-incompatible: In[0]: [256,2048], In[1]: [256,1024]
[[Node: MatMul = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false, _device="/job:localhost/replica:0/task:0/device:CPU:0"](Reshape, Variable_4/read)]]
Caused by op 'MatMul', defined at:
File "<string>", line 1, in <module>
File "C:\Python35\lib\idlelib\run.py", line 130, in main
ret = method(*args, **kwargs)
File "C:\Python35\lib\idlelib\run.py", line 357, in runcode
exec(code, self.locals)
File "D:/Personal details/Internship/cifar-10v1.0.py", line 344, in <module>
train_neural_network(x)
File "D:/Personal details/Internship/cifar-10v1.0.py", line 309, in train_neural_network
prediction = convolutional_neural_network(x)
File "D:/Personal details/Internship/cifar-10v1.0.py", line 300, in convolutional_neural_network
fc1 = tf.nn.relu(tf.matmul(fc1, weights['W_fc1']) + biases['b_fc1'])
File "C:\Python35\lib\site-packages\tensorflow\python\ops\math_ops.py", line 2122, in matmul
a, b, transpose_a=transpose_a, transpose_b=transpose_b, name=name)
File "C:\Python35\lib\site-packages\tensorflow\python\ops\gen_math_ops.py", line 4567, in mat_mul
name=name)
File "C:\Python35\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 787, in _apply_op_helper
op_def=op_def)
File "C:\Python35\lib\site-packages\tensorflow\python\framework\ops.py", line 3392, in create_op
op_def=op_def)
File "C:\Python35\lib\site-packages\tensorflow\python\framework\ops.py", line 1718, in __init__
self._traceback = self._graph._extract_stack() # pylint: disable=protected-access
InvalidArgumentError (see above for traceback): Matrix size-incompatible: In[0]: [256,2048], In[1]: [256,1024]
[[Node: MatMul = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false, _device="/job:localhost/replica:0/task:0/device:CPU:0"](Reshape, Variable_4/read)]]
It looks like the problem is in convolutional_neural_network layer() function wherein somehow it is mad at not being able to multiply the same dimension of the matrix. But it is not clear how to solve the issue
Thank you for the help in advance...
After reshaping conv4 at line fc1 = tf.reshape(conv4,[256,-1]), the shape of fc1 is (256, 2048) and the weight matrix W_fc1 has shape (256, 1024). Thus, you get a size incompatible error at the next line fc1 = tf.nn.relu(tf.matmul(fc1, weights['W_fc1']) + biases['b_fc1'])
in the matrix multiplication part. I suggest you to go through the dimensions at every step manually to find errors in future.

TensorFlow creating an Ai, error: You must feed a value for placeholder tensor 'input_1/X'

I am currently working on an AI for openai, I am trying to pass random data collected to make a model of a neural network, then use that model to create new data. When I try to make another model using the new trained data it wont let e create a new model and gives an
InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'input_1/X' with dtype float
[[Node: input_1/X = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]].
my code:
import gym
import random
import numpy as np
import tensorflow as tf
import tflearn
from tflearn.layers.core import input_data, dropout, fully_connected
from tflearn.layers.estimator import regression
from statistics import median, mean
from collections import Counter
import matplotlib.pyplot as plt
env = gym.make("CartPole-v1")
env.reset()#restarts the enviroment
epoch = 5
LR = 2e-4
max_score = 500
number_of_training_games = 100
generations = 3
training_scores = []
random_gen_score = []
def create_random_training_data():
x = 0
accepted_training_data = []
scores_and_data = []
array_of_scores = []
for i in range(number_of_training_games):
score = 0
prev_observation = []
training_data = []
for _ in range(max_score):
action = env.action_space.sample()
observation, reward, done, info = env.step(action)
if len(prev_observation) > 0:
training_data.append([prev_observation, action])
prev_observation = observation
score += reward
if done:
array_of_scores.append(score)
break
for i in training_data:
scores_and_data.append([score,i[0],i[1]])
# reset enviroment
env.reset()
training_scores = array_of_scores
for data in scores_and_data:
if data[0] > median(array_of_scores):
if data[2] == 1:
output = [0,1]
elif data[2] == 0:
output = [1,0]
accepted_training_data.append([data[1], output])
return accepted_training_data
def training_model(sample_data):
inputs = np.array([i[0] for i in sample_data]).reshape(-1,4,1)
correct_output = [i[1] for i in sample_data]
model = neural_network(input_size = len(inputs[0]))
model.fit({'input': inputs}, {'targets': correct_output}, n_epoch=epoch , snapshot_step=500, show_metric=True, run_id='openai_learning')
print(input)
return model
def neural_network(input_size):
# this is where our observation data will go
network = input_data(shape=[None, input_size, 1], name = 'input')
# our neural networks
network = fully_connected(network, 128, activation = 'relu')
#dropout is used to drop randon nodes inorder to reduce over training
network = dropout(network, 0.8)
network = fully_connected(network, 256, activation = 'relu')
network = dropout(network, 0.8)
network = fully_connected(network, 512, activation = 'relu')
network = dropout(network, 0.8)
network = fully_connected(network, 256, activation = 'relu')
network = dropout(network, 0.8)
network = fully_connected(network, 128, activation = 'relu')
network = dropout(network, 0.8)
# this is the output
network = fully_connected(network, 2, activation = 'softmax')
network = regression(network, optimizer='adam', learning_rate=LR, loss='categorical_crossentropy', name='targets')
model = tflearn.DNN(network, tensorboard_dir='log')
return model
def run_generation():
random_sample_data = []
trained_data = []
for i in range(generations):
if len(random_sample_data) ==0:
random_sample_data = create_random_training_data()
model1 = training_model(random_sample_data)
else:
trained_data = one_generation(model1)
model2 = training_model(trained_data)
return model2
def one_generation(model):
accepted_training_data = []
scores_and_data = []
array_of_scores = []
for i in range(number_of_training_games):
score = 0
prev_observation = []
training_data = []
for _ in range(max_score):
if len(prev_observation) == 0:
action = env.action_space.sample()
else:
action = np.argmax(model.predict(prev_observation.reshape(-1,len(prev_observation),1))[0])
observation, reward, done, info = env.step(action)
if len(prev_observation) > 0:
training_data.append([prev_observation, action])
prev_observation = observation
score += reward
if done:
array_of_scores.append(score)
break
for i in training_data:
scores_and_data.append([score,i[0],i[1]])
# reset enviroment
env.reset()
for data in scores_and_data:
if data[0] > median(array_of_scores):
if data[2] == 1:
output = [0,1]
elif data[2] == 0:
output = [1,0]
accepted_training_data.append([data[1], output])
return accepted_training_data
def testing():
scores = []
model = run_generation()
for _ in range(100):
score = 0
game_memory = []
prev_obs = []
env.reset()
for _ in range(max_score):
env.render()
#first move is going to be random
if len(prev_obs)==0:
action = random.randrange(0,2)
else:
action = np.argmax(model.predict(prev_obs.reshape(-1,len(prev_obs),1))[0])
#records actions
new_observation, reward, done, info = env.step(action)
prev_obs = new_observation
game_memory.append([new_observation, action])
score+=reward
if done: break
scores.append(score)
#print('Average training Score:',sum(training_scores)/len(training_scores))
print('Average Score:',sum(scores)/len(scores))
print (scores)
testing()
error:
Traceback (most recent call last):
File "/anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1039, in _do_call
return fn(*args)
File "/anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1021, in _run_fn
status, run_metadata)
File "/anaconda/lib/python3.6/contextlib.py", line 89, in __exit__
next(self.gen)
File "/anaconda/lib/python3.6/site-packages/tensorflow/python/framework/errors_impl.py", line 466, in raise_exception_on_not_ok_status
pywrap_tensorflow.TF_GetCode(status))
tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'input_1/X' with dtype float
[[Node: input_1/X = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/Duncan/Desktop/ai projects/evolutionDNN.py", line 259, in <module>
testing()
File "/Users/Duncan/Desktop/ai projects/evolutionDNN.py", line 219, in testing
model = run_generation()
File "/Users/Duncan/Desktop/ai projects/evolutionDNN.py", line 148, in run_generation
model2 = training_model(trained_data)
File "/Users/Duncan/Desktop/ai projects/evolutionDNN.py", line 92, in training_model
model.fit({'input': inputs}, {'targets': correct_output}, n_epoch=epoch , snapshot_step=500, show_metric=True, run_id='openai_learning')
File "/anaconda/lib/python3.6/site-packages/tflearn/models/dnn.py", line 215, in fit
callbacks=callbacks)
File "/anaconda/lib/python3.6/site-packages/tflearn/helpers/trainer.py", line 336, in fit
show_metric)
File "/anaconda/lib/python3.6/site-packages/tflearn/helpers/trainer.py", line 777, in _train
feed_batch)
File "/anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 778, in run
run_metadata_ptr)
File "/anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 982, in _run
feed_dict_string, options, run_metadata)
File "/anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1032, in _do_run
target_list, options, run_metadata)
File "/anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1052, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'input_1/X' with dtype float
[[Node: input_1/X = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
Caused by op 'input_1/X', defined at:
File "/Users/Duncan/Desktop/ai projects/evolutionDNN.py", line 259, in <module>
testing()
File "/Users/Duncan/Desktop/ai projects/evolutionDNN.py", line 219, in testing
model = run_generation()
File "/Users/Duncan/Desktop/ai projects/evolutionDNN.py", line 148, in run_generation
model2 = training_model(trained_data)
File "/Users/Duncan/Desktop/ai projects/evolutionDNN.py", line 90, in training_model
model = neural_network(input_size = len(inputs[0]))
File "/Users/Duncan/Desktop/ai projects/evolutionDNN.py", line 100, in neural_network
network = input_data(shape=[None, input_size, 1], name = 'input')
File "/anaconda/lib/python3.6/site-packages/tflearn/layers/core.py", line 81, in input_data
placeholder = tf.placeholder(shape=shape, dtype=dtype, name="X")
File "/anaconda/lib/python3.6/site-packages/tensorflow/python/ops/array_ops.py", line 1507, in placeholder
name=name)
File "/anaconda/lib/python3.6/site-packages/tensorflow/python/ops/gen_array_ops.py", line 1997, in _placeholder
name=name)
File "/anaconda/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py", line 768, in apply_op
op_def=op_def)
File "/anaconda/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 2336, in create_op
original_op=self._default_original_op, op_def=op_def)
File "/anaconda/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 1228, in __init__
self._traceback = _extract_stack()
InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'input_1/X' with dtype float
[[Node: input_1/X = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
this line:
network = input_data(shape=[None, input_size, 1], name = 'input')
should be
network = input_data(shape=[None, input_size,input_size , 1], name = 'input')
there should be 4 arguments first is taken as place holder.
Try this.

How to read next batch in tensorflow automatically?

I have 70 training sample, 10 testing samples, with every sample contains 11*99 elements. I want to use LSTM to classify the testing samples, here is the code:
import tensorflow as tf
import scipy.io as sc
# data read
feature_training = sc.loadmat("feature_training_reshaped.mat")
feature_training_reshaped = feature_training['feature_training_reshaped']
print (feature_training_reshaped.shape)
feature_testing = sc.loadmat("feature_testing_reshaped.mat")
feature_testing_reshaped = feature_testing['feature_testing_reshaped']
print (feature_testing_reshaped.shape)
label_training = sc.loadmat("label_training.mat")
label_training = label_training['aa']
print (label_training.shape)
label_testing = sc.loadmat("label_testing.mat")
label_testing = label_testing['label_testing']
print (label_testing.shape)
a=feature_training_reshaped.reshape([70, 11, 99])
b=feature_testing_reshaped.reshape([10, 11, 99])
print (a.shape)
# hyperparameters
lr = 0.001
training_iters = 1000
batch_size = 70
n_inputs = 99 # MNIST data input (img shape: 11*99)
n_steps = 11 # time steps
n_hidden_units = 128 # neurons in hidden layer
n_classes = 2 # MNIST classes (0-9 digits)
# tf Graph input
x = tf.placeholder(tf.float32, [None, n_steps, n_inputs])
y = tf.placeholder(tf.float32, [None, n_classes])
# Define weights
weights = {
# (28, 128)
'in': tf.Variable(tf.random_normal([n_inputs, n_hidden_units])),
# (128, 10)
'out': tf.Variable(tf.random_normal([n_hidden_units, n_classes]))
}
biases = {
# (128, )
'in': tf.Variable(tf.constant(0.1, shape=[n_hidden_units, ])),
# (10, )
'out': tf.Variable(tf.constant(0.1, shape=[n_classes, ]))
}
def RNN(X, weights, biases):
# hidden layer for input to cell
########################################
# all the data in this batch flow into this layer in one time
# transpose the inputs shape from 70batch, 11steps,99inputs
# X ==> (70 batch * 11 steps, 99 inputs)
X = tf.reshape(X, [-1, n_inputs])
# into hidden
# X_in = (70 batch * 11 steps, 99 inputs)
X_in = tf.matmul(X, weights['in']) + biases['in']
# another shape transpose X_in ==> (70 batch, 11 steps, 128 hidden),
X_in = tf.reshape(X_in, [-1, n_steps, n_hidden_units])
# cell
##########################################
# basic LSTM Cell.
lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(n_hidden_units, forget_bias=1.0, state_is_tuple=True)
# lstm cell is divided into two parts (c_state, h_state)
##### TAKE Care, batch_size should be 10 when the testing dataset only has 10 data
_init_state = lstm_cell.zero_state(batch_size, dtype=tf.float32)
print ("_init_state:", _init_state)
# You have 2 options for following step.
# 1: tf.nn.rnn(cell, inputs);
# 2: tf.nn.dynamic_rnn(cell, inputs).
# If use option 1, you have to modified the shape of X_in, go and check out this:
# https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3_NeuralNetworks/recurrent_network.py
# In here, we go for option 2.
# dynamic_rnn receive Tensor (batch, steps, inputs) or (steps, batch, inputs) as X_in.
# Make sure the time_major is changed accordingly.
outputs, final_state = tf.nn.dynamic_rnn(lstm_cell, X_in, initial_state=_init_state, time_major=False)
# outputs size would be a tensor [70,11,128]; size of X_in is (70 batch, 11 steps, 128 hidden)
# final_state size would be [batch_size, outputs],which is [70,128]
print (outputs)
print (final_state)
# hidden layer for output as the final results
#############################################
results = tf.matmul(final_state[1], weights['out']) + biases['out']
# # or
# unpack to list [(batch, outputs)..] * steps
# outputs = tf.unpack(tf.transpose(outputs, [1, 0, 2])) # states is the last outputs
# results = tf.matmul(outputs[-1], weights['out']) + biases['out']
return results
pred = RNN(x, weights, biases)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))
train_op = tf.train.AdamOptimizer(lr).minimize(cost)
correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
init = tf.initialize_all_variables()
with tf.Session() as sess:
sess.run(init)
step = 0
while step * batch_size < training_iters:
# batch_xs, batch_ys = fea.next_batch(batch_size)
# batch_xs = batch_xs.reshape([batch_size, n_steps, n_inputs])
sess.run([train_op], feed_dict={
x: a,
y: label_training,
})
if step % 10 == 0:
print(sess.run(accuracy, feed_dict={
x: b,
y: label_testing,
}))
step += 1
At last, I got the result & error:
(770, 99)
(110, 99)
(70, 2)
(10, 2)
(70, 11, 99)
('_init_state:', LSTMStateTuple(c=<tf.Tensor 'zeros:0' shape=(70, 128) dtype=float32>, h=<tf.Tensor 'zeros_1:0' shape=(70, 128) dtype=float32>))
Tensor("RNN/transpose:0", shape=(70, 11, 128), dtype=float32)
LSTMStateTuple(c=<tf.Tensor 'RNN/while/Exit_2:0' shape=(70, 128) dtype=float32>, h=<tf.Tensor 'RNN/while/Exit_3:0' shape=(70, 128) dtype=float32>)
Traceback (most recent call last):
File "/home/xiangzhang/RNN.py", line 150, in <module>
y: label_testing,
File "/home/xiangzhang/.local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 717, in run
run_metadata_ptr)
File "/home/xiangzhang/.local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 915, in _run
feed_dict_string, options, run_metadata)
File "/home/xiangzhang/.local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 965, in _do_run
target_list, options, run_metadata)
File "/home/xiangzhang/.local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 985, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors.InvalidArgumentError: ConcatOp : Dimensions of inputs should match: shape[0] = [10,128] vs. shape[1] = [70,128]
[[Node: RNN/while/BasicLSTMCell/Linear/concat = Concat[N=2, T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](RNN/while/BasicLSTMCell/Linear/concat/concat_dim, RNN/while/TensorArrayRead, RNN/while/Identity_3)]]
Caused by op u'RNN/while/BasicLSTMCell/Linear/concat', defined at:
File "/home/xiangzhang/RNN.py", line 128, in <module>
pred = RNN(x, weights, biases)
File "/home/xiangzhang/RNN.py", line 110, in RNN
outputs, final_state = tf.nn.dynamic_rnn(lstm_cell, X_in, initial_state=_init_state, time_major=False)
File "/home/xiangzhang/.local/lib/python2.7/site-packages/tensorflow/python/ops/rnn.py", line 836, in dynamic_rnn
dtype=dtype)
File "/home/xiangzhang/.local/lib/python2.7/site-packages/tensorflow/python/ops/rnn.py", line 1003, in _dynamic_rnn_loop
swap_memory=swap_memory)
File "/home/xiangzhang/.local/lib/python2.7/site-packages/tensorflow/python/ops/control_flow_ops.py", line 2518, in while_loop
result = context.BuildLoop(cond, body, loop_vars, shape_invariants)
File "/home/xiangzhang/.local/lib/python2.7/site-packages/tensorflow/python/ops/control_flow_ops.py", line 2356, in BuildLoop
pred, body, original_loop_vars, loop_vars, shape_invariants)
File "/home/xiangzhang/.local/lib/python2.7/site-packages/tensorflow/python/ops/control_flow_ops.py", line 2306, in _BuildLoop
body_result = body(*packed_vars_for_body)
File "/home/xiangzhang/.local/lib/python2.7/site-packages/tensorflow/python/ops/rnn.py", line 988, in _time_step
(output, new_state) = call_cell()
File "/home/xiangzhang/.local/lib/python2.7/site-packages/tensorflow/python/ops/rnn.py", line 974, in <lambda>
call_cell = lambda: cell(input_t, state)
File "/home/xiangzhang/.local/lib/python2.7/site-packages/tensorflow/python/ops/rnn_cell.py", line 310, in __call__
concat = _linear([inputs, h], 4 * self._num_units, True)
File "/home/xiangzhang/.local/lib/python2.7/site-packages/tensorflow/python/ops/rnn_cell.py", line 907, in _linear
res = math_ops.matmul(array_ops.concat(1, args), matrix)
File "/home/xiangzhang/.local/lib/python2.7/site-packages/tensorflow/python/ops/array_ops.py", line 872, in concat
name=name)
File "/home/xiangzhang/.local/lib/python2.7/site-packages/tensorflow/python/ops/gen_array_ops.py", line 436, in _concat
values=values, name=name)
File "/home/xiangzhang/.local/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 749, in apply_op
op_def=op_def)
File "/home/xiangzhang/.local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2380, in create_op
original_op=self._default_original_op, op_def=op_def)
File "/home/xiangzhang/.local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1298, in __init__
self._traceback = _extract_stack()
InvalidArgumentError (see above for traceback): ConcatOp : Dimensions of inputs should match: shape[0] = [10,128] vs. shape[1] = [70,128]
[[Node: RNN/while/BasicLSTMCell/Linear/concat = Concat[N=2, T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](RNN/while/BasicLSTMCell/Linear/concat/concat_dim, RNN/while/TensorArrayRead, RNN/while/Identity_3)]]
Process finished with exit code 1
I thought the reason maybe is the testing dataset is only 10, less than batch_size=70, so that when I run the testing dataset, the code _init_state = lstm_cell.zero_state(batch_size, dtype=tf.float32) would has the unmatch error.
There are two ways to solve it but I don't know how to implement any of it neither:
change the batch_size value, set it as 70 when training, 10 when testing. But, I don't know how to code it, please tell me how to do?
Or, I can set the batch_size=10 , and automatically read the training dataset ten by ten. Also, I don't know how to read next batch in tensorflow automatically, and the command next_batch in MNIST dataset can not work.
The second solution is particular important, please kindly to help me, thanks very much.

Invalid argument : You must feed a value for placeholder tensor with dtype float and shape [64,1]

I got unexpected error when running below code :
with tf.Session(graph=graph) as session:
tf.initialize_all_variables().run()
print('Initialized')
mean_loss = 0
for step in xrange(num_steps) :
print ("Train data ",len(train_data))
batch_inputs, batch_labels = generate_batches(train_dataset, batch_size=64, unrollings=5)
feed_dict = dict()
for i in range(unrollings):
batch_labels[i] = np.reshape(batch_labels[i], (batch_size, 1))
batch_inputs[i] = np.array(batch_inputs[i]).astype('int32')
batch_labels[i] = batch_labels[i].astype('float32')
print (train_inputs[i], train_labels[i])
feed_dict = {train_inputs[i] : batch_inputs[i], train_labels[i] : batch_labels[i]}
_, l, predictions, lr = session.run([optimizer, loss, train_prediction, learning_rate], feed_dict=feed_dict)
mean_loss += l
Here is the generating batches, lstm cell and calculating loss code :
def generate_batches(raw_data, batch_size, unrollings):
global data_index
data_len = len(raw_data)
num_batches = data_len // batch_size
inputs = []
labels = []
label = np.zeros(shape=(batch_size, 1), dtype=np.float)
print (num_batches, data_len, batch_size)
for j in xrange(unrollings) :
inputs.append([])
labels.append([])
for i in xrange(batch_size) :
inputs[j].append(raw_data[i + data_index])
label[i, 0] = raw_data[i + data_index + 1]
data_index = (data_index + 1) % len(raw_data)
print (len(inputs), len(inputs[0]), len(labels), label.shape)
labels[j].append(label.tolist())
return inputs, labels
embedding_size = 128
num_nodes = 32
graph = tf.Graph()
with graph.as_default():
# Parameters:
# Input,Forget,Candidate,Output gate: input, previous output, and bias.
ifcox = tf.Variable(tf.truncated_normal([embedding_size, num_nodes*4], -0.1, 0.1))
ifcom = tf.Variable(tf.truncated_normal([num_nodes, num_nodes*4], -0.1, 0.1))
ifcob = tf.Variable(tf.zeros([1, num_nodes*4]))
# Variables saving state across unrollings.
saved_output = tf.Variable(tf.zeros([batch_size, num_nodes]), trainable=False)
saved_state = tf.Variable(tf.zeros([batch_size, num_nodes]), trainable=False)
# Classifier weights and biases.
w = tf.Variable(tf.truncated_normal([num_nodes, 1], -0.1, 0.1))
b = tf.Variable(tf.zeros([1]))
# Definition of the cell computation.
def lstm_cell(i, o, state):
embeddings = tf.Variable(
tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0))
embed = tf.nn.embedding_lookup(embeddings, i)
i = tf.to_float(embed)
print (i.get_shape())
combined = tf.matmul(i, ifcox) + tf.matmul(o, ifcom) + ifcob
input_gate = tf.sigmoid(combined[:, 0:num_nodes])
forget_gate = tf.sigmoid(combined[:, num_nodes:2*num_nodes])
update = tf.sigmoid(combined[:, 2*num_nodes:3*num_nodes])
state = forget_gate * state + input_gate * tf.tanh(update)
output_gate = tf.sigmoid(combined[:, 3*num_nodes:4*num_nodes])
return output_gate * tf.tanh(state), state
train_data = list()
train_label = list()
for _ in range(unrollings) :
train_data.append(tf.placeholder(shape=[batch_size], dtype=tf.int32))
train_label.append(tf.placeholder(shape=[batch_size, 1], dtype=tf.float32))
train_inputs = train_data[:unrollings]
train_labels = train_label[:unrollings]
print (train_inputs, train_labels)
outputs = list()
output = saved_output
state = saved_state
for i in train_inputs :
output, state = lstm_cell(i, output, state)
outputs.append(output)
# State saving across unrollings.
with tf.control_dependencies([saved_output.assign(output),saved_state.assign(state)]):
# Classifier.
logits = tf.nn.xw_plus_b(tf.concat(0, outputs), w, b)
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits, tf.to_float(tf.concat(0, train_labels))))
# Optimizer.
global_step = tf.Variable(0)
learning_rate = tf.train.exponential_decay(10.0, global_step, 5000, 0.1, staircase=True)
optimizer = tf.train.AdamOptimizer(learning_rate)
gradients, v = zip(*optimizer.compute_gradients(loss))
gradients, _ = tf.clip_by_global_norm(gradients, 1.25)
optimizer = optimizer.apply_gradients(zip(gradients, v), global_step=global_step
The error :
tensorflow/core/framework/op_kernel.cc:940] Invalid argument: You must feed a value for placeholder tensor 'Placeholder_3' with dtype float and shape [64,1]
[[Node: Placeholder_3 = Placeholder[dtype=DT_FLOAT, shape=[64,1], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
Traceback (most recent call last):
File "ptb_rnn.py", line 232, in <module>
_, l, predictions, lr = session.run([optimizer, loss, train_prediction, learning_rate], feed_dict=feed_dict)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 710, in run
run_metadata_ptr)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 908, in _run
feed_dict_string, options, run_metadata)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 958, in _do_run
target_list, options, run_metadata)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 978, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors.InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder_3' with dtype float and shape [64,1]
[[Node: Placeholder_3 = Placeholder[dtype=DT_FLOAT, shape=[64,1], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
Caused by op u'Placeholder_3', defined at:
File "ptb_rnn.py", line 163, in <module>
train_label.append(tf.placeholder(shape=[batch_size, 1], dtype=tf.float32))
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/array_ops.py", line 1212, in placeholder
name=name)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_array_ops.py", line 1530, in _placeholder
name=name)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/op_def_library.py", line 703, in apply_op
op_def=op_def)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2317, in create_op
original_op=self._default_original_op, op_def=op_def)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1239, in __init__
self._traceback = _extract_stack()
It looks like I am not feeding using feed_dict the value to the tensor train_labels[i] with size (64, 1). But when I print using batch_labels[i].shape I get size (64,1) and dtype of both is float32.
The train_input has size (64,) and batch_inputs also has size (64, ) and both of same dtype.
So, where is the error in my code?
P.S. I think the error is in line where I am reshaping batch_labels batch_labels[i] = np.reshape(batch_labels[i], (batch_size, 1)). Is that the dimension or rank gets changed ? That could be one reason that train_labels[i] does not accept the size of batch_labels as (64, 1) as its dimension and rank may not be the same.As 3-d batch_labels[i] gets converted to 2-d (batch_size, 1) so does the rank increase? Below is generating batch output of 1 unrolling : ([9976, 9980, 9981, 9982, 9983, 9984, 9986, 9987, 9988, 9989, 9991, 9992, 9993, 9994, 9995, 9996, 9997, 9998, 9999, 2, 9256, 1, 3, 72, 393, 33, 2133, 0, 146, 19, 6, 9207, 276, 407, 3, 2, 23, 1, 13, 141, 4, 1, 5465, 0, 3081, 1596, 96, 2, 7682, 1, 3, 72, 393, 8, 337, 141, 4, 2477, 657, 2170, 955, 24, 521, 6], [[[9980.0], [9981.0], [9982.0], [9983.0], [9984.0], [9986.0], [9987.0], [9988.0], [9989.0], [9991.0], [9992.0], [9993.0], [9994.0], [9995.0], [9996.0], [9997.0], [9998.0], [9999.0], [2.0], [9256.0], [1.0], [3.0], [72.0], [393.0], [33.0], [2133.0], [0.0], [146.0], [19.0], [6.0], [9207.0], [276.0], [407.0], [3.0], [2.0], [23.0], [1.0], [13.0], [141.0], [4.0], [1.0], [5465.0], [0.0], [3081.0], [1596.0], [96.0], [2.0], [7682.0], [1.0], [3.0], [72.0], [393.0], [8.0], [337.0], [141.0], [4.0], [2477.0], [657.0], [2170.0], [955.0], [24.0], [521.0], [6.0], [9207.0]]])

fails to restore from checkpoint file and train in the distributed machines

I run the mnist conv code and save the model as "test_model1-1" and test_model1-1.meta:
#-*-coding:utf-8-*-
import tensorflow as tf
import numpy as np
import input_data
batch_size = 128
test_size = 256
def save(sess, path, pb_name, as_text):
# 从checkpoint保存variables的信息
if as_text:
tf.train.write_graph(sess.graph_def, path, pb_name,True)
else:
tf.train.write_graph(sess.graph_def, path, pb_name, False)
def init_weights(shape):
return tf.Variable(tf.random_normal(shape, stddev=0.01))
def model(X, w, w2, w3, w4, w_o, p_keep_conv, p_keep_hidden):
# define a constant 255
scale = tf.constant(255,tf.float32)
X = tf.mul(X,scale)
print np.max(X)
l1a = tf.nn.relu(tf.nn.conv2d(X, w, # l1a shape=(?, 28, 28, 32)
strides=[1, 1, 1, 1], padding='SAME'))
l1 = tf.nn.max_pool(l1a, ksize=[1, 2, 2, 1], # l1 shape=(?, 14, 14, 32)
strides=[1, 2, 2, 1], padding='SAME')
l1 = tf.nn.dropout(l1, p_keep_conv)
l2a = tf.nn.relu(tf.nn.conv2d(l1, w2, # l2a shape=(?, 14, 14, 64)
strides=[1, 1, 1, 1], padding='SAME'))
l2 = tf.nn.max_pool(l2a, ksize=[1, 2, 2, 1], # l2 shape=(?, 7, 7, 64)
strides=[1, 2, 2, 1], padding='SAME')
l2 = tf.nn.dropout(l2, p_keep_conv)
l3a = tf.nn.relu(tf.nn.conv2d(l2, w3, # l3a shape=(?, 7, 7, 128)
strides=[1, 1, 1, 1], padding='SAME'))
l3 = tf.nn.max_pool(l3a, ksize=[1, 2, 2, 1], # l3 shape=(?, 4, 4, 128)
strides=[1, 2, 2, 1], padding='SAME')
l3 = tf.reshape(l3, [-1, w4.get_shape().as_list()[0]]) # reshape to (?, 2048)
l3 = tf.nn.dropout(l3, p_keep_conv)
l4 = tf.nn.relu(tf.matmul(l3, w4))
l4 = tf.nn.dropout(l4, p_keep_hidden)
pyx = tf.matmul(l4, w_o)
return pyx
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels
trX = trX.reshape(-1, 28, 28, 1) # 28x28x1 input img
teX = teX.reshape(-1, 28, 28, 1) # 28x28x1 input img
print np.max(trX)
X = tf.placeholder("float", [None, 28, 28, 1], name='input_X')
Y = tf.placeholder("float", [None, 10], name='input_Y')
w = init_weights([3, 3, 1, 32]) # 3x3x1 conv, 32 outputs
w2 = init_weights([3, 3, 32, 64]) # 3x3x32 conv, 64 outputs
w3 = init_weights([3, 3, 64, 128]) # 3x3x32 conv, 128 outputs
w4 = init_weights([128 * 4 * 4, 625]) # FC 128 * 4 * 4 inputs, 625 outputs
w_o = init_weights([625, 10]) # FC 625 inputs, 10 outputs (labels)
p_keep_conv = tf.placeholder("float", name = 'p_keep_conv')
p_keep_hidden = tf.placeholder("float", name = 'p_keep_hidden')
py_x = model(X, w, w2, w3, w4, w_o, p_keep_conv, p_keep_hidden)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(py_x, Y), name='cost-reduce-mean')
train_op = tf.train.RMSPropOptimizer(0.001, 0.9).minimize(cost, name='RMSProp-min')
predict_op = tf.argmax(py_x, 1, name='argmax')
correct_prediction = tf.equal(tf.argmax(py_x,1), tf.argmax(Y,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32), name='accuracy-reduce-mean')
# Launch the graph in a session
with tf.Session() as sess:
#save(sess, './logs/','graph.pb', False)
# you need to initialize all variables
sess.run(tf.initialize_all_variables())
saver = tf.train.Saver()
for i in range(2):
training_batch = zip(range(0, len(trX), batch_size),
range(batch_size, len(trX)+1, batch_size))
for start, end in training_batch:
sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end],
p_keep_conv: 0.8, p_keep_hidden: 0.5})
saver.save(sess, 'test_model1', global_step=i)
#test_indices = np.arange(len(teX)) # Get A Test Batch
#np.random.shuffle(test_indices)
#test_indices = test_indices[0:test_size]
#writer = tf.train.SummaryWriter("logs/", sess.graph)
#print(i, np.mean(np.argmax(teY[test_indices], axis=1) ==
# sess.run(predict_op, feed_dict={X: teX[test_indices],
# Y: teY[test_indices],
# p_keep_conv: 1.0,
# p_keep_hidden: 1.0})))
save(sess,'./logs/','graph.pb', False)
#saver = tf.train.Saver(tf.all_variables())
#print tf.all_variables().
#saver.save(sess,"checkpoint.data")
I can retrain the model without define the layers in the same machines
import tensorflow as tf
import input_data
batch_size = 128
test_size = 256
mnist = input_data.read_data_sets("MNIST_data", one_hot=True)
trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images,mnist.test.labels
trX = trX.reshape(-1, 28, 28, 1)
teX = teX.reshape(-1, 28, 28, 1)
with tf.Session() as sess:
new_saver = tf.train.import_meta_graph('test_model1-1.meta')
new_saver.restore(sess, 'test_model1-1')
input_X = sess.graph.get_tensor_by_name('input_X:0')
input_Y = sess.graph.get_tensor_by_name('input_Y:0')
p_keep_conv = sess.graph.get_tensor_by_name('p_keep_conv:0')
p_keep_hidden = sess.graph.get_tensor_by_name('p_keep_hidden:0')
train_op = sess.graph.get_operation_by_name('RMSProp-min')
predict_op = sess.graph.get_tensor_by_name('argmax:0')
for i in range(2):
training_batch = zip(range(0,len(trX), batch_size),
range(batch_size, len(trX)+1, batch_size))
for start, end in training_batch:
_, result = sess.run([train_op, predict_op], feed_dict={input_X:trX[start:end],
input_Y:trY[start:end],
p_keep_conv:0.8,
p_keep_hidden:0.5})
print len(result)
new_saver.save(sess, 'test_model_re', global_step=i)
It's all right to run, But when i change the code to be distributed version to train in the distributed machines, i failed with this error:
Traceback (most recent call last):
File "mnist_conv2_metagraph.py", line 221, in <module>
tf.app.run()
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/platform/app.py", line 30, in run
sys.exit(main(sys.argv))
File "mnist_conv2_metagraph.py", line 111, in main
saver.restore(sess_pre, 'test_model1-1')
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/saver.py", line 1105, in restore
{self.saver_def.filename_tensor_name: save_path})
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 372, in run
run_metadata_ptr)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 636, in _run
feed_dict_string, options, run_metadata)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 708, in _do_run
target_list, options, run_metadata)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 728, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors.InvalidArgumentError: Cannot colocate nodes 'save/Assign_14' and 'Variable_4/RMSProp_1: Cannot merge devices with incompatible jobs: '/job:worker' and '/job:ps/task:1'
[[Node: save/Assign_14 = Assign[T=DT_FLOAT, _class=["loc:#Variable_4"], use_locking=true, validate_shape=true, _device="/job:worker"](Variable_4/RMSProp_1, save/restore_slice_14)]]
Caused by op u'save/Assign_14', defined at:
File "mnist_conv2_metagraph.py", line 221, in <module>
tf.app.run()
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/platform/app.py", line 30, in run
sys.exit(main(sys.argv))
File "mnist_conv2_metagraph.py", line 110, in main
saver = tf.train.import_meta_graph('test_model1-1.meta')
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/saver.py", line 1431, in import_meta_graph
return _import_meta_graph_def(read_meta_graph_file(meta_graph_or_file))
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/saver.py", line 1321, in _import_meta_graph_def
producer_op_list=producer_op_list)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/importer.py", line 274, in import_graph_def
op_def=op_def)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2260, in create_op
original_op=self._default_original_op, op_def=op_def)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1230, in __init__
self._traceback = _extract_stack()
the code is here:
#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
import input_data
import math
import sys
import tempfile
import time
import func_path
flags = tf.app.flags
flags.DEFINE_boolean("download_only", False,
"Only perform downloading of data; Do not proceed to "
"session preparation, model definition or training")
flags.DEFINE_integer("worker_index", 0,
"Worker task index, should be >= 0. worker_index=0 is "
"the master worker task the performs the variable "
"initialization ")
flags.DEFINE_integer("num_workers", 4,
"Total number of workers (must be >= 1)")
flags.DEFINE_integer("num_parameter_servers", 2,
"Total number of parameter servers (must be >= 1)")
flags.DEFINE_integer("replicas_to_aggregate", None,
"Number of replicas to aggregate before parameter update"
"is applied (For sync_replicas mode only; default: "
"num_workers)")
flags.DEFINE_integer("grpc_port", 2222,
"TensorFlow GRPC port")
flags.DEFINE_integer("train_steps", 200,
"Number of (global) training steps to perform")
flags.DEFINE_integer("batch_size", 100, "Training batch size")
flags.DEFINE_float("learning_rate", 0.01, "Learning rate")
flags.DEFINE_string("worker_grpc_url", "grpc://10.10.228.80:2222",
"Worker GRPC URL (e.g., grpc://1.2.3.4:2222, or "
"grpc://tf-worker0:2222)")
flags.DEFINE_boolean("sync_replicas", False,
"Use the sync_replicas (synchronized replicas) mode, "
"wherein the parameter updates from workers are aggregated "
"before applied to avoid stale gradients")
flags.DEFINE_string("ps_server", "",
"PS server lists separated by ';'")
flags.DEFINE_string("worker_server", "",
"Worker server lists separated by ';'")
FLAGS = flags.FLAGS
PARAM_SERVER_PREFIX = "tf-ps" # Prefix of the parameter servers' domain names
WORKER_PREFIX = "tf-worker" # Prefix of the workers' domain names
def get_device_setter(num_parameter_servers, num_workers):
ps_spec = []
ps_list = FLAGS.ps_server.split(';')
for j in range(num_parameter_servers):
ps_spec.append(ps_list[j])
worker_spec = []
worker_list = FLAGS.worker_server.split(';')
for k in range(num_workers):
worker_spec.append(worker_list[k])
cluster_spec = tf.train.ClusterSpec({
"ps": ps_spec,
"worker": worker_spec})
return tf.train.replica_device_setter(cluster=cluster_spec)
def main(_):
mnist = input_data.read_data_sets("MNIST_data", one_hot=True)
batch_size = 128
#test_size = 256
print("Worker GRPC URL: %s" % FLAGS.worker_grpc_url)
print("Worker index = %d" % FLAGS.worker_index)
print("Number of workers = %d" % FLAGS.num_workers)
if FLAGS.worker_index >= FLAGS.num_workers:
raise ValueError("Worker index %d exceeds number of workers %d ") % (FLAGS.worker_index, FLAGS.num_workers)
if FLAGS.num_parameter_servers <= 0:
raise ValueError("Invalid num_parameter_servers value: %d" % FLAGS.num_parameter_servers)
is_chief = (FLAGS.worker_index == 0)
if FLAGS.sync_replicas:
if FLAGS.replicas_to_aggregate is None:
replicas_to_aggregate = FLAGS.num_workers
else:
replicas_to_aggregate = FLAGS.replicas_to_aggregate
device_setter = get_device_setter(FLAGS.num_parameter_servers, FLAGS.num_workers)
def variable_summaries(var, name):
with tf.name_scope('summaries'):
mean = tf.reduce_mean(var)
tf.scalar_summary('mean/' + name, mean)
with tf.name_scope('stddev'):
stddev = tf.sqrt(tf.reduce_sum(tf.square(var-mean)))
tf.scalar_summary('stddev/'+name, stddev)
tf.scalar_summary('max/'+name, tf.reduce_max(var))
tf.scalar_summary('min/'+name, tf.reduce_min)
with tf.device(device_setter):
global_step = tf.Variable(0, name='global_step', trainable=False)
sess_pre = tf.Session()
saver = tf.train.import_meta_graph('test_model1-1.meta')
input_graph_def = tf.GraphDef()
for node in input_graph_def.node:
node.device = ""
_ = tf.import_graph_def(input_graph_def, name="")
saver.restore(sess_pre, 'test_model1-1')
pre_graph = sess_pre.graph
init_op = tf.initialize_all_variables()
train_dir = tempfile.mktemp()
merged = tf.merge_all_summaries()
saver = func_path.prepare()
sv = tf.train.Supervisor(graph=pre_graph,
is_chief=is_chief,
logdir=train_dir,
init_op=init_op,
recovery_wait_secs=1,
global_step=global_step)
sess_config = tf.ConfigProto(
allow_soft_placement=True,
log_device_placement=True,
device_filters=['/job:ps','/job:worker/task:%d'%FLAGS.worker_index])
if is_chief:
print("Worker %d: Initializing session..."% FLAGS.worker_index )
else:
print("Worker %d: Waiting for session to be initialized..." % FLAGS.worker_index)
sess = sv.prepare_or_wait_for_session(FLAGS.worker_grpc_url, config=sess_config)
#new_saver = tf.train.import_meta_graph('test_model1-1.meta')
#new_saver.restore(sess, 'test_model1-1')
input_X = sess.graph.get_tensor_by_name('input_X:0')
input_Y = sess.graph.get_tensor_by_name('input_Y:0')
p_keep_conv = sess.graph.get_tensor_by_name('p_keep_conv:0')
p_keep_hidden = sess.graph.get_tensor_by_name('p_keep_hidden:0')
cost = sess.graph.get_tensor_by_name('cost-reduce-mean')
train_op = sess.graph.get_operation_by_name('RMSProp')
accuracy = sess.graph.get_tensor_by_name('accuracy-reduce-mean')
train_step = train_op.minimize(cost, global_step=global_step)
if FLAGS.sync_replicas:
train_op = tf.train.SyncReplicasOptimizer(
train_op,
replicas_to_aggregate=replicas_to_aggregate,
total_num_replicas=FLAGS.num_workers,
replica_id=FLAGS.worker_index,
name="mnist_sync_replicas")
if FLAGS.sync_replicas and is_chief:
# Initial token and chief queue runners required by the sync_replicas mode
chief_queue_runner = train_op.get_chief_queue_runner()
init_tokens_op = train_op.get_init_tokens_op()
train_writer = tf.train.SummaryWriter(FLAGS.summaries_dir + '/train', sess.graph)
test_writer = tf.train.SummaryWriter(FLAGS.summaries_dir + '/test')
print("Worker %d: Session initialization complete."%FLAGS.worker_index)
if FLAGS.sync_replicas and is_chief:
print("Starting chief queue runner and running init_tokens_op")
sv.start_queue_runners(sess,[chief_queue_runner])
sess.run(init_tokens_op)
time_begin = time.time()
print("Training begins # %f" %time_begin)
local_step = 0
while True:
if local_step % 100 == 0:
batch_xs, batch_ys = mnist.test.next_batch(FLAGS.batch_size)
batch_xs = batch_xs.reshape(-1,28,28,1)
test_feed = {input_X: batch_xs,input_Y: batch_ys,p_keep_conv: 1.0, p_keep_hidden: 1.0}
summary, acc = sess.run([merged, accuracy], feed_dict=test_feed)
if is_chief:
test_writer.add_summary(summary, local_step)
print('Accuracy at step %s: %s'%(local_step, acc))
else:
batch_xs, batch_ys = mnist.train.next_batch(FLAGS.batch_size)
batch_xs = batch_xs.reshape(-1,28,28,1)
train_feed = {input_X: batch_xs, input_Y: batch_ys, p_keep_conv: 1.0, p_keep_hidden: 1.0}
# can't understand
_, step = sess.run([train_step, global_step], feed_dict=train_feed)
if local_step %100 ==99:
now = time.time()
print('%f: Workr %d: training step %d done (global step: %d)'%(now, FLAGS.worker_index, local_step, step))
if step >= FLAGS.train_steps:
break
if local_step % 100 == 1:
if FLAGS.worker_index == 1:
func_path.save(sess, saver, FLAGS.worker_index)
if FLAGS.worker_index == 2:
func_path.save(sess, saver, FLAGS.worker_index)
if FLAGS.worker_index == 3:
func_path.save(sess, saver, FLAGS.worker_index)
local_step+=1
time_end = time.time()
print('Training ends # %f' % time_end)
training_time = time_end - time_begin
print("Training elapsed time: %f s"% training_time)
val_images = mnist.validation.images
val_images = val_images.reshape(-1,28,28,1)
val_labels = mnist.validation.labels
val_feed = {input_X: val_images,input_Y: val_labels,p_keep_conv: 1.0, p_keep_hidden: 1.0}
val_xent = sess.run(cost, feed_dict=val_feed)
print("After %d training step(s), validation cross entropy = %g"%
(FLAGS.train_steps, val_xent))
acc = sess.run(accuracy, feed_dict=val_feed)
print("After %d training step(s), validation acc = %g"%(FLAGS.train_steps, acc))
if is_chief:
print("here")
func_path.save(sess, saver, FLAGS.worker_index)
if __name__ == '__main__':
tf.app.run()
Anybody can help me with the distributed version, thanks