{"QuestionId":56856263,"AnswerCount":1,"Tags":"","CreationDate":"2019-07-02T16:00:09.220","AcceptedAnswerId":null,"OwnerUserId":11730043.0,"Title":"How to make LSTM capture weekly seasonality?","Body":"

I am a beginner in the Deep Learning field and I need help with LSTMs.<\/p>\n\n

The data I analyze consists of a number of http errors for each timestep for a period of 1 month. I chose to consider data for every 10min timestep (in order to have more data for the training).<\/p>\n\n

Head of the data : <\/p>\n\n

data.head<\/a><\/p>\n\n

The data shows seasonality trends, there is a very low number of errors during the week ends and a great number during the working days (ie when people connect to the servers).<\/p>\n\n

My goal is to predict the number of errors for the next day. I created a new column with the data shifted by a day in order to predict it (shifted by 6*24 considering that we have 10min timesteps).\nSo I'm trying to predict 6*24 timesteps ahead.<\/p>\n\n

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

<\/pre>\n\n

I learnt that, in order to train the model, the data must have the following shape : [samples, timesteps, features]. It consists of several sub time series.\nSo first I tried the following shape : [60, 6*24, 1], so that is 60 samples and each one represents a day. <\/p>\n\n

I also tried several number of layers and hidden units but my problem is always the same : the model can't capture the weekly seasonality of the data, it seems like the predictions are shifted or maybe it makes predictions based on the previous day.<\/p>\n\n

Here is the plot I have for the forecasting: <\/p>\n\n

actual_vs_prediction<\/a><\/p>\n\n

Test data consists of 12 days following the month of the training data.<\/p>\n\n

I thought that if I specify to the model that the sub time series are weeks it will resolve the problem. So I also tried to gather more data and to consider the following shape for the input : [21, 6*24*7, 1], so that is 21 samples and each one represents a week (10min*6*24*7). It didn't work and I have a plot very similar to the previous one.<\/p>\n\n

I hope that my explanations are clear, if not feel free to ask for more details.<\/p>\n\n

Thanks<\/p>\n\n

PS: If the only way is to consider 1Hour or one day timesteps when gathering the data let me know. I didn't investigate this option because I would have very few number of training examples.<\/p>\n","answers":[{"AnswerId":"56856833","CreationDate":"2019-07-02T16:38:14.557","ParentId":null,"OwnerUserId":"1594060","Title":null,"Body":"

Discarding for a moment the specifics of LSTM if you know that day of the week is an important feature then you might want to include day of the week (or a boolean is_weekday) in your input data.<\/p>\n\n

Have you tried that?<\/p>\n"}]} {"QuestionId":56856264,"AnswerCount":0,"Tags":"","CreationDate":"2019-07-02T16:00:14.767","AcceptedAnswerId":null,"OwnerUserId":11730198.0,"Title":"Regarding accuracy measurement","Body":"

I have problem in calculating accuracy of the model designed ang fiving 0.5 value for every training step. It has one output neuron which should be useful for tomato rippen or not.<\/p>\n\n

I tried with removing and adding dropout layer and loss functions with BCEWithLogitsloss() at the end but no improvement.<\/p>\n\n

The part of the code is pasted<\/p>\n\n

<\/pre>\n\n

I expected accuracy should change in every step but it does not.<\/p>\n","answers":[]} {"QuestionId":56856365,"AnswerCount":0,"Tags":"","CreationDate":"2019-07-02T16:06:43.013","AcceptedAnswerId":null,"OwnerUserId":11730199.0,"Title":"Illegal instruction error when require('@tensorflow\/tfjs-node-gpu')","Body":"

I'm making a server with node.js, and I'm trying to add TensorFlow.js into it. I installed with npm, both the CPU and GPU versions, but when I include the library with require('@tensorflow\/tfjs-node') or require('@tensorflow\/tfjs-node-gpu'), it shows me an 'Illegal instruction' error. (Tell me if I misspelt something, I'm Spanish.)<\/p>\n\n

I tried to reinstall both the CPU and GPU versions, but I don't know what to do.<\/p>\n\n

This is the code I used:<\/p>\n\n

<\/pre>\n\n

It's supposed to show the 'Server running!' the message, but the only thing it shows is:<\/p>\n\n

Instrucci\u00f3n ilegal (`core' generado)<\/p>\n\n

Shows that because is in Spanish. In English is:<\/p>\n\n

Illegal instruction (core dumped)<\/p>\n","answers":[]} {"QuestionId":56856573,"AnswerCount":1,"Tags":"","CreationDate":"2019-07-02T16:20:33.973","AcceptedAnswerId":56856727.0,"OwnerUserId":4227746.0,"Title":"Pandas doesn't read a csv correctly","Body":"

I'm new to pandas and keras, and i'm trying to build a network to generate word embeddings. I'm following this guide<\/a>, trying to adapt it to my specific dataset. I should select some columns from my dataset<\/a> (DBLP-ACM, you can download it here) for further text elaboration, but pandas doesn't work as expected. <\/p>\n\n

I already tried with the same syntax of the guide i linked above, but pandas puts every column in a single big column (with a weird name: ['id,\"title\",\"authors\",\"venue\",\"year\";;;;;']). Needless to say, a lot of rows show errors like <\/p>\n\n

<\/p>\n\n

I also tried other solutions like<\/p>\n\n

<\/p>\n\n

<\/p>\n\n

but nothing works as expected. Basically, i don't understand why this dataset seems malformed (since it looks ok opening it with a csv viewer) and how can i read it correctly using pandas, to submit it to the next part of the program.<\/p>\n\n

EDIT:<\/strong> As i pointed out in the comments, i did something wrong splitting my dataset (for training and test) and it went malformed in the process. Fyi, i simply used an online csv splitter. The accepted solution works flawlessly for the original dataset.<\/p>\n","answers":[{"AnswerId":"56856727","CreationDate":"2019-07-02T16:29:37.620","ParentId":null,"OwnerUserId":"10067173","Title":null,"Body":"

df = pd.read_csv(\"DBLP2.csv\", sep=\",\", quotechar=\"\\\"\", encoding=\"latin_1\")\n<\/code><\/pre>\n\n

This worked for me. You haven't provided any example code and I don't know why it isn't working for you.<\/p>\n"}]} {"QuestionId":56856652,"AnswerCount":1,"Tags":"","CreationDate":"2019-07-02T16:25:43.543","AcceptedAnswerId":null,"OwnerUserId":8855704.0,"Title":"Keras fit_generator() with generator that extends Sequence is returning more samples than total","Body":"

I am training a neural network with Keras. Because of the size of the dataset, I need to use a generator and the fit_generator() method. I am following this tutorial:<\/p>\n\n

https:\/\/stanford.edu\/~shervine\/blog\/keras-how-to-generate-data-on-the-fly<\/a><\/p>\n\n

However, I prepared a small example to check the samples being fed to the network at each epoch and it seems that the number is higher than the number of samples.<\/p>\n\n

<\/pre>\n\n

Where and are my methods for getting the data. These methods include a print() for the image being loaded and I get more than I expect. For example:<\/p>\n\n

num_samples = 10\nbatch_size = 2<\/p>\n\n

Steps per epoch will be equal to 5 and that is what the keras progress bar shows, but I get more images (which I know because of the print inside the method).<\/p>\n\n

I tried debugging, and find that the function is called more than 5 times! The first five times will have indexes between 0 and 4 (as expected) but then I will get a repeated index and more data being loaded.<\/p>\n\n

Any idea why this is happening? I've debugged down to the data_utils.py in keras but can't find the exact place where index is being passed to . Everything inside getitem seems to be working fine.<\/p>\n","answers":[{"AnswerId":"56856745","CreationDate":"2019-07-02T16:31:12.703","ParentId":null,"OwnerUserId":"349130","Title":null,"Body":"

This is normal, for steps_per_epoch = 5<\/code>, your __getitem__<\/code> will be called 5 times for each epoch<\/em>. So of course, having more than one epoch means it will be called more times then just 5.<\/p>\n\n

Also note that there is parallelism involved, Keras automatically runs your Sequence<\/code> in another thread\/process (depending on configuration) so they might be called out of the expected sequence. This is also normal.<\/p>\n"}]} {"QuestionId":56856749,"AnswerCount":0,"Tags":"","CreationDate":"2019-07-02T16:31:31.393","AcceptedAnswerId":null,"OwnerUserId":8593566.0,"Title":"State or context error, when using multiprocessing with flask","Body":"

I am trying to use multiprocessing.Process() to call a function big_task() whenever a request is received so that the function(which takes time to get computed) can run in my computer, while flask can run parallelly and listen for requests. But I am getting an error:<\/p>\n\n

<\/pre>\n\n

Based on another SO answer I tried giving the root_path argument when calling app=Flask(name<\/strong>,root_path:\"C:\/Users\/..\");<\/p>\n\n

Now I get another error:<\/p>\n\n

<\/pre>\n\n

This is my roughly my current code:<\/p>\n\n

<\/pre>\n\n

I am new to flask, and don't quite understand why is this error happening. I think it is something related to flask creating its states or contexts, or something related to windows not being able to fork new process. Could someone give a good explanation ?<\/p>\n","answers":[]} {"QuestionId":56856871,"AnswerCount":1,"Tags":"","CreationDate":"2019-07-02T16:40:37.040","AcceptedAnswerId":null,"OwnerUserId":11175276.0,"Title":"How can I save my session or my GAN model into a js file","Body":"

I want to deploy my GANs model on a web based UI for this I need to convert my model's checkpoints into js files to be called by web code. There are functions for saved_model and keras to convert in to pb files but none for js<\/p>\n\n

my main concern is that I am confused how to dump a session or variable weights in js files<\/p>\n","answers":[{"AnswerId":"56857228","CreationDate":"2019-07-02T17:10:06.100","ParentId":null,"OwnerUserId":"2455494","Title":null,"Body":"

You can save a keras model from python. There is a full tutorial here<\/a> but basically it amounts to calling this after training:<\/p>\n\n

tfjs.converters.save_keras_model(model, tfjs_target_dir)\n<\/code><\/pre>\n\n

then hosting the result somewhere publicly accessible (or on the same server as your web UI) then you can load your model into tensorflow.js as follows:<\/p>\n\n

import * as tf from '@tensorflow\/tfjs';\n\nconst model = await tf.loadLayersModel('https:\/\/foo.bar\/tfjs_artifacts\/model.json');\n<\/code><\/pre>\n"}]}
{"QuestionId":56856903,"AnswerCount":1,"Tags":"","CreationDate":"2019-07-02T16:42:56.363","AcceptedAnswerId":56857773.0,"OwnerUserId":5889615.0,"Title":"Some questions about the plotted results of a Unet","Body":"
    \n
  1. what is the meaning of doing:<\/p>\n\n

    <\/pre>\n\n

    The dataset contains \"mask\" pictures composed by three colours (indeed they're called \"trimaps\"). As a test, I tried to plot before and after this piece of code, and it seems that the role of these code lines is to convert pictures from three-colours to two-colours ( and ), but I don't know how.<\/p><\/li>\n

  2. At the bottom of the \"Generators<\/strong>\" section, there's a picture composed by three subpictures. The sub-image in the middle is a \"black and white\" mask.\nWhich are the code lines which perform the conversion of the colours of \"mask\" pictures from to ?<\/p><\/li>\n

  3. Finally, I tried to plot through the code line , instead of plotting it through (as done in the code).\nBut the result of plotting through is a black picture, why?<\/p><\/li>\n<\/ol>\n","answers":[{"AnswerId":"56857773","CreationDate":"2019-07-02T17:53:48.390","ParentId":null,"OwnerUserId":"5629339","Title":null,"Body":"

      \n
    1. UNet, at least in its original form, works with binary masks. You have masks with three regions, background, object and some kind of edge. That piece of code is making the background (label 2) equal to zero and the object and its edge (labels 0 and 1) equal to one. This way you have a binary mask to use as ground truth. You see them in purple and yellow because matplotlib default color map is viridis<\/em> which happens to be purple at zero and yellow at 1. Not that this is actually throwing away useful informations from those masks that could be someway used to train a better model. But that's okay to simplify things a bit and better understand what's going on.<\/p><\/li>\n

    2. The last step in the mask preprocessing code converts single color masks to rgb. So when you plot them with colored images your mask can be either (0, 0, 0)<\/code> which is black, or (1, 1, 1)<\/code> which is white.<\/p><\/li>\n

    3. Not sure, it should work, probably something about default normalization in plt.imshow<\/code><\/p><\/li>\n<\/ol>\n"}]} {"QuestionId":56856996,"AnswerCount":2,"Tags":"","CreationDate":"2019-07-02T16:49:48.053","AcceptedAnswerId":null,"OwnerUserId":2160290.0,"Title":"Difference in shape of tensor torch.Size([]) and torch.Size([1]) in pytorch","Body":"

      I am new to pytorch. While playing around with tensors I observed 2 types of tensors-<\/p>\n\n

      <\/pre>\n\n

      I printed their shape and the output was respectively -<\/p>\n\n

      <\/pre>\n\n

      What is the difference between the two?<\/p>\n","answers":[{"AnswerId":"56857155","CreationDate":"2019-07-02T17:02:58.743","ParentId":null,"OwnerUserId":"10886420","Title":null,"Body":"

      First one is incorrect, hence it's size cannot be inferred.<\/p>\n\n

      You should use list<\/code> to initialize it, see here<\/a> for more information.<\/p>\n"},{"AnswerId":"56857388","CreationDate":"2019-07-02T17:23:45.600","ParentId":null,"OwnerUserId":"5884955","Title":null,"Body":"

      You can play with tensors having the single scalar value like this:<\/p>\n\n

      import torch\n\nt = torch.tensor(1)\nprint(t, t.shape) # tensor(1) torch.Size([])\n\nt = torch.tensor([1])\nprint(t, t.shape) # tensor([1]) torch.Size([1])\n\nt = torch.tensor([[1]])\nprint(t, t.shape) # tensor([[1]]) torch.Size([1, 1])\n\nt = torch.tensor([[[1]]])\nprint(t, t.shape) # tensor([[[1]]]) torch.Size([1, 1, 1])\n\nt = torch.unsqueeze(t, 0)\nprint(t, t.shape) # tensor([[[[1]]]]) torch.Size([1, 1, 1, 1])\n\nt = torch.unsqueeze(t, 0)\nprint(t, t.shape) # tensor([[[[[1]]]]]) torch.Size([1, 1, 1, 1, 1])\n\nt = torch.unsqueeze(t, 0)\nprint(t, t.shape) # tensor([[[[[[1]]]]]]) torch.Size([1, 1, 1, 1, 1, 1])\n\n#squize dimension with id 0\nt = torch.squeeze(t,dim=0)\nprint(t, t.shape) # tensor([[[[[1]]]]]) torch.Size([1, 1, 1, 1, 1])\n\n#back to beginning.\nt = torch.squeeze(t)\nprint(t, t.shape) # tensor(1) torch.Size([])\n\nprint(type(t)) # <class 'torch.Tensor'>\nprint(type(t.data)) # <class 'torch.Tensor'>\n<\/code><\/pre>\n\n

      Tensors, do have a size or shape. Which is the same. Which is actually a class torch.Size<\/code>.\nYou can write help(torch.Size)<\/code> to get more info.\nAny time you write t.shape<\/code>, or t.size()<\/code> you will get that size info.<\/p>\n\n

      The idea of tensors is they can have different compatible size dimension for the data inside it including torch.Size([])<\/code>.<\/p>\n\n

      Any time you unsqueeze a tensor it will add another dimension of 1.\nAny time you squeeze a tensor it will remove dimensions of 1, or in general case all dimensions of one.<\/p>\n"}]} {"QuestionId":56857043,"AnswerCount":0,"Tags":"","CreationDate":"2019-07-02T16:53:57.253","AcceptedAnswerId":null,"OwnerUserId":2076669.0,"Title":"Why is convert_variables_to_constants() deprecated in TF2?","Body":"

      As the title says, why is convert_variables_to_constants() deprecated in tensorflow 2? What's the easy replacement to get a saveable model to load into a downstream stand-alone application for inference (in my case, using the C API).<\/p>\n","answers":[]} {"QuestionId":56857364,"AnswerCount":0,"Tags":"","CreationDate":"2019-07-02T17:21:52.410","AcceptedAnswerId":null,"OwnerUserId":7700129.0,"Title":"Keras model.train_on_batch crashes my kernel but model.fit does not, even though my input is smaller with train_on_batch","Body":"

      I am training a convolutional neural network with Keras and the Tensorflow backend on a list of sequences of DNA to predict some of their features. I have two networks set up: <\/p>\n\n

        \n
      1. pads the beginning of my one-hot encoded sequences so that all sequences are the same length, meaning I can pass them through all at once using model.fit. This padding is reducing my training data as I cannot mask my input with Conv2D. <\/p><\/li>\n

      2. trains the model sequence by sequence, and does not pad them so that the model takes variable input lengths. I am hoping that this will improve model accuracy but every time I iterate over my list of sequences and call model.train_on_batch, my iPython kernel crashes.<\/p><\/li>\n<\/ol>\n\n

        Here is the model where I pass in padded inputs:<\/p>\n\n

        <\/pre>\n\n

        The model summary returns:<\/p>\n\n

        <\/pre>\n\n

        My batch model is slightly different as I have to use :<\/p>\n\n

        <\/pre>\n\n

        And the model summary for this is<\/p>\n\n

        <\/pre>\n\n

        I can train this model with something like:<\/p>\n\n

        <\/pre>\n\n

        I do not understand why using train_on_batch is crashing my iPython kernel while model.fit is not. model.fit is called on a model with the same number of sequences, and they are all padded which means it has far more parameters to train on than the train_on_batch model.<\/p>\n\n

        With model.fit I use a batch size of up to 200 sometimes, whereas the way I train with model.train_on_batch is essentially the same as using a batch size of 1 is it not?<\/p>\n\n

        Edit: The error which I get when running in the interpreter is: <\/p>\n\n

        <\/pre>\n","answers":[]}
        {"QuestionId":56857373,"AnswerCount":0,"Tags":"","CreationDate":"2019-07-02T17:22:45.037","AcceptedAnswerId":null,"OwnerUserId":9487505.0,"Title":"Tensorboard is not working after system update, how to bring it back?","Body":"

        After upgrading Ubuntu 16.04, with \"sudo apt-get upgrade\" tensorboard can't read data from logdir.<\/p>\n\n

        I allready tried to set the python path, but no success. :(<\/p>\n\n

        The command i use, to start tensorboard.\ntensorboard --logdir= 'training'<\/p>\n\n

        result: no data found<\/p>\n","answers":[]} {"QuestionId":56857400,"AnswerCount":1,"Tags":"","CreationDate":"2019-07-02T17:24:34.727","AcceptedAnswerId":null,"OwnerUserId":9298828.0,"Title":"Converting Mobilenet segmentation model to tflite","Body":"

        I beginner in Tensorflow so kindly forgive me for this simple question, but I am unable to find this answer any where. I am working on converting mobilenet Segmentation model (http:\/\/download.tensorflow.org\/models\/deeplabv3_mnv2_pascal_trainval_2018_01_29.tar.gz<\/a>) trained on Pascal dataset to Tensorflow-lite for mobile inference for more than a week but with no success. I am unable to define properly the input and output format for converter. <\/p>\n\n

        <\/pre>\n\n

        But, it is throwing lots of error like eager excecution. Kindly tell me how should I write the code to convert above Mobilenet model to tflite.<\/p>\n","answers":[{"AnswerId":"56921385","CreationDate":"2019-07-07T10:36:31.697","ParentId":null,"OwnerUserId":"8401096","Title":null,"Body":"

        try this in command prompt or bash shell\nYou can use either of the following two ways<\/p>\n\n

        for tensorflow installed from package manager<\/h1>\n\n
        python -m tensorflow.python.tools.optimize_for_inference \\\n--input=\/path\/to\/frozen_inference_graph.pb \\\n--output=\/path\/to\/frozen_inference_graph_stripped.pb \\\n--frozen_graph=True \\\n--input_names=\"sub_7\" \\\n--output_names=\"ResizeBilinear_3\"\n<\/code><\/pre>\n\n

        build from source<\/h1>\n\n
        bazel build tensorflow\/python\/tools:optimize_for_inference\nbazel-bin\/tensorflow\/python\/tools\/optimize_for_inference \\\n--input=\/path\/to\/frozen_inference_graph.pb \\\n--output=\/path\/to\/frozen_inference_graph_stripped.pb \\\n--frozen_graph=True \\\n--input_names=\"sub_7\" \\\n--output_names=\"ResizeBilinear_3\"\n<\/code><\/pre>\n\n

        Hope it works!!<\/p>\n"}]} {"QuestionId":56857622,"AnswerCount":0,"Tags":"","CreationDate":"2019-07-02T17:41:09.193","AcceptedAnswerId":null,"OwnerUserId":11034759.0,"Title":"Can we convert hdf5 model to tflite with dropout in hdf5 model? How the model architecture looks after conversion with dropout?","Body":"

        Can we convert .HDF5 model with dropout in it to .tflite using the tflite converter? <\/p>\n\n

        If yes, how the model architecture with dropout should look after conversion. I am not able to justify how the dropout in model architecture should look after converting to .tflite file.<\/p>\n","answers":[]} {"QuestionId":56857730,"AnswerCount":0,"Tags":"","CreationDate":"2019-07-02T17:49:52.433","AcceptedAnswerId":null,"OwnerUserId":11503237.0,"Title":"Pooling to a constant size from any size of feature map","Body":"

        I need to pool a feature map to a fixed size from any size of the feature map. The idea is that of RoI pooling<\/strong> but I couldn't implement it due to various issues including dependency issues from various Github<\/strong> repositories. Is there any alternative way to do the same or can anybody provide a practical implementation of RoI pooling<\/strong> for the same?<\/p>\n","answers":[]} {"QuestionId":56857927,"AnswerCount":1,"Tags":"","CreationDate":"2019-07-02T18:04:33.023","AcceptedAnswerId":56875252.0,"OwnerUserId":3088888.0,"Title":"Use of window() function in TensorFlow Dataset to access more than one row","Body":"

        I've got a problem with transforming the dataset read from .csv files by tf.data.experimental.CsvDataset<\/a> into \"timeseries\".<\/p>\n\n

        What I'm trying to do is to access more than one row of the dataset at once in order to append features of previous 2 rows to the current row and keep the label of the current row. I'd like to do it for every row (apart from the first two). I thought that applying function is the right approach but now I'm not so sure.<\/p>\n\n

        The original dataset consisting of approximately 300 columns is created by reading a set of .csv files like this:<\/p>\n\n

        <\/pre>\n\n

        For reproducibility I'm using the combination of Dataset.from_tensor_slices() and Dataset.zip():<\/p>\n\n

        <\/pre>\n\n

        I'm still getting my head around window() transformation, I saw this<\/a> GitHub issue but it doesn't solve my problem.<\/p>\n\n

        What I'm getting now is:<\/p>\n\n

        <\/pre>\n\n

        The problem is that it behaves like batch - processes rows in triples. What I'd like to achieve is the following:<\/p>\n\n

        <\/pre>\n\n

        I'm stuck a bit, I'm not sure if using window() function for accessing more than one row of the dataset is even the right approach. I've asked very similar question previously but I deleted it as I think I've included too much details, here I've tried to keep it as lean as possible. Any help would be appreciated, thanks!<\/p>\n","answers":[{"AnswerId":"56875252","CreationDate":"2019-07-03T17:24:18.590","ParentId":null,"OwnerUserId":"3088888","Title":null,"Body":"

        Ok after tackling the problem from many sides I've finally managed to achieve the required result. I've got two solutions: one that processes features and labels as separate datasets and the one which appies transformations to the dataset in one go. Both might be useful depending on the use case.<\/p>\n\n

          \n
        1. Process features and labels as separate datasets:<\/li>\n<\/ol>\n\n
          import tensorflow as tf\n\ntf.enable_eager_execution()\n\nwith tf.Graph().as_default(), tf.Session() as sess:\n    # Simulate what's being returned from CsvDataset():\n    feature_1_ds = tf.data.Dataset.from_tensor_slices([1., 3., 5., 7., 9.])\n    feature_2_ds = tf.data.Dataset.from_tensor_slices([2., 4., 6., 8., 10.])\n    label_1_ds = tf.data.Dataset.from_tensor_slices([1.0, 1.0, 0.0, 1.0, 0.0])\n\n    ds = tf.data.Dataset.zip((feature_1_ds, feature_2_ds, label_1_ds))\n\n    # Do transformations to obtain \"timeseries\" data.\n    def _parse_function_features(*row):\n        features = tf.stack(row[:2], axis=-1)\n        return features\n\n    def _parse_function_labels(*row):\n        labels = tf.stack(row[2:], axis=-1)\n        return labels\n\n    def _reshape(x):\n        # Flatten rows into one.\n        return tf.reshape(x, shape=[-1])\n\n    ds_features = ds.map(_parse_function_features).window(3, shift=1).flat_map(lambda x: x.batch(3)).map(_reshape)\n    ds_labels = ds.map(_parse_function_labels).window(3, shift=1).flat_map(lambda x: x.skip(2))\n    ds = tf.data.Dataset.zip((ds_features, ds_labels))\n\n    iter = ds.make_one_shot_iterator().get_next()\n    # Show dataset contents\n    print('Result:')\n    while True:\n        try:\n            print(sess.run(iter))\n        except tf.errors.OutOfRangeError:\n            break\n<\/code><\/pre>\n\n
            \n
          1. Transform the dataset in one go:<\/li>\n<\/ol>\n\n
            import tensorflow as tf\n\ntf.enable_eager_execution()\n\nwith tf.Graph().as_default(), tf.Session() as sess:\n    # Simulate what's being returned from CsvDataset():\n    feature_1_ds = tf.data.Dataset.from_tensor_slices([1., 3., 5., 7., 9.])\n    feature_2_ds = tf.data.Dataset.from_tensor_slices([2., 4., 6., 8., 10.])\n    label_1_ds = tf.data.Dataset.from_tensor_slices([1.0, 1.0, 0.0, 1.0, 0.0])\n\n    ds = tf.data.Dataset.zip((feature_1_ds, feature_2_ds, label_1_ds))\n\n    # Do transformations to obtain \"timeseries\" data.\n    def _parse_function(*row):\n        features = tf.stack(row[:2], axis=-1)\n        labels = tf.stack(row[2:], axis=-1)\n        return features, labels\n\n\n    def _reshape(features, labels):\n        # Flatten features into one row.\n        return tf.reshape(features, shape=[-1]), labels\n\n\n    ds = ds.map(_parse_function)\n    ds = ds.window(3, shift=1)\n    ds = ds.flat_map(lambda x, y: tf.data.Dataset.zip((x.batch(3), y.skip(2))))\n    ds = ds.map(_reshape)\n\n    iter = ds.make_one_shot_iterator().get_next()\n    # Show dataset contents\n    print('Result:')\n    while True:\n        try:\n            print(sess.run(iter))\n        except tf.errors.OutOfRangeError:\n            break\n<\/code><\/pre>\n\n

            For both of these the output is:<\/p>\n\n

            Result:\n(array([1., 2., 3., 4., 5., 6.], dtype=float32), array([0.], dtype=float32))\n(array([3., 4., 5., 6., 7., 8.], dtype=float32), array([1.], dtype=float32))\n(array([ 5.,  6.,  7.,  8.,  9., 10.], dtype=float32), array([0.], dtype=float32))\n<\/code><\/pre>\n"}]}
            {"QuestionId":56858022,"AnswerCount":1,"Tags":"","CreationDate":"2019-07-02T18:10:47.880","AcceptedAnswerId":null,"OwnerUserId":9187995.0,"Title":"Failed to marshal the object to TFJob; the spec is invalid: failed to marshal the object to TFJob","Body":"

            i am rather new to both kubernetes and tensorflow, trying to run basic kubeflow distributed-tensorflow example from this link (https:\/\/github.com\/learnk8s\/distributed-tensorflow-on-k8s<\/a>). I am currently running local bare-metal kubernetes cluster with 2-nodes (1-master & 1-worker). Everything works fine when i run it in minikube (following the documentation), both training and serving run successfully. But running the job on local cluster is giving me this error!<\/p>\n\n

            Any help would be appreciated.<\/p>\n\n

            For this setup, i created a pod for nfs-storage that would be used by the jobs. Because local cluster doesn't have dynamic provisioning enabled, i created persistent volume manually (the files used are attached). <\/p>\n\n

            Nfs pod-storage file:<\/p>\n\n

            <\/pre>\n\n

            Persistent Volume & PVC file:<\/p>\n\n

            <\/pre>\n\n

            TFJob File:<\/p>\n\n

            <\/pre>\n\n

            When i run the job, it give me this error <\/p>\n\n

            <\/pre>\n\n

            After searching a little, someone pointed \"v1alpha1\" could be out-dated so you should use \"v1beta1\" (strangely this \"v1alpha1\" was working with my minikube setup so i am very confused!). But with that although the tfjob gets created, i do not see any new containers starting as opposed to the minikube run, where new pods start and finish successfully. When i describe the Tfjob, i see this error <\/p>\n\n

            <\/pre>\n\n

            Since the only difference is the nfs-storage, i think there might be something wrong with my manual setup. Please let me know if i messed up somewhere because i do not have enough background!<\/p>\n","answers":[{"AnswerId":"57081207","CreationDate":"2019-07-17T17:19:52.913","ParentId":null,"OwnerUserId":"9187995","Title":null,"Body":"

            I found the issue that was causing specific error. First, the api-version changed so i had to move from v1alpha1<\/code> to v1beta2<\/code>. Second, the tutorial i followed was using kubeflow v0.1.2 (rather old) and the syntax for defining tfjob in the yaml file has changed ever since (not exactly sure in which version the change happened!). So by looking at the latest example in the git i was able to update the job spec. Here are the files for someone interested! <\/p>\n\n

            Tutorial version:<\/p>\n\n

            apiVersion: kubeflow.org\/v1alpha1\nkind: TFJob\nmetadata:\n  name: tfjob1\nspec:\n  replicaSpecs:\n    - replicas: 1\n      tfReplicaType: MASTER\n      template:\n        spec:\n          volumes:\n            - name: nfs-volume\n              persistentVolumeClaim:\n                claimName: nfs\n          containers:\n            - name: tensorflow\n              image: learnk8s\/mnist:1.0.0\n              imagePullPolicy: IfNotPresent\n              args:\n                - --model_dir\n                - .\/out\/vars\n                - --export_dir\n                - .\/out\/models\n              volumeMounts:\n                - mountPath: \/app\/out\n                  name: nfs-volume\n          restartPolicy: OnFailure\n    - replicas: 2\n      tfReplicaType: WORKER\n      template:\n        spec:\n          containers:\n            - name: tensorflow\n              image: learnk8s\/mnist:1.0.0\n              imagePullPolicy: IfNotPresent\n          restartPolicy: OnFailure\n    - replicas: 1\n      tfReplicaType: PS\n      template:\n        spec:\n          volumes:\n            - name: nfs-volume\n              persistentVolumeClaim:\n                claimName: nfs\n          containers:\n            - name: tensorflow\n              image: learnk8s\/mnist:1.0.0\n              imagePullPolicy: IfNotPresent\n              volumeMounts:\n                - mountPath: \/app\/out\n                  name: nfs-volume\n          restartPolicy: OnFailure\n<\/code><\/pre>\n\n

            updated version:<\/p>\n\n

            apiVersion: kubeflow.org\/v1beta2\nkind: TFJob\nmetadata:\n  name: tfjob1\nspec:\n  tfReplicaSpecs:\n    Chief:\n      replicas: 1\n      template:\n        spec:\n          volumes:\n            - name: nfs-volume\n              persistentVolumeClaim:\n                claimName: nfs\n          containers:\n            - name: tensorflow\n              image: learnk8s\/mnist:1.0.0\n              imagePullPolicy: IfNotPresent\n              args:\n                - --model_dir\n                - .\/out\/vars\n                - --export_dir\n                - .\/out\/models\n              volumeMounts:\n                - mountPath: \/app\/out\n                  name: nfs-volume\n          restartPolicy: OnFailure\n    Worker:\n      replicas: 2\n      template:\n        spec:\n          containers:\n            - name: tensorflow\n              image: learnk8s\/mnist:1.0.0\n              imagePullPolicy: IfNotPresent\n          restartPolicy: OnFailure\n    PS:\n      replicas: 1\n      template:\n        spec:\n          volumes:\n            - name: nfs-volume\n              persistentVolumeClaim:\n                claimName: nfs\n          containers:\n            - name: tensorflow\n              image: learnk8s\/mnist:1.0.0\n              imagePullPolicy: IfNotPresent\n              volumeMounts:\n                - mountPath: \/app\/out\n                  name: nfs-volume\n          restartPolicy: OnFailure\n<\/code><\/pre>\n"}]}
            {"QuestionId":56858378,"AnswerCount":1,"Tags":"","CreationDate":"2019-07-02T18:37:16.197","AcceptedAnswerId":null,"OwnerUserId":11210924.0,"Title":"tf.tape.gradient() returns None for certain losses","Body":"

            I am trying to figure out why sometimes returns , so I used the below three loss functions(, , ), although the formats are a bit different for mmd0 and mmd1, the gradients are still returned, but for mmd2, the gradients are . I print out the loss from those three function, does anyone why why it behaves like this?<\/p>\n\n

            <\/pre>\n","answers":[{"AnswerId":"57533244","CreationDate":"2019-08-17T04:24:19.550","ParentId":null,"OwnerUserId":"3667142","Title":null,"Body":"

            Have you seen this<\/a> answer? I think I'm having a similar issue, and I believe that your might be related to mine. It has to do with the loss that is computed with a step somewhere in the process where the tensor of interest is \"lost\" from the start of the tape to the end. The referenced answer notes that the original poster had an area where a numpy array was returned instead of a tensorflow tensor, thus leading to the Gradient Tape failing to compute the gradient.<\/p>\n\n

            I could be wrong because I am nowhere near a tensorflow expert, but that is something I keep seeing popping up while searching for a solution to my similar issue.<\/p>\n"}]} {"QuestionId":56858430,"AnswerCount":0,"Tags":"","CreationDate":"2019-07-02T18:42:38.590","AcceptedAnswerId":null,"OwnerUserId":10028427.0,"Title":"Combine several tensorflow models for different clients into one","Body":"

            Let's say, the problem I'm solving is to predict the doctor (label) for a patient (features) of a particular clinic. We have several DNN models for different clinics which do the job, but it does not cost efficient - for every model we need to pay separately on AWS SageMaker.<\/p>\n\n

            The main question: how to combine models for different clinics into one model, that they still continue to work with independent accuracies?<\/p>\n\n

            I've tried to add an additional feature \"clinic\" which intended to help the DNN model to understand the context of the clinic. I've also defined other features as cross-columns of \"clinic\" with vanilla (previous) feature definition.<\/p>\n\n

            <\/pre>\n\n

            I do have a \"validation\" function which I can execute at any time on test data for a particular clinic (it is similar to \"evaluate\" action).<\/p>\n\n

            After I train the model with the data of 1st clinic I measure the accuracy (validate) and it is 90%.<\/p>\n\n

            As a next step, I continue to train the same model on data of 2nd clinic and measure the accuracy.<\/p>\n\n

            Expected result: it is still 90% (I'm trying to make models independent during training).<\/p>\n\n

            Actual result: the accuracy of the combined model for 1st clinic drops to 10%.<\/p>\n","answers":[]} {"QuestionId":56858486,"AnswerCount":0,"Tags":"","CreationDate":"2019-07-02T18:48:41.970","AcceptedAnswerId":null,"OwnerUserId":6356474.0,"Title":"get name of array in Tensorflow graphdef","Body":"

            I have a graphdef that I did not create I am trying to convert this to TensorFlow lite but I need the input array. having not created this model I do not know what the input array would be called. Is there any way I can find the name of the array or do the conversion without it. I've tried using Gfile to load the graphdef but that did not work.<\/p>\n\n

            <\/pre>\n","answers":[]}
            {"QuestionId":56858580,"AnswerCount":0,"Tags":"","CreationDate":"2019-07-02T18:58:03.003","AcceptedAnswerId":null,"OwnerUserId":7205986.0,"Title":"How do I construct a mixed-data model using keras and tensorflow in R?","Body":"

            I want to predict a binary classifier using two differently structured pieces of data (mixed data) using keras\/tensorflow in R.<\/p>\n\n

            I have come across an interesting tutorial, which uses keras in python:<\/p>\n\n

            https:\/\/www.pyimagesearch.com\/2019\/02\/04\/keras-multiple-inputs-and-mixed-data\/<\/a><\/p>\n\n

            I would like to do something similar in my question: use two different aspects as two branches of a model, which then gets concatenated and from then on trained together. As I have only worked with sequential models in keras before, I do not really know how to do this.<\/p>\n\n

            My first branch contains measurements for patients ranging from 0 to 1 (normalized).<\/p>\n\n

            Dimensions of this data could e.g. be 200x100 for 200 measurements in 100 patients.<\/p>\n\n

            My second branch contains a kind of network information \/ (nearest) neighbour construction for the same measurements and patients. This information is saved as a vector of neighbours.<\/p>\n\n

            Dimensions of this data could e.g. be 200x100x4 for the 4 nearest neighbours of the 200 measurements in those 100 patients.<\/p>\n\n

            How do I construct my branches and my model in R? I would like to start with the most simple way and then I can try to expand on it.<\/p>\n\n

            The first part can e.g. look like this and works ok:<\/p>\n\n

            <\/pre>\n","answers":[]}
            {"QuestionId":56858680,"AnswerCount":0,"Tags":"","CreationDate":"2019-07-02T19:06:52.987","AcceptedAnswerId":null,"OwnerUserId":8245117.0,"Title":"Parallelize simple for loop using Pytorch on single GPU","Body":"

            I have a for-loop which operates on independent columns of a large matrix. I have parallelized the for-loop on CPU using the prange function in Numba. Now I want to perform this operation using PyTorch tensors on a GPU. I'm a PyTorch novice and don't know how to do it.<\/p>\n\n

            Any help will be really appreciated.<\/p>\n\n

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

            <\/pre>\n\n

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

            <\/pre>\n\n

            How can I parallelize the for loops?<\/p>\n","answers":[]} {"QuestionId":56858741,"AnswerCount":0,"Tags":"","CreationDate":"2019-07-02T19:12:42.743","AcceptedAnswerId":null,"OwnerUserId":6361137.0,"Title":"Get hidden layers autoencoder","Body":"

            I am trying to use autoencoders with Tensorflow, and I want to extract the hidden layer in order to reduce dimensionality of the original features.<\/p>\n\n

            I've defined a basic autoencoder as following, with the \"encoded\" hidden layer of size 35, starting from 151 input features:<\/p>\n\n

            <\/pre>\n\n

            How do I get the hidden layer? I want all the corresponding vectors of length 35 <\/p>\n","answers":[]} {"QuestionId":56858924,"AnswerCount":2,"Tags":"","CreationDate":"2019-07-02T19:27:34.773","AcceptedAnswerId":56893248.0,"OwnerUserId":5990202.0,"Title":"Multivariate input LSTM in pytorch","Body":"

            I would like to implement<\/strong> LSTM for multivariate input in Pytorch<\/strong>. <\/p>\n\n

            Following this article https:\/\/machinelearningmastery.com\/how-to-develop-lstm-models-for-time-series-forecasting\/<\/a> which uses keras, the input data are in shape of (number of samples, number of timesteps, number of parallel features)<\/p>\n\n

            <\/pre>\n\n

            In keras it seems to be easy:<\/p>\n\n

            <\/p>\n\n

            Can it be done in other way, than creating of LSTMs as first layer and feed each separately (imagine as multiple streams of sequences) and then flatten their output to linear layer?<\/p>\n\n

            I'm not 100% sure but by nature of LSTM the input cannot be flattened and passed as 1D array, because each sequence \"plays by different rules\" which the LSTM is supposed to learn.<\/p>\n\n

            So how does such implementation with keras equal to PyTorch\n(source https:\/\/pytorch.org\/docs\/stable\/nn.html#lstm<\/a>)<\/p>\n\n


            \n\n

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

            \n

            Can it be done in other way, than creating of LSTMs as first layer and feed each separately (imagine as multiple streams of sequences) and then flatten their output to linear layer? <\/p>\n<\/blockquote>\n\n

            According to PyTorch docs<\/a> the input_size<\/em> parameter actually means number of features (if it means number of parallel sequences)<\/p>\n","answers":[{"AnswerId":"56859197","CreationDate":"2019-07-02T19:52:18.793","ParentId":null,"OwnerUserId":"8426627","Title":null,"Body":"

            input in any rnn cell in pytorch is 3d input, formatted as (seq_len, batch, input_size) or (batch, seq_len, input_size), if you prefer second (like also me lol) init lstm layer )or other rnn layer) with arg <\/p>\n\n

            bach_first = True\n<\/code><\/pre>\n\n

            https:\/\/discuss.pytorch.org\/t\/could-someone-explain-batch-first-true-in-lstm\/15402<\/a><\/p>\n\n

            also you dont have any reccurent relation in the setup. \nIf you want to create many to one counter , create input if size (-1, n,1) \nwhere -1 is size what you want, n is number of digits, one digit per tick like input [[10][20][30]] , output - 60, input [[30,][70]] output 100 etc, input must have different lengths from 1 to some max, in order to learn rnn relation<\/p>\n\n

            import random\n\nimport numpy as np\n\nimport torch\n\n\ndef rnd_io():    \n    return  np.random.randint(100, size=(random.randint(1,10), 1))\n\n\nclass CountRNN(torch.nn.Module):\n\ndef __init__(self):\n    super(CountRNN, self).__init__()\n\n    self.rnn = torch.nn.RNN(1, 20,num_layers=1, batch_first=True)\n    self.fc = torch.nn.Linear(20, 1)\n\n\ndef forward(self, x):        \n    full_out, last_out = self.rnn(x)\n    return self.fc(last_out)\n\n\nnnet = CountRNN()\n\ncriterion = torch.nn.MSELoss(reduction='sum')\n\noptimizer = torch.optim.Adam(nnet.parameters(), lr=0.0005)\n\nbatch_size = 100\n\nbatches = 10000 * 1000\n\nprintout = max(batches \/\/(20* 1000),1)\n\nfor t in range(batches):\n\noptimizer.zero_grad()\n\nx_batch = torch.unsqueeze(torch.from_numpy(rnd_io()).float(),0)\n\ny_batch = torch.unsqueeze(torch.sum(x_batch),0)\n\noutput = nnet.forward(x_batch) \n\nloss = criterion(output, y_batch)\n\nif t % printout == 0:\n    print('step : ' , t , 'loss : ' , loss.item())  \n    torch.save(nnet.state_dict(), '.\/rnn_summ.pth')  \n\nloss.backward()\n\noptimizer.step()\n<\/code><\/pre>\n"},{"AnswerId":"56893248","CreationDate":"2019-07-04T19:09:00.710","ParentId":null,"OwnerUserId":"5990202","Title":null,"Body":"

            I hope that problematic parts are commented to make sense:<\/p>\n\n

            Data preparation<\/h2>\n\n
            import random\nimport numpy as np\nimport torch\n\n# multivariate data preparation\nfrom numpy import array\nfrom numpy import hstack\n\n# split a multivariate sequence into samples\ndef split_sequences(sequences, n_steps):\n    X, y = list(), list()\n    for i in range(len(sequences)):\n        # find the end of this pattern\n        end_ix = i + n_steps\n        # check if we are beyond the dataset\n        if end_ix > len(sequences):\n            break\n        # gather input and output parts of the pattern\n        seq_x, seq_y = sequences[i:end_ix, :-1], sequences[end_ix-1, -1]\n        X.append(seq_x)\n        y.append(seq_y)\n    return array(X), array(y)\n\n# define input sequence\nin_seq1 = array([x for x in range(0,100,10)])\nin_seq2 = array([x for x in range(5,105,10)])\nout_seq = array([in_seq1[i]+in_seq2[i] for i in range(len(in_seq1))])\n# convert to [rows, columns] structure\nin_seq1 = in_seq1.reshape((len(in_seq1), 1))\nin_seq2 = in_seq2.reshape((len(in_seq2), 1))\nout_seq = out_seq.reshape((len(out_seq), 1))\n# horizontally stack columns\ndataset = hstack((in_seq1, in_seq2, out_seq))\n<\/code><\/pre>\n\n

            Multivariate LSTM Network<\/h2>\n\n
            class MV_LSTM(torch.nn.Module):\n    def __init__(self,n_features,seq_length):\n        super(MV_LSTM, self).__init__()\n        self.n_features = n_features\n        self.seq_len = seq_length\n        self.n_hidden = 20 # number of hidden states\n        self.n_layers = 1 # number of LSTM layers (stacked)\n\n        self.l_lstm = torch.nn.LSTM(input_size = n_features, \n                                 hidden_size = self.n_hidden,\n                                 num_layers = self.n_layers, \n                                 batch_first = True)\n        # according to pytorch docs LSTM output is \n        # (batch_size,seq_len, num_directions * hidden_size)\n        # when considering batch_first = True\n        self.l_linear = torch.nn.Linear(self.n_hidden*self.seq_len, 1)\n\n\n    def init_hidden(self, batch_size):\n        # even with batch_first = True this remains same as docs\n        hidden_state = torch.zeros(self.n_layers,batch_size,self.n_hidden)\n        cell_state = torch.zeros(self.n_layers,batch_size,self.n_hidden)\n        self.hidden = (hidden_state, cell_state)\n\n\n    def forward(self, x):        \n        batch_size, seq_len, _ = x.size()\n\n        lstm_out, self.hidden = self.l_lstm(x,self.hidden)\n        # lstm_out(with batch_first = True) is \n        # (batch_size,seq_len,num_directions * hidden_size)\n        # for following linear layer we want to keep batch_size dimension and merge rest       \n        # .contiguous() -> solves tensor compatibility error\n        x = lstm_out.contiguous().view(batch_size,-1)\n        return self.l_linear(x)\n<\/code><\/pre>\n\n

            Initialization<\/h2>\n\n
            n_features = 2 # this is number of parallel inputs\nn_timesteps = 3 # this is number of timesteps\n\n# convert dataset into input\/output\nX, y = split_sequences(dataset, n_timesteps)\nprint(X.shape, y.shape)\n\n# create NN\nmv_net = MV_LSTM(n_features,n_timesteps)\ncriterion = torch.nn.MSELoss() # reduction='sum' created huge loss value\noptimizer = torch.optim.Adam(mv_net.parameters(), lr=1e-1)\n\ntrain_episodes = 500\nbatch_size = 16\n<\/code><\/pre>\n\n

            Training<\/h2>\n\n
            mv_net.train()\nfor t in range(train_episodes):\n    for b in range(0,len(X),batch_size):\n        inpt = X[b:b+batch_size,:,:]\n        target = y[b:b+batch_size]    \n\n        x_batch = torch.tensor(inpt,dtype=torch.float32)    \n        y_batch = torch.tensor(target,dtype=torch.float32)\n\n        mv_net.init_hidden(x_batch.size(0))\n    #    lstm_out, _ = mv_net.l_lstm(x_batch,nnet.hidden)    \n    #    lstm_out.contiguous().view(x_batch.size(0),-1)\n        output = mv_net(x_batch) \n        loss = criterion(output.view(-1), y_batch)  \n\n        loss.backward()\n        optimizer.step()        \n        optimizer.zero_grad() \n    print('step : ' , t , 'loss : ' , loss.item())\n<\/code><\/pre>\n\n

            Results<\/h2>\n\n
            step :  499 loss :  0.0010267728939652443 # probably overfitted due to 500 training episodes\n<\/code><\/pre>\n"}]}
            {"QuestionId":56859073,"AnswerCount":0,"Tags":"","CreationDate":"2019-07-02T19:42:36.297","AcceptedAnswerId":null,"OwnerUserId":11730801.0,"Title":"My Neural Network Model for predicting soccer outcomes doesn't increase to more than 50%","Body":"

            I am building a model to predict soccer outcomes, I've tried a lot of different models, such as Neural Network in Matlab, Deep Networks using keras in Python and LSTM. My accuracy doesn't increase more than 50%<\/p>\n\n

            I have collected 24000 matches from 13 different leagues that have the same aspect (win by points). My data is consisted by:<\/p>\n\n

            <\/pre>\n\n

            I have made a mean weighted average of the last 5 matches from all that data to use as inputs in a neural network model playing home, and playing away. So, if a home team are going to play a match, the data will be the mean weighted average from the last 5 matches playing in the home field (the last one have more weight than the second last one, and so on). The output is one hot encoded: (1 0 0) for win home, (0 1 0) draw...<\/p>\n\n

            I've tried several models, and now I'm trying Keras Dense model.<\/p>\n\n

            I am scaling the input data using:<\/p>\n\n

            <\/pre>\n\n

            and the model is:<\/p>\n\n

            <\/pre>\n\n

            The maximum result i could achieve was 50% accuracy on test set, but with the confusion matrix i could see that the model was not predicting any draws, so I add a weight to classes:<\/p>\n\n

            <\/pre>\n\n

            And achieved 46% of accuracy but with a better confusion matrix.<\/p>\n\n

            I really don't know what to do, I've tried a lot of different models, activation functions, and methods but the accuracy doesn't seem to change too much.<\/p>\n\n

            Edit: I did the correlation matrix and saw that the maximum correlation with the result is no higher than 0.2. And I saw that 6 variables are correlated with each other with 0.87 correlation coeficient. I have deleted the variables with correlation less than 0.05 with the result. From 57 variables, I have now 44, and still got the same accuracy of 45%.<\/p>\n","answers":[]} {"QuestionId":56859126,"AnswerCount":1,"Tags":"","CreationDate":"2019-07-02T19:46:49.973","AcceptedAnswerId":null,"OwnerUserId":1419123.0,"Title":"Keras: Using weights for NCE loss","Body":"

            So here is the model with the standard loss function.<\/p>\n\n

            <\/pre>\n\n

            It works fine. Given NCE loss isnt available in keras, I wrote up a custom loss.<\/p>\n\n

            <\/pre>\n\n

            And changed the last line to:<\/p>\n\n

            <\/pre>\n\n

            This compiles by the way.<\/p>\n\n

            And on execution dies.<\/p>\n\n

            <\/pre>\n\n

            The issue is of course, that the weights aren't quite getting updated in the layer, hence the non gradient. How could i do that without making a custom layer? I tried that approach but I give up on measuring things like val_acc using a layer.<\/p>\n","answers":[{"AnswerId":"56984440","CreationDate":"2019-07-11T08:06:40.147","ParentId":null,"OwnerUserId":"11692518","Title":null,"Body":"

            It seems like you cannot do it in Keras without Layer's API. You can try this solution using custom layer: Keras NCE Implementation<\/a><\/p>\n"}]} {"QuestionId":56859738,"AnswerCount":1,"Tags":"","CreationDate":"2019-07-02T20:37:45.680","AcceptedAnswerId":null,"OwnerUserId":10167906.0,"Title":"How to fix ''ValueError: Input 0 is incompatible with layer flatten: expected min_ndim=3, found ndim=2\" error when loading model","Body":"

            I'm trying to save and load my keras model. It trains, evaluates, and saves fine (using .h5 to save model) but when I try to load the model I get the following error: \nValueError: Input 0 is incompatible with layer flatten: expected min_ndim=3, found ndim=2.\nAm I loading the model incorrectly? Any help would be appreciated!<\/p>\n\n

            This is the code block from where I'm saving the model.<\/p>\n\n

            <\/pre>\n\n

            To load from a different script:<\/p>\n\n

            <\/pre>\n\n

            While attempting to load the model I get the following error:<\/p>\n\n

            ValueError: Input 0 is incompatible with layer flatten: expected min_ndim=3, found ndim=2<\/p>\n","answers":[{"AnswerId":"56861374","CreationDate":"2019-07-03T00:06:02.283","ParentId":null,"OwnerUserId":"11731700","Title":null,"Body":"

            you can try to save only the weights of your model, then re-create it using exactly the same code, and loading only the weights. \nso change <\/p>\n\n

            model.save\n<\/code><\/pre>\n\n

            to <\/p>\n\n

            model.save_weights('my_model.h5')\n<\/code><\/pre>\n\n

            Then when you want to load your model, first, you re-create your model:<\/p>\n\n

            model = tf.keras.models.Sequential()\nmodel.add(tf.keras.layers.Flatten())\nself.addLayer(model,145,6)\nmodel.add(tf.keras.layers.Dense(1))\n<\/code><\/pre>\n\n

            and finally load the weights:<\/p>\n\n

            model.load_weights('my_model.h5')\n<\/code><\/pre>\n\n

            This worked for me. \nAlso, you could add an Input layer, together with the explicit input_shape in your model. <\/p>\n"}]} {"QuestionId":56859748,"AnswerCount":2,"Tags":"","CreationDate":"2019-07-02T20:38:25.113","AcceptedAnswerId":56901721.0,"OwnerUserId":1501383.0,"Title":"Does batch normalisation work with a small batch size?","Body":"

            I'm using batch normalization with a batch size of size 10 for face detection, I wanted to know if it is better to remove the batch norm layers or keep them.\nAnd if it is better to remove them what can I use instead?<\/p>\n","answers":[{"AnswerId":"56862784","CreationDate":"2019-07-03T04:08:25.253","ParentId":null,"OwnerUserId":"10237052","Title":null,"Body":"

            This question depends on a few things, first being the depth of your neural network. Batch normalization is useful for increasing the training of your data when there are a lot of hidden layers. It can decrease the number of epochs it takes to train your model and hep regulate your data. By standardizing the inputs to your network, you reduce the risk of chasing a 'moving target', meaning your learning algorithm is not performing as optimally as it could be.<\/p>\n\n

            My advice would be to include batch normalization layers in your code if you have a deep neural network. Reminder, you should probably include some Dropout in your layers as well.<\/p>\n\n

            Let me know if this helps!<\/p>\n"},{"AnswerId":"56901721","CreationDate":"2019-07-05T10:56:34.280","ParentId":null,"OwnerUserId":"5884955","Title":null,"Body":"

            Yes, it works for the smaller size, it will work even with the smallest possible size you set.<\/p>\n\n

            The trick is the bach size also adds to the regularization effect, not only the batch norm.\nI will show you few pics:<\/p>\n\n

            \"bs=10\"<\/a><\/p>\n\n

            We are on the same scale tracking the bach loss. The left-hand side is a module without the batch norm layer (black), the right-hand side is with the batch norm layer. \nNote how the regularization effect is evident even for the bs=10<\/code>.<\/p>\n\n

            \"bs=64\"<\/a><\/p>\n\n

            When we set the bs=64<\/code> the batch loss regularization is super evident. Note the y<\/code> scale is always [0, 4]<\/code>.<\/p>\n\n

            My examination was purely on nn.BatchNorm1d(10, affine=False)<\/code> without learnable parameters gamma<\/code> and beta<\/code> i.e. w<\/code> and b<\/code>.<\/p>\n\n

            This is why when you have low batch size, it has sense to use the BatchNorm layer.<\/p>\n"}]} {"QuestionId":56859772,"AnswerCount":1,"Tags":"","CreationDate":"2019-07-02T20:40:24.710","AcceptedAnswerId":null,"OwnerUserId":11731200.0,"Title":"Keras- Input Layer and Embedding layer error","Body":"

            I am trying to make a model for Tv script generation and while running the following model, input layer and embedding layer error is occurring.\nI have tried running the model without these two lines and it works fine. Can someone please help me with the error?<\/p>\n\n

            <\/pre>\n\n
            \n\n
            <\/pre>\n","answers":[{"AnswerId":"56860024","CreationDate":"2019-07-02T21:03:02.777","ParentId":null,"OwnerUserId":"8285811","Title":null,"Body":"

            Input is not a Layer Object. Which is why you get the first error. You do not need to pass something like that with a call to Sequential(). Embedding() can be your first layer.<\/p>\n\n

            And the second error is because you are passing inp<\/code> to it. The first value should either be inp<\/code> or vocab_size<\/code> but it cannot be both.<\/p>\n\n

            Basically,<\/p>\n\n

            embedding = 300\nlstm_size = 128\nvocab_size = len(vocab) #8420\nseq_len = 100\n\n\nmodel = Sequential()\nmodel.add(Embedding(vocab_size, embedding, input_length = 1000))\n<\/code><\/pre>\n"}]}
            {"QuestionId":56859956,"AnswerCount":1,"Tags":"","CreationDate":"2019-07-02T20:57:27.823","AcceptedAnswerId":56992329.0,"OwnerUserId":7128294.0,"Title":"How to load tensorflow .pb model in java exported from keras","Body":"

            I'm trying to load a model in java which is originally saved in keras in Java so that I can do inference in-process in an existing production system which runs in Java. <\/p>\n\n

            I didn't see a way to load Keras h5 models easily in Java, so I'm attempting to first convert it into a .pb file by using simple_save, and then loading it using the default tag for simple_save. I tried saving the graph directly using a freeze_session routine and tf.train.write_graph, but I had the same error.<\/p>\n\n

            Here's the code to save my model to a .pb file<\/p>\n\n

            <\/pre>\n\n

            Here's my Java code for loading the model, using the default tag for saved_model:<\/p>\n\n

            <\/pre>\n\n

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

            Exception in thread \"main\" org.tensorflow.TensorFlowException:<\/strong> \nCould not find SavedModel .pb or .pbtxt at supplied export directory path: output_dir<\/em><\/p>\n\n

            Any idea what I might be doing wrong? I know that simple_save is deprecated, but I'm just trying to get anything to work at this point.<\/p>\n","answers":[{"AnswerId":"56992329","CreationDate":"2019-07-11T15:08:48.157","ParentId":null,"OwnerUserId":"7128294","Title":null,"Body":"

            I looked at the native source code<\/a> which loads the model, and it turns out there is a hard-coded file name \"saved_model.pb\", or for the text version \"saved_model.pbtxt\" it expects in the directory (which wasn\u2019t specified in the documentation I looked at). <\/p>\n"}]} {"QuestionId":56860021,"AnswerCount":0,"Tags":"","CreationDate":"2019-07-02T21:02:57.677","AcceptedAnswerId":null,"OwnerUserId":4052624.0,"Title":"How to make Keras really support sparse matrix?","Body":"

            I am trying to build my deep learning model using Keras and TensorFlow. My model needs to input a matrix as the features.<\/p>\n\n

            The matrix is too big to be fitted into the memory. Fortunately, however, the matrix is very sparse. So I use to store it.<\/p>\n\n

            The problem is Keras doesn't support a sparse matrix as the input(maybe TensorFlow does?). I searched on internet and found some solutions to this problem, just like this one: Keras, sparse matrix issue<\/a>. It used a function to turn the sparse matrix to a dense one.<\/p>\n\n

            But these are stupid solutions. They are actually 'fake solutions', because if I could put a dense matrix into memory, why would I use a sparse one?<\/p>\n\n

            So anyone has 'real solutions' to this problem?<\/p>\n","answers":[]} {"QuestionId":56860180,"AnswerCount":5,"Tags":"","CreationDate":"2019-07-02T21:21:35.020","AcceptedAnswerId":56879016.0,"OwnerUserId":9328846.0,"Title":"Tensorflow CUDA - CUPTI error: CUPTI could not be loaded or symbol could not be found","Body":"

            I use the Tensorflow v 1.14.0. I work on Windows 10. And here is how relevant environment variables<\/strong> look in the :<\/p>\n\n

            <\/pre>\n\n

            Maybe also worth to mention, just in case it might be relevant.. I use Sublime Text 3 for development and I do not use Anaconda. I find it a bit cumbersome to make updates on tensorflow in the conda environment so I just use Sublime Text right now. (I was using Anaconda (Spyder) previously but I uninstalled it from my computer.) <\/p>\n\n

            Things seem to work fine except with some occasional strange warnings. But one consistent warning I get is the following whenever I run the function.<\/p>\n\n

            <\/pre>\n\n

            And here is how I call the fit function:<\/p>\n\n

            <\/pre>\n\n

            I just wonder why I see the <\/strong> message during the run time? It is only printed out once. Is that something that I need to fix or is it something that can be ignored? This message does not tell anything concrete to me to be able to take any action.<\/p>\n","answers":[{"AnswerId":"58683307","CreationDate":"2019-11-03T18:25:14.537","ParentId":null,"OwnerUserId":"448357","Title":null,"Body":"

            \n

            The NVIDIA\u00ae CUDA Profiling Tools Interface (CUPTI) is a dynamic\n library that enables the creation of profiling and tracing tools that\n target CUDA applications.<\/p>\n<\/blockquote>\n\n

            CPUTI seems to have been added by the Tensorflow Developors to allow profiling. You can simply ignore the error if you don't mind the exception or adapt your environment path, so the dynamically linked library (DLL) can be found during execution.<\/p>\n\n

            Inside of you CUDA installation directory, there is an extras\\CUPTI\\lib64<\/code> directory that contains the cupti64_101.dll<\/code> that is trying to be loaded. Adding that directory to your path should resolve the issue, e.g., <\/p>\n\n

            SET PATH=C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.1\\extras\\CUPTI\\lib64;%PATH%\n<\/code><\/pre>\n\n

            N.B. in case you get an INSUFFICIENT_PRIVILEGES error<\/a> next, try to run your program as administrator.<\/p>\n"},{"AnswerId":"58752904","CreationDate":"2019-11-07T16:17:29.460","ParentId":null,"OwnerUserId":"2912518","Title":null,"Body":"

            This answer is for Ubuntu-16.04<\/code><\/strong>. <\/p>\n\n

            I had this issue when I upgraded to Tensorflow-1.14<\/code> with Python2.7<\/code> and Python3.6<\/code>. I had to add \/usr\/local\/cuda\/extras\/CUPTI\/lib64<\/code> to LD_LIBRARY_PATH<\/code> with export LD_LIBRARY_PATH=\/usr\/local\/cuda\/extras\/CUPTI\/lib64:$LD_LIBRARY_PATH<\/code> and logout and login. source ~\/.bashrc<\/code> didn't help. Note that my cuda<\/code> folder was pointing to cuda-10.0<\/code>. <\/p>\n"},{"AnswerId":"56862642","CreationDate":"2019-07-03T03:44:55.653","ParentId":null,"OwnerUserId":"11731732","Title":null,"Body":"

            I had a similar error when trying to get tensorboard graph, I think it only affects you if you plan to use tensorboard.<\/p>\n\n

            I found the solution in this post but it is for linux\nhttps:\/\/gist.github.com\/Brainiarc7\/6d6c3f23ea057775b72c52817759b25c<\/a>\nI think you need to create a library configuration file for cupti. <\/p>\n"},{"AnswerId":"56879016","CreationDate":"2019-07-03T23:25:16.547","ParentId":null,"OwnerUserId":"9328846","Title":null,"Body":"

            Here is what solved \"my\" problem: <\/p>\n\n

            I just replaced my tensorflow v 1.14<\/code> with tensorflow v 1.13.1<\/code>. And no more CUPTI error<\/strong> messages. And even some other strange warnings \/ problems have disappeared. All issues should obviously have specific reasons but Tensorflow (many times) unfortunately does not provide understandable error\/warning messages that give a good\/fair idea that helps to solve the issue. And I end up spending hours (even days) on such strange problems, that reduces my productivity significantly.<\/p>\n\n

            One general learning for me (that might be relevant to share here) is that I should not be in hurry to upgrade my tensorflow installation to the latest version of it. The latest one is almost never stable, whenever I made a try, I ended up spending significant<\/strong> amount of time on problems that are caused by tensorflow. Poor documentation and error messages make it very very difficult to work with.<\/p>\n\n

            If anyone has a better answer, s\/he is more than welcome to share his\/her insights on the issue I shared in this question.<\/p>\n"},{"AnswerId":"57592360","CreationDate":"2019-08-21T13:05:56.100","ParentId":null,"OwnerUserId":"11125723","Title":null,"Body":"

            Add this in path<\/code> for Windows:<\/p>\n\n

            C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.0\\extras\\CUPTI\\libx64\n<\/code><\/pre>\n"}]}
            {"QuestionId":56860236,"AnswerCount":1,"Tags":"","CreationDate":"2019-07-02T21:28:04.877","AcceptedAnswerId":null,"OwnerUserId":4735674.0,"Title":"Vectorized implementation of field-aware factorization","Body":"

            I would like to implement the field-aware factorization model (FFM) in a vectorized way. In FFM, a prediction is made by the following equation<\/p>\n\n

            \"$<\/p>\n\n

            To do so, I have defined the following parameter:<\/p>\n\n

            <\/pre>\n\n

            Now, given an input of size , I want to be able to compute the previous equation. Here is my current (non-vectorized) implementation:<\/p>\n\n

            <\/pre>\n\n

            Unsurprisingly, this implementation is horribly slow since can easily be as large as 1000! Note however that most of the entries of are 0. All inputs are appreciated!<\/p>\n\n

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

            If it can help in any ways, here are some implementations of this model in PyTorch:<\/p>\n\n

            where w are the embeddings that depend on the feature and the field of the other feature. For more info, see equation in FFM<\/a>.<\/p>\n\n

I'm studying this example about Unet<\/a>.\nIt is about binary segmentation, and I have some questions about the code:<\/p>\n\n