{"QuestionId":39283605,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-02T02:48:28.010","AcceptedAnswerId":null,"OwnerUserId":288609.0,"Title":"Regarding the use of tf.train.shuffle_batch() to create batches","Body":"

In Tensorflow tutorial<\/a>, it gives the following example regarding :<\/p>\n\n

<\/pre>\n\n

I am not very clear about the meaning of and . In this example, it is set as and respectively. What is the logic for this kind of setup, or what does that mean. If input has 200 images and 200 labels, what will happen?<\/p>\n","answers":[{"AnswerId":"41971507","CreationDate":"2017-02-01T03:40:55.577","ParentId":null,"OwnerUserId":"3574081","Title":null,"Body":"

The tf.train.shuffle_batch()<\/code><\/a> function uses a tf.RandomShuffleQueue<\/code><\/a> internally to accumulate batches of batch_size<\/code> elements, which are sampled uniformly at random from the elements currently in the queue.<\/p>\n\n

Many training algorithms, such as the stochastic gradient descent–based algorithms that TensorFlow uses to optimize neural networks, rely on sampling records uniformly at random from the entire training set. However, it is not always practical to load the entire training set in memory (in order to sample from it), so tf.train.shuffle_batch()<\/code> offers a compromise: it fills an internal buffer with between min_after_dequeue<\/code> and capacity<\/code> elements, and samples uniformly at random from that buffer. For many training processes, this improves the accuracy of the model and provides adequate randomization.<\/p>\n\n

The min_after_dequeue<\/code> and capacity<\/code> arguments have an indirect effect on training performance. Setting a large min_after_dequeue<\/code> value will delay the start of training, because TensorFlow has to process at least that many elements before training can start. The capacity<\/code> is an upper bound on the amount of memory that the input pipeline will consume: setting this too large may cause the training process to run out of memory (and possibly start swapping, which will impair the training throughput).<\/p>\n\n

If the dataset has only 200 images, it would be easily possible to load the entire dataset in memory. tf.train.shuffle_batch()<\/code> would be quite inefficient, because it enqueue each image and label multiple times in the tf.RandomShuffleQueue<\/code>. In this case, you may find it more efficient to do the following instead, using tf.train.slice_input_producer()<\/code><\/a> and tf.train.batch()<\/code><\/a>:<\/p>\n\n

random_image, random_label = tf.train.slice_input_producer([all_images, all_labels],\n                                                           shuffle=True)\n\nimage_batch, label_batch = tf.train.batch([random_image, random_label],\n                                          batch_size=32)\n<\/code><\/pre>\n"}]}
{"QuestionId":39284872,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-02T05:28:11.787","AcceptedAnswerId":39289972.0,"OwnerUserId":986267.0,"Title":"Leaky_Relu in Caffe","Body":"

The ReLu definition looks like this:<\/p>\n\n

<\/pre>\n\n

I tried doing this but it threw me an error:<\/p>\n\n

<\/pre>\n\n

Any help is very much appreciated.<\/p>\n\n

Thanks!<\/p>\n","answers":[{"AnswerId":"39289972","CreationDate":"2016-09-02T10:16:25.567","ParentId":null,"OwnerUserId":"5635517","Title":null,"Body":"

As defined in the documentation, negative_slope<\/strong> is a parameter. And parameters are defined in the following way. Try This:<\/p>\n\n

layer {\n   name: \"relu1\"\n   type: \"ReLU\"\n   bottom: \"conv1\"\n   top: \"conv1\"\n   relu_param{\n      negative_slope: 0.1\n   }\n }\n<\/code><\/pre>\n"}]}
{"QuestionId":39285297,"AnswerCount":0,"Tags":"","CreationDate":"2016-09-02T06:01:24.247","AcceptedAnswerId":null,"OwnerUserId":4494128.0,"Title":"Caffe throws mkl error while importing using mod_wsgi and httpd","Body":"

I have a flask app which uses caffe compiled with mkl. The app is working fine when running using flask internal server or gunicorn. But when i try to run it using mod_wsgi and httpd, it throws the following error:<\/p>\n\n

<\/pre>\n\n

I am using Anaconda 4.1.1 which comes with mkl. For httpd, i am using mpm prefork and mod_wsgi 4.5.3 (i tried older and newer versions as well).<\/p>\n\n

Note: caffe imports fine when done outside httpd\/mod_wsgi.<\/p>\n","answers":[]} {"QuestionId":39287275,"AnswerCount":0,"Tags":"","CreationDate":"2016-09-02T08:02:00.980","AcceptedAnswerId":null,"OwnerUserId":2530674.0,"Title":"Predicting in Stateful LSTMs","Body":"

I have the following Keras model, although it could be generalised to a normal RNN using GRUs.<\/p>\n\n

<\/pre>\n\n

If I don't have the statement with regards to resetting the state, the mean squared error has always been higher. Considering that the test set is right after the train set<\/strong> wouldn't it make sense that you would want to preserve the state of the last memory block?<\/p>\n\n

This tutorial seems to suggest otherwise: http:\/\/machinelearningmastery.com\/time-series-prediction-lstm-recurrent-neural-networks-python-keras\/<\/a> (i.e. he simply doesn't have that if statement, doesn't explicitly mention anything about keeping the last state).<\/p>\n\n

So just wondering if I am correct about this.<\/p>\n","answers":[]} {"QuestionId":39288341,"AnswerCount":2,"Tags":"","CreationDate":"2016-09-02T08:58:19.940","AcceptedAnswerId":null,"OwnerUserId":5082406.0,"Title":"Time series prediction with LSTM using Keras: Wrong number of dimensions: expected 3, got 2 with shape","Body":"

I am trying to predict the next value in the time series using the previous 20 values. Here is a sample from my code:<\/p>\n\n

is <\/p>\n\n

is <\/p>\n\n

<\/pre>\n\n

Though when I ran my code I got the following error:<\/p>\n\n

<\/p>\n\n

I was trying to replicate the results in this post: neural networks for algorithmic trading<\/a>. Here is a link to the git repo: link<\/a><\/p>\n\n

It seems to be a conceptual error. Please post any sources where I can get a better understanding of LSTMS for time series prediction. Also please explain me how I fix this error, so that I can reproduce the results mentioned in the article mentioned above.<\/p>\n","answers":[{"AnswerId":"41350401","CreationDate":"2016-12-27T18:34:29.343","ParentId":null,"OwnerUserId":"1576464","Title":null,"Body":"

LSTM in Keras has an input tensor shape of (nb_samples, timesteps, feature_dim)<\/code><\/p>\n\n

In your case, X_train<\/code> should probably have an input shape of (15015, 20, 1)<\/code>. Just reshape it accordingly and the model should run.<\/p>\n"},{"AnswerId":"39289342","CreationDate":"2016-09-02T09:44:48.133","ParentId":null,"OwnerUserId":"4116272","Title":null,"Body":"

If I understand your problem correctly, your input data a set of 15015 1D sequences of length 20. According to Keras doc, the input is a 3D tensor with shape (nb_samples, timesteps, input_dim). In your case, the shape of X<\/code> should then be (15015, 20, 1)<\/code>.<\/p>\n\n

Also, you just need to give input_dim<\/code> to the first LSTM<\/code> layer. input_shape<\/code> is redundant and the second layer will infer its input shape automatically:<\/p>\n\n

model = Sequential()\nmodel.add(LSTM(input_dim=EMB_SIZE, output_dim=HIDDEN_RNN, return_sequences=True))\nmodel.add(LSTM(output_dim=HIDDEN_RNN, return_sequences=False))\n<\/code><\/pre>\n"}]}
{"QuestionId":39289050,"AnswerCount":2,"Tags":"","CreationDate":"2016-09-02T09:31:26.460","AcceptedAnswerId":null,"OwnerUserId":6778775.0,"Title":"Sentence similarity using keras","Body":"

My problem is that the loss goes directly to starting from the first epoch. What am I doing wrong?<\/p>\n\n

I have already tried updating to latest keras and theano versions.<\/p>\n\n

The code for my model is:<\/p>\n\n

<\/pre>\n\n

I also tried using a simple instead of the layer, but it has the same result.<\/p>\n\n

<\/pre>\n","answers":[{"AnswerId":"44359356","CreationDate":"2017-06-04T22:20:34.760","ParentId":null,"OwnerUserId":"2362381","Title":null,"Body":"

I didn't run into the nan<\/code> issue, but my loss wouldn't change. I found this info \ncheck this out<\/a><\/p>\n\n

def cosine_distance(shapes):\n    y_true, y_pred = shapes\n    def l2_normalize(x, axis):\n        norm = K.sqrt(K.sum(K.square(x), axis=axis, keepdims=True))\n        return K.sign(x) * K.maximum(K.abs(x), K.epsilon()) \/     K.maximum(norm, K.epsilon())\n    y_true = l2_normalize(y_true, axis=-1)\n    y_pred = l2_normalize(y_pred, axis=-1)\n    return K.mean(1 - K.sum((y_true * y_pred), axis=-1))\n<\/code><\/pre>\n"},{"AnswerId":"40976201","CreationDate":"2016-12-05T14:10:11.117","ParentId":null,"OwnerUserId":"4801125","Title":null,"Body":"

The nan is a common issue in deep learning regression. Because you are using Siamese network, you can try followings:<\/p>\n\n

    \n
  1. check your data: do they need to be normalized?<\/li>\n
  2. try to add an Dense layer into your network as the last layer, but be careful picking up an activation function, e.g. relu<\/li>\n
  3. try to use another loss function, e.g. contrastive_loss<\/li>\n
  4. smaller your learning rate, e.g. 0.0001<\/li>\n
  5. cos mode does not carefully deal with division by zero, might be the cause of NaN<\/li>\n<\/ol>\n\n

    It is not easy to make deep learning work perfectly.<\/p>\n"}]} {"QuestionId":39289285,"AnswerCount":3,"Tags":"","CreationDate":"2016-09-02T09:42:25.073","AcceptedAnswerId":39291033.0,"OwnerUserId":6655645.0,"Title":"How to create a Image Dataset just like MNIST dataset?","Body":"

    I have 10000 BMP images of some handwritten digits. If i want to feed the datas to a neural network what do i need to do ? For MNIST dataset i just had to write<\/p>\n\n

    <\/pre>\n\n

    I am using Keras library in python . How can i create such dataset ?<\/p>\n","answers":[{"AnswerId":"59042654","CreationDate":"2019-11-26T02:03:55.497","ParentId":null,"OwnerUserId":"4767778","Title":null,"Body":"

    numpy can save array to file as binary \nnumpy save<\/a><\/p>\n\n

    import numpy as np\n\ndef save_data():\n  [images, labels] = read_data()\n  outshape = len(images[0])\n  npimages = np.empty((0, outshape), dtype=np.int32)\n  nplabels = np.empty((0,), dtype=np.int32)\n\n  for i in range(len(labels)):\n      label = labels[i]\n      npimages = np.append(npimages, [images[i]], axis=0)\n      nplabels = np.append(nplabels, y)\n\n  np.save('images', npimages)\n  np.save('labels', nplabels)\n\n\ndef read_data():\n  return [np.load('images.npy'), np.load('labels.npy')]\n\n<\/code><\/pre>\n"},{"AnswerId":"55058581","CreationDate":"2019-03-08T07:28:06.317","ParentId":null,"OwnerUserId":"3544031","Title":null,"Body":"

    You should write your own function to load all the images or do it like:<\/p>\n\n

    imagePaths = sorted(list(paths.list_images(args[\"testset\"])))\n\n# loop over the input images\nfor imagePath in imagePaths:\n    # load the image, pre-process it, and store it in the data list\n    image = cv2.imread(imagePath)\n    image = cv2.resize(image, (IMAGE_DIMS[1], IMAGE_DIMS[0]))\n    image = img_to_array(image)\n    data.append(image)\n    # extract the class label from the image path and update the\n    # labels list\n\n\ndata = np.array(data, dtype=\"float\") \/ 255.0\n<\/code><\/pre>\n"},{"AnswerId":"39291033","CreationDate":"2016-09-02T11:15:12.057","ParentId":null,"OwnerUserId":"4116272","Title":null,"Body":"

    You can either write a function that loads all your images and stack them into a numpy array if all fits in RAM or use Keras ImageDataGenerator (https:\/\/keras.io\/preprocessing\/image\/<\/a>) which includes a function flow_from_directory<\/code>. You can find an example here https:\/\/gist.github.com\/fchollet\/0830affa1f7f19fd47b06d4cf89ed44d<\/a>.<\/p>\n"}]} {"QuestionId":39289431,"AnswerCount":3,"Tags":"","CreationDate":"2016-09-02T09:49:27.190","AcceptedAnswerId":null,"OwnerUserId":6787005.0,"Title":"TFLearn - Evaluate a model","Body":"

    I am using TFLearn Alexnet<\/a> sample with my own dataset. <\/p>\n\n

    Next I want to perform classification on test data and to determine the accuracy of the model.<\/p>\n\n

      \n
    1. TFLearn API provides methods and . <\/li>\n
    2. gives prediction result for each image in the test data set. How can I use the result to get the accuracy?<\/li>\n
    3. gives the accuracy score on the test data. Is there a way to get the accuracy for each batch as well? <\/li>\n<\/ol>\n","answers":[{"AnswerId":"40751038","CreationDate":"2016-11-22T20:29:30.853","ParentId":null,"OwnerUserId":"1721793","Title":null,"Body":"

      Below the responses: <\/p>\n\n

        \n
      1. You can calculate the accuracy by comparing predicted classes against effective ones when using model.predict()<\/code><\/li>\n
      2. No, that I am aware of. I am not sure would be useful as a use case either: usually you are interested on the overall accuracy for the dataset\/partition you are evaluating.<\/li>\n<\/ol>\n"},{"AnswerId":"44205199","CreationDate":"2017-05-26T15:28:17.327","ParentId":null,"OwnerUserId":"5418136","Title":null,"Body":"

        Accuracy from Prediction results<\/strong><\/p>\n\n

        As stated by @Martin, the maximum value in the predictions array is the class predicted by model. you compare that class to the actual value: a match increases accuracy while mismatch decreases. <\/p>\n\n

        #METHOD 1\naccuracy = model.evaluate(x_test, y_test)\n\n#METHOD 2\npredictions = model.predict(x_test)\naccuracy = 0\nfor prediction, actual in zip(predictions, y_test):\n    predicted_class = numpy.argmax(prediction)\n    actual_class = numpy.argmax(actual)\n    if(predicted_class == actual_class):\n        accuracy+=1\n\naccuracy = accuracy \/ len(y_test)\n<\/code><\/pre>\n"},{"AnswerId":"42139800","CreationDate":"2017-02-09T14:51:12.393","ParentId":null,"OwnerUserId":"562769","Title":null,"Body":"
        # Evaluate model\nscore = model.evaluate(test_x, test_y)\nprint('Test accuarcy: %0.4f%%' % (score[0] * 100))\n\n# Run the model on one example\nprediction = model.predict([test_x[0]])\nprint(\"Prediction: %s\" % str(prediction[0][:3]))  # only show first 3 probas\n<\/code><\/pre>\n\n

        How can I use the result to get the accuracy?<\/h2>\n\n
          \n
        1. Take the argmax of each prediction to get the predicted class<\/li>\n
        2. Probably also take the argmax of the labels to get indices if you have one-hot encoded labels<\/li>\n
        3. accuracy = sum(predicted label == target label) \/ len(predicted labels)<\/li>\n<\/ol>\n\n

          Is there a way to get the accuracy for each batch?<\/h2>\n\n
          batch_index = 42\nbatch_size = 128\nbatch_x = test_x[batch_index * batch_size : (batch_index + 1) * batch_size]\nbatch_y = test_y[batch_index * batch_size : (batch_index + 1) * batch_size]\nscore = model.evaluate(batch_x, batch_y)\nprint('Batch accuarcy: %0.4f%%' % (score[0] * 100))\n<\/code><\/pre>\n"}]}
          {"QuestionId":39289915,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-02T10:13:53.440","AcceptedAnswerId":39294735.0,"OwnerUserId":3871961.0,"Title":"How to avoid cmake to read in its \"system cache\" $HOME\/.cmake\/","Body":"

          When I run with some projects such as or , it writes some information at the system level. Specifically, on a linux system, it generates some directories such as and <\/p>\n\n

          My problem is that this information is hereafter used for any project I compile. As a consequence, the programs referenced in are (partially) found, even if I do not want it (as far as I am concerned, I define external variables to control with external programs is allowed to consider for a given compilation).\ny current solution is to delete the directory when needed (i.e before compiling my new program). I consider to add a in but this not fully satisfactory (nor sophisticated!). Could anyone propose a better solution ?<\/p>\n\n

          NB<\/strong>: the expression \"system cache\" in the question is probably wrong. I would be grateful to get a better term. Thank you for any feedback on this (actually, if I knew the correct expression, I may have already found the solution on the web...)<\/p>\n\n


          \n\n

          Edit:<\/p>\n\n

          Once you know the \"system cache\" is actually the User Package Registry<\/a><\/em> the answer is easy. See below...<\/p>\n","answers":[{"AnswerId":"39294735","CreationDate":"2016-09-02T14:23:45.403","ParentId":null,"OwnerUserId":"3871961","Title":null,"Body":"

          The directory $HOME\/.cmake<\/code> is the User Package Registry<\/em>. To avoid find_package()<\/code> to search in this directory, use option NO_CMAKE_PACKAGE_REGISTRY<\/code>. See point 6 of its documentation:<\/p>\n\n

          https:\/\/cmake.org\/cmake\/help\/v3.0\/command\/find_package.html<\/a><\/p>\n"}]} {"QuestionId":39290339,"AnswerCount":2,"Tags":"","CreationDate":"2016-09-02T10:37:00.440","AcceptedAnswerId":39296122.0,"OwnerUserId":2997327.0,"Title":"Finetuning Caffe Deep Learning Check failed: error == cudaSuccess out of memory","Body":"

          I am relatively new in Deep learning and its framework. Currently, I am experimenting with Caffe framework and trying to fine tune the Vgg16_places_365. <\/p>\n\n

          I am using the Amazone EC2 instance g2.8xlarge with 4 GPUs (each has 4 GB of RAM). However, when I try to train my model (using a single GPU), I got this error:<\/p>\n\n

          \n

          Check failed: error == cudaSuccess (2 vs. 0) out of memory<\/p>\n<\/blockquote>\n\n

          After I did some research, I found that one of the ways to solve this out of memory problem is by reducing the batch size in my train.prototxt<\/p>\n\n

          Caffe | Check failed: error == cudaSuccess (2 vs. 0) out of memory<\/a>.<\/p>\n\n

          Initially, I set the batch size into 50, and iteratively reduced it until 10 (since it worked when batch_size = 10). \nNow, the model is being trained and I am pretty sure it will take quite long time. However, as a newcomer in this domain, I am curious about the relation between this batch size and another parameter such as the learning rate, stepsize and even the max iteration that we specify in the solver.prototxt.<\/p>\n\n

          How significant the size of the batch will affect the quality of the model (like accuracy may be). How the other parameters can be used to leverage the quality. Also, instead of reducing the batch size or scale up my machine, is there another way to fix this problem? <\/p>\n","answers":[{"AnswerId":"39296122","CreationDate":"2016-09-02T15:37:18.763","ParentId":null,"OwnerUserId":"696913","Title":null,"Body":"

          To answer your first question regarding the relationship between parameters such as batch size, learning rate and maximum number of iterations, you are best of reading about the mathematical background. A good place to start might be this stats.stackexchange question: How large should the batch size be for stochastic gradient descent?<\/a>. The answer will briefly discuss the relation between batch size and learning rate (from your question I assume learning rate = stepsize) and also provide some references for further reading.<\/p>\n\n

          To answer your last question, with the dataset you are finetuning on and the model (i.e. the VGG16) being fixed (i.e. the input data of fixed size, and the model of fixed size), you will have a hard time avoiding the out of memory problem for large batch sizes. However, if you are willing to reduce the input size or the model size you might be able to use larger batch sizes. Depending on how (and what) exactly you are finetuning, reducing the model size may already be achieved by discarding learned layers or reducing the number\/size of fully connected layers.<\/p>\n\n

          The remaining questions, i.e. how significant the batchsize influences quality\/accuracy and how other parameters influence quality\/accuracy, are hard to answer without knowing the concrete problem you are trying to solve. The influence of e.g. the batchsize on the achieved accuracy might depend on various factors such as the noise in your dataset, the dimensionality of your dataset, the size of your dataset as well as other parameters such as learning rate (=stepsize) or momentum parameter. For these sort of questions, I recommend the textbook by Goodfellow et al.<\/a>, e.g. chapter 11 may provide some general guidelines on choosing these hyperparmeters (i.e. batchsize, learning rate etc.).<\/p>\n"},{"AnswerId":"39303300","CreationDate":"2016-09-03T04:42:36.783","ParentId":null,"OwnerUserId":"5465000","Title":null,"Body":"

          another way to solve your problem is using all the GPUs on your machine. If you have 4x4=16<\/code>GB RAM on your GPUs, that would be enough. If you are running caffe in command mode, just add the --gpu argument as follows (assuming you have 4 GPUs indexed as default 0,1,2,3):<\/p>\n\n

           build\/tools\/caffe train --solver=solver.prototxt --gpu=0,1,2,3\n<\/code><\/pre>\n\n

          However if you are using the python interface, running with multiple GPUs is not yet supported.<\/p>\n\n

          I can point out some general hints to answer your question on the batchsize:\n- The smaller the batchsize is, the more stochastic your learning would be --> less probability of overfitting on the training data; higher probability of not converging.\n- each iteration in caffe fetches one batch of data, runs forward and ends with a backpropagation.\n- Let's say your training data is 50'000 and your batchsize is 10; then in 1000 iterations, 10'000 of your data has been fed to the network. In the same scenario scenario, if your batchsize is 50, in 1000 iterations, all your training data are seen by the network. This is called one epoch. You should design your batchsize and maximum iterations in a way that your network is trained for a certain number of epochs.\n- stepsize in caffe, is the number of iterations your solver will run before multiplying the learning rate with the gamma value (if you have set your training approach as \"step\"). <\/p>\n"}]} {"QuestionId":39290811,"AnswerCount":0,"Tags":"","CreationDate":"2016-09-02T11:01:29.820","AcceptedAnswerId":null,"OwnerUserId":2532005.0,"Title":"tensorflow code other than placeholder depends on batch size","Body":"

          I am new to TF. As an experiment I tried to modify the MNIST example, to implement a nonlinearity directly rather than using a predefined function. <\/p>\n\n

          The MNIST input data appears in the program as a tensor of size (10,784) where 10 is the batch size. When this data is passed through my (modified) program, I get a shape error (\"must have same rank\") unless the rest of the code also<\/em> references the batch size. This is contrary to what I expect from tutorials, where it is implied that the batch size need only be considered for Placeholders, and can be generally ignored othersize. I had expected that most of the code could be written as if it is processing one datapoint at a time.<\/p>\n\n

          Here is the relevant part of the code. mkmodule is called from a modified version of inference() in mnist.py (from the provided example) which in turn is called from fully_connected_feed.py. The argumet to mkmodule() is a batch of images, size (10,784). <\/p>\n\n

          <\/pre>\n\n

          The sprit of the algorithm is to multiply by the weight matrix W of size (784,32), then\npass the activations through an elementwise nonlinearity that is zero if the activation is less\nthan constant and increases linearly otherwise, represented by the multiplication. That is, in pseudocode, <\/p>\n\n

          <\/pre>\n\n

          Here is the code<\/p>\n\n

          <\/pre>\n\n

          and selection<\/p>\n\n

          <\/pre>\n\n

          Anyway, the algorithm here is just a thoughtless experiment. Please focus just on the tensor shapes.<\/p>\n\n

          When run, it gives the following error from the :<\/p>\n\n

          <\/pre>\n\n

          The output from the print statements is:<\/p>\n\n

          <\/pre>\n\n

          I am primarily surpised that the output of the has size (10,32) rather than size 32.\nDoes it mean that some variables in the graph (such as here) should include the batch size as one of the dimensions? But other variables such as do not need it? <\/p>\n\n

          That would be messy. I think I must be misunderstanding something. <\/p>\n","answers":[]} {"QuestionId":39292076,"AnswerCount":3,"Tags":"","CreationDate":"2016-09-02T12:08:50.540","AcceptedAnswerId":null,"OwnerUserId":1747088.0,"Title":"Tensorflow Concat Error: shape mismatch","Body":"

          I currently have a network whereby I start with a 16 x 16 x 2 input tensor, I perform a few convolution and pooling operations and reduce that down to a tensor that is declared like this:<\/p>\n\n

          <\/pre>\n\n

          That tensor then passes through a couple more layers of matrix multiplications and relus before outputting a category. <\/p>\n\n

          What I would like to do is extend the output of convolution stage by adding another 10 parameters to the vector above.<\/p>\n\n

          I have a placeholder where the data is loaded in which is defined like this:<\/p>\n\n

          <\/pre>\n\n

          I'm trying to concatenate these variables together like this:<\/p>\n\n

          <\/pre>\n\n

          I'm getting the following error message:<\/p>\n\n

          <\/pre>\n\n

          I'm sure that there is something simple that I'm doing wrong but I can't see it.<\/p>\n","answers":[{"AnswerId":"43763824","CreationDate":"2017-05-03T15:06:47.323","ParentId":null,"OwnerUserId":"7357128","Title":null,"Body":"

          The reason is likely in the tensorflow version<\/strong>.<\/p>\n\n

          From the tensorflow latest official api, tf.conat is defined as <\/p>\n\n

          tf.concat<\/p>\n\n

          concat(\n values,\n axis,\n name='concat'\n)<\/p>\n\n

          So, the better way is calling this function by key value. \nI tried the following code, no error. <\/p>\n\n

           xnew = tf.concat(axis=0, values=[x1, x2])\n<\/code><\/pre>\n\n

          --------------------------------------------------<\/h1>\n\n

          Copy the offical api explanation as follows. <\/p>\n\n

          tf.concat\nconcat(\n values,\n axis,\n name='concat'\n)<\/p>\n\n

          Defined in tensorflow\/python\/ops\/array_ops.py.<\/p>\n\n

          See the guide: Tensor Transformations > Slicing and Joining<\/p>\n\n

          Concatenates tensors along one dimension.<\/p>\n\n

          Concatenates the list of tensors values along dimension axis. If values[i].shape = [D0, D1, ... Daxis(i), ...Dn], the concatenated result has shape<\/p>\n\n

          [D0, D1, ... Raxis, ...Dn]\nwhere<\/p>\n\n

          Raxis = sum(Daxis(i))\nThat is, the data from the input tensors is joined along the axis dimension.<\/p>\n\n

          The number of dimensions of the input tensors must match, and all dimensions except axis must be equal.<\/p>\n\n

          For example:<\/p>\n\n

          t1 = [[1, 2, 3], [4, 5, 6]]\nt2 = [[7, 8, 9], [10, 11, 12]]\ntf.concat([t1, t2], 0) ==> [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]\ntf.concat([t1, t2], 1) ==> [[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12]]\n\n# tensor t3 with shape [2, 3]\n# tensor t4 with shape [2, 3]\ntf.shape(tf.concat([t3, t4], 0)) ==> [4, 3]\ntf.shape(tf.concat([t3, t4], 1)) ==> [2, 6]\n<\/code><\/pre>\n"},{"AnswerId":"39293416","CreationDate":"2016-09-02T13:16:48.960","ParentId":null,"OwnerUserId":"6678014","Title":null,"Body":"

          I don't really understand why you have the None in the shape of the placeholder. If you remove it, it should work<\/p>\n"},{"AnswerId":"39296947","CreationDate":"2016-09-02T16:23:58.143","ParentId":null,"OwnerUserId":"5215538","Title":null,"Body":"

          x1<\/code> and x2<\/code> have different ranks, 1 and 2 respectively, so nothing strange that concat<\/code> fails. Here is an example that works for me:<\/p>\n\n

          x1 = tf.Variable(tf.constant(1.0, shape=[32]))\n# create a placeholder that will hold another 10 parameters\nx2 = tf.placeholder(tf.float32, shape=[10])\n# concatenate x1 and x2\nxnew = tf.concat(0, [x1, x2])\ninit = tf.initialize_all_variables()\nwith tf.Session() as sess:\n    sess.run(init)\n    _xnew = sess.run([xnew], feed_dict={x2: range(10)})\n<\/code><\/pre>\n\n

          \"enter<\/a><\/p>\n"}]} {"QuestionId":39293290,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-02T13:10:42.170","AcceptedAnswerId":null,"OwnerUserId":6787761.0,"Title":"Can tensorflow use matrix of matrix?","Body":"

          I know tensorflow can calculate expressions like when the elements are primitive data type (integer or float). \nIs it possible to perform a similar computation when each of , and is a 1x3 matrix and , and are 3x1 matrices?<\/p>\n\n

          Can TensorFlow calculate and optimize this formula?<\/p>\n","answers":[{"AnswerId":"39301632","CreationDate":"2016-09-02T22:54:03.887","ParentId":null,"OwnerUserId":"3574081","Title":null,"Body":"

          The tf.batch_matmul()<\/code><\/a> operator can perform matrix multiplications on batches of matrices. In this case, you would have a tensor abc<\/code> of shape (3, 1, 3)<\/code> (where abc[0, :, :] = a<\/code>, abc[1, :, :] = b<\/code>, etc.) and a tensor xyz<\/code> of shape (3, 3, 1)<\/code> (where xyz[0, :, :] = x<\/code>, etc.).<\/p>\n\n

          abc = ...\nxyz = ...\n\nresult = tf.batch_matmul(abc, xyz)\n\nprint result.get_shape()  # ==> \"(3, 1, 1)\"\n<\/code><\/pre>\n\n

          result<\/code> is a 3-D tensor with contents equivalent to tf.pack([tf.matmul(a, x), tf.matmul(b, y), tf.matmul(c, z)])<\/code>.<\/p>\n"}]} {"QuestionId":39294159,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-02T13:55:14.160","AcceptedAnswerId":39296538.0,"OwnerUserId":6787721.0,"Title":"tensorflow : restore from checkpoint for continue training","Body":"

          in this case ,i want to continue train my model from checkpoint.i use the cifar-10 example and did a little change in cifar-10_train.py like below,they are almost the same,except i want to restore from checkpoint:\ni replaced cifar-10 by md.<\/p>\n\n

          <\/pre>\n\n

          when i run the code,errors like this:<\/p>\n\n

          <\/pre>\n\n

          when i uncomment the line 107 \"sess.run(init)\" ,it runs perfectly,but a initialised model,just a new one from sctrach. i want to restore variables from checkpoint , and continue my training.i want to restore.<\/p>\n","answers":[{"AnswerId":"39296538","CreationDate":"2016-09-02T15:59:30.423","ParentId":null,"OwnerUserId":"4385912","Title":null,"Body":"

          Without having the rest of your code handy, I'd say that the following part is problematic:<\/p>\n\n

          for v in tf.all_variables():\n    if v in tf.trainable_variables():\n        restore_name = variable_averages.average_name(v)\n    else:\n        restore_name = v.op.name\n    variables_to_restore[restore_name] = v\n<\/code><\/pre>\n\n

          Because you specify a list of variables you want to restore here, but you exclude some (i.e. the v.op.name for the ones in the trainable vars). That will change the name of the variable in the net that throws the error (again, without the rest of the code, I cannot really say), s.t. one (or more) vars are not restored properly. Two approaches (which are not very sophisticated) will help you here: <\/p>\n\n

            \n
          1. If you do not store all variables, do an initialization first, and then restore the variables you have actually stored. This makes sure that tensors you do not really care about get initialized none the less<\/li>\n
          2. TF is very efficient when it comes to storing nets. If in doubt, store all variables ...<\/li>\n<\/ol>\n"}]} {"QuestionId":39295136,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-02T14:44:00.290","AcceptedAnswerId":39295309.0,"OwnerUserId":1243445.0,"Title":"Gradient clipping appears to choke on None","Body":"

            I'm trying to add gradient clipping to my graph. I used the approach recommended here: How to effectively apply gradient clipping in tensor flow?<\/a><\/p>\n\n

            <\/pre>\n\n

            But when I turn on gradient clipping, I get the following stack trace:<\/p>\n\n

            <\/pre>\n\n

            How do I solve this problem?<\/p>\n","answers":[{"AnswerId":"39295309","CreationDate":"2016-09-02T14:51:22.997","ParentId":null,"OwnerUserId":"1243445","Title":null,"Body":"

            So, one option that seems to work is this:<\/p>\n\n

                optimizer = tf.train.GradientDescentOptimizer(learning_rate)\n    if gradient_clipping:\n        gradients = optimizer.compute_gradients(loss)\n\n        def ClipIfNotNone(grad):\n            if grad is None:\n                return grad\n            return tf.clip_by_value(grad, -1, 1)\n        clipped_gradients = [(ClipIfNotNone(grad), var) for grad, var in gradients]\n        opt = optimizer.apply_gradients(clipped_gradients, global_step=global_step)\n    else:\n        opt = optimizer.minimize(loss, global_step=global_step)\n<\/code><\/pre>\n\n

            It looks like compute_gradients returns None instead of a zero tensor when the gradient would be a zero tensor and tf.clip_by_value does not support a None value. So just don't pass None to it and preserve None values.<\/p>\n"}]} {"QuestionId":39295263,"AnswerCount":3,"Tags":"","CreationDate":"2016-09-02T14:49:30.670","AcceptedAnswerId":39312792.0,"OwnerUserId":5651936.0,"Title":"Good way to input PASCAL-VOC 2012 training data and labels with tensorflow","Body":"

            I want to do object detection of PASCAL-VOC 2012 dataset<\/a> with tensorflow. <\/p>\n\n

            I want to input the whole image<\/strong> with object labels<\/strong> and the corresponding bounding boxes<\/strong> into the tensorflow for training. <\/p>\n\n

            Is there any good way to write a data file for tensorflow to read? Or just read the original XML file in tensorflow?<\/p>\n\n

            Thank you very much.<\/p>\n\n

            Here is an image example:\n\"enter<\/a> <\/p>\n","answers":[{"AnswerId":"39312792","CreationDate":"2016-09-04T01:34:40.393","ParentId":null,"OwnerUserId":"4744283","Title":null,"Body":"

            It seems that TF have no support of xml files yet. <\/p>\n\n

              \n
            1. You can try to make batches by yourself and feed them to TF placeholders. \nhttps:\/\/www.tensorflow.org\/versions\/r0.10\/how_tos\/reading_data\/index.html#feeding<\/a><\/p><\/li>\n

            2. You can write your own file format and your own decoder. Then you can read file and get file bytes with tf.decode_raw<\/code> function and do whatever you whant. Related question if you whant to read multiple files simultaneously: Tensorflow read images with labels<\/a><\/p><\/li>\n<\/ol>\n\n

              I think that first option is easier to implement.<\/p>\n"},{"AnswerId":"42286247","CreationDate":"2017-02-16T22:53:27.857","ParentId":null,"OwnerUserId":"3970726","Title":null,"Body":"

              There are pre-made tools for that, look for Tensorflow models repository.\nTheir approach in essence is:<\/p>\n\n

                \n
              1. Parse the xml annotation files and flatten the data structure within them.<\/li>\n
              2. Produce tfrecord<\/code> that combines annotation and images,<\/li>\n<\/ol>\n\n

                this is arguably the best way.<\/p>\n\n

                For sake of training you can implement your own converter that takes a pair (xml<\/code>,image<\/code>) and saves into tfrecord example<\/code>.<\/p>\n\n

                Tfrecord is tensorflow format for storing data, every tfrecord file is bascially a list containing examples<\/code>, every example<\/code> is an object that holds data in key : value<\/code> pairs, where value is an array of primitive types (int, string, float) and key<\/code> is a string.<\/p>\n\n

                So, first you flatten your xml<\/code> annotation to match constraints of tfrecord<\/code> file then you use tensorflow TFRecordWriter to save data into file.\nCheck Tensorflow API - it will pay off.<\/p>\n"},{"AnswerId":"50689226","CreationDate":"2018-06-04T21:48:32.383","ParentId":null,"OwnerUserId":"9894455","Title":null,"Body":"

                First use labelImg-master to convert the boxed pictures into VOC Annotated format the use my utility from the link below to convert the VOC Annotated Files to npz .npz is a very good format and performance efficient way to store both data and label for image processing using KERAS on Tensorflow.<\/p>\n\n

                Below is the code to convert any PASCAL VOC ANNOTATED format files to npz.<\/p>\n\n

                https:\/\/github.com\/MATRIX4284\/VOC_NPZ<\/a><\/p>\n"}]} {"QuestionId":39296922,"AnswerCount":0,"Tags":"","CreationDate":"2016-09-02T16:22:36.017","AcceptedAnswerId":null,"OwnerUserId":3397008.0,"Title":"CAFFE: Run forward pass with fewer nodes in FC layer","Body":"

                I am trying to perform an experiment in Caffe with a very simple single hidden layer NN. I am using the MNIST dataset trained with a single hidden layer (of 128 nodes). I have all the weights from the fully trained network already. <\/p>\n\n

                However, during the feed forward stage I would like to use only a smaller subset of these nodes i.e 32 or 64. So for example, I would like to calculate the activations of 64 nodes during the feed forward pass and save them. then during the next run, calculate the activations of the other 64 nodes and combine them with the activations of the first 64 so i get the activations of all 128 nodes. Thus calculating the activations of all 128 nodes but in two 'passes'. <\/p>\n\n

                Is there a way to achieve this in Caffe? Please excuse me as I am very new to Caffe ( just started using it this week! ). <\/p>\n","answers":[]} {"QuestionId":39297694,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-02T17:15:44.853","AcceptedAnswerId":39298880.0,"OwnerUserId":6788616.0,"Title":"How to repeat unknown dimension in TensorFlow","Body":"

                For example (I can do this with Theano without a problem):<\/p>\n\n

                <\/p>\n\n

                wrt TF Mean has shape (?, num), but log_var has shape (num,)<\/p>\n\n

                I don't know how to do the same in TensorFlow...<\/p>\n","answers":[{"AnswerId":"39298880","CreationDate":"2016-09-02T18:42:35.823","ParentId":null,"OwnerUserId":"1576602","Title":null,"Body":"

                You can use shape<\/code> to extract the shape of a placeholder during evaluation. Then simply tile<\/code> the tensor. For instance, for:<\/p>\n\n

                num = 3\np1 = tf.placeholder(tf.float32, (None, num))\np2 = tf.placeholder(tf.float32, (num,))\n<\/code><\/pre>\n\n

                the operation:<\/p>\n\n

                op = tf.tile(tf.reshape(p2, [1, -1]), (tf.shape(p1)[0], 1))\nsess.run(op, feed_dict={p1:[[1,2,3],\n                            [4,5,6]], \n                        p2: [1,2,1]})\n<\/code><\/pre>\n\n

                will give:<\/p>\n\n

                array([[ 1.,  2.,  1.],\n       [ 1.,  2.,  1.]], dtype=float32)\n<\/code><\/pre>\n\n

                However, in most cases you actually do not need to do that since you can rely on the broadcasting behavior of TF operations. For instance:<\/p>\n\n

                op = tf.add(p1, p2)\nsess.run(op, feed_dict={p1:[[1,2,3],\n                            [4,5,6]], \n                        p2: [1,2,1]})\n<\/code><\/pre>\n\n

                gives:<\/p>\n\n

                array([[ 2.,  4.,  4.],\n       [ 5.,  7.,  7.]], dtype=float32)\n<\/code><\/pre>\n"}]}
                {"QuestionId":39297736,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-02T17:19:11.703","AcceptedAnswerId":null,"OwnerUserId":2616326.0,"Title":"pymc3 theano function usage","Body":"

                I'm trying to define a complex custom likelihood function using pymc3. The likelihood function involves a lot of iteration, and therefore I'm trying to use theano's scan method to define iteration directly within theano. Here's a greatly simplified example that illustrates the challenge that I'm facing. The (fake) likelihood function I'm trying to define is simply the sum of two pymc3 random variables, p and theta. Of course, I could simply return p+theta, but the actual likelihood function I'm trying to write is more complicated, and I believe I need to use theano.scan since it involves a lot of iteration.<\/p>\n\n

                <\/pre>\n\n

                When I run this, I get the error:<\/p>\n\n

                <\/pre>\n\n

                I understand that the issue occurs in line \n result=get_ll(p, theta)<\/p>\n\n

                because p and theta are of type pymc3.TransformedRV, and that the input to a theano function needs to be a scalar number of a simple numpy array. However, a pymc3 TransformedRV does not seem to have any obvious way of obtaining the current value of the random variable itself.<\/p>\n\n

                Is it possible to define a log likelihood function that involves the use of a theano function that takes as input a pymc3 random variable?<\/p>\n","answers":[{"AnswerId":"41124125","CreationDate":"2016-12-13T14:56:35.513","ParentId":null,"OwnerUserId":"7132951","Title":null,"Body":"

                The problem is that your th.function get_ll is a compiled theano function, which takes as input numerical arrays. Instead, pymc3 is sending it a symbolic variable (theano tensor). That's why you're getting the error.<\/p>\n\n

                As to your solution, you're right in saying that just returning p+theta is the way to go. If you have scans and whatnot in your logp, then you would return the scan variable of interest; there is no need to compile a theano function here. For example, if you wanted to add 1 to each element of a vector (as an impractical toy example), you would do:<\/p>\n\n

                def logp(X):\n    the_sum, the_sum_upd = th.scan(lambda x: x+1, sequences=[X])\n    return the_sum\n<\/code><\/pre>\n\n

                That being said, if you need gradients, you would need to calculate your the_sum variable in a theano Op and provide a grad() method along with it (you can see a toy example of that on the answer here<\/a>). If you do not need gradients, you might be better off doing everything in python (or C, numba, cython, for performance) and using the as_op decorator.<\/p>\n"}]} {"QuestionId":39297995,"AnswerCount":2,"Tags":"","CreationDate":"2016-09-02T17:36:27.417","AcceptedAnswerId":40338235.0,"OwnerUserId":4937674.0,"Title":"getting \"pygpu was configured but could not be imported\" error while trying with OpenCL+Theano on AMD Radeon","Body":"

                I have followed the instructions from this:<\/p>\n\n

                https:\/\/gist.github.com\/jarutis\/ff28bca8cfb9ce0c8b1a<\/a><\/p>\n\n

                But then when I tried : THEANO_FLAGS=device=opencl0:0 python test.py
                \non the test file I am getting error:<\/p>\n\n

                ERROR (theano.sandbox.gpuarray): pygpu was configured but could not be imported\nTraceback (most recent call last):\n File \"\/home\/mesayantan\/.local\/lib\/python2.7\/site-packages\/theano\/sandbox\/gpuarray\/init<\/strong>.py\", line 20, in <\/p>\n\n

                <\/pre>\n\n

                File \"\/usr\/src\/gtest\/clBLAS\/build\/libgpuarray\/pygpu\/init<\/strong>.py\", line 7, in <\/p>\n\n

                <\/pre>\n\n

                File \"\/usr\/src\/gtest\/clBLAS\/build\/libgpuarray\/pygpu\/elemwise.py\", line 3, in <\/p>\n\n

                <\/pre>\n\n

                File \"\/usr\/src\/gtest\/clBLAS\/build\/libgpuarray\/pygpu\/dtypes.py\", line 6, in <\/p>\n\n

                <\/pre>\n\n

                ImportError: cannot import name gpuarray<\/p>\n\n

                I do not have good idea. I am using all these for the first time. I am working on Ubuntu 14.04 LTS. How can I resolve this error?<\/p>\n","answers":[{"AnswerId":"41882535","CreationDate":"2017-01-26T20:36:58.327","ParentId":null,"OwnerUserId":"5957020","Title":null,"Body":"

                Installing the blas<\/code> library seems enough. I'm doing tests for the same problem.<\/p>\n\n

                cd ~\ngit clone https:\/\/github.com\/clMathLibraries\/clBLAS.git\ncd clBLAS\/\nmkdir build\ncd build\/\nsudo apt-cache search openblas\nsudo apt-get install libopenblas-base libopenblas-dev\nsudo apt-get install liblapack3gf liblapack-doc liblapack-dev\ncmake ..\/src\nmake\nsudo make install\n<\/code><\/pre>\n\n

                And after that<\/p>\n\n

                git clone https:\/\/github.com\/Theano\/libgpuarray.git\ncd libgpuarray\nmkdir Build\ncd Build\ncmake .. -DCMAKE_BUILD_TYPE=Release\n\nmake\nsudo make install\ncd ..\nsudo apt-get install cython\nsudo apt-get install python-numpy python-scipy python-dev python-pip python-nose g++ libopenblas-dev git\n<\/code><\/pre>\n\n

                Building and Installing with regard to python3<\/code> <\/p>\n\n

                python3 setup.py build\nsudo -H python3 setup.py install\n<\/code><\/pre>\n\n

                I hope it can help you. Now just the dev version of theano<\/code> is missing for me.<\/p>\n"},{"AnswerId":"40338235","CreationDate":"2016-10-31T07:45:19.397","ParentId":null,"OwnerUserId":"7094150","Title":null,"Body":"

                I fixed this issue with the step-by-step installation given in the lipgpuarray website!<\/p>\n\n

                Download<\/p>\n\n

                git clone https:\/\/github.com\/Theano\/libgpuarray.git\ncd libgpuarray\n<\/code><\/pre>\n\n

                Install libgpuarray<\/code><\/p>\n\n

                # extract or clone the source to <dir>\ncd <dir> \nmkdir Build\ncd Build\n# you can pass -DCMAKE_INSTALL_PREFIX=\/path\/to\/somewhere to install to an alternate location\ncmake .. -DCMAKE_BUILD_TYPE=Release # or Debug if you are investigating a crash\nmake\nmake install\ncd ..\n<\/code><\/pre>\n\n

                Install pygpu<\/code><\/p>\n\n

                # This must be done after libgpuarray is installed as per instructions above.\npython setup.py build\npython setup.py install\n<\/code><\/pre>\n\n

                Source:\nhttp:\/\/deeplearning.net\/software\/libgpuarray\/installation.html<\/a><\/p>\n\n

                This worked for me!\nGood Luck<\/p>\n"}]} {"QuestionId":39298462,"AnswerCount":4,"Tags":"","CreationDate":"2016-09-02T18:09:22.373","AcceptedAnswerId":44854569.0,"OwnerUserId":6499614.0,"Title":"Keras stateful LSTM error","Body":"

                I want to create stateful LSTM in keras. I gave it a command like this:<\/p>\n\n

                <\/pre>\n\n

                where batch size=19. But on running it gives error<\/p>\n\n

                <\/pre>\n\n

                I did not specify batch size 32 anywhere in my script and 19 is divisible by 8816<\/p>\n","answers":[{"AnswerId":"53228386","CreationDate":"2018-11-09T15:13:05.240","ParentId":null,"OwnerUserId":"7560187","Title":null,"Body":"

                Both training and validation data need to be divisible by the batch size. Make sure that any part of the model using batch size takes the same number (e.g. batch_input_shape<\/code> in your LSTM layer, and batch_size<\/code> in model.fit()<\/code> and model.predict()<\/code>. Down-sample training and validation data if need be to make this work.<\/p>\n\n

                e.g.<\/p>\n\n

                >>> batch_size = 100\n>>> print(x_samples_train.shape)\n>>> print(x_samples_validation.shape)\n    (42028, 24, 14)\n    (10451, 24, 14) \n\n# Down-sample so training and validation are both divisible by batch_size\n>>> x_samples_train_ds = x_samples_train[-42000:]\n>>> print(x_samples_train_ds.shape)\n>>> y_samples_train_ds = y_samples_train[-42000:]\n>>> print(y_samples_train_ds.shape)\n    (42000, 24, 14)\n    (42000,)\n>>> x_samples_validation_ds = x_samples_validation[-10000:]\n>>> print(x_samples_validation_ds.shape)\n>>> y_samples_validation_ds = y_samples_validation[-10000:]\n>>> print(y_samples_validation_ds.shape)\n    (10000, 24, 14)\n    (10000,)\n<\/code><\/pre>\n"},{"AnswerId":"50666348","CreationDate":"2018-06-03T12:20:02.120","ParentId":null,"OwnerUserId":"9515557","Title":null,"Body":"

                there are two cases where batch_size error could occur.<\/p>\n\n

                  \n
                1. model.fit(train_x, train_y, batch_size= n_batch<\/strong>, shuffle=True,verbose=2)<\/p><\/li>\n

                2. trainPredict = model.predict(train_x, batch_size=n_batch<\/strong>)\nor testPredict = model.predict(test_x,batch_size=n_batch<\/strong>)<\/p><\/li>\n<\/ol>\n\n

                  in both cases, you have to mention no. of batches.<\/p>\n\n

                  note:<\/strong> we need to predict train and test both, so best practice is divide the test and train in such a way that your batch size is multiple of both in stateful=True<\/strong> case<\/p>\n"},{"AnswerId":"39299689","CreationDate":"2016-09-02T19:42:47.770","ParentId":null,"OwnerUserId":"1643939","Title":null,"Body":"

                  model.fit()<\/code><\/a> does the batching (as opposed to model.train_on_batch<\/code><\/a> for example). Consequently it has a batch_size<\/code> parameter which defaults to 32.<\/p>\n\n

                  Change this to your input batch size and it should work as expected.<\/p>\n\n

                  Example:<\/p>\n\n

                  batch_size = 19\n\nmodel = Sequential()\nmodel.add(LSTM(300,input_dim=4,activation='tanh',stateful=True,batch_input_shape=(19,13,4),return_sequences=True))\n\nmodel.fit(x, y, batch_size=batch_size)\n<\/code><\/pre>\n"},{"AnswerId":"44854569","CreationDate":"2017-06-30T20:43:27.260","ParentId":null,"OwnerUserId":"1347267","Title":null,"Body":"

                  To dynamically size your data and batches:<\/p>\n\n

                  Size data and training sample split:<\/p>\n\n

                  data_size = int(len(supervised_values))\ntrain_size_initial = int(data_size * train_split)\nx_samples = supervised_values[-data_size:, :]\n<\/code><\/pre>\n\n

                  Size number of training samples to batch size:<\/p>\n\n

                  if train_size_initial < batch_size_div:\n    batch_size = 1\nelse:\n    batch_size = int(train_size_initial \/ batch_size_div)\ntrain_size = int(int(train_size_initial \/ batch_size) * batch_size)  # provide even division of training \/ batches\nval_size = int(int((data_size - train_size) \/ batch_size) * batch_size)  # provide even division of val \/ batches\nprint('Data Size: {}  Train Size: {}   Batch Size: {}'.format(data_size, train_size, batch_size))\n<\/code><\/pre>\n\n

                  Split data into train and validation sets<\/p>\n\n

                  train, val = x_samples[0:train_size, 0:-1], x_samples[train_size:train_size + val_size, 0:-1]\n<\/code><\/pre>\n"}]}
                  {"QuestionId":39299488,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-02T19:26:04.057","AcceptedAnswerId":39314340.0,"OwnerUserId":5475451.0,"Title":"TensorFlow: Understanding the parameters returned by evaluate","Body":"

                  I've created a Linear classifier model using tensorflow. When I evaluate the model the following is returned.<\/p>\n\n

                  <\/pre>\n\n

                  Could somebody please explain me how eval_auc and loss is calculated? Thanks!<\/p>\n","answers":[{"AnswerId":"39314340","CreationDate":"2016-09-04T06:55:42.513","ParentId":null,"OwnerUserId":"4332642","Title":null,"Body":"

                  eval_auc<\/code> must be the AUC = Area Under the ROC Curve.\nSee explanation, for example, here<\/a><\/p>\n\n

                  loss<\/code> must be logloss = logarithmic loss.\nSee explanation, for example, here<\/a><\/p>\n"}]} {"QuestionId":39300401,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-02T20:39:44.643","AcceptedAnswerId":39300842.0,"OwnerUserId":5737561.0,"Title":"How many session objects are needed for synchronous in-graph replication?","Body":"

                  When using synchronous in-graph replication I only call once.<\/p>\n\n

                  Question 1:<\/strong> Do I still have to create a new session object for each worker and have to pass the URL of the master server (the one that calls ) as the session target?<\/p>\n\n

                  Question 2:<\/strong> Can I get the session target for each server by using or do I have to specify the URL of the master server specifically?<\/p>\n","answers":[{"AnswerId":"39300842","CreationDate":"2016-09-02T21:18:34.203","ParentId":null,"OwnerUserId":"3574081","Title":null,"Body":"

                  If you are using \"in-graph replication\", the graph contains multiple copies of the computational nodes, typically with one copy per device (i.e. one per worker task if you're doing distributed CPU training, or one per GPU if you're doing distributed or local multi-GPU training). Since all of the replicas are in the same graph, you only need one tf.Session<\/code> to control the entire training process. You don't<\/strong> need to create tf.Session<\/code> objects in the workers that don't call Session.run()<\/code>. <\/p>\n\n

                  For in-graph training, it's typical to have a single master that is separate from the worker tasks (for performance isolation), but you could colocate it with your client program. In that case, you could simply create a single-task job called \"client\"<\/code> and in that task create a session using server.target<\/code>. The following example shows how you could write a single script for your \"client\"<\/code>, \"worker\"<\/code>, and \"ps\"<\/code> jobs:<\/p>\n\n

                  server = tf.train.Server({\"client\": [\"client_host:2222\"],\n                          \"worker\": [\"worker_host0:2222\", ...],\n                          \"ps\": [\"ps_host0:2222\", ...]})\n\nif job_name == \"ps\" or job_name == \"worker\":\n    server.join()\n\nelif job_name == \"client\":\n    # Build a replicated graph.\n    # ...\n\n    sess = tf.Session(server.target)\n\n    # Insert training loop here.\n    # ...\n<\/code><\/pre>\n"}]}
                  {"QuestionId":39300880,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-02T21:22:13.663","AcceptedAnswerId":39303937.0,"OwnerUserId":3796320.0,"Title":"How to find wrong prediction cases in test set (CNNs using Keras)","Body":"

                  I'm using MNIST example with 60000 training image and 10000 testing image. How do I find which of the 10000 testing image that has an incorrect classification\/prediction?<\/p>\n","answers":[{"AnswerId":"39303937","CreationDate":"2016-09-03T06:29:18.710","ParentId":null,"OwnerUserId":"4449586","Title":null,"Body":"

                  Simply use model.predict_classes()<\/code> and compare the output with true labes. i.e:<\/p>\n\n

                  incorrects = np.nonzero(model.predict_class(X_test).reshape((-1,)) != y_test)\n<\/code><\/pre>\n\n

                  to get indices of incorrect predictions<\/p>\n"}]} {"QuestionId":39301758,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-02T23:13:43.173","AcceptedAnswerId":39335310.0,"OwnerUserId":3656912.0,"Title":"Getting dimensions wrong when creating a feed-forward auto-encoder in Theano\/Lasagne","Body":"

                  I want to create a simple autoencoder with 3000 input, 2 hidden and 3000 output neurons:<\/p>\n\n

                  <\/pre>\n\n

                  The shape of the training data is as follows:<\/p>\n\n

                  <\/pre>\n\n

                  This is input, target and loss function definition:<\/p>\n\n

                  <\/pre>\n\n

                  I'm just running one epoch but get an error:<\/p>\n\n

                  <\/pre>\n\n

                  This is the error:<\/p>\n\n

                  \n

                  ValueError: ('shapes (3000,3) and (3000,2) not aligned: 3 (dim 1) !=\n 3000 (dim 0)', (3000, 3), (3000, 2)) Apply node that caused the error:\n Dot22(inputs, W) Toposort index: 3 Inputs types: [TensorType(float64,\n matrix), TensorType(float64, matrix)] Inputs shapes: [(3000, 3),\n (3000, 2)] Inputs strides: [(24, 8), (16, 8)] Inputs values: ['not\n shown', 'not shown'] Outputs clients:\n [[Elemwise{add,no_inplace}(Dot22.0, InplaceDimShuffle{x,0}.0),\n Elemwise{Composite{(i0 * (Abs(i1) + i2 + i3))}}[(0,\n 2)](TensorConstant{(1, 1) of 0.5}, Elemwise{add,no_inplace}.0,\n Dot22.0, InplaceDimShuffle{x,0}.0)]]<\/p>\n<\/blockquote>\n\n

                  To me it seems that the bottleneck of the auto encoder is the problem. Any ideas?<\/p>\n","answers":[{"AnswerId":"39335310","CreationDate":"2016-09-05T17:30:02.053","ParentId":null,"OwnerUserId":"3656912","Title":null,"Body":"

                  Just got some help from my IBM college (Erwan<\/a>), I've posted the working solution to this GIST<\/a>, the relevant sections are these ones:<\/p>\n\n

                  First, get the shape of the training data correct:<\/p>\n\n

                  train.shape = (3, 3000)\n<\/code><\/pre>\n\n

                  Then use the same shape on the InputLayer:<\/p>\n\n

                  def build_autoencoder(input_var=None):\n    l_in = InputLayer(shape=(3, 3000), input_var=input_var)\n\n    l_hid = DenseLayer(\n            l_in, num_units=2,\n            nonlinearity=rectify,\n            W=lasagne.init.GlorotUniform())\n\n    l_out = DenseLayer(\n            l_hid, num_units=3000,\n            nonlinearity=softmax)\n\nreturn l_out\n<\/code><\/pre>\n\n

                  So this is solved, next problem is getting a descending cost during training, but this is another topic<\/a> :) <\/p>\n"}]} {"QuestionId":39301773,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-02T23:15:16.967","AcceptedAnswerId":39301914.0,"OwnerUserId":5737561.0,"Title":"Tensor too big for graph distribution - \"InternalError: Message length was negative\"","Body":"

                  I tried to run the following graph:<\/strong>\n\"Graph<\/a><\/p>\n\n

                  Unfortunately, I receive the following error message:<\/strong><\/p>\n\n

                  <\/pre>\n\n

                  I noticed that this error message does not occur if the size of is 800MB, but it does occur if the size is 8GB.<\/p>\n\n

                  (Notice that has to be transferred from one device to another device.)<\/p>\n\n

                  Question:<\/strong> Is there a limit on how big a tensor can be, if that tensor has to be transferred between devices?<\/p>\n","answers":[{"AnswerId":"39301914","CreationDate":"2016-09-02T23:39:33.413","ParentId":null,"OwnerUserId":"3574081","Title":null,"Body":"

                  Yes, currently there is a 2GB limit<\/strong> on an individual tensor when sending it between processes. This limit is imposed by the protocol buffer representation (more precisely, by the auto-generated C++ wrappers produced by the protoc<\/code> compiler) that is used in TensorFlow's communication layer.<\/p>\n\n

                  We are investigating ways to lift this restriction. In the mean time, you can work around it by manually adding tf.split()<\/code> or tf.slice()<\/code>, and tf.concat()<\/code> operations to partition the tensor for transfer. If you have very large tf.Variable<\/code> objects, you can use variable partitioners<\/a> to perform this transformation automatically. Note that in your program you have multiple 8GB tensors in memory at once, so the peak memory utilization will be at least 16GB.<\/p>\n"}]} {"QuestionId":39302344,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-03T01:00:05.520","AcceptedAnswerId":39310331.0,"OwnerUserId":1595417.0,"Title":"Tensorflow RNN input size","Body":"

                  I am trying to use tensorflow to create a recurrent neural network. My code is something like this:<\/p>\n\n

                  <\/pre>\n\n

                  Now, everything runs just fine. However, I am rather confused by what is actually going on. The output dimensions are always the batch size x the size of the rnn cell's hidden state - how can they be completely independent of the input size?<\/p>\n\n

                  If my understanding is correct, the inputs are concatenated to the rnn's hidden state at each step, and then multiplied by a weight matrix (among other operations). This means that the dimensions of the weight matrix need to depend on the input size, which is impossible, because the rnn_cell is created before the inputs are even declared!<\/p>\n","answers":[{"AnswerId":"39310331","CreationDate":"2016-09-03T18:54:55.847","ParentId":null,"OwnerUserId":"1595417","Title":null,"Body":"

                  After seeing the answer<\/a> to a question about tensorflow's GRU implementation, I've realized what's going on. Counter to my intuition, the GRUCell constructor doesn't create any weight or bias variables at all. Instead, it creates its own variable scope, and then instantiates the variables on demand when actually called. Tensorflow's variable scoping mechanism ensures that the variables are only created once, and shared across subsequent calls to the GRU.<\/p>\n\n

                  I'm not sure why they decided to go with this rather confusing implementation, which is as far as I can tell is undocumented. To me it seems more appropriate to use python's object-level variable scoping to encapsulate the tensorflow variables within the GRUCell itself, rather than relying on an additional implicit scoping mechanism.<\/p>\n"}]} {"QuestionId":39302743,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-03T02:36:55.097","AcceptedAnswerId":null,"OwnerUserId":1118236.0,"Title":"RNN loss becomes NaN due to very large prediction values","Body":"

                  Below is the RNN that I build using Keras:<\/p>\n\n

                  <\/pre>\n\n

                  The output is as following:<\/p>\n\n

                  <\/pre>\n\n

                  The loss goes very high in the second batch and then becomes nan. The true outcome y does not contains very large values. The max y is less than 400.<\/p>\n\n

                  On the other hand, I check the prediction output y_hat. The RNN returns some very high prediction, which leads to infinite. <\/p>\n\n

                  However, I am still puzzled how to improve my model.<\/p>\n","answers":[{"AnswerId":"39319530","CreationDate":"2016-09-04T17:18:17.190","ParentId":null,"OwnerUserId":"1118236","Title":null,"Body":"

                  The problem is \"kind of\" solved by 1) changing the activation of the output layer from \"linear\" to \"relu\" and\/or 2) decreasing the learning rate. <\/p>\n\n

                  However, the predictions now are all zero.<\/p>\n"}]} {"QuestionId":39302865,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-03T03:06:31.070","AcceptedAnswerId":41523295.0,"OwnerUserId":1576602.0,"Title":"Is there a scatter operation in TensorFlow?","Body":"

                  Is there a way to perform the reverse operation to or , basically distributing a tensor into specific indices of another tensor (and filling the remaining entries with 0)?<\/p>\n\n

                  In particular, I would like to scatter columns of a matrix into specific columns of another matrix.<\/p>\n","answers":[{"AnswerId":"41523295","CreationDate":"2017-01-07T15:55:10.133","ParentId":null,"OwnerUserId":"681714","Title":null,"Body":"

                  There's an operator called tf.scatter_nd<\/code><\/a>, which does exactly what you're looking for.<\/p>\n"}]} {"QuestionId":39303039,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-03T03:45:50.680","AcceptedAnswerId":null,"OwnerUserId":6720221.0,"Title":"Tensorflow: Can I combine several name_scopes into one for optimizer update?","Body":"

                  I have two named scopes for separate subgraphs of a CNN (using tf.variable_scope). Can I combine the two scopes into one so that my optimizer updates only the variables in the two scopes?<\/p>\n","answers":[{"AnswerId":"39334454","CreationDate":"2016-09-05T16:21:47.167","ParentId":null,"OwnerUserId":"3893224","Title":null,"Body":"

                  According to the tf.Optmizer documentation<\/a>, the function minimize<\/code> can take a var_list (these vars reference the learned variable weights inside the graph). So using that you just need to get a list of variables (like [w1, b1] for a simple MLP) from the graph. <\/p>\n\n


                  \n\n

                  If you have named them with tf.variable_scope, you should be able to use tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLESscope=\"my_scope_name\")<\/code>, as described in the tf.get_collection documentation<\/a>. If you have two variable scopes to get, you should be able to get the combined list with the +<\/code> operator, as the call returns a python list.<\/p>\n\n


                  \n\n

                  So, comining the two ideas, I believe you can do:<\/p>\n\n

                  loss = ...\nvars_to_minimize = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='var_scope_name_1') + \n                   tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='var_scope_name_2')\nminimize_op = tf.Optimizer().minimize(loss, var_list=vars_to_minimize)\n<\/code><\/pre>\n\n
                  \n\n

                  Note: see GraphKeys documentation<\/a> for more details on availabe keys to use in the get_collection call.<\/p>\n"}]} {"QuestionId":39303378,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-03T04:55:29.700","AcceptedAnswerId":null,"OwnerUserId":5228890.0,"Title":"Tensorflow: Ran out of memory trying to allocate 1.5KiB","Body":"

                  I am running tensorflow in a loop with 300 random structures to find a good network structure. \nAfter the first epoch on the data are finished, I remove the worst 10% of them and start the second epoch on the networks. But, it fails in iteration ~350. \nI am running it on Tesla K80 with 11.25 GiB of memory. I also have tensorflow version 0.9.0 and aggregation_method = tf.AggregationMethod.EXPERIMENTAL_TREE is set on tf.train.MomentumOptimizer. \nFollowing is the error that I am getting. (Since it is a very long, I just selected the point that it is started, the change of details and the final logs. <\/p>\n\n

                  I appreciate any help. \nAfshin<\/p>\n\n

                  <\/pre>\n","answers":[{"AnswerId":"54985249","CreationDate":"2019-03-04T14:27:50.930","ParentId":null,"OwnerUserId":"5228890","Title":null,"Body":"

                  I cleared the utilized GPU memory by deleting the the session objects for every new network and it works.<\/p>\n"}]} {"QuestionId":39303623,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-03T05:38:55.910","AcceptedAnswerId":null,"OwnerUserId":5005052.0,"Title":"Cannot install Keras on Pycharm on Macbook","Body":"

                  Macbook.<\/p>\n\n

                  I can perform \"pip install Keras==1.0.8\" successfully on terminal though.<\/p>\n\n

                  Problem: Installing Keras to Pycharm, cannot make it.<\/strong><\/p>\n\n

                  Error as shown by screenshots below:\n\"enter<\/a><\/p>\n\n

                  \"enter<\/a><\/p>\n","answers":[{"AnswerId":"39303904","CreationDate":"2016-09-03T06:25:31.033","ParentId":null,"OwnerUserId":"4449586","Title":null,"Body":"

                  There are some non-python dependencies for Keras, so pip won't install them and fails if they are not found. The error here is related to fortran compiler and can be resolved by installing for example gfortran<\/code>. But there would be probably other packages that you miss.<\/p>\n\n

                  I recommend taking steps in installation guide of theano on OS X<\/a> because for now keras depends on theano. If you take the steps to have a working installation of theano there shouldn't be any problem installing Keras with pip.<\/p>\n"}]} {"QuestionId":39304912,"AnswerCount":0,"Tags":"","CreationDate":"2016-09-03T08:34:36.160","AcceptedAnswerId":null,"OwnerUserId":6790234.0,"Title":"How to use Tensorflow to implement an input delay neural network","Body":"

                  I want to implement an input delay neural network, but I don't know how to realize the tap delay in the input part, as shown in the picture below.<\/p>\n\n

                  \"Network<\/p>\n","answers":[]} {"QuestionId":39304995,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-03T08:43:48.243","AcceptedAnswerId":null,"OwnerUserId":1611416.0,"Title":"Reuse large dequeued variable in Tensorflow","Body":"

                  I have a large tensor (some hundreds of megabytes) that is dequeued.<\/p>\n\n

                  <\/pre>\n\n

                  I'd like to reuse the variable on subsequent calls to , but I'm not sure how to do with the existing tensorflow variable sharing<\/a> paradigm. requires an initializer, so this is the wrong way to do it but illustrates what I'm trying to do:<\/p>\n\n

                  <\/pre>\n\n

                  EDIT 1<\/strong>: Here is the a more complete example -- I'd like to cache and in <\/p>\n\n

                  <\/pre>\n","answers":[{"AnswerId":"39312666","CreationDate":"2016-09-04T01:02:55.377","ParentId":null,"OwnerUserId":"4744283","Title":null,"Body":"

                  I don't sure that I understand your question. <\/p>\n\n

                  If you just want to get Tensor<\/code> variable you need tf.get_variable<\/code> after scope.reuse_variables()<\/code>:<\/p>\n\n

                  with tf.scope('my_scope') as scope:\n    scope.reuse_variables()\n    large_var = tf.get_variable('my_large_var')\n    #do something\n<\/code><\/pre>\n\n

                  If you need to evaluate multiple variables I suppose you need sess.run([var1, var2])<\/code> (I'm not sure but in cifair10 example there is string _, loss_value = sess.run([train_op, loss])<\/code>).<\/p>\n"}]} {"QuestionId":39305174,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-03T09:05:27.323","AcceptedAnswerId":39305493.0,"OwnerUserId":6080827.0,"Title":"what does x = tf.placeholder(tf.float32, [None, 784]) means?","Body":"

                  I know basic use for tf.placeholder:<\/p>\n\n

                  <\/pre>\n\n

                  I know the second parameter is about shape<\/strong>. However I don't know what is that mean when the first one is None<\/strong> in the shape. ex:[None,784].<\/p>\n","answers":[{"AnswerId":"39305493","CreationDate":"2016-09-03T09:43:57.607","ParentId":null,"OwnerUserId":"2891324","Title":null,"Body":"

                  From the tutorial: Deep MNIST for Experts\n<\/a><\/p>\n\n

                  \n

                  Here we assign it a shape of [None, 784], where 784 is the dimensionality of a single flattened 28 by 28 pixel MNIST image, and None indicates that the first dimension, corresponding to the batch size, can be of any size<\/strong>. <\/p>\n<\/blockquote>\n"}]} {"QuestionId":39306167,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-03T11:01:52.273","AcceptedAnswerId":39333531.0,"OwnerUserId":2191652.0,"Title":"What is the order of mean values in Caffe's train.prototxt?","Body":"

                  In my Caffe I'm doing some input data transformation, like this:<\/p>\n\n

                  <\/pre>\n\n

                  Now I want to store a modified version of my input images such that certain image regions are set to those mean values. The rational is that those regions are then set to 0 during mean subtraction. However I don't know what the order of channels is that caffe expects in such a prototxt file and I couldn't look it up in the caffe code either.
                  \nDoes someone now whether the 3 values given above are in RGB or BGR order? <\/p>\n\n

                  (I'm not sure since caffe is using opencv internally which stores images in the unusual BGR format)<\/p>\n","answers":[{"AnswerId":"39333531","CreationDate":"2016-09-05T15:15:28.663","ParentId":null,"OwnerUserId":"395857","Title":null,"Body":"

                  https:\/\/groups.google.com\/forum\/#!topic\/caffe-users\/9opH6AW3Irw<\/a> (answer by Evan Shelhamer): <\/p>\n\n

                  \n

                  [Mean] values are BGR for historical reasons -- the original CaffeNet training lmdb was made with image processing by OpenCV which defaults to BGR order.<\/p>\n<\/blockquote>\n"}]} {"QuestionId":39307108,"AnswerCount":2,"Tags":"","CreationDate":"2016-09-03T12:52:48.510","AcceptedAnswerId":39307302.0,"OwnerUserId":6631334.0,"Title":"Placeholder_2:0 is both fed and fetched","Body":"

                  When I run this code: <\/p>\n\n

                  <\/pre>\n\n

                  I get this error: <\/p>\n\n

                  <\/p>\n\n

                  I'm not sure what I'm doing wrong here. Why does this not work?<\/p>\n","answers":[{"AnswerId":"39307309","CreationDate":"2016-09-03T13:13:38.817","ParentId":null,"OwnerUserId":"6631334","Title":null,"Body":"

                  I found out what I was doing wrong. <\/p>\n\n

                  x<\/code> is a placeholder -- it holds information and evaluating x does not do anything. I forgot that vital piece of information and proceeded to attempt to run the Tensor x<\/code> inside sess.run()<\/code><\/p>\n\n

                  Code similar to this would work if, say, there was another Tensor y<\/code> that depended on x<\/code> and I ran that like sess.run([y], feed_dict=feed_dict)<\/code><\/p>\n"},{"AnswerId":"39307302","CreationDate":"2016-09-03T13:12:35.183","ParentId":null,"OwnerUserId":"2658050","Title":null,"Body":"

                  Are you sure this code covers what you are trying to achieve? \nYou ask to read out whatever you pass through. This is not a valid call in tensorflow. If you want to pass through values and do nothing with it (what for?) you should have an identity operation.<\/p>\n\n

                  x = tf.placeholder(tf.int32, shape=(None, 3))\ny = tf.identity(x)\n\nwith tf.Session() as sess: \n    feed_dict = dict()\n    feed_dict[x] = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])\n    input = sess.run([y], feed_dict=feed_dict)\n<\/code><\/pre>\n\n

                  The problem is \"feeding\" actually kind of overwrites whatever your op generates<\/strong>, thus you cannot fetch it at this moment (since there is nothing being really produced by this particular op anymore). If you add this identity op, you correctly feed (override x) do nothing with the result (identity) and fetch it (what identity produces, which is whatever you feeded as an output of x)<\/p>\n"}]} {"QuestionId":39308273,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-03T14:59:09.257","AcceptedAnswerId":39309565.0,"OwnerUserId":6783647.0,"Title":"Getting shape dimension errors with a simple regression using Keras","Body":"

                  I am trying to train a simple regression network on Keras. The input of the network (X_test) are 100 images, and the output another 100. The problem is that I am getting a shape error: I have played with another network architecture, activations,... and the error is still there.<\/p>\n\n

                  Here I place my code:<\/p>\n\n

                  <\/pre>\n\n

                  When I run the script, I get the following error:<\/p>\n\n

                  <\/pre>\n\n

                  The X_train and y_train shapes are:<\/p>\n\n

                  <\/pre>\n\n

                  It is my first time doing regression in Keras and I don't know what I am doing wrong.<\/p>\n\n

                  Thank you for your time!<\/p>\n","answers":[{"AnswerId":"39309565","CreationDate":"2016-09-03T17:30:33.643","ParentId":null,"OwnerUserId":"4116272","Title":null,"Body":"

                  The output shape of your model is (None, 256, 7, 7). That should match with the shape of y_train. To get the shape (None, 3, 32, 32), you'd need to change your architecture, possibly by adding upsampling layers. See https:\/\/blog.keras.io\/building-autoencoders-in-keras.html<\/a> for example.<\/p>\n"}]} {"QuestionId":39309327,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-03T17:01:16.147","AcceptedAnswerId":null,"OwnerUserId":4962207.0,"Title":"Why does this piece of code gets slower with time?","Body":"

                  I'm trying to preprocess my images adding them to a 4D array. It starts off right but it gets slower with time, I thought this was due to my CPU but I tried running it on a GPU on the cloud and it still gets slower. Is this due to RAM? How can I optimize this to run faster?<\/p>\n\n

                  <\/pre>\n\n

                  I also ran pyinstrument and I get this<\/p>\n\n

                  <\/pre>\n","answers":[{"AnswerId":"39309525","CreationDate":"2016-09-03T17:25:34.297","ParentId":null,"OwnerUserId":"14660","Title":null,"Body":"

                  I don't know much about TensorFlow, but I believe the problem is process_image<\/code> is using a bunch of globals, particularly tf<\/code>. Every time it's called you're running TensorFlow on an ever increasing set of images. First there's 1, then 2, then 3, then 4, 5, 6, ...<\/a><\/p>\n\n

                  1 + 2 + 3 + 4 + 5 + ... + n = n ( n + 1 ) \/ 2\n<\/code><\/pre>\n\n

                  So by 100 images you've actually processed 5,050. This is an O(n2<\/sup>) algorithm which means its runtime (and, in this case, memory) will grow exponentially as the number of images increases.<\/p>\n\n

                  Again, I don't know much about TensorFlow, but perhaps leaving calling sess.run<\/code> for the end makes more sense? Though you appear to be interested in the intermediate results?<\/p>\n\n

                  And, as a very good rule of thumb, avoid globals. It's hard to tell them apart from local variables, they break the neat encapsulation of functions making the program hard to understand, and they and lead to accumulation problems like this.<\/p>\n"}]} {"QuestionId":39309367,"AnswerCount":2,"Tags":"","CreationDate":"2016-09-03T17:05:58.473","AcceptedAnswerId":39479736.0,"OwnerUserId":3319713.0,"Title":"Unable to feed value for placeholder tensor","Body":"

                  I have written a simple version bidirectional lstm for sentence classification. But it keeps giving me \"You must feed a value for placeholder tensor 'train_x'\" error and it seems this come from the variable initialization step. <\/p>\n\n

                  <\/pre>\n\n

                  And the class code (in a different directory):<\/p>\n\n

                  <\/pre>\n\n

                  The output (including the error):<\/strong><\/p>\n\n

                  <\/pre>\n\n

                  I have tried move the and placeholder initialization before and feed them to RNNClassifier() as two args but it still give the same error. Why?<\/p>\n","answers":[{"AnswerId":"39479736","CreationDate":"2016-09-13T22:10:34.650","ParentId":null,"OwnerUserId":"3574081","Title":null,"Body":"

                  It looks like the problem is in this method, in RNNClassifier<\/code>:<\/p>\n\n

                  def batch_data(self):\n    # ...\n    batched_inputs, batched_labels = tf.train.batch(\n        tensors=[self._train_x, self._train_y],\n        batch_size=self.params.batch_size,\n        dynamic_pad=True,\n        enqueue_many=True,\n        name='batching')\n<\/code><\/pre>\n\n

                  The two tensor arguments to tf.train.batch()<\/code><\/a> are self._train_x<\/code> and self._train_y<\/code>. In the RNNClassifier<\/code> constructor, it seems like you create these as tf.placeholder()<\/code><\/a> tensors:<\/p>\n\n

                  def __init__(self, FLAGS):\n    # ...\n    with tf.device(\"\/cpu:0\"):\n        self.train_x = tf.placeholder(tf.int32, [6248, 42], name='train_x')\n        self.train_y = tf.placeholder(tf.int32, [6248, 3], name='train_y')\n<\/code><\/pre>\n\n

                  ...though I'm assuming that the difference between self._train_x<\/code> and self.train_x<\/code> is a copy-paste error, because self._train_x<\/code> doesn't seem to be defined anywhere else.<\/p>\n\n

                  Now, one of the surprising things about tf.train.batch()<\/code> is that it consumes its inputs in a completely separate thread, called a \"queue runner\", and started when you call tf.train.start_queue_runners()<\/code><\/a>. This thread calls Session.run()<\/code><\/a> on a subgraph that depends on your placeholders, but doesn't know how to feed these placeholders, so it is this call that fails, leading to the error you are seeing.<\/p>\n\n

                  How then should you fix it? One option would be to use a \"feeding queue runner\"<\/a>, for which there is experimental support. A simpler option would be to use the tf.train.slice_input_producer()<\/code><\/a> to produce slices from your input data, as follows:<\/p>\n\n

                  def batch_data(self, train_x, train_y):\n    input_slice, label_slice = tf.train.slice_input_producer([train_x, train_y])\n    batched_inputs, batched_labels = tf.train.batch(\n        tensors=[input_slice, label_slice],\n        batch_size=self.params.batch_size,\n        dynamic_pad=False,   # All rows are the same shape.\n        enqueue_many=False,  # tf.train.slice_input_producer() produces one row at a time.\n        name='batching')\n    return batched_inputs, batched_labels\n\n# ...\n# Create batches from the entire training data, where `array_input` and\n# `array_labels` are two NumPy arrays.\nbatched_inputs, batched_labels = model.batch_data(array_input, array_labels)\n<\/code><\/pre>\n"},{"AnswerId":"39440287","CreationDate":"2016-09-11T20:21:28.980","ParentId":null,"OwnerUserId":"3319713","Title":null,"Body":"

                  This is what I did.. <\/p>\n\n

                  I could change the way I initialised my input variables as:<\/p>\n\n

                  data = load_data(FLAGS.data)\nmodel = RNNClassifier(FLAGS, data)\ninit = tf.initialize_all_variables()\n\nwith tf.Session() as sess:\n    sess.run(init)\n    coord = tf.train.Coordinator()\n    threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n    for epoch in range(FLAGS.max_max_epoch):\n        sess.run(model.train_step)\n        loss, acc = sess.run([model.mean_cost, model.accuracy])\n        print(\"Epoch {:2d}: Loss = {:.6f}; Training Accuracy = {:.5f}\".format(epoch+1, loss, acc))\n    print()\n    coord.request_stop()\n    coord.join(threads)\n<\/code><\/pre>\n\n

                  And in RNNClassifier class I could replace <\/p>\n\n

                      self.train_x = tf.placeholder(tf.int32, [6248, 42], name='train_x')\n    self.train_y = tf.placeholder(tf.int32, [6248, 3], name='train_y')\n    self.embedding_placeholder = tf.placeholder(tf.float32, [1193515, 100])\n<\/code><\/pre>\n\n

                  (and remove use_embedding()<\/code>) to<\/p>\n\n

                  def __init__(self, FLAGS, data):\n    self._train_x = tf.convert_to_tensor(data.train_x, dtype=tf.int32)\n    self._train_y = tf.convert_to_tensor(data.train_y, dtype=tf.int32)\n    embedding = tf.get_variable(\"embedding\", shape=self.embedding_shape, trainable=False)\n    self.embedding_init = embedding.assign(data.glove_vec)\n<\/code><\/pre>\n\n

                  This way everything is initialised with RNNClassifier(FLAGS, data)<\/code> before making the call to the queue runners. <\/p>\n\n

                  I still don't know why the previous way aka using placeholders, didn't work. I have checked the dtype and data shape, they all match. This post<\/a> seems to have a similar problem and the \"answer\" suggests to replace placeholder with tf.Variable. I have tried this -> input values can now be fed but obvs it doesn't work as placeholders do and only feed the initialised values..<\/p>\n\n

                  UPDATE:<\/strong> I think the error might be caused by operating inputs batching in the RNNClassifier class, that somehow effected feeding input data into the graph (again please correct me if you know the cause to the error, thanks!<\/em>). I have instead relocated my batching and embedding functions onto my main code before initialising my session, this way I think it makes sure all inputs are defined to the main pipeline and batching&prefetching would be handled inside the tf graph (by not using placeholders).<\/p>\n\n

                  Here's my code:<\/p>\n\n

                  def batch(x, y):\n    with tf.device(\"\/cpu:0\"):\n        x = tf.convert_to_tensor(x, dtype=tf.int32)\n        y = tf.convert_to_tensor(y, dtype=tf.int32)\n        batched_x, batched_y = tf.train.batch(\n            tensors=[x, y],\n            batch_size=50,\n            dynamic_pad=True,\n            enqueue_many=True,\n            name='batching'\n            )\n    return (batched_x, batched_y)\n\n\ndef embed(df):\n    with tf.device(\"\/cpu:0\"), tf.variable_scope(\"embed\"):\n        embedding = tf.get_variable(\"embedding\", shape=df.embed_shape, trainable=False)\n        embedding_init = embedding.assign(df.embed_vec)\n    return embedding_init\n\n\ndata = load_data(FLAGS.data)\npretrained_embed = embed(data)\nbatched_train_x, batched_train_y = batch(data.train_x, data.train_y)\nbatched_test_x, batched_test_y = batch(data.train_x, data.train_y)\n\nmodel = RNNClassifier(FLAGS, pretrained_embed)\nlogits = model.inference(batched_train_x)\ntest_pred = model.inference(batched_test_x, reuse=True)\nloss = model.loss(logits, batched_train_y)\ntest_loss = model.loss(test_pred, batched_test_y)\ntrain_op = model.training(loss[0])\n\ninit = tf.group(tf.initialize_all_variables(),\n                tf.initialize_local_variables())\n\n\nwith tf.Session() as sess:\n    t0 = time.time()\n    sess.run(init)\n    coord = tf.train.Coordinator()\n    threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n    np.random.seed(FLAGS.random_state)\n    for epoch in range(FLAGS.max_max_epoch):\n        _, output = sess.run([train_op, loss])\n        loss_value, acc = output\n        print(\"Epoch {:2d}: Loss = {:.6f}; Training Accuracy = {:.5f}\".format(epoch+1, loss_value, acc))\n    print()\n    coord.request_stop()\n    coord.join(threads)\n<\/code><\/pre>\n\n

                  And the RNNClassifier:<\/p>\n\n

                  class RNNClassifier:\n\n    def __init__(self, FLAGS, embedding_init):\n        self.batch_size = FLAGS.batch_size\n        self.num_hidden = FLAGS.num_hidden\n        self.num_classes = FLAGS.num_classes\n        self.seq_len = FLAGS.seq_len\n        self.embedding_init = embedding_init\n\n    def inference(self, batched_inputs, reuse=None):\n        embed_inputs = tf.nn.embedding_lookup(self.embedding_init, tf.transpose(batched_inputs))\n\n        with tf.variable_scope('hidden', reuse=reuse):\n            with tf.variable_scope('forward_lstm'):\n                lstm_fw_cell = tf.nn.rnn_cell.LSTMCell(num_units=self.num_hidden, use_peepholes=False, \n                                                    activation=tf.nn.relu, forget_bias=0.0, \n                                                    initializer=tf.random_uniform_initializer(-1.0, 1.0),\n                                                    state_is_tuple=True)\n                lstm_fw_cell = tf.nn.rnn_cell.DropoutWrapper(cell=lstm_fw_cell, input_keep_prob=0.7)\n\n            with tf.variable_scope('backward_lstm'):\n                lstm_bw_cell = tf.nn.rnn_cell.LSTMCell(num_units=self.num_hidden, use_peepholes=False, \n                                                    activation=tf.nn.relu, forget_bias=0.0, \n                                                    initializer=tf.random_uniform_initializer(-1.0, 1.0),\n                                                    state_is_tuple=True)\n                lstm_bw_cell = tf.nn.rnn_cell.DropoutWrapper(cell=lstm_bw_cell, input_keep_prob=0.7)\n\n            fw_initial_state = lstm_fw_cell.zero_state(self.batch_size, tf.float32)\n            bw_initial_state = lstm_bw_cell.zero_state(self.batch_size, tf.float32)\n\n            rnn_outputs, output_state_fw, output_state_bw  = tf.nn.bidirectional_rnn(\n                cell_fw=lstm_fw_cell,\n                cell_bw=lstm_bw_cell,\n                inputs=tf.unpack(embed_inputs),\n                # sequence_length=self.seq_len,\n                initial_state_fw=fw_initial_state,\n                initial_state_bw=bw_initial_state\n                )\n\n        with tf.variable_scope('output', reuse=reuse):\n            with tf.variable_scope('softmax'):\n                W = tf.get_variable('W', [self.num_hidden*2, self.num_classes],\n                                    initializer=tf.truncated_normal_initializer(stddev=0.1))\n                b = tf.get_variable('b', [self.num_classes], initializer=tf.constant_initializer(0.1))\n            logits = tf.matmul(rnn_outputs[-1], W) + b\n        return logits\n\n\n    def loss(self, logits, labels):\n        cost = tf.nn.softmax_cross_entropy_with_logits(logits, tf.cast(labels, tf.float32))\n        # self.total_cost = tf.reduce_sum(self.cost)\n        mean_cost = tf.reduce_mean(cost)\n        correct_pred = tf.equal(tf.argmax(logits, 1), tf.argmax(labels, 1))\n        accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n        return mean_cost, accuracy\n\n\n    def training(self, cost):\n        optimizer = tf.train.AdamOptimizer(learning_rate=0.001)\n        train_op = optimizer.minimize(cost)\n        return train_op\n<\/code><\/pre>\n\n

                  On a side note, I wish the Tensorflow community on stackoverflow would be more active..<\/p>\n"}]} {"QuestionId":39309388,"AnswerCount":3,"Tags":"","CreationDate":"2016-09-03T17:08:28.497","AcceptedAnswerId":39343910.0,"OwnerUserId":1118236.0,"Title":"Keras RNN loss does not decrease over epoch","Body":"

                  I built a RNN using Keras. The RNN is used to solve a regression problem:<\/p>\n\n

                  <\/pre>\n\n

                  The whole process looks fine. But the loss stays the exact same over epochs. <\/p>\n\n

                  <\/pre>\n\n

                  I do NOT think it is normal. Do I miss something?<\/p>\n\n


                  \n\n

                  UPDATE:\nI find that all predictions are always zero after all epochs. This is the reason why all RMSDs are all the same because the predictions are all the same, i.e. 0. I checked the training y. It only contains just a few zeros. So it is not due to data imbalance. <\/p>\n\n

                  So now I am thinking if it is because of the layers and activation that I am using.<\/p>\n","answers":[{"AnswerId":"39343910","CreationDate":"2016-09-06T08:15:11.150","ParentId":null,"OwnerUserId":"5443758","Title":null,"Body":"

                  Your RNN functions seems to be ok.<\/p>\n\n

                  The speed of reduction in loss depends on optimizer and learning rate.<\/p>\n\n

                  Any how you are using decay rate 0.9. try with bigger learning rate, any how it is going to decrease with 0.9 rate.<\/p>\n\n

                  Try out other optimizers with different learning rates\nOther optimizers available with keras: https:\/\/keras.io\/optimizers\/<\/a><\/p>\n\n

                  Many times, some optimizers work well on some data sets while some may fails.<\/p>\n"},{"AnswerId":"45651106","CreationDate":"2017-08-12T13:58:14.840","ParentId":null,"OwnerUserId":"4196231","Title":null,"Body":"

                  Have you tried changing activation function from relu to softmax?<\/p>\n\n

                  Relu activation has the tendency to diverge. However, if initializing the weight with eigenmatrix may result in a better convergence.<\/p>\n"},{"AnswerId":"45683440","CreationDate":"2017-08-14T21:38:44.383","ParentId":null,"OwnerUserId":"8290497","Title":null,"Body":"

                  Since you are using RNNs for regression problem (not for classification), you should use 'linear' activation at the last layer.<\/p>\n\n

                  In your code, <\/p>\n\n

                  model.add(TimeDistributed(Dense(output_dim=1, activation='relu'))) # sequence labeling \n<\/code><\/pre>\n\n

                  change to activation='linear'<\/code> instead of 'relu'<\/code>.<\/p>\n\n

                  If it doesn't work, remove activation='relu'<\/code> in second layer.<\/p>\n\n

                  Also learning rate for rmsprop usually ranges from 0.1 to 0.0001. <\/p>\n"}]} {"QuestionId":39314509,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-04T07:22:46.387","AcceptedAnswerId":42904439.0,"OwnerUserId":4892685.0,"Title":"Keras dependencies needed for prediction only in AWS Lambda","Body":"

                  I'm trying to package my trained Keras classifier models (Theano backend) and their HDF5 weights as AWS Lambda functions that process classification requests coming from an API. Lambda has a 50MB limit for the zip file that contains the function code and<\/strong> dependencies, so I'm wondering whether any of the dependencies needed for training are not needed for prediction, so that I can leave them out of the Lambda zip file. Right now I'm just squeaking by at ~45MB with all dependencies (numpy, scipy, etc.), but I'd like to drop any dead weight if possible.<\/p>\n","answers":[{"AnswerId":"42904439","CreationDate":"2017-03-20T13:07:59.610","ParentId":null,"OwnerUserId":"810492","Title":null,"Body":"

                  You can strip your binaries to save space<\/p>\n\n

                  find . | xargs strip\n<\/code><\/pre>\n"}]}
                  {"QuestionId":39314946,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-04T08:23:58.640","AcceptedAnswerId":null,"OwnerUserId":3395249.0,"Title":"Why does my linear regression get nan values instead of learning?","Body":"

                  I'm running the following code:<\/p>\n\n

                  <\/pre>\n\n

                  and that is result follow <\/p>\n\n

                  <\/pre>\n\n

                  I don't understand why this result is ?<\/p>\n\n

                  If i change the initial data to this<\/p>\n\n

                  <\/pre>\n\n

                  Then it was working no problem. Why is that?<\/p>\n","answers":[{"AnswerId":"39315068","CreationDate":"2016-09-04T08:40:53.877","ParentId":null,"OwnerUserId":"2001031","Title":null,"Body":"

                  You are overflowing float32 because the learning rate is too high for your problem, and instead of converging the weight variable (W<\/code>) is oscillating towards larger and larger magnitudes on each step of gradient descent.<\/p>\n\n

                  If you change<\/p>\n\n

                  a = tf.Variable(0.1)\n<\/code><\/pre>\n\n

                  to <\/p>\n\n

                  a = tf.Variable(0.001)\n<\/code><\/pre>\n\n

                  the weights should converge better. You will probably want to increase number of iterations (to ~ 50000) too.<\/p>\n\n

                  Picking a good learning rate is often the first challenge when implementing or using a machine learning algorithm. Getting increased loss values instead of converging to a minimum is usually a sign that learning rate is too high.<\/p>\n\n

                  In your case the specific problem of fitting to the line is made more vulnerable to diverging weights when you use larger magnitudes in the training data. This is one reason why it is common to normalise data prior to training in e.g. neural networks.<\/p>\n\n

                  In addition your starting weight and bias are given a very large range, which means they can be very far from ideal values and have very large loss values and gradients at the start. Picking a good range for initial values is another critical thing to get right as you look at more advanced learning algorithms.<\/p>\n"}]} {"QuestionId":39315197,"AnswerCount":1,"Tags":"

                  I am very unfamiliar with Caffe. My task is to train an autoencoder net on image pairs, given in .tif format, where one is a grayscale image of nerves, and the other is the corresponding binary mask which shows if a certain structure is present on the image or not. I have these in the same \"train\" folder. What I would like to accomplish, is a meaningful experiment with these images (segmentation, classification, it is not specified). My first problem is that I do not know how to feed the images into the net without an existing train.txt. Can I use the images directly, or another format like lmdb, hdf5 needed? Any suggestion is appreciated.<\/p>\n","answers":[{"AnswerId":"39315847","CreationDate":"2016-09-04T10:15:06.197","ParentId":null,"OwnerUserId":"3553155","Title":null,"Body":"

                  you can accomplish it with simple classification (existing like alexnet, googlenet, lenet). You can use only the binary mask or gray scale image and the class name to do this. Nvidia Digits is a good graphical tool to make the pair dataset and learning....<\/p>\n\n

                  Please see this link:<\/p>\n\n

                  https:\/\/developer.nvidia.com\/digits<\/a><\/p>\n"}]} {"QuestionId":39315270,"AnswerCount":5,"Tags":"","CreationDate":"2016-09-04T09:05:24.990","AcceptedAnswerId":null,"OwnerUserId":257705.0,"Title":"ImportError: No module named 'theano'","Body":"

                  I have installed (\/library\/python\/2.7\/site-packages) theano on my mac and still get this error.<\/p>\n\n

                  My code is<\/strong><\/p>\n\n

                  <\/pre>\n\n

                  and the error<\/strong><\/p>\n\n

                  <\/pre>\n\n

                  I did install theano using pip install theano for python 2.7. <\/p>\n\n

                  Any idea on why its throwing up the error.<\/p>\n\n

                  Also I installed Anaconda and it throws the same error as working on idle.<\/p>\n","answers":[{"AnswerId":"42208720","CreationDate":"2017-02-13T16:19:00.467","ParentId":null,"OwnerUserId":"7558750","Title":null,"Body":"

                  I had similar issue,\nmy problem was i messed up (i am very new with python) with python bins,\nso i had 3 versions :\n-- os level\n-- anaconda\n-- anaconda with virtual env <\/p>\n\n

                  as being not aware some packegs\/updates i was doing on one of above options, and theano was not working, finally realized all this mees i have created, and using virtual env version is wrokign for me<\/p>\n"},{"AnswerId":"44961466","CreationDate":"2017-07-07T02:05:18.667","ParentId":null,"OwnerUserId":"7305434","Title":null,"Body":"

                  I had similiar problem too,I tried serval methods,but not work.\nLast,this commond help me.\nyou can try:<\/p>\n\n

                  \n

                  pip install -r\n https:\/\/raw.githubusercontent.com\/Lasagne\/Lasagne\/v0.1\/requirements.txt<\/a><\/p>\n \n

                  pip install -r\n https:\/\/raw.githubusercontent.com\/Lasagne\/Lasagne\/master\/requirements.txt<\/a><\/p>\n \n

                  pip install https:\/\/github.com\/Lasagne\/Lasagne\/archive\/master.zip<\/a><\/p>\n \n

                  pip install -r\n https:\/\/raw.githubusercontent.com\/dnouri\/kfkd-tutorial\/master\/requirements.txt<\/a><\/p>\n<\/blockquote>\n"},{"AnswerId":"44219304","CreationDate":"2017-05-27T16:42:48.100","ParentId":null,"OwnerUserId":"2432389","Title":null,"Body":"

                  I had similiar problem, i fixed it with uninstalling all versions of Python (which were overshadowing each other), and then installing latest version 'Windows x86-64 executable installer' from here<\/a>.<\/p>\n"},{"AnswerId":"39317160","CreationDate":"2016-09-04T12:59:35.390","ParentId":null,"OwnerUserId":"5177604","Title":null,"Body":"

                  I had the same problem trying to install pygame, i'm using python 3.4.1 so I'm not 100% sure this will work for you<\/p>\n\n

                  Here is my folder: C:\\Python34\\Scripts\"enter<\/a><\/p>\n\n

                  The problem:<\/strong>\nThis will of course be different for you, but this is what I did anyway:\nI did pip install pygame<\/code> and it seemed to work but when I tried import pygame<\/code> I got the same error as you<\/p>\n\n

                  My solution:<\/strong> \ninstead of installing pygame with pip, I did pip3 install pygame<\/code> and it worked! so for you, look at what files you have in this folder \/library\/python\/2.7\/site-packages<\/strong> and try all of them, try pip2 install theano<\/code>, try pip2.7 install theano<\/code>, try pip3 install theano<\/code>, try everything!<\/p>\n\n

                  Again I'm not certain this will work for python 2.7, but its worth a try :)<\/p>\n"},{"AnswerId":"45449567","CreationDate":"2017-08-02T00:23:41.617","ParentId":null,"OwnerUserId":"8402528","Title":null,"Body":"

                  On windows 7, Python 3.6.0 - Anaconda 4.3.1 (64bits)  <\/pre>\n\n
                  >pip install theano   \u00a1thanks!<\/pre>\n\n

                  Used command view image clic<\/a><\/p>\n"}]} {"QuestionId":39315920,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-04T10:24:28.757","AcceptedAnswerId":null,"OwnerUserId":6672068.0,"Title":"Use .ckpt and .meta -files to make predictions with Inception in TensorFlow","Body":"

                  I used the Inception-library (Tensorflow\/models\/Inception-tutorial on github)<\/em>, \nfeeding selfmade TFRecord-files to imagenet_train.py, and ended up with a 7Gb directory containing .ckpt and .meta files.<\/p>\n\n

                  How do i use them to make actual predictions?(also evaluating, testing, testing with actual .jpg files<\/strong>, continue the training)<\/p>\n\n

                  What would be the next steps?Are there dummy-friendly examples(tutorials)?<\/p>\n\n

                  [I know there\u00b4s a thread with a similar name, but it contains barely a question nor answers.]<\/em><\/p>\n","answers":[{"AnswerId":"39333832","CreationDate":"2016-09-05T15:34:54.370","ParentId":null,"OwnerUserId":"3893224","Title":null,"Body":"

                  https:\/\/www.tensorflow.org\/versions\/r0.10\/how_tos\/variables\/index.html#restoring-variables<\/a> provides pretty much everything you should need.<\/p>\n\n

                  The code there is:<\/p>\n\n

                  # Add ops to save and restore all the variables.\nsaver = tf.train.Saver()\n\n# Later, launch the model, use the saver to restore variables from disk, and\n# do some work with the model.\nwith tf.Session() as sess:\n  # Restore variables from disk.\n  saver.restore(sess, \"\/tmp\/model.ckpt\")\n  print(\"Model restored.\")\n  # Do some work with the model\n  ...\n<\/code><\/pre>\n\n

                  So at the ...<\/code> part, you could load your .jpegs and feed them into the network with placeholders and feeddicts. <\/p>\n"}]} {"QuestionId":39316440,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-04T11:30:05.930","AcceptedAnswerId":39316983.0,"OwnerUserId":6788616.0,"Title":"How to use unknown dimension in ops calculations with TF","Body":"

                  For example > I've an Theano code, which works (T == Theano): <\/p>\n\n

                  <\/pre>\n\n

                  I don't really know how to use variable N in TF op's calculation if it's an unknown dimension.<\/p>\n","answers":[{"AnswerId":"39316983","CreationDate":"2016-09-04T12:36:14.140","ParentId":null,"OwnerUserId":"2891324","Title":null,"Body":"

                  In Tensorflow you don't need to know the number of element you'll process during graph execution. You have to delegate this task to tensorflow, using the tf.reduce_*<\/code><\/a> operations.<\/p>\n\n

                  \n

                  Reduction<\/p>\n \n

                  TensorFlow provides several operations that you can use to perform common math computations that reduce various dimensions of a tensor.<\/p>\n<\/blockquote>\n\n

                  The MSE function you defined in Theano can be defined in Tensorlow easily;<\/p>\n\n

                  mse = tf.reduce_mean(tf.pow(tf.sub(ytarg, ytarg), 2.0))\n<\/code><\/pre>\n"}]}
                  {"QuestionId":39317389,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-04T13:25:56.320","AcceptedAnswerId":null,"OwnerUserId":6631334.0,"Title":"Saving weights after model has finished training - Tensorflow","Body":"

                  In Tensorflow, how can I save the weights and all other variables of the program after it has finished training? I would like to be able to use the model I trained later on. Thanks in advance. <\/p>\n","answers":[{"AnswerId":"39356600","CreationDate":"2016-09-06T19:38:26.630","ParentId":null,"OwnerUserId":"5587428","Title":null,"Body":"

                  You can define a saver object like this:<\/p>\n\n

                  saver = tf.train.Saver(max_to_keep=5, keep_checkpoint_every_n_hours=1)\n<\/code><\/pre>\n\n

                  In this case, the saver is configured to keep the five most recent checkpoints and also to keep a checkpoint every hour during training.<\/p>\n\n

                  The saver can then be called periodically in your main training loop with a call such as the following. <\/p>\n\n

                  sess=tf.Session()\n\n    ...\n\n    # Save the model every 100 iterations\n    if step % 100 == 0:\n        saver.save(sess, \".\/model\", global_step=step)\n<\/code><\/pre>\n\n

                  In this example the saver is saving a checkpoint into the .\/model subdirectory every 100 training steps. The optional parameter global_step<\/code> appends this value to the checkpoint filenames.<\/p>\n\n

                  The model weights and other values may be restored at a later time for additional training or inference by the following:<\/p>\n\n

                          saver.restore(sess, path.model_checkpoint_path)\n<\/code><\/pre>\n\n

                  There are a variety of other useful variants and options. A good place to start learning about them is the TF how-to on variable creation, storage and retrieval here<\/a><\/p>\n"}]} {"QuestionId":39317485,"AnswerCount":0,"Tags":"","CreationDate":"2016-09-04T13:35:10.683","AcceptedAnswerId":null,"OwnerUserId":6182430.0,"Title":"Does upgrading to ubuntu 16.04 damage my work?","Body":"

                  I'm currently working on Ubuntu Linux 14.04, and most of my work is about python development (deep learning using 'caffe').<\/p>\n\n

                  Could upgrading to Ubuntu 16.04 create incompatibilities with existing packages like 'caffe' or 'Anaconda' (for python 2)? <\/p>\n","answers":[]} {"QuestionId":39317825,"AnswerCount":0,"Tags":"","CreationDate":"2016-09-04T14:13:31.437","AcceptedAnswerId":null,"OwnerUserId":3854058.0,"Title":"Performance of tf inside jupyter notebooks vs. command line","Body":"

                  I am noticing quite significant performance (speed) differences when running tensorflow code from inside a jupyter notebook, versus running it as a script from the command line. <\/p>\n\n

                  For example, below are the results of running the MNIST CNN tutorial (https:\/\/www.tensorflow.org\/code\/tensorflow\/examples\/tutorials\/mnist\/fully_connected_feed.py<\/a>)<\/p>\n\n

                  Setup:<\/strong> <\/p>\n\n

                  AWS instance with 32 Xeon-CPUS, 62GB memory, 4 K520 GPUS (4GB mem)<\/p>\n\n

                  Linux: 3.13.0-79 Ubuntu<\/p>\n\n

                  Tensorflow: 0.10.0rc0 (built from sources with GPU support)<\/p>\n\n

                  Python: 3.5.2 |Anaconda custom (64-bit)|<\/p>\n\n

                  CUDA libraries : libcublas.so.7.5 , libcudnn.so.5, libcufft.so.7.5, libcuda.so.1, libcurand.so.7.5 <\/p>\n\n

                  Training steps: 2000<\/p>\n\n

                  Jupyter notebook execution time:<\/strong> <\/p>\n\n

                  This does not<\/em> include time for imports and loading the dataset - just the training phase<\/p>\n\n

                  <\/p>\n\n

                  Command line execution:<\/strong> <\/p>\n\n

                  This is the time for execution of the full script.<\/p>\n\n

                  <\/p>\n\n

                  The GPU is being used in both cases, but utilization is higher (typically 35% during training phase for the command-line vs 2-3% for the notebook version). I even tried manually placing it on different GPUs but that doesn't make a big difference to the notebook execution time.<\/p>\n\n

                  Any ideas \/ suggestions about why this might be ?<\/p>\n","answers":[]} {"QuestionId":39318257,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-04T15:00:03.263","AcceptedAnswerId":null,"OwnerUserId":909515.0,"Title":"lua cjson cannot decode specific unicode char?","Body":"

                  I'm getting the following error from lua cjson when trying to decode a specific unicode char,<\/p>\n\n

                  <\/pre>\n\n

                  by following the source, I can see that train.lua read_json is using cjson under the covers.<\/p>\n\n

                  The unicode escape code in question is \\uda85<\/p>\n\n

                  If I go to https:\/\/www.branah.com\/unicode-converter<\/a> it tells me the character the escape should decode to.<\/p>\n\n

                  The unicode escape was generated using python unichr(55941) and written to a file with PYTHONIOENCODING=UTF-8 via redirection of the python script output.<\/p>\n\n

                  The following demonstrates how the character was generated;<\/p>\n\n

                  <\/pre>\n\n

                  What I am trying to do overall is take a set of integers in the range 0-65535 and using python map them to UTF-8 chars and write them out to a file. Then I would like to use torch-rnn that uses LUA to train an RNN on the sequence of chars. I'm getting the error when attempting to run th train.lua on the files generated by the torch-rnn python scripts\/preprocess.py<\/p>\n","answers":[{"AnswerId":"39320587","CreationDate":"2016-09-04T19:17:01.387","ParentId":null,"OwnerUserId":"909515","Title":null,"Body":"

                  It seems the problem was unicode surrogates, understanding that means I can filter\/switch them for different values. In this use case, thats not such a big problem.<\/p>\n"}]} {"QuestionId":39318586,"AnswerCount":2,"Tags":"","CreationDate":"2016-09-04T15:33:31.290","AcceptedAnswerId":null,"OwnerUserId":1908727.0,"Title":"Tensorflow Android demo: load a custom graph in?","Body":"

                  The Tensorflow Android demo<\/a> provides a decent base for building an Android app that uses a TensorFlow graph, but I've been getting stuck on how to repurpose it for an app that does not do image classification. As it is, it loads in the Inception graph from a .pb file and uses that to run inferences (and the code assumes as such), but what I'd like to do is load my own graph in (from a .pb file), and do a custom implementation of how to handle the input\/output of the graph.<\/p>\n\n

                  The graph in question is from Assignment 6<\/a> of Udacity's deep learning course, an RNN that uses LSTMs to generate text. (I've already frozen it into a .pb file.) However, the Android demo's code is based on the assumption that they're dealing with an image classifier. So far I've figured out that I'll need to change the values of the parameters passed into (called in ), but several of the parameters represent properties of image inputs (e.g. ), which the graph I'm looking to load in doesn't have. Does this mean I'll have to change the native code? More generally, how can I approach this entire issue?<\/p>\n","answers":[{"AnswerId":"46269126","CreationDate":"2017-09-17T21:41:05.137","ParentId":null,"OwnerUserId":"112705","Title":null,"Body":"

                  Good news: it recently became a lot easier to embed a pre-trained TensorFlow model in your Android app. Check out my blog posts here:
                  \n
                  https:\/\/medium.com\/@daj\/using-a-pre-trained-tensorflow-model-on-android-e747831a3d6<\/a> (part 1)\nhttps:\/\/medium.com\/@daj\/using-a-pre-trained-tensorflow-model-on-android-part-2-153ebdd4c465<\/a> (part 2)<\/p>\n\n

                  My blog post goes into a lot more detail, but in summary, all you need to do is:<\/p>\n\n

                    \n
                  1. Include the compile org.tensorflow:tensorflow-android:+<\/code> dependency in your build.gradle. <\/li>\n
                  2. Use the Java TensorFlowInferenceInterface<\/code> class to interface with your model (no need to modify any of the native code).<\/li>\n<\/ol>\n\n

                    The TensorFlow Android demo app has been updated to use this new approach. See TensorFlowImageClassifier.recognizeImage<\/a> for where it uses the TensorFlowInferenceInterface<\/code>. <\/p>\n\n

                    You'll still need to specify some configuration, like the names of the input and output nodes in the graph, and the size of the input, but you should be able to figure that information out from using TensorBoard<\/a>, or inspecting the training script.<\/p>\n"},{"AnswerId":"39358832","CreationDate":"2016-09-06T22:41:27.063","ParentId":null,"OwnerUserId":"992489","Title":null,"Body":"

                    Look at TensorFlow Serving<\/a> for a generic way to load and serve tensorflow models.<\/p>\n"}]} {"QuestionId":39319197,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-04T16:41:03.230","AcceptedAnswerId":39319342.0,"OwnerUserId":4962207.0,"Title":"Can't read data on TensorFlow","Body":"

                    Prior to this I converted my input images to TFRecords files. Now I have the following methods that I've mostly gathered from the tutorials and modified a little:<\/p>\n\n

                    <\/pre>\n\n

                    But when I try to call a batch on iPython\/Jupyter, the process never ends (there appears to be a loop). I call it this way:<\/p>\n\n

                    <\/pre>\n","answers":[{"AnswerId":"39319342","CreationDate":"2016-09-04T16:57:05.013","ParentId":null,"OwnerUserId":"3574081","Title":null,"Body":"

                    It looks like you are missing a call to tf.train.start_queue_runners()<\/code><\/a>, which starts the background threads that drive the input pipeline (e.g. some of these are the threads implied by num_threads=2<\/code> in the call to tf.train.shuffle_batch()<\/code>, and the tf.train.string_input_producer()<\/code><\/a> also requires a background thread). The following small change should unblock things:<\/p>\n\n

                    batch_x, batch_y = inputs(True, 100,1)\ntf.initialize_all_variables.run()    # Initializes variables.\ntf.initialize_local_variables.run()  # Needed after TF version 0.10.\ntf.train.start_queue_runners()       # Starts the necessary background threads.\nprint batch_x.eval()\n<\/code><\/pre>\n"}]}
                    {"QuestionId":39319275,"AnswerCount":2,"Tags":"","CreationDate":"2016-09-04T16:49:27.640","AcceptedAnswerId":null,"OwnerUserId":6426856.0,"Title":"how to build an deep learning image processing server","Body":"

                    I am building am application to process user's photo on server. Basically, user upload a photo to the server and do some filtering processing using deep learning model. Once it's done filter, user can download the new photo. The filter program is based on the deep learning algorithm, using torch framework, it runs on python\/lua. I currently run this filter code on my local ubuntu machine. Just wonder how to turn this into a web service. I have 0 server side knowledge, I did some research, maybe I should use flask or tornado, or other architecture? <\/p>\n","answers":[{"AnswerId":"41001426","CreationDate":"2016-12-06T17:33:22.007","ParentId":null,"OwnerUserId":"5839007","Title":null,"Body":"

                    It does make sense to look at the whole task and how it fits to your actual server, Nginx or Lighttpd or Apache since you are serving static content. If you are going to call a library to create the static content, the integration of your library to your web framework would be simpler if you use Flask but it might be a fit for AWS S3 and Lambda services.\nIt may be worth it to roughly design the whole site and match your content to the tools at hand. <\/p>\n"}]} {"QuestionId":39320274,"AnswerCount":0,"Tags":"","CreationDate":"2016-09-04T18:39:20.093","AcceptedAnswerId":null,"OwnerUserId":806160.0,"Title":"How can calculate Accuracy , Precision and recall in multi-task learning models in tensorflowand slim?","Body":"

                    Here<\/a> described creating loss function in multi-task learning models in :<\/p>\n\n

                    <\/pre>\n\n

                    And here<\/a> described evaluation of a one-task model with :<\/p>\n\n

                    <\/pre>\n\n

                    My problem is that if I want evaluated a multi-task model, how can do this in or or only the mathematical way to solve this?<\/p>\n","answers":[]} {"QuestionId":39320405,"AnswerCount":2,"Tags":"","CreationDate":"2016-09-04T18:53:33.490","AcceptedAnswerId":null,"OwnerUserId":1310660.0,"Title":"Saving wide and deep tensorflow model","Body":"

                    I'm playing with Wide and Deep learning example from Tensorflow<\/a>. I would like to save the trained classifier to be used for prediction tasks later on but I don't really see how. The doesn't have a save method available and pickling the object fails as well.<\/p>\n\n

                    Any ideas how to save it?<\/p>\n","answers":[{"AnswerId":"39332892","CreationDate":"2016-09-05T14:35:58.847","ParentId":null,"OwnerUserId":"3893224","Title":null,"Body":"

                    Are you looking for https:\/\/www.tensorflow.org\/versions\/r0.10\/how_tos\/variables\/index.html#saving-and-restoring<\/a>?<\/p>\n\n

                    Specifically Saving Variables<\/strong> and Restoring Variables<\/strong>. Additionally, you can use the Checkpoint Files<\/strong> to save the weights periodically (useful if your computer stops training halfway through, you don't have to start from the beginning).<\/p>\n"},{"AnswerId":"39358945","CreationDate":"2016-09-06T22:54:39.300","ParentId":null,"OwnerUserId":"992489","Title":null,"Body":"

                    The checkpoint saving section of this doc<\/a> should answer your question.<\/p>\n"}]} {"QuestionId":39320675,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-04T19:25:48.943","AcceptedAnswerId":39321863.0,"OwnerUserId":395857.0,"Title":"Theano: when was the filter_flip parameter for conv2d introduced? (TypeError: __init__() got an unexpected keyword argument 'filter_flip')","Body":"

                    When was the parameter for introduced in Theano? (i.e., which is the minimum Theano version that supports it?)<\/p>\n\n

                    My version () doesn't have it: <\/p>\n\n

                    <\/pre>\n\n

                    Theano's change log<\/a> doesn't mention . The documentation for <\/a> doesn't mention the minimum required version.<\/p>\n","answers":[{"AnswerId":"39321863","CreationDate":"2016-09-04T22:00:48.383","ParentId":null,"OwnerUserId":"6394138","Title":null,"Body":"

                    It appears in version 0.8.0<\/a>.<\/p>\n\n

                    Note that in that release the implementation of theano.tensor.nnet.conv2d()<\/code> found in theano\/tensor\/nnet\/conv.py<\/code> becomes deprecated<\/a> and is replaced by the new implementation placed into theano\/tensor\/nnet\/__init__.py<\/code><\/a> and theano\/tensor\/nnet\/abstract_conv.py<\/code><\/a>.<\/p>\n"}]} {"QuestionId":39321500,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-04T21:05:56.170","AcceptedAnswerId":null,"OwnerUserId":2505295.0,"Title":"How can this tensorflow model converge on a CPU but not on a GPU?","Body":"

                    We ran into the strange problem that our relatively simple model converges on the CPU, but not on the server with GPU. No modifications to the code are done whatsoever between the two runs. Nor does the code contain any explicit conditional statements to change the workflow on different architectures.<\/p>\n\n

                    What could possibly be the reason?\nHow can this tensorflow model converge on a CPU but not on a GPU?\nIn the likely event that the code is too long for you to read we are still thankful about general speculations and hints.<\/p>\n\n

                    <\/pre>\n","answers":[{"AnswerId":"39359082","CreationDate":"2016-09-06T23:12:07.287","ParentId":null,"OwnerUserId":"992489","Title":null,"Body":"

                    In general floating point computations can be a little nondeterministic when it comes to adding many numbers (and some GPUs are buggy). Did you try retuning hyperparameters (varying learning rates and whatnot) to account for this?<\/p>\n"}]} {"QuestionId":39321752,"AnswerCount":0,"Tags":"","CreationDate":"2016-09-04T21:44:40.790","AcceptedAnswerId":null,"OwnerUserId":6794223.0,"Title":"Training a neural network when order of indices in target label is meaningless, abitrary","Body":"

                    I am trying to train an NN to approximate some coordinates from some 2d data - a matrix for a conv net and a long vector for a traditional NN. <\/p>\n\n

                    So the network takes the data as input, outputs 6 floats and tries to learn from labels, x1,y1, x2,y2, x3,y3 by minimizing mean squared error. <\/p>\n\n

                    The issue is that the ordering of the points in the label is meaningless. x1,y1 could just as easily be x3,y3 or vice versa. Nothing in the input data distinguishes one point from any other besides its position.<\/strong><\/p>\n\n

                    but, the network when by minimizing sum((approximation - target)^2)\/6 assumes that order does matter so that even if the network guessed for ex: .42,.23 when there was a point at .44,.22, the cost function might be very high if it guessed the point in indices 0 and 1 when .44,.22 was in indices 2 and 3 in the target label. As is, the network cannot learn because it has no way of learning which point should go first, second, third, for any given training sample, even if the network does learn the function that maps the input data to the a pair of coordinates.<\/p>\n\n

                    Are there any elegant solutions to this problem?<\/p>\n\n

                    I have tried artificially ordering the points, such that points are sorted by x value. (x1 is always the smallest and x3 is always the largest). This helps, but it is not ideal as the network then has to learn an additional function on top of finding the coordinates of these points. <\/p>\n\n

                    Please don't tell me to just use other methods, I am, but i would like to explore how these other methods stack up against dnns.<\/p>\n\n

                    thank you!<\/p>\n","answers":[]} {"QuestionId":39322441,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-04T23:47:36.120","AcceptedAnswerId":39322554.0,"OwnerUserId":4962207.0,"Title":"tf.train.shuffle_batch not working for me","Body":"

                    I'm trying to process my input data using the TensorFlow clean way (tf.train.shuffle_batch), most of this code I gathered from the tutorials with slight modifications like the decode_jpeg function.<\/p>\n\n

                    <\/pre>\n\n

                    When I try to run<\/p>\n\n

                    <\/pre>\n\n

                    I get the following error:<\/p>\n\n

                    <\/pre>\n\n

                    I'm not sure what is causing this error, I imagine it has something to do with the way I'm processing my image because it shows that they have no dimensions when they should have 3 channels (RGB).<\/p>\n","answers":[{"AnswerId":"39322554","CreationDate":"2016-09-05T00:14:04.340","ParentId":null,"OwnerUserId":"3574081","Title":null,"Body":"

                    The batching methods in TensorFlow<\/a> (tf.train.batch()<\/code>, tf.train.batch_join()<\/code>, tf.train.shuffle_batch()<\/code>, and tf.train.shuffle_batch_join()<\/code>) require that every element of the batch has the exact same shape*, so that they can be packed into dense tensors. In your code, it appears that the third dimension of the image<\/code> tensor that you pass to tf.train.shuffle_batch()<\/code> has unknown size. This corresponds to the number of channels in each image, which is 1 for monochrome images, 3 for color images, or 4 for color images with an alpha channel. If you pass an explicit channels=N<\/code> (where N<\/code> is 1, 3, or 4 as appropriate), this will give TensorFlow enough information about the shape of the image tensor to proceed.<\/p>\n\n


                    \n\n

                     * With one exception: when you pass dynamic_pad=True<\/code> to tf.train.batch()<\/code> or tf.train.batch_join()<\/code> the elements can have different shapes, but they must have the same rank. In general, this is used only for sequential data, rather than image data (where it will have undesirable behavior at the edges of the image).<\/p>\n"}]} {"QuestionId":39322761,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-05T01:03:15.493","AcceptedAnswerId":null,"OwnerUserId":4778857.0,"Title":"Weigh a image within the positive class","Body":"

                    I have a set of ~35,000 images that I am training a CNN on in Tensorflow.<\/p>\n\n

                    ~5% of the images are the positive class, 95% the negative class.<\/p>\n\n

                    Within the positive class, there are some images that are \"more positive\" and some that are \"less positive\" if that makes sense. <\/p>\n\n

                    I was wondering if it were possible to assign a weight to these \"more positive\" samples within the positive class (in addition to having to oversample this class in general) so that these images were considered more important.<\/p>\n\n

                    Any ideas, or is this just not possible?<\/p>\n","answers":[{"AnswerId":"39322847","CreationDate":"2016-09-05T01:20:56.340","ParentId":null,"OwnerUserId":"2876799","Title":null,"Body":"

                    You could just multiply the cost function by whatever weight you decide to use for the positive and more positive classes. Right now I am working on a network where 1\/3 is positive and 2\/3 are negative. However I make sure that statistically the batches are split 50\/50 between the classes. I just end up repeating some of my positive class throughout the epoch. <\/p>\n\n

                    If some classes are more positive than others maybe you should have more than two classes. Like Negative, Neutral, Sort of Positive, and Positive. <\/p>\n"}]} {"QuestionId":39323443,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-05T03:14:32.603","AcceptedAnswerId":39323487.0,"OwnerUserId":6785672.0,"Title":"why is multi GPU tensorflow retraining not working","Body":"

                    I have been training my tensorflow retraining algorithm using a single GTX Titan and it works just fine, but when I try to use multiple gpus in the flower of retraining example it does not work and seems to only utilize one GPU when I run it in Nvidia SMI. <\/p>\n\n

                    Why is this happening as it does work with multiple gpus when retraining at Inception model from scratch but not during retraining?<\/p>\n","answers":[{"AnswerId":"39323487","CreationDate":"2016-09-05T03:21:22.830","ParentId":null,"OwnerUserId":"2774397","Title":null,"Body":"

                    TensorFlow's flower retraining example does not work with multiple GPUs at all, even if you set --num_gpus<\/code> > 1. It should support a single GPU as you noted.<\/p>\n\n

                    The model needs to be modified to utilize multiple GPUs in parallel. Unfortunately, a single TensorFlow operation like the flower retraining example can't automatically be split over multiple GPUs at this time.<\/p>\n"}]} {"QuestionId":39324520,"AnswerCount":2,"Tags":"","CreationDate":"2016-09-05T05:43:29.963","AcceptedAnswerId":39325925.0,"OwnerUserId":3801648.0,"Title":"Understanding Tensorflow LSTM Input shape","Body":"

                    I have a dataset X which consists N = 4000 samples<\/strong>, each sample consists of d = 2 features<\/strong> (continuous values) spanning back t = 10 time steps<\/strong>. I also have the corresponding 'labels' of each sample which are also continuous values, at time step 11. <\/p>\n\n

                    At the moment my dataset is in the shape X: [4000,20], Y: [4000].<\/p>\n\n

                    I want to train an LSTM using TensorFlow to predict the value of Y (regression), given the 10 previous inputs of d features, but I am having a tough time implementing this in TensorFlow.<\/p>\n\n

                    The main problem I have at the moment is understanding how TensorFlow is expecting the input to be formatted. I have seen various examples such as this<\/a>, but these examples deal with one big string of continuous time series data. My data is different samples, each an independent time series.<\/p>\n","answers":[{"AnswerId":"53761509","CreationDate":"2018-12-13T12:07:00.567","ParentId":null,"OwnerUserId":"9273596","Title":null,"Body":"

                    (This answer \"addreses\" the problem when direct np.reshape() doesn't organize the final array as we want it. If we want to directly reshape into 3D np.reshape will do it, but watch out for the final organization of the input).<\/em><\/p>\n\n

                    In my personal try to finally resolve this problem of feeding input shape for RNN<\/strong> and not confuse anymore, I will give my \"personal\" explanation for this.<\/p>\n\n

                    In my case (and I think that many others may have this organization scheme in their feature matrices), most of the blogs outside \"don't help\". Let's give it a try in how to convert a 2D feature matrix into a 3D shaped one for RNNs.<\/p>\n\n

                    Let's say we have this organization type in our feature matrix<\/strong>: we have 5 observations<\/strong> (i.e. rows - for convention I think it is the most logical term to use) and in each row, we have 2 features for EACH timestep (and we have 2 timesteps)<\/strong>, like this: <\/p>\n\n

                    (The df<\/code> is to better understand visually my words)<\/p>\n\n

                    In [1]: import numpy as np                                                           \n\nIn [2]: arr = np.random.randint(0,10,20).reshape((5,4))                              \n\nIn [3]: arr                                                                          \nOut[3]: \narray([[3, 7, 4, 4],\n       [7, 0, 6, 0],\n       [2, 0, 2, 4],\n       [3, 9, 3, 4],\n       [1, 2, 3, 0]])\n\nIn [4]: import pandas as pd                                                          \n\nIn [5]: df = pd.DataFrame(arr, columns=['f1_t1', 'f2_t1', 'f1_t2', 'f2_t2'])         \n\nIn [6]: df                                                                           \nOut[6]: \n   f1_t1  f2_t1  f1_t2  f2_t2\n0      3      7      4      4\n1      7      0      6      0\n2      2      0      2      4\n3      3      9      3      4\n4      1      2      3      0\n<\/code><\/pre>\n\n

                    We will now take the values to work with them. The thing here is that RNNs incorporate the \"timestep\" dimension to their input<\/strong>, because of their architechtural nature. We can imagine that dimension as stacking 2D arrays one behind the other for the number of timesteps we have.<\/strong> In this case, we have two timesteps; so we will have two 2D arrays stacked: one for timestep1 and behind that, the one for timestep2.<\/p>\n\n

                    In reality, in that 3D input we need to make, we still have 5 observations. The thing is that we need to arrange them differently: the RNN will take the first row (or specified batch - but we will keep it simple here) of the first array (i.e. timestep1) and the first row of the second stacked array (i.e. timestep2). Then the second row...until the last one (the 5th one in our example). So, in each row of each timestep, we need to have the two features, of course, separated in different arrays each one corresponding to its timestep<\/em>. Let's see this with the numbers.<\/p>\n\n

                    I will make two arrays for easier understanding. Remember that, because of our organizational scheme in the df, you might have noticed that we need to take the first two columns (i.e. features 1 and 2 for the timestep1) as our FIRST ARRAY OF THE STACK and the last two columns, that is, the 3rd and the 4th, as our SECOND ARRAY OF THE STACK<\/strong>, so that everything makes sense finally. <\/p>\n\n

                    In [7]: arrStack1 = arr[:,0:2]                                                       \n\nIn [8]: arrStack1                                                                    \nOut[8]: \narray([[3, 7],\n       [7, 0],\n       [2, 0],\n       [3, 9],\n       [1, 2]])\n\nIn [9]: arrStack2 = arr[:,2:4]                                                       \n\nIn [10]: arrStack2                                                                   \nOut[10]: \narray([[4, 4],\n       [6, 0],\n       [2, 4],\n       [3, 4],\n       [3, 0]])\n<\/code><\/pre>\n\n

                    Finally, the only thing we need to do is stack both arrays (\"one behind the other\") as if they were part of the same final structure:<\/p>\n\n

                    In [11]: arrfinal3D = np.stack([arrStack1, arrStack2])                               \n\nIn [12]: arrfinal3D                                                                  \nOut[12]: \narray([[[3, 7],\n        [7, 0],\n        [2, 0],\n        [3, 9],\n        [1, 2]],\n\n       [[4, 4],\n        [6, 0],\n        [2, 4],\n        [3, 4],\n        [3, 0]]])\n\nIn [13]: arrfinal3D.shape                                                            \nOut[13]: (2, 5, 2)\n<\/code><\/pre>\n\n

                    That's it: we have our feature matrix ready to be fed into the RNN cell, taking into account our organization of the 2D feature matrix. <\/p>\n\n

                    (For a one liner regarding all this you could use:<\/p>\n\n

                    In [14]: arrfinal3D_1 = np.stack([arr[:,0:2], arr[:,2:4]])                           \n\nIn [15]: arrfinal3D_1                                                                \nOut[15]: \narray([[[3, 7],\n        [7, 0],\n        [2, 0],\n        [3, 9],\n        [1, 2]],\n\n       [[4, 4],\n        [6, 0],\n        [2, 4],\n        [3, 4],\n        [3, 0]]])\n<\/code><\/pre>\n\n

                    \u00a1Hope this helps!<\/p>\n"},{"AnswerId":"39325925","CreationDate":"2016-09-05T07:46:02.310","ParentId":null,"OwnerUserId":"249642","Title":null,"Body":"

                    The documentation of tf.nn.dynamic_rnn<\/code><\/a> states:<\/p>\n\n

                    \n

                    inputs<\/code>: The RNN inputs. If time_major == False<\/code> (default), this must be a Tensor of shape: [batch_size, max_time, ...]<\/code>, or a nested tuple of such elements.<\/p>\n<\/blockquote>\n\n

                    In your case, this means that the input should have a shape of [batch_size, 10, 2]<\/code>. Instead of training on all 4000 sequences at once, you'd use only batch_size<\/code> many of them in each training iteration. Something like the following should work (added reshape for clarity):<\/p>\n\n

                    batch_size = 32\n# batch_size sequences of length 10 with 2 values for each timestep\ninput = get_batch(X, batch_size).reshape([batch_size, 10, 2])\n# Create LSTM cell with state size 256. Could also use GRUCell, ...\n# Note: state_is_tuple=False is deprecated;\n# the option might be completely removed in the future\ncell = tf.nn.rnn_cell.LSTMCell(256, state_is_tuple=True)\noutputs, state = tf.nn.dynamic_rnn(cell,\n                                   input,\n                                   sequence_length=[10]*batch_size,\n                                   dtype=tf.float32)\n<\/code><\/pre>\n\n

                    From the documentation<\/a>, outputs<\/code> will be of shape [batch_size, 10, 256]<\/code>, i.e. one 256-output for each timestep. state<\/code> will be a tuple<\/a> of shapes [batch_size, 256]<\/code>. You could predict your final value, one for each sequence, from that:<\/p>\n\n

                    predictions = tf.contrib.layers.fully_connected(state.h,\n                                                num_outputs=1,\n                                                activation_fn=None)\nloss = get_loss(get_batch(Y).reshape([batch_size, 1]), predictions)\n<\/code><\/pre>\n\n

                    The number 256 in the shapes of outputs<\/code> and state<\/code> is determined by cell.output_size<\/code> resp. cell.state_size<\/code>. When creating the LSTMCell<\/code> like above, these are the same. Also see the LSTMCell documentation<\/a>.<\/p>\n"}]} {"QuestionId":39324856,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-05T06:21:40.117","AcceptedAnswerId":null,"OwnerUserId":4976362.0,"Title":"Tensorflow - Using batching to make predictions","Body":"

                    I'm attempting to make predictions using a trained convolutional neural network, slightly modified from the example in the example expert tensorflow tutorial. I have followed the instructions at https:\/\/www.tensorflow.org\/versions\/master\/how_tos\/reading_data\/index.html<\/a> to read data from a CSV file. <\/p>\n\n

                    I have trained the model and evaluated its accuracy. I then saved the model and loaded it into a new python script for making predictions. Can I still use the batching method detailed in the link above or should I use instead? Most tutorials I've seen online use the latter. <\/p>\n\n

                    My code is shown below, I have essentially duplicated the code for reading from my training data, which was stored as lines within a single .csv file. Conv_nn is simply a class that contains the convolutional neural network detailed in the expert MNIST tutorial. Most of the content is probably not very useful except for the part where I run the graph. <\/p>\n\n

                    I suspect I have badly mixed up training and prediction - I'm not sure if the test images are being fed to the prediction operation correctly or if it is valid to use the same batch operations for both datasets.<\/strong> <\/p>\n\n

                    <\/pre>\n","answers":[{"AnswerId":"49220888","CreationDate":"2018-03-11T14:06:44.313","ParentId":null,"OwnerUserId":"4323562","Title":null,"Body":"

                    This question is old, but I am going to answer anyway, as it has been viewed nearly 1000 times.<\/p>\n\n

                    So if your model had Y<\/strong> labels and X<\/strong> inputs then<\/p>\n\n

                    prediction=tf.argmax(Y,1)\nresult = prediction.eval(feed_dict={X: [data]}, session=sess)\n<\/code><\/pre>\n\n

                    This evaluates a single input, for example a single mnist image, but it can be a batch.<\/p>\n"}]} {"QuestionId":39325275,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-05T06:57:38.497","AcceptedAnswerId":39331675.0,"OwnerUserId":1828289.0,"Title":"How to train TensorFlow network using a generator to produce inputs?","Body":"

                    The TensorFlow docs<\/a> describe a bunch of ways to read data using TFRecordReader, TextLineReader, QueueRunner etc and queues.<\/p>\n\n

                    What I would like to do is much, much simpler: I have a python generator function that produces an infinite sequence of training data as (X, y) tuples (both are numpy arrays, and the first dimension is the batch size). I just want to train a network using that data as inputs. <\/p>\n\n

                    Is there a simple self-contained example of training a TensorFlow network using a generator which produces the data? (along the lines of the MNIST or CIFAR examples)<\/p>\n","answers":[{"AnswerId":"39331675","CreationDate":"2016-09-05T13:27:49.880","ParentId":null,"OwnerUserId":"6791223","Title":null,"Body":"

                    Suppose you have a function that generates data: <\/p>\n\n\n\n

                     def generator(data): \n    ...\n    yield (X, y)\n<\/code><\/pre>\n\n

                    Now you need another function that describes your model architecture. It could be any function that processes X and has to predict y as output (say, neural network).<\/p>\n\n

                    Suppose your function accepts X and y as inputs, computes a prediction for y from X in some way and returns loss function (e.g. cross-entropy or MSE in the case of regression) between y and predicted y:<\/p>\n\n\n\n

                     def neural_network(X, y): \n    # computation of prediction for y using X\n    ...\n    return loss(y, y_pred)\n<\/code><\/pre>\n\n

                    To make your model work, you need to define placeholders for both X and y and then run a session:<\/p>\n\n\n\n

                     X = tf.placeholder(tf.float32, shape=(batch_size, x_dim))\n y = tf.placeholder(tf.float32, shape=(batch_size, y_dim))\n<\/code><\/pre>\n\n

                    Placeholders are something like \"free variables\" which you need to specify when running the session by feed_dict<\/code>:<\/p>\n\n\n\n

                     with tf.Session() as sess:\n     # variables need to be initialized before any sess.run() calls\n     tf.global_variables_initializer().run()\n\n     for X_batch, y_batch in generator(data):\n         feed_dict = {X: X_batch, y: y_batch} \n         _, loss_value, ... = sess.run([train_op, loss, ...], feed_dict)\n         # train_op here stands for optimization operation you have defined\n         # and loss for loss function (return value of neural_network function)\n<\/code><\/pre>\n\n

                    Hope you would find it useful. However, bear in mind this is not fully working implementation but rather a pseudocode since you specified almost no details.<\/p>\n"}]} {"QuestionId":39327090,"AnswerCount":1,"Tags":"","CreationDate":"2016-09-05T09:01:18.337","AcceptedAnswerId":39373917.0,"OwnerUserId":4842101.0,"Title":"Tensorflow inception retraining : bottleneck files creation","Body":"

                    I'm following the tutorial<\/a> to retrain the inception model adapted to my own problem.\nI have about 50 000 images in around 100 folders \/ categories.<\/p>\n\n

                    Running this <\/p>\n\n

                    <\/p>\n\n

                    <\/p>\n\n

                    on Amazon EC2 g2.2xlarge I was hoping that the full process would be quite fast (faster than on my laptop) but the bottleneck files creation takes a long time.\nAssuming it's already been 2 hours and only 800 files have been created, I will need more than 5 days (!!) to just create the files...<\/p>\n\n

                    Is it supposed to be faster than this rythm ( ~ 400 bottleneck files created \/ hour) because of the GPU ?<\/p>\n\n

                    How could I make the process faster ? <\/p>\n","answers":[{"AnswerId":"39373917","CreationDate":"2016-09-07T15:26:46.073","ParentId":null,"OwnerUserId":"4842101","Title":null,"Body":"

                    Finally found the answer to my question.<\/p>\n\n

                    Bazel was working without GPU support. To solve this, I modified files regarding these issues :<\/p>\n\n

                    I'd recommend using Django<\/a> if you are comfortable with python and working with an AWS serviced database! It is pretty intuitive, and a lot of resources and examples are available on the web. For example, here is the file upload documentation<\/a>.<\/p>\n"},{"AnswerId":"48819337","CreationDate":"2018-02-16T02:37:32.580","ParentId":null,"OwnerUserId":"3791995","Title":null,"Body":"

I'm trying to implement sentence similarity architecture based on this work using the STS dataset<\/a>. Labels are normalized similarity scores from 0 to 1 so it is assumed to be a regression model.<\/p>\n\n

I'm trying to use Leaky_Relu layer in caffe and can't really figure out where to define it. From the layer definitions here<\/a>, I can see that ReLu has an optional parameter called negative_slope which can be used to define a leaky_relu but I can't figure out where this negative_slope parameter goes into.<\/p>\n\n