{"QuestionId":56228711,"AnswerCount":1,"Tags":"","CreationDate":"2019-05-20T21:59:53.063","AcceptedAnswerId":56237863.0,"OwnerUserId":null,"Title":"Error on tensorflow: Shape must be rank 2 but is rank 1 for 'MatMul_25'","Body":"

I'm trying to create a conditional GAN. However, i'm stuck as to why no matter what i do, it appears the same error over and over again. \nHere's the code:<\/p>\n\n

<\/pre>\n\n

Right after executing the Generator i get the following error:<\/p>\n\n

<\/pre>\n\n

What to do?<\/p>\n","answers":[{"AnswerId":"56237863","CreationDate":"2019-05-21T12:01:11.360","ParentId":null,"OwnerUserId":"2455494","Title":null,"Body":"

I think you just missed one call to xavier_init()<\/code> when initialising your weights.<\/p>\n\n

You have this:<\/p>\n\n

weights = {\n    'disc_H' : tf.Variable(xavier_init([image_dim + Y_dimension, disc_hidd_dim])),\n    'disc_final' : tf.Variable(xavier_init([disc_hidd_dim, 1])),\n    'gen_H': tf.Variable([z_noise_dim + Y_dimension, gen_hidd_dim]),\n    'gen_final': tf.Variable(xavier_init([gen_hidd_dim, image_dim]))\n}\n<\/code><\/pre>\n\n

but I think you want this:<\/p>\n\n

weights = {\n    'disc_H' : tf.Variable(xavier_init([image_dim + Y_dimension, disc_hidd_dim])),\n    'disc_final' : tf.Variable(xavier_init([disc_hidd_dim, 1])),\n    'gen_H': tf.Variable(xavier_init([z_noise_dim + Y_dimension, gen_hidd_dim])),\n    'gen_final': tf.Variable(xavier_init([gen_hidd_dim, image_dim]))\n}\n<\/code><\/pre>\n\n

The error message was because weights['gen_H']<\/code> had shape [2]<\/code> whereas you expected it to have shape [110, 256]<\/code>. This meant that the call to tf.matmul()<\/code> failed because it's impossible to matrix multiply a matrix with shape [m, 110]<\/code> by a matrix of shape [2]<\/code><\/p>\n"}]} {"QuestionId":56228959,"AnswerCount":0,"Tags":"","CreationDate":"2019-05-20T22:30:14.537","AcceptedAnswerId":null,"OwnerUserId":11472298.0,"Title":"Is there any package to check GPUs status for Jupyter notebook?","Body":"

I'm working on the gpu workstation with my collegues and often I need to check GPUs status to see which gpus are free. Usually I use NvidiaSMI tool but then I need to manually update it every time I want to see the status. Is there a package for Jupyter notebook or maybe stand alone app which can show status in real time or send notifications when somebody started to use one of the GPUs?<\/p>\n","answers":[]} {"QuestionId":56229468,"AnswerCount":1,"Tags":"","CreationDate":"2019-05-20T23:51:54.943","AcceptedAnswerId":null,"OwnerUserId":3725021.0,"Title":"Custom Keras metric return 'axis out of bounds' error","Body":"

I've built a multi-class, multi-label image classification network using Keras. There are 25 classes overall and each image has at least one class in it. I want to implement a custom accuracy metric which tells me how often the highest probability class is in the image (regular accuracy is less meaningful as the true positives are swamped by the true negatives). <\/p>\n\n

I've built a simple function which generates the desired accuracy metric when I manually feed in y_true and y_pred. However when I try and insert this function into the model training process, it produces an error. <\/p>\n\n

<\/pre>\n\n
\n

AxisError: axis 1 is out of bounds for array of dimension 1<\/p>\n<\/blockquote>\n","answers":[{"AnswerId":"56229636","CreationDate":"2019-05-21T00:22:14.690","ParentId":null,"OwnerUserId":"8272600","Title":null,"Body":"

TL;DR<\/h2>\n\n

y_pred<\/code> is 1D, it only has one possible axis. Remove axis=1<\/code> from your np.argmax<\/code> call.<\/p>\n\n


\n\n

Walkthrough<\/h2>\n\n

The problem in this particular case is this line:<\/p>\n\n

classPreds = np.array([np.eye(numClasses)[x] for x in  np.argmax(y_pred, axis=1)])\n<\/code><\/pre>\n\n

Specifically: np.argmax(y_pred, axis=1)<\/code>.\nYour y_pred<\/code> is a one-dimensional array - such as [0.1, 0.2]<\/code> - and you're telling np.argmax<\/code> to look for values across axis=1<\/code> which doesn't exist unless you pass arrays with two or more dimensions - such as [[0.1, 0.2], [0.3, 0.4]]<\/code>.<\/p>\n\n

An actionable example:<\/p>\n\n

>>> import numpy as np\n>>> num_classes = 25\n>>> np.argmax([0.1, 0.5, 0.9]) # max value's index on 1D array\n2\n>>> np.argmax([0.1, 0.5, 0.9], axis=1) # max value's index on axis 1 of 1D array\nAxisError: axis 1 is out of bounds for array of dimension 1\n<\/code><\/pre>\n\n

Had y_pred<\/code> been a 2D array, the axis error wouldn't happen - but np.argmax<\/code> would then return a list of indexes instead of a scalar<\/strong>, such as below:<\/p>\n\n

>>> np.argmax([\n...     [0.1, 0.5, 0.9],\n...     [0.9, 0.5, 0.1]\n... ], axis=1)\narray([2, 0], dtype=int64) # first array's max at index 2, second array's max at index 0\n<\/code><\/pre>\n\n

By taking away axis=1<\/code> from argmax<\/code>, you'll then get the correct, scalar index for the maximum value within y_pred<\/code>.<\/p>\n"}]} {"QuestionId":56229630,"AnswerCount":1,"Tags":"","CreationDate":"2019-05-21T00:20:56.383","AcceptedAnswerId":56416231.0,"OwnerUserId":3757672.0,"Title":"Keras fit_generator() - How does batch for time series work?","Body":"

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

I am currently working on time series prediction using Keras with Tensorflow backend and, therefore, studied the tutorial provided here<\/a>.<\/p>\n\n

Following this tutorial, I came to the point where the generator for the method is described.\nThe output this generator generates is as follows (left sample, right target):<\/p>\n\n

<\/pre>\n\n

In the tutorial the was used, but for my question it is secondary if a custom generator or this class is used.\nRegarding the data, we have 8 steps_per_epoch and a sample of shape (8, 1, 2, 2).\nThe generator is fed to a Recurrent Neural Network, implemented by an LSTM.<\/p>\n\n

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

only allows a single target per batch, as outputted by the .\nWhen I first read about the option of batches for fit(), I thought that I could have multiple samples and a corresponding number of targets (which are processed batchwise, meaning row by row). But this is not allowed by and, therefore, obviously false.\nThis would look for example like:<\/p>\n\n

<\/pre>\n\n

Secondly, I thought that, for example, [10, 15] and [20, 25] were used as input for the RNN consecutively for the target [30, 35], meaning that this is analog to inputting [10, 15, 20, 25]. Since the output from the RNN differs using the second approach (I tested it), this also has to be a wrong conclusion.<\/p>\n\n

Hence, my questions are:<\/p>\n\n

    \n
  1. Why is only one target per batch allowed (I know there are some\nworkarounds, but there has to be a reason)? <\/li>\n
  2. How may I understand the\ncalculation of one batch? Meaning, how is some input like processed and why is it not analog to\n<\/li>\n<\/ol>\n\n


    \n
    \nEdit according to todays answer<\/em><\/strong>
    \nSince there is some misunderstanding about my definition of samples and targets - I follow what I understand Keras is trying to tell me when saying:<\/p>\n\n

    \n

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

    This error occurs, when I create for example a batch which looks like:<\/p>\n\n

    <\/pre>\n\n

    This is supposed to be a single batch containing two time-sequences of length 5 (5 consecutive data points \/ time-steps), whose targets are also two corresponding sequences. is the target of and is the corresponding target of .
    \nThe sample-shape in this would be and the target-shape .
    \nKeras sees 2 target samples (in the ValueError), because I have two provide 3D-samples as input and 2D-targets as output (maybe I just don't get how to provide 3D-targets..).<\/p>\n\n

    Anyhow, according to @todays answer\/comments, this is interpreted as two timesteps and five features by Keras. Regarding my first question (where I still see a sequence as target to my sequence, as in this edit-example), I seek information how\/if I can achieve this and how such a batch would look like (like I tried to visualize in the question).<\/p>\n","answers":[{"AnswerId":"56416231","CreationDate":"2019-06-02T15:05:10.450","ParentId":null,"OwnerUserId":"2099607","Title":null,"Body":"

    Short answers:<\/strong><\/p>\n\n

    \n

    Why is only one target per batch allowed (I know there are some workarounds, but there has to be a reason)?<\/p>\n<\/blockquote>\n\n

    That's not the case at all. There is no restriction on the number of target samples in a batch. The only requirement is that you should have the same number of input and target samples in each batch. Read the long answer for further clarification.<\/p>\n\n

    \n

    How may I understand the calculation of one batch? Meaning, how is some input like [[[40,\n 45], [50, 55]]] => [[60, 65]]<\/code> processed and why is it not analog to [[[40, 45, 50, 55]]] => [[60, 65]]<\/code>?<\/p>\n<\/blockquote>\n\n

    The first one is a multi-variate timeseries (i.e. each timestep has more than one features), and the second one is a uni-variate timeseris (i.e. each timestep has one feature). So they are not equivalent. Read the long answer for further clarification.<\/p>\n\n

    Long answer:<\/strong><\/p>\n\n

    I'll give the answer I mentioned in comments section and try to elaborate on it using examples:<\/em><\/p>\n\n

    I think you are mixing samples, timesteps, features and targets. Let me describe how I understand it: in the first example you provided, it seems that each input sample consists of 2 timesteps, e.g. [10, 15]<\/code> and [20, 25]<\/code>, where each timestep consists of two features, e.g. 10 and 15 or 20 and 25. Further, the corresponding target consists of one timestep, e.g. [30, 35]<\/code>, which also has two features. In other words, each input sample in a batch must<\/strong> have a corresponding target. However, the shape of each input sample and its corresponding target may not be necessarily the same.<\/p>\n\n

    For example, consider a model where both its input and output are timeseries. If we denote the shape of each input sample<\/strong> as (input_num_timesteps, input_num_features)<\/code> and the shape of each target (i.e. output) array<\/strong> as (output_num_timesteps, output_num_features)<\/code>, we would have the following cases:<\/p>\n\n

    1) The number of input and output timesteps are the same (i.e. input_num_timesteps == output_num_timesteps<\/code>). Just as an example, the following model could achieve this:<\/p>\n\n

    from keras import layers\nfrom keras import models\n\ninp = layers.Input(shape=(input_num_timesteps, input_num_features))\n\n# a stack of RNN layers on top of each other (this is optional)\nx = layers.LSTM(..., return_sequences=True)(inp)\n# ...\nx = layers.LSTM(..., return_sequences=True)(x)\n\n# a final RNN layer that has `output_num_features` unit\nout = layers.LSTM(output_num_features, return_sequneces=True)(x)\n\nmodel = models.Model(inp, out)\n<\/code><\/pre>\n\n

    2) The number of input and output timesteps are different (i.e. input_num_timesteps ~= output_num_timesteps<\/code>). This is usually achieved by first encoding the input timeseries into a vector using a stack of one or more LSTM layers, and then repeating that vector output_num_timesteps<\/code> times to get a timeseries of desired length. For the repeat operation, we can easily use RepeatVector<\/code> layer in Keras. Again, just as an example, the following model could achieve this:<\/p>\n\n

    from keras import layers\nfrom keras import models\n\ninp = layers.Input(shape=(input_num_timesteps, input_num_features))\n\n# a stack of RNN layers on top of each other (this is optional)\nx = layers.LSTM(..., return_sequences=True)(inp)\n# ...\nx = layers.LSTM(...)(x)  # The last layer ONLY returns the last output of RNN (i.e. return_sequences=False)\n\n# repeat `x` as needed (i.e. as the number of timesteps in output timseries)\nx = layers.RepeatVector(output_num_timesteps)(x)\n\n# a stack of RNN layers on top of each other (this is optional)\nx = layers.LSTM(..., return_sequences=True)(x)\n# ...\nout = layers.LSTM(output_num_features, return_sequneces=True)(x)\n\nmodel = models.Model(inp, out)\n<\/code><\/pre>\n\n

    As a special case, if the number of output timesteps is 1 (e.g. the network is trying to predict the next timestep given the last t<\/code> timesteps), we may not need to use repeat and instead we can just use a Dense<\/code> layer (in this case the output shape of the model would be (None, output_num_features)<\/code>, and not (None, 1, output_num_features)<\/code>):<\/p>\n\n

    inp = layers.Input(shape=(input_num_timesteps, input_num_features))\n\n# a stack of RNN layers on top of each other (this is optional)\nx = layers.LSTM(..., return_sequences=True)(inp)\n# ...\nx = layers.LSTM(...)(x)  # The last layer ONLY returns the last output of RNN (i.e. return_sequences=False)\n\nout = layers.Dense(output_num_features, activation=...)(x)\n\nmodel = models.Model(inp, out)\n<\/code><\/pre>\n\n
    \n\n

    Note that the architectures provided above are just for illustration, and you may need to tune or adapt them, e.g. by adding more layers such as Dense<\/code> layer, based on your use case and the problem you are trying to solve.<\/strong><\/p>\n\n


    \n\n

    Update:<\/strong> The problem is that you don't pay enough attention when reading, both my comments and answer as well as the error raised by Keras. The error clearly states that:<\/p>\n\n

    \n

    ... Found 1 input samples and 2 target samples.<\/p>\n<\/blockquote>\n\n

    So, after reading this carefully, if I were you I would say to myself: \"OK, Keras thinks that the input batch has 1 input sample, but I think I am providing two samples!! Since I am a very good person(!), I think it's very likely that I would be wrong than Keras, so let's find out what I am doing wrong!\". A simple and quick check would be to just examine the shape of input array:<\/p>\n\n

    >>> np.array([[[0, 1, 2, 3, 4],\n               [5, 6, 7, 8, 9]]]).shape\n(1,2,5)\n<\/code><\/pre>\n\n

    \"Oh, it says (1,2,5)<\/code>! So that means one<\/strong> sample which has two<\/strong> timesteps and each timestep has five features!!! So I was wrong into thinking that this array consists of two samples of length 5 where each timestep is of length 1!! So what should I do now???\" Well, you can fix it, step-by-step:<\/p>\n\n

    # step 1: I want a numpy array\ns1 = np.array([])\n\n# step 2: I want it to have two samples\ns2 = np.array([\n               [],\n               []\n              ])\n\n# step 3: I want each sample to have 5 timesteps of length 1 in them\ns3 = np.array([\n               [\n                [0], [1], [2], [3], [4]\n               ],\n               [\n                [5], [6], [7], [8], [9]\n               ]\n              ])\n\n>>> s3.shape\n(2, 5, 1)\n<\/code><\/pre>\n\n

    Voila! We did it! This was the input array; now check the target array, it must have two target samples of length 5 each with one feature, i.e. having a shape of (2, 5, 1)<\/code>:<\/p>\n\n

    >>> np.array([[ 5,  6,  7,  8,  9],\n              [10, 11, 12, 13, 14]]).shape\n(2,5)\n<\/code><\/pre>\n\n

    Almost! The last dimension (i.e. 1<\/code>) is missing (NOTE:<\/strong> depending on the architecture of your model you may or may not need that last axis). So we can use the step-by-step approach above to find our mistake, or alternatively we can be a bit clever and just add an axis to the end:<\/p>\n\n

    >>> t = np.array([[ 5,  6,  7,  8,  9],\n                  [10, 11, 12, 13, 14]])\n>>> t = np.expand_dims(t, axis=-1)\n>>> t.shape\n(2, 5, 1)\n<\/code><\/pre>\n\n

    Sorry, I can't explain it better than this! But in any case, when you see that something (i.e. shape of input\/target arrays) is repeated over and over in my comments and my answer, assume that it must be something important and should be checked.<\/p>\n"}]} {"QuestionId":56229730,"AnswerCount":0,"Tags":"","CreationDate":"2019-05-21T00:38:39.157","AcceptedAnswerId":null,"OwnerUserId":11506976.0,"Title":"Trouble with zero-padding inputs for Steered Convolution Layer","Body":"

    I'm using Tensorflow's new graphics library to apply a steered convolution to a series of meshes. In many cases, you will have a series of meshes that are not the same size and you must zero-pad the smaller ones. According to the documentation, the \"sizes\" argument of the graph_conv.feature_steered_convolution_layer function takes in an int tensor consisting of the number of non-padded elements of each mesh. For some reason, when this argument is set something other than \"None\", I get a warning telling me that the sparse array used in the \"neighbors\" argument is being converted to a dense matrix. This causes my program to run absurdly slowly. <\/p>\n\n

    The issue seems to be tied to the way that it calculates gradients. If the optimizer is commented out, the error does not come up. <\/p>\n\n

    I read about a similar problem (link below) where the solution to the problem was to use tf.dynamic_partition rather than tf.gather. However, the tf.gather functions, in this case are located within the graph_convolution library. I attempted to make some edits in my copy of the library, but to no avail.<\/p>\n\n

    How to deal with UserWarning: Converting sparse IndexedSlices to a dense Tensor of unknown shape<\/a><\/p>\n\n

    <\/pre>\n\n

    When the above code is run, I get the following warning:<\/p>\n\n

    <\/pre>\n\n

    I am starting to think that this might have more to do with the library itself than with this piece of code. I have referenced this posed in GitHub in case it requires updates (or additional documentation) to the library.\nhttps:\/\/github.com\/tensorflow\/graphics\/issues\/13<\/a><\/p>\n","answers":[]} {"QuestionId":56229994,"AnswerCount":0,"Tags":"","CreationDate":"2019-05-21T01:33:52.937","AcceptedAnswerId":null,"OwnerUserId":9064615.0,"Title":"keyerror the name \"import\/Placeholder\" refers to an operation not in the graph","Body":"

    So I was trying to run the Tensorflow retraining for the Inception V3 model, and no matter what I tried, running the label_image command didn't work.<\/p>\n\n

    I tried resetting the values as such:<\/p>\n\n

    <\/pre>\n\n

    and like so:<\/p>\n\n

    <\/pre>\n\n

    the command <\/p>\n\n

    <\/pre>\n\n

    yields the error in the title.<\/p>\n\n

    changing the command to:<\/p>\n\n

    <\/pre>\n\n

    gives the same error but with 'import\/input'<\/p>\n\n

    Command as it is now:<\/p>\n\n

    <\/pre>\n\n

    Error:<\/p>\n\n

    <\/pre>\n","answers":[]}
    {"QuestionId":56230051,"AnswerCount":0,"Tags":"","CreationDate":"2019-05-21T01:44:37.947","AcceptedAnswerId":null,"OwnerUserId":7976906.0,"Title":"Implementation of Cox Layer in order to predict time to event in Keras","Body":"

    I am trying to implement a convolutional neural network which takes as input images (histology images) and generates as output a variable representing time to event (the time until death).\nI have built a convolutional neural network similar to VGG in order to be able to extract features from images. In addition to those i want to add a Cox proportional hazard layer in order to use it for back propagation.\nDo you know if there exist an implementation of this kind of layer in keras? <\/p>\n\n

    I was thinking of creating it as a fully connected layer with a custom activation function, but it seems kind of difficult to get it right.<\/p>\n","answers":[]} {"QuestionId":56230171,"AnswerCount":1,"Tags":"","CreationDate":"2019-05-21T02:04:06.417","AcceptedAnswerId":56230603.0,"OwnerUserId":239879.0,"Title":"ValueError: Argument must be a dense tensor: ((10, 4945), 1024) - got shape [2], but wanted [2, 2]","Body":"

    My model is:<\/p>\n\n

    <\/pre>\n\n

    and I get an error:<\/p>\n\n

    <\/pre>\n\n

    I'm not sure what I'm doing incorrectly. Any help would be appreciated.<\/p>\n","answers":[{"AnswerId":"56230603","CreationDate":"2019-05-21T03:16:11.593","ParentId":null,"OwnerUserId":"5810950","Title":null,"Body":"

    As per the keras<\/a> official Documentation, input_dim<\/strong> parameter of embedding layer should be the size of the vocabulary, i.e. maximum integer index + 1 (int>0).<\/p>\n\n

    So, you code should be:<\/p>\n\n

    model.add(Embedding(input_dim=len(self._tokens), output_dim=1024))\n<\/code><\/pre>\n\n

    In case, you haven't added input_length<\/strong> and input_shape<\/strong> parameters in the embedding layer, then <\/p>\n\n

    input_shape = (None,)\n<\/code><\/pre>\n\n

    else<\/p>\n\n

    input_shape = (input_length,) # added 'input_length=' parameter\n<\/code><\/pre>\n\n

    For more info check the official code here<\/a>.<\/p>\n"}]} {"QuestionId":56230196,"AnswerCount":0,"Tags":"","CreationDate":"2019-05-21T02:07:13.970","AcceptedAnswerId":null,"OwnerUserId":11531123.0,"Title":"How can I test 2D convolution with keras","Body":"

    I am creating my own 2D depthwise seperable convolution method and I want to test it against what keras does.<\/p>\n\n

    From what I understand, the right function is <\/p>\n\n

    I am trying to give it an input tensor and get an output tensor, but can't seem to manage it.<\/p>\n\n

    I am trying to keep it simple. A 3x3 input matrix and a 3x3 kernel.<\/p>\n\n

    <\/pre>\n\n

    Like I said I want to keep it simple. So if this is my depthwise kernel and my pointwise kernel is weighted all 1s, how would I get this to work with keras?<\/p>\n","answers":[]} {"QuestionId":56230316,"AnswerCount":0,"Tags":"","CreationDate":"2019-05-21T02:25:51.167","AcceptedAnswerId":null,"OwnerUserId":11531091.0,"Title":"Try to use tf.keras to learn the stocks and after learning 500 stocks, tf became very slow","Body":"

    I try to use to compute the pattern of stocks. I use the following codes to compute about 500 stocks at the beginning of some month. And then store some good results in memory (predict each of the stocks in that month). Then the 2nd month I will again compute these 500 stocks and then do the daily predictions. And so on. I am using and . From the 2nd months' learning, it became slower and slower. Especially the first epoch for every stock. <\/p>\n\n

    Is this because of the low efficiency of the GPU-memory reading data from memory of PC? What I can do about it? <\/p>\n\n

    I tried using code like the following to limit the taking-up of GPU-memory. But no use. It still becomes slower.<\/p>\n\n

    <\/pre>\n\n

    You can see after several months the first epoch of every stocks' learning became ridiculously slow.<\/p>\n","answers":[]} {"QuestionId":56230510,"AnswerCount":1,"Tags":"","CreationDate":"2019-05-21T03:00:34.713","AcceptedAnswerId":null,"OwnerUserId":10655237.0,"Title":"Tensorflow Keras cannot properly resume training at initial epoch from checkpoint file","Body":"

    I am loading a keras model in tensorflow to resume training. I want to continue training from the epoch I stopped at so that epoch numbers are unique and I can keep track of the number of epochs. The model is loaded from a checkpoint file created by a callback that saves the highest accuracy. When I resume training in model.fit(), I set the \"initial epoch\" to be 52 and set \"epoch\" to 52+5. However, it starts training from epoch 1\/57 instead of 53\/57 and will keep going up to 57 even though I only want 5 epochs. Am I loading something wrongly? Training resumes as 'normal' and accuracy is where I left off, but the epoch numbers do not continue from where I want, and keep restarting from 1.<\/p>\n\n

    I have tried removing the checkpoint callback initialisation when loading form the checkpoint file, but that generates a name error as the \"callbacks list\" is not defined.<\/p>\n\n

    <\/pre>\n\n

    I expect to see epoch 53\/57 and 5 epochs of training when resuming from a saved file.\nI get epoch 1\/57 and 57 epochs of training<\/p>\n","answers":[{"AnswerId":"58469365","CreationDate":"2019-10-20T01:33:54.753","ParentId":null,"OwnerUserId":"8147466","Title":null,"Body":"

    Had the same issue, \nTo solve it I modified the ModelCheckpoint<\/em>(Callback) class.<\/p>\n\n

    I added and saved a dedicated tensorflow checkpoint for epoch, in the on_epoch_begin<\/em> callback function.<\/p>\n\n

    The network doesn't store its training progress with respect to training data - this is not part of its state, because at any point you could decide to change what data set to feed it. <\/a><\/p>\n\n

    class EpochModelCheckpoint(tf.keras.callbacks.ModelCheckpoint):\n\n    def __init__(self,filepath, monitor='val_loss', verbose=1, \n                 save_best_only=True, save_weights_only=True, \n                 mode='auto', ):\n\n        super(EpochModelCheckpoint, self).__init__(filepath=filepath,monitor=monitor,\n             verbose=verbose,save_best_only=save_best_only,\n             save_weights_only=save_weights_only, mode=mode)\n\n        self.ckpt = tf.train.Checkpoint(completed_epochs=tf.Variable(0,trainable=False,dtype='int32'))\n        ckpt_dir = f'{os.path.dirname(filepath)}\/tf_ckpts'\n        self.manager = tf.train.CheckpointManager(self.ckpt, ckpt_dir, max_to_keep=3)\n\n    def on_epoch_begin(self,epoch,logs=None):        \n        self.ckpt.completed_epochs.assign(epoch)\n        self.manager.save()\n        print( f\"Epoch checkpoint {self.ckpt.completed_epochs.numpy()}  saved to: {self.manager.latest_checkpoint}\" ) \n        print(logs)\n\ndef callbacks(checkpoint_dir, model_name):\n\n    best_model = os.path.join(checkpoint_dir, '{}_best.hdf5'.format(model_name))\n    save_best = EpochModelCheckpoint( best_model  )\n    return [ save_best ]\n\ndef train():\n\n    ...\n\n    model = get_compiled_model()\n    checkpoint_dir = \".\/checkpoint_dir\"\n    model_name = \"my_model\"\n    # Init checkpoint value\n    ckpt = tf.train.Checkpoint(completed_epochs=tf.Variable(0,trainable=False,dtype='int32'))\n    manager = tf.train.CheckpointManager(ckpt, f'{checkpoint_dir}\/tf_ckpts', max_to_keep=3)    \n\n    best_weights = os.path.join(checkpoint_dir, f'{model_name}_best.hdf5') \n    if os.path.exists(best_weights):\n        print(f'Loading model {best_weights}')\n        model.load_weights(best_weights)\n\n        # Restore last Epoch\n        ckpt.restore(manager.latest_checkpoint)\n        if manager.latest_checkpoint:\n            print(f\"Restored epoch ckpt from {manager.latest_checkpoint}, value is \",ckpt.completed_epochs.numpy())\n        else:\n            print(\"Initializing from scratch.\")\n\n     ...\n    # Set initial_epoch in the model fit to last seen Epoch\n    completed_epochs=ckpt.completed_epochs.numpy()\n    history = model.fit(\n        x=train_ds,\n        epochs=cfg.epochs,\n        steps_per_epoch=cfg.steps,\n        callbacks=callbacks( checkpoint_dir, model_name ),        \n        validation_data=val_ds,\n        validation_steps=cfg.val_steps,\n        initial_epoch=completed_epochs )\n<\/code><\/pre>\n"}]}
    {"QuestionId":56230511,"AnswerCount":1,"Tags":"","CreationDate":"2019-05-21T03:00:45.633","AcceptedAnswerId":56245037.0,"OwnerUserId":10609482.0,"Title":"How to properly convert pytorch LSTM to keras CuDNNLSTM?","Body":"

    I am trying to hand-convert a Pytorch model to Tensorflow for deployment. ONNX doesn't seem to natively go from Pytorch LSTMs to Tensorflow CuDNNLSTMs so that's why I'm writing it by hand.<\/p>\n\n

    I've tried the code below:\nThis is running in an Anaconda environment running Python 2.7, Pytorch 1.0, tensorflow 1.12, cuda9. I'm running this with no bias in the Pytorch layer as it follows a batchnorm, but since Keras does not provide that option I'm simply assigning a 0 bias. <\/p>\n\n

    <\/pre>\n\n
    <\/pre>\n\n

    Now, this does work with the generic Keras LSTM:<\/p>\n\n

    <\/pre>\n\n

    But I need the speed advantages of the CuDNNLSTM, and Pytorch is using the same backend anyway.<\/p>\n","answers":[{"AnswerId":"56245037","CreationDate":"2019-05-21T19:14:28.037","ParentId":null,"OwnerUserId":"10609482","Title":null,"Body":"

    Update: the solution was to convert the torch model into a keras base LSTM model, then call<\/p>\n\n

    base_lstm_model.save_weights('1.h5')\ncudnn_lstm_model.load_weights('1.h5')\n<\/code><\/pre>\n"}]}
    {"QuestionId":56230765,"AnswerCount":0,"Tags":"","CreationDate":"2019-05-21T03:41:07.500","AcceptedAnswerId":null,"OwnerUserId":10736572.0,"Title":"Error: No operation named [input] in the Graph","Body":"

    I am running tensorflow with react native. I have a retrained Inception V3 graph. I used a GitHub repo example to test if a model other than my own would work, and it functioned perfectly well. When I attempt to use my own model, I get the Error:<\/p>\n\n

    \n

    \"No Operation named [input] in the graph\"<\/p>\n<\/blockquote>\n\n

    Dev Info, , , <\/p>\n\n

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

    <\/pre>\n","answers":[]}
    {"QuestionId":56230827,"AnswerCount":2,"Tags":"","CreationDate":"2019-05-21T03:50:23.353","AcceptedAnswerId":56241150.0,"OwnerUserId":3017656.0,"Title":"Control dependencies in TensorFlow","Body":"

    I am trying to understand the following behavior: When I run the code<\/p>\n\n

    <\/pre>\n\n

    the result is sometimes as I would expect, but sometimes it is . The result of indicates that the dependency was ignored. However, since I sometimes get , must have been computed, which to my understanding could only have been triggered by the dependency.<\/p>\n\n

    If I do something similar, but without the tensor , e.g,<\/p>\n\n

    <\/pre>\n\n

    the result is always as expected.<\/p>\n\n

    Can someone please explain why the behavior is different in the second case, and how I could enforce the evaluation of after has been updated in the first case?<\/p>\n","answers":[{"AnswerId":"56241150","CreationDate":"2019-05-21T14:59:46.830","ParentId":null,"OwnerUserId":"1782792","Title":null,"Body":"

    You have to make sure that f<\/code> is computed after the first assignment has taken place. So:<\/p>\n\n

    import tensorflow as tf\n\nx = tf.Variable(1.0)\ny = tf.Variable(0.0)\n\nop0 = tf.assign_add(x, 1.0)\nwith tf.control_dependencies([op0]):\n  f = x * x \nop1 = tf.assign(y, f)\n\nwith tf.Session() as sess:\n  sess.run(tf.global_variables_initializer())\n  sess.run(tf.local_variables_initializer())\n  sess.run(op1)\n  print(y.eval())\n  # 4.0\n<\/code><\/pre>\n"},{"AnswerId":"56241012","CreationDate":"2019-05-21T14:53:08.047","ParentId":null,"OwnerUserId":"3017656","Title":null,"Body":"

    I think I found a solution. In my application I actually evaluate the gradient of f<\/code>, not f<\/code> itself, so the following seems to work:<\/p>\n\n

    import tensorflow as tf\n\nx = tf.Variable(1.0)\ny = tf.Variable(0.0)\nf = x*x\ndf = tf.gradients(f, x)[0]\n\nop0 = tf.assign_add(x, 1.0)\nwith tf.control_dependencies([op0]):\n  #op1 = tf.assign(y, df) <--- does not work\n  df_new = tf.gradients(f, x)[0]\n  op1 = tf.assign(y, df_new) # <--- seems to work\n\nwith tf.Session() as sess:\n  sess.run(tf.global_variables_initializer())\n  sess.run(tf.local_variables_initializer())\n  sess.run(op1)\n  print(y.eval())\n<\/code><\/pre>\n"}]}
    {"QuestionId":56231191,"AnswerCount":0,"Tags":"","CreationDate":"2019-05-21T04:40:07.443","AcceptedAnswerId":null,"OwnerUserId":11531494.0,"Title":"Error when adding Maxpooling layer in ConvLSTM model","Body":"

    I want to add Maxpooling1D layer after ConvLSTM2D layer. Does it makes sense to add maxpooling layer after convlstm2d layer?<\/p>\n\n

    Dimensions of my dataset are <\/p>\n\n

    <\/pre>\n\n

    I am getting the following error,<\/p>\n\n

    <\/pre>\n","answers":[]}
    {"QuestionId":56231695,"AnswerCount":1,"Tags":"","CreationDate":"2019-05-21T05:36:59.070","AcceptedAnswerId":56231916.0,"OwnerUserId":7353970.0,"Title":"When should tf.losses.add_loss() be used in TensorFlow?","Body":"

    I cannot find an answer to this question in the TensorFlow documentation. I once read that one should add losses from functions but it isn't necessary for functions from . Therefore:<\/p>\n\n

    When should I use ?<\/p>\n\n

    Example:<\/p>\n\n

    <\/pre>\n\n

    Thank yoou.<\/p>\n","answers":[{"AnswerId":"56231916","CreationDate":"2019-05-21T05:59:10.380","ParentId":null,"OwnerUserId":"867889","Title":null,"Body":"

    One would use this method to register the loss defined by user.<\/p>\n\n

    Namely, if you have created a tensor that defines your loss, for example as my_loss = tf.mean(output)<\/code> you can use this method to add it to loss collection. You might want to do that if you are not tracking all your losses manually. For example if you are using a method like tf.losses.get_total_loss()<\/code>.<\/p>\n\n

    Inside tf.losses.add_loss<\/code> is very much straightforward:<\/p>\n\n

    def add_loss(loss, loss_collection=ops.GraphKeys.LOSSES):\n  if loss_collection and not context.executing_eagerly():\n    ops.add_to_collection(loss_collection, loss)\n<\/code><\/pre>\n"}]}
    {"QuestionId":56231698,"AnswerCount":0,"Tags":"","CreationDate":"2019-05-21T05:37:12.070","AcceptedAnswerId":null,"OwnerUserId":10175640.0,"Title":"Unable to calculate validation error in pytroch","Body":"

    I\u2019m trying to fit a neural network using a training loop in Pytorch but I'm unable to calculate the validation error in the training loop because of an output-input size mismatch. The primary problem is that the size of the output in the validation set is always equal to the size of the output in the last stage of the training neural network and is not equal to the size of the input given by the validation data loader. <\/p>\n\n

    In the following code, the expected output size of is of length 40 but the code below gives of length 8 which is the size of y_pred in the last training loop. As a result, the loss function doesn't work because it gets one input of length 8 and one input of length 40 . I would be very grateful if someone could help me find a way to get of the correct length. <\/p>\n\n

    Note: If I run the validation set outside the entire training loop (i.e. after all the epochs are over), the validation error calculated. Here is my code <\/p>\n\n

    <\/pre>\n","answers":[]}
    {"QuestionId":56232389,"AnswerCount":1,"Tags":"","CreationDate":"2019-05-21T06:33:51.327","AcceptedAnswerId":56232612.0,"OwnerUserId":4332075.0,"Title":"Why ImageDataGenerator is iterating forever?","Body":"

    I have just started with Keras and was doing some image pre-processing where I observed that the generator received from is being iterated indefinitely in . <\/p>\n\n

    <\/pre>\n\n

    Output<\/strong><\/p>\n\n

    <\/pre>\n\n

    Question<\/strong><\/p>\n\n

      \n
    1. Is this the way is meant to work? If so, Can I avoid checking part somehow?<\/li>\n
    2. Am I missing something while preparing a generator which leads to such behavior?<\/li>\n<\/ol>\n\n

      Keras version: ---> \nTensorflow version: ---> <\/p>\n","answers":[{"AnswerId":"56232612","CreationDate":"2019-05-21T06:49:36.963","ParentId":null,"OwnerUserId":"4917205","Title":null,"Body":"

      Actually, train_data_gen<\/code> will generate data batch by batch infinitely.<\/p>\n\n

      When we call model.fit_generator()<\/code>, we specify the train_data_gen<\/code> as generator, and set steps_per_epoch<\/code> (should be len(train_data)\/batch_size<\/code>). Then the model would know when a single epoch is finished.<\/p>\n"}]} {"QuestionId":56232547,"AnswerCount":3,"Tags":"","CreationDate":"2019-05-21T06:46:25.200","AcceptedAnswerId":null,"OwnerUserId":1059417.0,"Title":"How to detect hand palm and its orientation (like facing outwards)?","Body":"

      I am working on a hand detection project. There are many good project on web to do this, but what I need is a specific hand pose detection. It needs a totally open palm and the whole palm face to outwards, like the image below:
      \n\"left<\/a><\/p>\n\n

      The first hand faces to inwards, so it will not be detected, and the right one faces to outwards, it will be detected. Now I can detect hand with OpenCV. but how to tell the hand orientation?<\/p>\n","answers":[{"AnswerId":"56332540","CreationDate":"2019-05-27T21:17:11.670","ParentId":null,"OwnerUserId":"10955990","Title":null,"Body":"

      Take a look at what leap frog has done with the oculus rift. I'm not sure what they're using internally to segment hand poses, but there is another paper that produces hand poses effectively. If you have a stereo camera setup, you can use this paper's methods: https:\/\/arxiv.org\/pdf\/1610.07214.pdf<\/a>.<\/p>\n\n

      The only promising solutions I've seen for mono camera train on large datasets. <\/p>\n"},{"AnswerId":"56333165","CreationDate":"2019-05-27T22:46:20.767","ParentId":null,"OwnerUserId":"7996768","Title":null,"Body":"

      well if you go for a MacGyver way you can notice that the left hand has bones sticking out in a certain direction, while the right hand has all finger lines and a few lines in the hand palms. <\/p>\n\n

      These lines are always sort of the same, so you could try to detect them with opencv edge detection or hough lines. Due to the dark color of the lines, you might even be able to threshold them out of it. Then gather the information from those lines, like angles, regressions, see which features you can collect and train a simple decision tree.<\/p>\n\n

      That was assuming you do not have enough data, if you have then you go into deeplearning, just take a basic inceptionV3 model and retrain the last dense layer to classify between two classes with a softmax, or to predict the probablity if the hand being up\/down with sigmoid. Check this link<\/a>, Tensorflow got your back on the training of this one, pure already ready code to execute.<\/p>\n\n

      Questions? Ask away<\/p>\n"},{"AnswerId":"56339542","CreationDate":"2019-05-28T09:54:15.143","ParentId":null,"OwnerUserId":"1312858","Title":null,"Body":"

      Problem of matching with the forehand belongs to the texture classification, it's a classic pattern recognition problem. I suggest you to try one of the following methods:<\/p>\n\n

        \n
      1. Gabor filters: it is good to detect the orientation and pixel intensities (as forehand has different features), opencv has getGaborKernel<\/em> function, the very important params of this function is theta (orientation) and lambd: (frequencies). To make it simple you can apply this process on a cropped zone of palm (as you have already detected it, it would be easy to crop for example the thumb, or a rectangular zone around the gravity center..etc). Then you can convolute it with a small database of images of the same zone to get the a rate of matching, or you can use the SVM classifier, where you have to train your SVM on a set of images by constructing the training matrix needed for SVM (check this question<\/a>), this paper<\/a><\/li>\n
      2. Local Binary Patterns (LBP): it's an important feature descriptor used for texture matching, you can apply it on whole palm image or on a cropped zone or finger of image, it's easy to use in opencv, a lot of tutorials with codes are available for this method. I recommend you to read this paper<\/a> talking about Invariant Texture Classification\nwith Local Binary Patterns. here is a good tutorial<\/a> <\/li>\n
      3. Haralick Texture: I've read that it works perfectly when a set of features quantifies the entire image (Global Feature Descriptors). it's not implemented in opencv but easy to be implemented, check this useful tutorial<\/a> <\/p><\/li>\n

      4. Training Models: I've already suggested a SVM classifier, to be coupled with some descriptor, that can works perfectly. \nOpencv has an interesting FaceRecognizer class for face recognition, it could be an interesting idea to use it replacing the face images by the palm ones, (do resizing and rotation to get an unique pose of palm), this class has three methods can be used, one of them is Local Binary Patterns Histograms, which is recommended for texture recognition. and why not to try the other models (Eigenfaces and Fisherfaces ) , check this tutorial<\/a><\/p><\/li>\n<\/ol>\n"}]} {"QuestionId":56232891,"AnswerCount":0,"Tags":"","CreationDate":"2019-05-21T07:08:18.850","AcceptedAnswerId":null,"OwnerUserId":4407260.0,"Title":"Unable to deploy R model using Rstudio on google cloud platform","Body":"

        I am using Rstudio on Google cloud Compute engine and using examples on <\/p>\n\n

        https:\/\/tensorflow.rstudio.com\/keras\/<\/a><\/p>\n\n

        My final objective is to be able to deploy R - model to AI platform and get predictions out of it. I have tried many examples using keras,tfestimators,tensorflow but none of them are able to run completely. All of the only run till training but when Its time to export_savemodel() they all fail. Local prediction,evaluation works fine.<\/p>\n\n

        <\/pre>\n\n

        Want my model version to appear here.<\/strong><\/p>\n\n

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

        Issues:<\/p>\n\n

        After completing the training , I am unable to export model to GCS bucket as command for this is failing.<\/p>\n\n

        <\/pre>\n\n

        Error message:<\/strong><\/p>\n\n

        <\/pre>\n\n

        Then I changed my code to below but still get error message:<\/p>\n\n

        <\/pre>\n\n

        Error:<\/p>\n\n

        <\/pre>\n\n

        What I need:<\/p>\n\n

        How can I fix the issue ?\nOr any guidance on how to deploy R packages on Google cloud platform will be appreciated.<\/p>\n","answers":[]} {"QuestionId":56233355,"AnswerCount":1,"Tags":"","CreationDate":"2019-05-21T07:34:25.550","AcceptedAnswerId":null,"OwnerUserId":8723840.0,"Title":"How to use metric with three inputs(GAP metric) in Keras while training?","Body":"

        This is GAP metric code from kaggle<\/a><\/p>\n\n

        <\/pre>\n\n

        I want to use it while training, but it get argument - vector of probability or confidence scores for prediction. But metrics must get only two arguments. Does any possibility to use it like this:<\/p>\n\n

        <\/pre>\n","answers":[{"AnswerId":"56302251","CreationDate":"2019-05-25T06:11:07.507","ParentId":null,"OwnerUserId":"10193890","Title":null,"Body":"

        Yes.. There is a way you can do this with a small tweak. Note that frameworks like Keras support loss functions and metrics of the form fun(true, pred)<\/code>. The function definition should be in this form only.<\/p>\n\n

        Also, the second limitation is, the shapes of both true<\/code> and pred<\/code> must be same.<\/p>\n\n

        Tweaking the first limitation: Concatenate the two output tensors into one. Suppose you have x<\/code> number of output classes, then shape of conf<\/code> and pred<\/code> will be (None, x)<\/code>. You can concatenate these two tensors into one producing final_output<\/code> with shape (None, 2, x)<\/code>.<\/p>\n\n

        Doing this is only the first step. It won't work unless we tweak the second limitation.<\/p>\n\n

        Now let us tweak the second limitation: This limitation can be shortened to: \"The dimensions of both these tensors must be same.\" Note that I am trying to reduce the limitation from shape to dimensions. This can be done by having dynamic shapes, for ex: shape(true) = (None, 1, x) and shape(pred) = (None, None, x)<\/code> will not throw errors as None<\/code> can take any value at runtime. In short, add a layer at the end of the model to combine outputs and that layer should have dynamic output shape.<\/p>\n\n

        But in your case, true<\/code> will also have shape (None, x)<\/code>. You can just expand dimensions of this tensor at axis=1<\/code> to get (None, 1, x)<\/code> and then the newly generated true can be provided as input to the model.<\/p>\n\n

        Note that as you are combining two<\/strong> tensors, the final_output<\/code> will always have shape (None, 2, x)<\/code> which isn't equal to (None, 1, x)<\/code>. But as we have configured the last layer to return dynamic shape i.e. (None, None, x)<\/code>, this will not be a problem at compile time. And Keras never checks for shape mismatch at runtime except an operation on tensor causes that error<\/strong>.<\/p>\n\n

        Now, that you have final_output<\/code> with same shape as true<\/code>, you just need to slice the final_output<\/code> to get back the original two tensors pred<\/code> and conf<\/code> in your custom loss function and metrics.<\/p>\n\n

        The above was purely logical.. To see an example implementation, check out layers and loss function here<\/a>.<\/p>\n"}]} {"QuestionId":56233410,"AnswerCount":1,"Tags":"","CreationDate":"2019-05-21T07:38:40.320","AcceptedAnswerId":56236065.0,"OwnerUserId":11525610.0,"Title":"Proper way to evaluate classification model ('UndefinedMetricWarning:')","Body":"

        I am currently using a neural network that outputs a one hot encoded output.<\/p>\n\n

        Upon evaluating it with a classification report I am receiving this error:<\/p>\n\n

        <\/pre>\n\n

        When one-hot encoding my output during the phase, I had to drop one of the columns in order to avoid the Dummy Variable Trap. As a result, some of the predictions of my neural network are , signaling that it belongs to the fifth category. I believe this to be the cause of the . <\/p>\n\n

        Is there a solution to this? Or should I avoid classification reports in the first place and is there a better way to evaluate these sorts of neural networks? I'm fairly new to machine learning and neural networks, please forgive my ignorance. Thank you for all the help!!<\/p>\n\n


        \n\n

        Edit #1: <\/p>\n\n

        Here is my network: <\/p>\n\n

        <\/pre>\n\n

        The above is my network. After training the network, I predict values and convert them to class labels using:<\/p>\n\n

        <\/pre>\n\n

        Upon calling a classification report comparing and , I receive the error.<\/p>\n\n

        **As a side note for anyone curious, I am experimenting with natural language processing and neural networks. The reason the input vector of my network is so large is that it takes in count-vectorized text as part of its inputs. <\/p>\n\n


        \n\n

        Edit #2:<\/p>\n\n

        I converted the predictions into a dataframe and dropped duplicates for both the test set and predictions getting this result: <\/p>\n\n

        <\/pre>\n\n

        So, essentially what's happening is due to the way softmax is being converted to binary, the predictions will never result in a . When one hot encoding , should I just not drop the first column? <\/p>\n","answers":[{"AnswerId":"56236065","CreationDate":"2019-05-21T10:15:30.963","ParentId":null,"OwnerUserId":"5632058","Title":null,"Body":"

        Yes I would say that you should not drop the first column. Because what you do now is to get the softmax and then take the neuron with the highest value as label (labels = np.argmax(predictions, axis = -1) ). With this approach you can never get a [0,0,0,0] result vector. So instead of doing this just create a onehot vector with positions for all 5 classes. You're problem with sklearn should then disappear, as you will get samples with true labels for your 5th class.<\/p>\n\n

        I'm also not sure if the dummy variable trap is a problem for neural networks. I have never heard from this before and a short google scholar search did not find any results. Also in all resources I've seen so far about neural networks I never saw this problem. So I guess (but this is really just a guess), that it isn't really a problem that you have when training neural networks. This conclusion is also driven by the fact that the majority of NNs use a softmax at the end. <\/p>\n"}]} {"QuestionId":56233463,"AnswerCount":1,"Tags":"","CreationDate":"2019-05-21T07:41:51.457","AcceptedAnswerId":null,"OwnerUserId":11529280.0,"Title":"TensorFlow: Saving py_func to .pb file","Body":"

        I try to build a tensorflow model - where i use the tf.py_func to create a part of the code in ordinary python code. The problem is that when I save the model to a .pb file, the .pb file itself is very small and does not include the py_func:0 tensor. When I try to load and run the model from the .pb file I get this error: get ValueError: callback pyfunc_0 is not found.<\/p>\n\n

        It works when I dont save and load as a .pb file<\/p>\n\n

        Is anyone able ton help. This is super important to me and have given me a couple of sleepless nights.<\/p>\n\n

        <\/pre>\n","answers":[{"AnswerId":"57208019","CreationDate":"2019-07-25T18:16:32.310","ParentId":null,"OwnerUserId":"6078821","Title":null,"Body":"

        There is<\/strong> a way to save TF models with tf.py_func<\/code>, but you have to do it without<\/strong> using a SavedModel<\/code>.<\/p>\n\n

        TF has 2 levels of model saving: checkpoints and SavedModels<\/code>. See this answer<\/a> for more details, but to quote it here:<\/p>\n\n

        \n