{"QuestionId":55636740,"AnswerCount":0,"Tags":"","CreationDate":"2019-04-11T16:00:20.313","AcceptedAnswerId":null,"OwnerUserId":7448090.0,"Title":"How to implement average reduction in caffe using Scale","Body":"

I want to implement Average-reduction in , not as part of the input layer. \nAlso I want it to be channel-wise, of some constant values (different from each other). I have tried with Layer and didn't find a way to subtract each channel individually.<\/p>\n\n

I will glad for some help<\/p>\n\n

EDIT<\/h2>\n\n

I was able to figure it out using layer, which as i understand is used for implementing layer. <\/p>\n\n

I'm sharing my solution:<\/h3>\n\n

first create the prototxt:<\/p>\n\n

<\/pre>\n\n

After it, injecting the data to the layer params<\/strong>, like this:<\/p>\n\n

<\/pre>\n","answers":[]}
{"QuestionId":55636903,"AnswerCount":0,"Tags":"","CreationDate":"2019-04-11T16:08:37.607","AcceptedAnswerId":null,"OwnerUserId":11347248.0,"Title":"Tensrflow \"Illegal Instruction\" error on session.run() line running on armv7l","Body":"

I'm trying to run Tensorflow on a board. I have installed it successfully using armv7l wheels for and . However, whenever I run any sample scripts that call I get an error. <\/p>\n\n

I have tried Tensorflow v1.5, v1.8, v1.9, v1.11, v1.12. <\/p>\n\n

Does anyone know anything I can try to fix this or know of where I can find a wheel that would work?<\/p>\n\n

Thank you!<\/p>\n","answers":[]} {"QuestionId":55637271,"AnswerCount":1,"Tags":"","CreationDate":"2019-04-11T16:30:32.100","AcceptedAnswerId":55637824.0,"OwnerUserId":4309985.0,"Title":"Preventing PyTorch Dataset iteration from exceeding length of dataset","Body":"

I am using a custom PyTorch Dataset with the following:<\/p>\n\n

<\/pre>\n\n

However, when I iterate over this dataset, iteration loops back to the start of the dataset instead of terminating at the end of the dataset. This effectively becomes an infinite loop in the iterator, with the epoch print statement never occurring for subsequent epochs.<\/p>\n\n

<\/pre>\n\n

Print output (... for values in between):<\/p>\n\n

<\/pre>\n\n

Why is the basic iteration over the Dataset continuing past the defined of the DataSet, and how can I ensure that iteration over the dataset terminates after hitting the length of the dataset when using this method (or is manually iterating over the range of the dataset length the only solution)?<\/p>\n\n

Thank you.<\/p>\n","answers":[{"AnswerId":"55637824","CreationDate":"2019-04-11T17:06:19.253","ParentId":null,"OwnerUserId":"10749432","Title":null,"Body":"

Dataset<\/code> class doesn't have implemented StopIteration<\/code> signal.<\/p>\n\n

\n

The for<\/code> loop listens for StopIteration<\/code>. The purpose of the for statement is to loop over the sequence provided by an iterator and the exception is used to signal that the iterator is now done...<\/p>\n<\/blockquote>\n\n

More: Why does next raise a 'StopIteration', but 'for' do a normal return?<\/a> | The Iterator Protocol<\/a><\/p>\n"}]} {"QuestionId":55637278,"AnswerCount":0,"Tags":"","CreationDate":"2019-04-11T16:30:58.253","AcceptedAnswerId":null,"OwnerUserId":4462831.0,"Title":"Cannot run Tensorflow models from multiple threads","Body":"

I'm working on a project in which I need to load and run different neural networks at the same time.<\/p>\n\n

The models I am using for testing the code are taken from DeepLab Demo<\/a>, I basically encapsulated their code in a class (called DeepLabModel) and I instantiate it once for each different model they propose.<\/p>\n\n

Up to now I wrote a version of the code in which models are loaded (and used) sequentially from the same process, and everything works well<\/em>. <\/p>\n\n

Since I do some processing on the results and I need to simulate a distributed environment I need to parallelize each class containing the model.<\/p>\n\n

My first version was a class which got as parameter a previously loaded instance of DeepLabModel. Each Agent had a \"predict\" function which got executed in a different Process, but I noticed that the agents hanged on the session.run() function (inside the function) without any output.<\/p>\n\n

Since I couldn't find the reason for this, I tried rewriting the code such that now each only gets the filename of each model, and I wrote a function in which I load the model, wait for an input image in a Queue and run the model on the input that is received.<\/p>\n\n

Here's some code from the last version (only relevant parts, DeepLabModel is just a wrapper of the code in the link provided above):<\/p>\n\n

<\/pre>\n\n

The problem is that when the Processes try to execute each one fails with the error:\n<\/p>\n\n

But no other warnings are printed. I tried running this both on gpu and cpu. I'm running a docker image (nvidia-docker), TF 1.12, everything works fine if I don't try to run tensorflow from different processes.<\/p>\n\n

I'm also wandering why the code hangs if the models are first loaded then passed to the processes (one to each process).<\/p>\n\n

Thank you in advance.<\/p>\n","answers":[]} {"QuestionId":55637345,"AnswerCount":1,"Tags":"","CreationDate":"2019-04-11T16:35:11.023","AcceptedAnswerId":55637346.0,"OwnerUserId":3623290.0,"Title":"Applying a permutation along one axis in TensorFlow","Body":"

How to permute \"dimensions\" along a single axis of a tensor?<\/p>\n\n

Something akin to , but at the level of \"dimensions\" along an axis, instead of at the level of axes.<\/p>\n\n

To permute them randomly (along the first axis), there it , and to shift them, there is . But I can't find a more general function that would apply any given permutation.<\/p>\n","answers":[{"AnswerId":"55637346","CreationDate":"2019-04-11T16:35:11.023","ParentId":null,"OwnerUserId":"3623290","Title":null,"Body":"

tf.gather<\/code> can be used to that end. In fact, it is even more general, as the indices it takes as one of its inputs don't need to represent a permutation.<\/p>\n"}]} {"QuestionId":55637407,"AnswerCount":0,"Tags":"","CreationDate":"2019-04-11T16:38:15.783","AcceptedAnswerId":null,"OwnerUserId":11347415.0,"Title":"Dimension of the loss function and gradients for adversarial example","Body":"

I was working on some adversarial problem with mnist database. I was trying to find the gradient value for each pixel.For that, I calculated the categorical_crossentropy loss between mnist_model.input and target_number (target_number was first one hot encoded and then converted to a Keras variable) and the gradients. The dimension of my loss function is 28 by 28 by 10 and gradients are 28 by 28 by 1. I am not sure how the codes are working.\nHere is the following code, <\/p>\n\n

<\/pre>\n","answers":[]}
{"QuestionId":55637564,"AnswerCount":0,"Tags":"","CreationDate":"2019-04-11T16:49:32.147","AcceptedAnswerId":null,"OwnerUserId":10887556.0,"Title":"How do I use Pytorch's NLLLoss with count data?","Body":"

I have a model where I'm trying to predict with integer data, where an example of an expected output would be [40]. How do I use nn.PoissonNLLLoss to do this? Setting log_input=False slowly decreases my loss below 0.<\/p>\n","answers":[]} {"QuestionId":55637648,"AnswerCount":0,"Tags":"","CreationDate":"2019-04-11T16:54:51.717","AcceptedAnswerId":null,"OwnerUserId":9226396.0,"Title":"How to go about changing the kernel size in convolutional neural network","Body":"

I've got a discriminator and generator model in a GAN and I want to change the kernel sizes to be bigger. The input image is coming in at 64x64. At the moment the kernels are of size 4x4 (ks is set to 4):<\/p>\n\n

<\/pre>\n\n

If I want to change it to 5 or 3, do I merely change ks to equal 5 or 3? Surely theres a problem because if you keep dividing the image size by two, the final layer has a size of 4x4 so It wouldnt fit on top of it properly. <\/p>\n","answers":[]} {"QuestionId":55637807,"AnswerCount":0,"Tags":"","CreationDate":"2019-04-11T17:05:26.633","AcceptedAnswerId":null,"OwnerUserId":7934786.0,"Title":"Attention layer on top of LSTM Autoencoder getting incompatibility error","Body":"

I am deploying a , and am adding on top of that.<\/p>\n\n

Before adding attention layer it is working fine. I got the idea from this post<\/a> for adding attention layer. \nAfter adding attention it complains about the dimension incompatibility.<\/p>\n\n

This is my code after adding attention:<\/p>\n\n

<\/pre>\n\n

this is the error I got:<\/p>\n\n

<\/pre>\n\n

I have read a couple of post regarding this error, namely: this<\/a> and this<\/a> and this<\/a>.\nbut they are not the same as my error. Also, Some suggested to make return_sequences=False, but I do not think this is the correct way. Later in the code, it again raises an error if we set it False!<\/p>\n\n

So, I feel like I am doing something wrong, otherwise, why the network should raise the error with the standard architecture.<\/p>\n\n

So my question is that:\nwhat is wrong with this network\nand how can I fix it.<\/p>\n\n

I appreciate it if you could explain in detail so I can grasp better or give me some links which talk about the conflict in my code.<\/p>\n\n

Thanks in advance!<\/p>\n","answers":[]} {"QuestionId":55638143,"AnswerCount":0,"Tags":"","CreationDate":"2019-04-11T17:26:13.323","AcceptedAnswerId":null,"OwnerUserId":11347571.0,"Title":"Failed to create a directory: logs\/fit","Body":"

With TensorFlow 1.13.1, I can save the logs with Tensorboard but when I upgrade to TensorFlow 2.0.0_alpha0 the same code gives me the error: <\/p>\n\n

<\/pre>\n\n

What can I do to correct this for TensorFlow 2.0.0_alpha0<\/p>\n\n

<\/pre>\n","answers":[]}
{"QuestionId":55638192,"AnswerCount":0,"Tags":"","CreationDate":"2019-04-11T17:29:20.320","AcceptedAnswerId":null,"OwnerUserId":3449567.0,"Title":"Solving a ML exercise with tensor flow","Body":"

First of all let me say than I'm a newcomer to machine\/deep lerning and tensorflow and after reading for a while i have some questions for an exercise i would like to solve.<\/p>\n\n

The exercise is the next one:<\/p>\n\n

Lets say that i have a training dataset which contains per each batch\/row a total of 50 questions of an undeterminated group of questions of two types:<\/p>\n\n

type 1. Questions with four posible answers. Only one answer per question is correct (single choise)<\/p>\n\n

type 2. Questions with four or five posible answers. Only two or tree posible correct answers. All correct answers have to be choosen (multiple choise)<\/p>\n\n

We can identify wheter if the question is type 1 or type 2.<\/p>\n\n

We can have x questions of type 1 and y questions of type 2 or x-2 questions of type 1 and y+2 of questions of type 2. (An undetermined amount of each type, changing each row)<\/p>\n\n

In the training dataset, each row contains 20 questions in total (and we can say how many of each type).<\/p>\n\n

We do also have the total percentil of success of the set of questions answered (total amount of correct answers in the set\/total amount of questions in the set * 100) BUT i can not tell if one particular question is right or wrong.<\/em><\/p>\n\n

Example of the batch\/each row:<\/p>\n\n

<\/pre>\n\n

goal:<\/p>\n\n

for a given question (type 1 or 2) that might or might not be in the training dataset (which could be expanded in each iteration\/epoch) give a percentil of succes for all posible answers. Example:<\/p>\n\n

<\/pre>\n\n

My questions:<\/p>\n\n

    \n
  1. Is this a problem that tensorflow (and the underling theory) can solve?<\/li>\n<\/ol>\n\n

    In case of no or maybe: alternatives?<\/p>\n\n

    In case yes:<\/p>\n\n

      \n
    1. Can you provide resources, examples.... on how to solve the problem?<\/li>\n<\/ol>\n\n

      Thank you!<\/p>\n","answers":[]} {"QuestionId":55638347,"AnswerCount":1,"Tags":"","CreationDate":"2019-04-11T17:41:11.640","AcceptedAnswerId":null,"OwnerUserId":3990607.0,"Title":"AttributeError: 'NoneType' object has no attribute '_inbound_nodes' in Keras while trying to do a resnet","Body":"

      I get the error while trying to create a Keras model using Keras'<\/p>\n\n

      <\/p>\n\n

      From my understanding of other questions here on Stackoverflow (eg: Q1<\/a>, Q2<\/a>, Q3<\/a>, Q4<\/a>) about the same error, the trick should be to connect to using only Keras layer objects, even if it means using . I am pretty sure that I did that.<\/p>\n\n

      My code is as follows:<\/p>\n\n

      <\/pre>\n\n

      Where is a Keras layer module. So it seems to me that everything from the to is transformed using Keras layers. Even for the additions I use .<\/p>\n","answers":[{"AnswerId":"55638388","CreationDate":"2019-04-11T17:43:06.700","ParentId":null,"OwnerUserId":"3990607","Title":null,"Body":"

      I found the problem. <\/p>\n\n

      x = K.identity(input)\n<\/code><\/pre>\n\n

      is not a Keras layer!<\/p>\n\n

      Changing that line for <\/p>\n\n

      def identity(z):\n    return z\n\nx = Lambda(identity)(input)\n<\/code><\/pre>\n\n

      solves the problem. <\/p>\n"}]} {"QuestionId":55638989,"AnswerCount":1,"Tags":"","CreationDate":"2019-04-11T18:26:20.353","AcceptedAnswerId":55639871.0,"OwnerUserId":8807447.0,"Title":"Eager tf.GradientTape() returns only Nones","Body":"

      I try to calculate the gradients with Tensorflow in the eager mode, but\ntf.GradientTape () returns only None values. I can not understand why.\nThe gradients are calculated in the update_policy () function.<\/p>\n\n

      The output of the line:<\/p>\n\n

      <\/pre>\n\n

      is<\/p>\n\n

      <\/pre>\n\n

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

      <\/pre>\n","answers":[{"AnswerId":"55639871","CreationDate":"2019-04-11T19:29:24.610","ParentId":null,"OwnerUserId":"5154274","Title":null,"Body":"

      You don't have a forward pass in your model. The Model.predict()<\/code> method returns numpy()<\/code> array without taping the forward pass. Take a look at this example:<\/p>\n\n

      Given a following data and model:<\/p>\n\n

      import tensorflow as tf\nimport numpy as np\n\nx_train = tf.convert_to_tensor(np.ones((1, 2), np.float32), dtype=tf.float32)\ny_train = tf.convert_to_tensor([[0, 1]])\n\nmodel = tf.keras.models.Sequential([tf.keras.layers.Dense(2, input_shape=(2, ))])\n<\/code><\/pre>\n\n

      First we use predict()<\/code>:<\/p>\n\n

      with tf.GradientTape() as tape:\n    logits = model.predict(x_train)\n    print('`logits` has type {0}'.format(type(logits)))\n    # `logits` has type <class 'numpy.ndarray'>\n    xentropy = tf.nn.softmax_cross_entropy_with_logits(labels=y_train, logits=logits)\n    reduced = tf.reduce_mean(xentropy)\n    grads = tape.gradient(reduced, model.trainable_variables)\n    print('grads are: {0}'.format(grads))\n    # grads are: [None, None]\n<\/code><\/pre>\n\n

      Now we use model's input:<\/p>\n\n

      with tf.GradientTape() as tape:\n    logits = model(x_train)\n    print('`logits` has type {0}'.format(type(logits)))\n    # `logits` has type <class 'tensorflow.python.framework.ops.EagerTensor'>\n    xentropy = tf.nn.softmax_cross_entropy_with_logits(labels=y_train, logits=logits)\n    reduced = tf.reduce_mean(xentropy)\n    grads = tape.gradient(reduced, model.trainable_variables)\n    print('grads are: {0}'.format(grads))\n    # grads are: [<tf.Tensor: id=2044, shape=(2, 2), dtype=float32, numpy=\n    # array([[ 0.77717704, -0.777177  ],\n    #        [ 0.77717704, -0.777177  ]], dtype=float32)>, <tf.Tensor: id=2042, \n    # shape=(2,), dtype=float32, numpy=array([ 0.77717704, -0.777177  ], dtype=float32)>]\n\n<\/code><\/pre>\n\n

      So use model's __call__()<\/code> (i.e. model(x)<\/code>) for forward pass and not predict()<\/code>.<\/p>\n"}]} {"QuestionId":55639151,"AnswerCount":1,"Tags":"","CreationDate":"2019-04-11T18:37:12.190","AcceptedAnswerId":null,"OwnerUserId":11120877.0,"Title":"Mixing datasets in set ratio","Body":"

      In tensorlfow dataset, how do I mix 2 datasets, taking 75% of the set from my original data and 25% from the augmented data?<\/p>\n\n

      <\/pre>\n","answers":[{"AnswerId":"55640140","CreationDate":"2019-04-11T19:47:37.970","ParentId":null,"OwnerUserId":"5786339","Title":null,"Body":"

      The problem is you can't use len()<\/code> on a dataset object, so it's sometimes hard to know exact number of examples until you iterate a full epoch. But you can approximate this with take<\/code> and skip<\/code> methods.<\/p>\n\n

      train_dataset = dataset.take(number_examples_for_train)\ntest_dataset = dataset.skip(number_examples_for_train)\n<\/code><\/pre>\n\n

      Those methods are a direct alternative to each other. \nhttps:\/\/www.tensorflow.org\/api_docs\/python\/tf\/data\/Dataset#take<\/a><\/p>\n"}]} {"QuestionId":55639232,"AnswerCount":0,"Tags":"","CreationDate":"2019-04-11T18:42:33.303","AcceptedAnswerId":null,"OwnerUserId":7803841.0,"Title":"OS Error: cannot identify the image file ","Body":"

      I am getting an error. I have tried all the previous solution on internet but it's not working. I guess the problem is with but not getting it.<\/p>\n\n

      <\/pre>\n\n

      \"enter<\/a><\/p>\n\n

      \"enter<\/a><\/p>\n","answers":[]} {"QuestionId":55639955,"AnswerCount":1,"Tags":"","CreationDate":"2019-04-11T19:35:24.457","AcceptedAnswerId":null,"OwnerUserId":10426463.0,"Title":"PyTorch Error The size of tensor a (128) must match the size of tensor b (9) at non-singleton dimension 0","Body":"

      I am running an CNN model of HAR using PyTorch 1.01 in Anaconda with GPU \nWhile doing the iteration it's giving me the error \nThe size of tensor a (128) must match the size of tensor b (9) at non-singleton dimension 0.\nI believe it's the datamodel while enumerate the train_model giving error. Anyone faced similar issues in PyTorch ? Need little support as new to PyTorch.<\/p>\n\n

      I have tried all the datamodel tricks found in google.<\/p>\n\n

      '''<\/p>\n\n

      <\/pre>\n\n

      '''<\/p>\n","answers":[{"AnswerId":"55641208","CreationDate":"2019-04-11T21:09:35.260","ParentId":null,"OwnerUserId":"3758174","Title":null,"Body":"

      The mean<\/code> in the normalize<\/code> transform must have the same size as the number of channels of the sample<\/code>. For example, if the sample is N x 9 x 5 x 7<\/code> mean<\/code> be size 9<\/code>. In this case, your sample has 128 channels but mean is of size 9<\/code>.<\/p>\n\n

      It looks like you try to reshape the sample using sample.view(-1, 9, 1, 128)<\/code> but that happens after the error in data loading.<\/p>\n\n

      You need to reshape the tensor before the normalize<\/code> transform. For example,<\/p>\n\n

      def reshape_tensor(x):\n    return x.reshape(9, 1, 128)\n\ntrain_dataset = datasets.ImageFolder(\n    traindir,\n    transforms.Compose([\n        ...,\n        reshape_tensor,\n        normalize,\n    ]))\n<\/code><\/pre>\n"}]}
      {"QuestionId":55640149,"AnswerCount":1,"Tags":"","CreationDate":"2019-04-11T19:48:36.350","AcceptedAnswerId":null,"OwnerUserId":3162360.0,"Title":"Error in Keras when I want to calculate the Sensitivity and Specificity","Body":"

      I am writing a code for classification between two types of images based on a CNN.\nI want to measure the accuracy, sensitivity, and specificity for my work but unfortunately, I have the following error. \nCould you please let me know what my problem is. <\/p>\n\n

      <\/pre>\n\n

      error:<\/p>\n\n

      <\/pre>\n","answers":[{"AnswerId":"55688340","CreationDate":"2019-04-15T11:36:32.737","ParentId":null,"OwnerUserId":"4931156","Title":null,"Body":"

      The metric tf.keras.metrics.SensitivityAtSpecificity calculates sensitivity at a given specificity Click here<\/a>.<\/p>\n\n

      Unfortunately sensitivity and specificity metrics are not yet included in Keras, so you have to write your own custom metric as is specified here<\/a>.<\/p>\n\n

      The following is one simple way to calculate specificity found at this answer<\/a>.<\/p>\n\n

      def specificity(y_true, y_pred):\n    \"\"\"\n    param:\n    y_pred - Predicted labels\n    y_true - True labels \n    Returns:\n    Specificity score\n    \"\"\"\n    neg_y_true = 1 - y_true\n    neg_y_pred = 1 - y_pred\n    fp = K.sum(neg_y_true * y_pred)\n    tn = K.sum(neg_y_true * neg_y_pred)\n    specificity = tn \/ (tn + fp + K.epsilon())\n    return specificity\n<\/code><\/pre>\n\n

      You can get Keras implementations for specificity and sensitivity on this link<\/a>.<\/p>\n"}]} {"QuestionId":55640342,"AnswerCount":0,"Tags":"","CreationDate":"2019-04-11T20:04:55.003","AcceptedAnswerId":null,"OwnerUserId":9750363.0,"Title":"Proper hashing of categorical variables for RNN - Binary Classifcation","Body":"

      I'm currently working on a project that has all categorical data as input and a binary output (1=Yes 0=No).<\/p>\n\n

      A little bit about the data.\nThere are 3127854 rows. Each feature column is categorical in nature. \nThe following is how many unique values are in each column.<\/p>\n\n

      attribute_1 - 87<\/p>\n\n

      attribute_2 - 2<\/p>\n\n

      attribute_3 - 202<\/p>\n\n

      attribute_4 - 3<\/p>\n\n

      attribute_5 - 3<\/p>\n\n

      attribute_6 - 367<\/p>\n\n

      I keep on running into issues with how to hash\/embed the columns in a manner that allows me to input them into a RNN. Ideally what i'd like to do is hash the columns, embed, pass through LSTM layer, concat, flatten, dense layer, then output a binary prediction.<\/p>\n\n

      sorry if the code is a little sloppy\/repetitive as im tinkering around right now.<\/p>\n\n

      <\/pre>\n\n

      What ends up happening at this point is the model.fit call doesnt end up working, saying<\/p>\n\n

      ValueError: Input arrays should have the same number of samples as target arrays. Found 3 input samples and 3127854 target samples.<\/p>\n\n

      Any input or guidance would be helpful, and as always please let me know if any clarification is needed.<\/p>\n\n

      Thanks in advance!<\/p>\n","answers":[]} {"QuestionId":55640352,"AnswerCount":0,"Tags":"","CreationDate":"2019-04-11T20:05:21.237","AcceptedAnswerId":null,"OwnerUserId":11014272.0,"Title":"Using Keras optimizers and models outside of the training process","Body":"

      I have a basic question. I want to know whether it is possible to use Keras (e.g. the functional API) to specify a neural network model, and then use the Keras optimization routines to train the network outside of the Keras training process. In other words, use Keras purely to specify a neural network, pull the weights out and put them into a loss function (outside the Keras APIs if necessary) then use one of the built-in optimization routines purely to minimize the loss function over a single batch of data (no multiple epochs etc. or anything beyond minimization of the loss function with regard to one set of data at this point).<\/p>\n\n

      My reason for wanting to do this is that I would like to use a dynamic optimization process that changes from batch iteration to batch iteration, which seems difficult to implement entirely within the Keras APIs.<\/p>\n","answers":[]} {"QuestionId":55640538,"AnswerCount":1,"Tags":"","CreationDate":"2019-04-11T20:21:08.750","AcceptedAnswerId":55640919.0,"OwnerUserId":11347242.0,"Title":"What does it mean \"The tensor's graph is different from the session's graph.\"","Body":"

      I'm trying to run this very simple tensorflow code I found on colab, but it seems I'm missing something basic about it.<\/p>\n\n

      I already tried to replace xy_sum.eval() with xy_sum.eval(session=sess) but the problem seems to persist.\nHere's \"my\" code:<\/p>\n\n

      <\/pre>\n\n

      I expect the output to be 13 as shown on https:\/\/colab.research.google.com\/notebooks\/mlcc\/tensorflow_programming_concepts.ipynb#scrollTo=Md8ze8e9geMi<\/a>,\nbut the ouput i get from spyder is<\/p>\n\n

      <\/pre>\n\n

      if I try, as suggested, to pass an explicit session I get:<\/p>\n\n

      <\/pre>\n","answers":[{"AnswerId":"55640919","CreationDate":"2019-04-11T20:47:27.180","ParentId":null,"OwnerUserId":"5179463","Title":null,"Body":"

      The tf.Session<\/code> uses the default graph. So in order to use the graph g<\/code> you would either have to indent the session initialization into the with g.as_default():<\/code> block, or pass the graph to the session at initialization<\/a>.<\/p>\n"}]} {"QuestionId":55640544,"AnswerCount":1,"Tags":"","CreationDate":"2019-04-11T20:21:45.250","AcceptedAnswerId":null,"OwnerUserId":10952884.0,"Title":"model.fit_generator() fails with use_multiprocessing=True","Body":"

      In the code example below, I can train the model only when NOT using multiprocessing.<\/p>\n\n

      My generator is straight from the tensorflow.keras.utils.Sequence description https:\/\/www.tensorflow.org\/api_docs\/python\/tf\/keras\/utils\/Sequence<\/a><\/p>\n\n

      Any idea how to fix the generator to allow multiprocessing?<\/p>\n\n

      Running on Win 10, tensorflow 1.13.1, python 3.6.8<\/p>\n\n

      <\/pre>\n\n

      I expected the second fit_generator() call to train the model like the first one. Instead, I get no output, not even an error message.<\/p>\n","answers":[{"AnswerId":"57022645","CreationDate":"2019-07-13T20:35:22.287","ParentId":null,"OwnerUserId":"11749543","Title":null,"Body":"

      I tried your code on Ubuntu 18.04.2 LTS machine with python 3.6.8 and tensorflow 1.13.1. It works in both cases as log shown below:<\/p>\n\n

      2019-07-13 12:56:17.003119: I tensorflow\/stream_executor\/dso_loader.cc:152] successfully opened CUDA library libcublas.so.10.0 locally\n100\/100 [==============================] - 3s 27ms\/step - loss: 0.9987\n100\/100 [==============================] - 10s 103ms\/step - loss: 0.9973 - val_loss: 0.9987\nEpoch 2\/2\n100\/100 [==============================] - 3s 26ms\/step - loss: 0.9955\n100\/100 [==============================] - 8s 83ms\/step - loss: 1.0028 - val_loss: 0.9955\nMultiprocessing=True ......\nEpoch 1\/2\n100\/100 [==============================] - 3s 32ms\/step - loss: 0.9952\n100\/100 [==============================] - 9s 89ms\/step - loss: 0.9962 - val_loss: 0.9952\nEpoch 2\/2\n100\/100 [==============================] - 3s 28ms\/step - loss: 0.9967\n100\/100 [==============================] - 9s 86ms\/step - loss: 0.9968 - val_loss: 0.9967\"\n<\/code><\/pre>\n\n

      My suggestion is to first try with CPU only mode, by putting BOTH the model and the fit_generator code under \"with tf.device('\/cpu:0'):\". If it works, it would be GPU related issue, such as proper driver, tensorflow with GPU support etc. Most likely, the issue was caused by GPU hanging.<\/p>\n"}]} {"QuestionId":55640642,"AnswerCount":1,"Tags":"","CreationDate":"2019-04-11T20:27:52.087","AcceptedAnswerId":55657233.0,"OwnerUserId":11348106.0,"Title":"Error when attempting to change tensor shape in keras model","Body":"

      I want to change the shape and the content of the tensor in a keras model. Tensor is the output of a layer and has <\/p>\n\n

      <\/p>\n\n

      and I want to convert to <\/p>\n\n

      <\/p>\n\n

      suitable as input of the next layer. Here sentences are made of tokens, and are zero-padded so every sentence has . \nIn detail:<\/p>\n\n

        \n
      1. I wanto to concatenate all the sentences of a batch taking only the nonzero part of the sentences;<\/li>\n
      2. then I zero-pad this concatenation to a .<\/li>\n<\/ol>\n\n

        So passing from to is not only a reshape as mathematical operations are involved.<\/p>\n\n

        I created the function that iterates on the tensor of shape1 to transform it into shape2. I call the function using a Lambda layer in the model, it works in debug with fictious data, but when I try to call it during the build of the model an error is raised: <\/p>\n\n

        <\/p>\n\n

        <\/pre>\n\n

        How to fix this?<\/p>\n","answers":[{"AnswerId":"55657233","CreationDate":"2019-04-12T17:54:38.403","ParentId":null,"OwnerUserId":"2912797","Title":null,"Body":"

        You can use py_function<\/code><\/a>, which allows you to switch from the graph mode (used by Keras) to the eager mode (where it is possible to iterate over tensors like in your function).<\/p>\n\n

        def to_docs(x):\n  return tf.py_function(embedding_to_docs, [x], tf.float32)\n\ntensor_of_shape2 = Lambda(to_docs)(tensor_of_shape1)\n<\/code><\/pre>\n\n

        Note that the code run within your embedding_to_docs<\/code> must be written in tensorflow eager instead of numpy. This means that you'd need to replace some of the numpy calls with tensorflow. You'd surely need to replace the return line with:<\/p>\n\n

        return tf.convert_to_tensor(new_output)\n<\/code><\/pre>\n\n

        Using numpy arrays will stop the gradient computation, but you are likely not interested in gradient flowing through the input data anyway.<\/p>\n"}]} {"QuestionId":55640836,"AnswerCount":2,"Tags":"","CreationDate":"2019-04-11T20:41:36.430","AcceptedAnswerId":null,"OwnerUserId":1601580.0,"Title":"How does one dynamically add new parameters to optimizers in Pytorch?","Body":"

        I was going through this post<\/a> in the pytorch forum, and I also wanted to do this. The original post removes and adds layers but I think my situation is not that different. I also want to add layers or more filters or word embeddings. My main motivation is that the AI agent does not know the whole vocabulary\/dictionary in advance because its large. I prefer strongly (for the moment) to not do character by character RNNs.<\/p>\n\n

        So what will happen for me is when the agent starts a forward pass it might find new words it has never seen and will need to add them to the embedding table (or perhaps add new filters before it starts the forward pass).<\/p>\n\n

        So what I want to make sure is:<\/p>\n\n

          \n
        1. embeddings are added correctly (at the right time, when a new computation graph is made) so that they are updatable by the optimizer<\/li>\n
        2. no issues with stored info of past parameters e.g. if its using some sort of momentum<\/li>\n<\/ol>\n\n

          How does one do this? Any sample code that works?<\/p>\n","answers":[{"AnswerId":"55776832","CreationDate":"2019-04-20T19:09:55.167","ParentId":null,"OwnerUserId":"5884955","Title":null,"Body":"

          Just to add an answer to the title of your question: \"How does one dynamically add new parameters to optimizers in Pytorch?\"<\/p>\n\n

          You can append params at any time to the optimizer:<\/p>\n\n

          import torch\nimport torch.optim as optim\n\nmodel = torch.nn.Linear(2, 2) \n\n# Initialize optimizer\noptimizer = optim.Adam(model.parameters(), lr=0.001, momentum=0.9)\n\nextra_params = torch.randn(2, 2)\noptimizer.param_groups.append({'params': extra_params })\n\n#then you can print your `extra_params`\nprint(\"extra params\", extra_params)\nprint(\"optimizer params\", optimizer.param_groups)\n<\/code><\/pre>\n"},{"AnswerId":"55766749","CreationDate":"2019-04-19T19:14:55.600","ParentId":null,"OwnerUserId":"4385912","Title":null,"Body":"

          \nThat is a tricky question, as I would argue that the answer is \"depends\", in particular on how you want to deal with the optimizer.<\/p>\n\n

          Let's start with your specific problem - an embedding. In particular, you are asking on how to add embeddings to allow for a larger vocabulary dynamically. My first advice is, that if you have a good sense of an upper boundary of your vocabulary size, make the embedding large enough to cope with it from the beginning, as this is more efficient, and as you will need the memory eventually anyway. But this is not what you asked. So - to dynamically change your embedding, you'll need to overwrite your old one with a new one, and inform your optimizer of the change. You can simply do that whenever you run into an exception with your old embedding, in a try ... except<\/code> block. This should roughly follow this idea:<\/p>\n\n

          # from within whichever module owns the embedding\n# remember the already trained weights\nold_embedding_weights = self.embedding.weight.data\n# create a new embedding of the new size\nself.embedding = nn.Embedding(new_vocab_size, embedding_dim)\n# initialize the values for the new embedding. this does random, but you might want to use something like GloVe\nnew_weights = torch.randn(new_vocab_size, embedding_dim)\n# as your old values may have been updated, you want to retrieve these updates values\nnew_weights[:old_vocab_size] = old_embedding_weights\nself.embedding.weights.data.copy_(new_weights)\n<\/code><\/pre>\n\n

          However, you should not do this for every single new word you receive, as this copying takes time (and a whole lot of memory, as the embedding exists twice for a short time - if you're nearly out memory, just make your embedding large enough from the start). So instead increase the size dynamically by a couple of hundred slots at a time.<\/p>\n\n

          Additionally, this first step already raises some questions:<\/p>\n\n

            \n
          1. How does my respective nn.Module<\/code> know about the new embedding parameter? \nThe __setattr__<\/code> method of nn.Module<\/code> takes care of that (see here<\/a>)<\/li>\n
          2. Second, why don't I simply change my parameter? That's already pointing towards some of the problems of changing the optimizer: pytorch internally keeps references by object ID. This means that if you change your object, all these references will point towards a potentially incompatible object, as its properties have changed. So we should simply create a new parameter instead.<\/li>\n
          3. What about other nn.Parameters<\/code> or nn.Modules<\/code> that are not embeddings? These you treat the same. You basically just instantiate them, and attach them to their parent module. The __setattr__<\/code> method will take care of the rest. So you can do so completely dyncamically ...<\/li>\n<\/ol>\n\n

            Except, of course, the optimizer. The optimizer is the only other thing that \"knows\" about your parameters except for your main model-module. So you need to let the optimizer know of any change. <\/p>\n\n

            And this is tricky, if you want to be sophisticated about it, and very easy if you don't care about keeping the optimizer state. However, even if you want to be sophisticated about it, there is a very good reason why you probably should not do this anyways. More about that below.<\/p>\n\n

            Anyways, if you don't care, a simple<\/p>\n\n

            # simply overwrite your old optimizer\noptimizer = optim.SGD(model.parameters(), lr=0.001)\n<\/code><\/pre>\n\n

            will do. If you care, however, you want to transfer your old state, you can do so the same way that you can store, and later load parameters and optimizer states from disk: using the .state_dict()<\/code> and .load_state_dict()<\/code> methods. This, however, does only work with a twist:<\/p>\n\n

            # extract the state dict from your old optimizer\nold_state_dict = optimizer.state_dict()\n# create a new optimizer\noptimizer = optim.SGD(model.parameters())\nnew_state_dict = optimizer.state_dict()\n# the old state dict will have references to the old parameters, in state_dict['param_groups'][xyz]['params'] and in state_dict['state']\n# you now need to find the parameter mismatches between the old and new statedicts\n# if your optimizer has multiple param groups, you need to loop over them, too (I use xyz as a placeholder here. mostly, you'll only have 1 anyways, so just replace xyz with 0\nnew_pars = [p for p in new_state_dict['param_groups'][xyz]['params'] if not p in old_state_dict['param_groups'][xyz]['params']]\nold_pars = [p for p in old_state_dict['param_groups'][xyz]['params'] if not p in new_state_dict['param_groups'][xyz]['params']]\n# then you remove all the outdated ones from the state dict\nfor pid in old_pars:\n    old_state_dict['state'].pop(pid)\n# and add a new state for each new parameter to the state:\nfor pid in new_pars:\n    old_state_dict['param_groups'][xyz]['params'].append(pid)\n    old_state_dict['state'][pid] = { ... }  # your new state def here, depending on your optimizer\n<\/code><\/pre>\n\n

            However, here's the reason why you should probably never<\/em> update your optimizer like this, but should instead re-initialize from scratch, and just accept the loss of state information: When you change your computation graph, you change forward and backward computation for all parameters along your computation path (if you do not have a branching architecture, this path will be your entire graph). This more specifically means, that the input to your functions (=layer\/nn.Module<\/code>) will be different if you change some function (=layer\/nn.Module<\/code>) applied earlier, and the gradients will change if you change some function (=layer\/nn.Module<\/code>) applied later. That in turn invalidates the entire state of your optimizer<\/strong>. So if you keep your optimizer's state around, it will be a state computed for a different computation graph, and will probably end up in catastrophic behavior on part of your optimizer, if you try to apply it to a new computation graph. (I've been there ...)<\/p>\n\n

            So - to sum it up: I'd really recommend to try to keep it simple, and to only change a parameter as conservatively as possible, and not to touch the optimizer.<\/p>\n"}]} {"QuestionId":55640948,"AnswerCount":0,"Tags":"","CreationDate":"2019-04-11T20:49:32.697","AcceptedAnswerId":null,"OwnerUserId":11131827.0,"Title":"What is the difference between using HDF5Matrix + .fit vs .fit_generator in Keras?","Body":"

            I already know the difference between fit() and fit_generator() in Keras. The former is used when the training data is \"small\" enough to fit into memory, while the latter is used to generate data from a file residing on disk because the training data would be too large to load into memory.<\/p>\n\n

            But another way to handle the problem of large data (saved as .hdf5) is to import your training data using the keras HDF5Matrix as follows:<\/p>\n\n

            <\/pre>\n\n

            And then train your model using .fit()<\/p>\n\n

            <\/pre>\n\n

            In that case, would there be an advantage for using a fit_generator over the simple .fit() function?<\/p>\n\n

            The only answer I found on the net was here:<\/p>\n\n

            https:\/\/github.com\/keras-team\/keras\/issues\/6298#issuecomment-294586859<\/a><\/p>\n\n

            Thank you<\/p>\n","answers":[]} {"QuestionId":55641125,"AnswerCount":2,"Tags":"","CreationDate":"2019-04-11T21:02:19.503","AcceptedAnswerId":55757076.0,"OwnerUserId":10597829.0,"Title":"Minimum required hardware component to install tensorflow-gpu in python","Body":"

            I'm tried many PC with different hardware capability to install tensorflow on gpu, they are either un-compatible or compatible but stuck in some point. I would like to know the minimum hardware required to install tensorflow-gpu. And also I would like to ask about some hardware, Is they are allowed or not:\nCan I use core i5 instead of core i7 ??\nIs 4 GB gpu enough for training the dataset??\nIs 8 GB ram enough for training and evaluating the dataset ??\nI'm not good in hardware, can anyone please help me? Thanks.<\/p>\n","answers":[{"AnswerId":"55757076","CreationDate":"2019-04-19T05:34:09.457","ParentId":null,"OwnerUserId":"11127923","Title":null,"Body":"

            TensorFlow (TF) GPU 1.6 and above requires cuda compute capability (ccc) of 3.5 or higher and requires AVX instruction support.
            \n
            https:\/\/www.tensorflow.org\/install\/gpu#hardware_requirements<\/a>.\nhttps:\/\/www.tensorflow.org\/install\/pip#hardware-requirements<\/a>.<\/p>\n\n

            Therefore you would want to buy a graphics card that has ccc above 3.5.\nHere's a link that shows ccc for various nvidia graphic cards https:\/\/developer.nvidia.com\/cuda-gpus<\/a>.<\/p>\n\n

            However if your cuda compute capability is below 3.5 you have to compile TF from sources yourself. This procedure may or may not work depending on the build flags you choose while compiling and is not straightforward.\nIn my humble opinion, The simplest way is to use TF-GPU pre-built binaries to install TF GPU.<\/p>\n\n

            To answer your questions. Yes you can use TF comfortably on i5 with 4gb of graphics card and 8gb ram. The training time may take longer though, depending on task at hand.<\/p>\n\n

            In summary, the main hardware requirement to install TF GPU is getting a Nvidia graphics card with cuda compute capability more than 3.5, more the merrier.\nNote that TF officially supports only NVIDIA graphics card.<\/p>\n"},{"AnswerId":"55642174","CreationDate":"2019-04-11T22:43:32.673","ParentId":null,"OwnerUserId":"3443106","Title":null,"Body":"

            You should find your answers here:<\/p>\n\n

            https:\/\/www.nvidia.com\/en-gb\/data-center\/gpu-accelerated-applications\/tensorflow\/<\/a><\/p>\n\n

            From the link:<\/p>\n\n

            \n

            The GPU-enabled version of TensorFlow has the following requirements:<\/p>\n \n