{"QuestionId":54260957,"AnswerCount":1,"Tags":"","CreationDate":"2019-01-18T20:24:23.547","AcceptedAnswerId":null,"OwnerUserId":10935106.0,"Title":"I'm currently writing Xpredict function which is a wrapper for keras.predict function() for all the keras model in general","Body":"

I would like to know how do I find the corresponding class name of the predictions? <\/p>\n\n

Generator.class_indices works for few of the models where the data is coming from generator. However, for few models where the data is not coming from generator it throws an error saying<\/p>\n\n

AttributeError: 'NumpyArrayIterator' object has no attribute 'class_indices'<\/p>\n\n

<\/pre>\n\n

Expected:<\/p>\n\n

I want to know how to write a general function to predict the class_name from any keras general model.<\/p>\n\n

Actual:<\/p>\n\n

only works for training_data coming from generator using generator.class_indices.<\/p>\n","answers":[{"AnswerId":"54261408","CreationDate":"2019-01-18T21:03:40.690","ParentId":null,"OwnerUserId":"349130","Title":null,"Body":"

No, you can't do this in general, the class names is something the developer has to provide, Keras does not know about this and it is not stored anywhere.<\/p>\n"}]} {"QuestionId":54261604,"AnswerCount":0,"Tags":"","CreationDate":"2019-01-18T21:24:21.210","AcceptedAnswerId":null,"OwnerUserId":8422306.0,"Title":"Issue with linking torch and hdf5 lib together","Body":"

I'm trying to set up my project in C++ with HDF5 file usages and pyTorch (C++ API), and there are some linking problem. <\/p>\n\n

So... I run Ubuntu 18.04 LTS. I had installed HDF5 with APT, then I download zip from pyTorch and put it into third_party dir in my project structure.<\/p>\n\n

<\/pre>\n\n

My main.cpp looks like: <\/p>\n\n

<\/pre>\n\n

Then CMakeLists: <\/p>\n\n

<\/pre>\n\n

And run.sh <\/p>\n\n

<\/pre>\n\n

And now I'll describe the issue. For example, when in CMake I comment out all lines connected with HDF5 then torch works fine, same when I comment out Torch's lines in CMake - HDF5 runs well. But when I try to run above code I receive errors: <\/p>\n\n

<\/pre>\n\n

If anybody have any idea how to solve it? I find it as linking problem, but I'm not sure. <\/p>\n","answers":[]} {"QuestionId":54261772,"AnswerCount":1,"Tags":"","CreationDate":"2019-01-18T21:40:34.493","AcceptedAnswerId":54527964.0,"OwnerUserId":10360610.0,"Title":"Tensorflow Lite toco --mean_values --std_values?","Body":"

So I have trained a tensorflow model with fake quantization and froze it with a .pb file as output. Now I want to feed this .pb file to tensorflow lite toco for fully quantization and get the .tflite file.<\/p>\n\n

I am using this tensorflow example: https:\/\/github.com\/tensorflow\/tensorflow\/tree\/master\/tensorflow\/lite\/experimental\/micro\/examples\/micro_speech<\/a><\/p>\n\n

The part where I have question:<\/p>\n\n

<\/pre>\n\n

The above part calls toco and does the convert. Note that, the mean_values is set to 0, and std_values is set to 2 by Google. How did they calculate these 2 values? For this particular model, it is trained to recognize words \"yes\" and \"no\". What if I want to recognize the 10 digits, do I need to change the mean and std values in this case? I didn't find any official documentation illustrating this part. Any help would be appreciated. <\/p>\n","answers":[{"AnswerId":"54527964","CreationDate":"2019-02-05T05:06:52.070","ParentId":null,"OwnerUserId":"2130551","Title":null,"Body":"

For uint8 quantized models the input values are expected to be in the range 0 to 255. Even with FakeQuantization, the input values during training are often float values in a different range (for example, 0.0 to 1.0). The mean_value and std_value controls how the uint8 values in the range 0 to 255 map to the float values used during training. You can use this heuristic to determine these values:<\/p>\n\n

mean_value = the uint8 value in the range [0, 255] that corresponds to floating point 0.0. So if the float range is [0.0, 1.0], then mean_value = 0.<\/p>\n\n

std_value = (uint8_max - uint8_min) \/ (float_max - float_min). So if the float range is [0.0, 1.0], then std_value = 255 \/ 1.0 = 255.<\/p>\n\n

We are working on ways to make this simpler. Hope this helps!<\/p>\n"}]} {"QuestionId":54261787,"AnswerCount":0,"Tags":"","CreationDate":"2019-01-18T21:41:21.440","AcceptedAnswerId":null,"OwnerUserId":5680412.0,"Title":"How to speed up many `tf.gradients` operations","Body":"

I want to compute the gradients of a vector-valued<\/strong> function with respect to a scalar variable in . A little bit search tells me to do it in a loop. However, if is very large, the compilation is very slow. Is there any smart way to do it? <\/p>\n\n

In the code below, I have already computed the gradients of , so the gradients of with respect to should have been computed already (internally). I was thinking of recovering intermediate gradients without calling extra (in this is easy as I can the tensors have attributes)<\/p>\n\n

<\/pre>\n","answers":[]}
{"QuestionId":54261892,"AnswerCount":1,"Tags":"","CreationDate":"2019-01-18T21:50:55.037","AcceptedAnswerId":null,"OwnerUserId":2578846.0,"Title":"Saving and Loading Pytorch Model Checkpoint for inference not working","Body":"

I have a trained model using LSTM. The model is trained on GPU<\/strong> (On Google COLABORATORY).\nI have to save the model for inference; which I will run on CPU<\/strong>.\nOnce trained, I saved the model checkpoint as follows:<\/p>\n\n

<\/pre>\n\n

And, for inference, I loaded the model as :<\/p>\n\n

<\/pre>\n\n

But, it is raising the following error:<\/p>\n\n

<\/pre>\n\n

Is there anything I missed while saving the checkpoint? <\/p>\n","answers":[{"AnswerId":"54314282","CreationDate":"2019-01-22T18:18:22.953","ParentId":null,"OwnerUserId":"9312233","Title":null,"Body":"

There are two things to be considered here.<\/p>\n\n

    \n
  1. You mentioned that you're training your model on GPU and using it for inference on CPU, so u need to add a parameter map_location<\/strong> in load<\/strong> function passing torch.device('cpu')<\/strong>.<\/p><\/li>\n

  2. There is a mismatch of state_dict keys (indicated in your ouput message), which might be caused by some missing keys or having more keys in state_dict<\/em> you are loading than the model u are using currently. And for it you have to add a parameter strict<\/strong> with value False<\/strong> in the load_state_dict<\/strong> function. This will make method to ignore the mismatch of keys.<\/p><\/li>\n<\/ol>\n\n

    Side note : Try to use extension of pt or pth for checkpoint files as it is a convention . <\/p>\n"}]} {"QuestionId":54261913,"AnswerCount":2,"Tags":"","CreationDate":"2019-01-18T21:53:01.297","AcceptedAnswerId":null,"OwnerUserId":8037821.0,"Title":"How to test a trained CNN model in an external non-Tensorflow environment?","Body":"

    I have trained a pre-trained Tensorflow model for my custom object detection and I have exported the inference graph file and the checkpoint files. Now I want somebody else also to test out my trained model, by feeding some new images to it and seeing the results. But what is the best way to do so if the external 'evaluators' don't have any Tensorflow environment and they don't want to set it up either?<\/p>\n\n

    I used:<\/p>\n\n

    Miniconda3, Tensorflow v1.10.0 (gpu), \nTensorboard v1.10.0, \nCudatoolkit 8.0, TF pre-trained model \"SSD with Mobilenet v1\".<\/p>\n\n

    All manuals that I have found and read, only guide you to test your model from running some code from the Tensorflow object_detection folder. But setting up a TF can be quite a hassle for somebody who hasn't done it before. I thought maybe there is a way to somehow \"package it up\" so others can just easily run it with as little effort as possible. For just an example, let's consider \"easy\" a scenario where I send them a file package with a ready made Jupyter Notebook in it, so the only effort would be to unpack it and learn how to use the notebook.<\/p>\n\n

    Please kindly help with suggestions, possibly different ones, with different expertise levels and different understanding of \"easily\". But please consider that I am also a newbie in this field.<\/p>\n","answers":[{"AnswerId":"54262222","CreationDate":"2019-01-18T22:25:59.893","ParentId":null,"OwnerUserId":"8378726","Title":null,"Body":"

    Take a look at tfdeploy<\/code><\/a>.<\/p>\n\n

    It is a lightweight package that allows you to deploy your tensorflow models as a callable object using numpy<\/code> (which is a way more reasonable dependency to have).<\/p>\n"},{"AnswerId":"54269129","CreationDate":"2019-01-19T16:29:48.967","ParentId":null,"OwnerUserId":"2641587","Title":null,"Body":"

    TensorFlow Serving<\/a> maybe an overkill here (as it requires Docker), but it provides the inference environment via REST API. <\/p>\n"}]} {"QuestionId":54262318,"AnswerCount":2,"Tags":"","CreationDate":"2019-01-18T22:37:01.133","AcceptedAnswerId":57623323.0,"OwnerUserId":5136891.0,"Title":"How to use pre-trained BERT model for next sentence labeling?","Body":"

    I\u201dm new to AI and NLP. \nI want to check how bert works. \nI use BERT pre-trained model:\nhttps:\/\/github.com\/google-research\/bert<\/a><\/p>\n\n

    I ran extract_features.py example , described in extract features paragraph in readme.md. \nI got vectors, as output. <\/p>\n\n

    Guys, how to transform result, i got in extract_features.py, to get next\/ not next label?<\/p>\n\n

    I want to run bert to check whether two sentences are related, and see result. <\/p>\n\n

    Thanks!<\/p>\n","answers":[{"AnswerId":"57623323","CreationDate":"2019-08-23T09:23:07.553","ParentId":null,"OwnerUserId":"5136891","Title":null,"Body":"

    The answer is to use weights, what was used nor next sentence trainings, and logits from there. So, to use Bert for nextSentence input two sentences in a format used for training:<\/p>\n\n

    def convert_single_example(ex_index, example, label_list, max_seq_length,\n                       tokenizer):\n\"\"\"Converts a single `InputExample` into a single `InputFeatures`.\"\"\"\nlabel_map = {}\nfor (i, label) in enumerate(label_list):\n    label_map[label] = i\n\ntokens_a = tokenizer.tokenize(example.text_a)\ntokens_b = None\nif example.text_b:\n    tokens_b = tokenizer.tokenize(example.text_b)\n\nif tokens_b:\n    # Modifies `tokens_a` and `tokens_b` in place so that the total\n    # length is less than the specified length.\n    # Account for [CLS], [SEP], [SEP] with \"- 3\"\n    _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)\nelse:\n    # Account for [CLS] and [SEP] with \"- 2\"\n    if len(tokens_a) > max_seq_length - 2:\n        tokens_a = tokens_a[0:(max_seq_length - 2)]\n\n# The convention in BERT is:\n# (a) For sequence pairs:\n#  tokens:   [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]\n#  type_ids: 0     0  0    0    0     0       0 0     1  1  1  1   1 1\n# (b) For single sequences:\n#  tokens:   [CLS] the dog is hairy . [SEP]\n#  type_ids: 0     0   0   0  0     0 0\n#\n# Where \"type_ids\" are used to indicate whether this is the first\n# sequence or the second sequence. The embedding vectors for `type=0` and\n# `type=1` were learned during pre-training and are added to the wordpiece\n# embedding vector (and position vector). This is not *strictly* necessary\n# since the [SEP] token unambiguously separates the sequences, but it makes\n# it easier for the model to learn the concept of sequences.\n#\n# For classification tasks, the first vector (corresponding to [CLS]) is\n# used as as the \"sentence vector\". Note that this only makes sense because\n# the entire model is fine-tuned.\ntokens = []\nsegment_ids = []\ntokens.append(\"[CLS]\")\nsegment_ids.append(0)\nfor token in tokens_a:\n    tokens.append(token)\n    segment_ids.append(0)\ntokens.append(\"[SEP]\")\nsegment_ids.append(0)\n\nif tokens_b:\n    for token in tokens_b:\n        tokens.append(token)\n        segment_ids.append(1)\n    tokens.append(\"[SEP]\")\n    segment_ids.append(1)\n\ninput_ids = tokenizer.convert_tokens_to_ids(tokens)\n\n# The mask has 1 for real tokens and 0 for padding tokens. Only real\n# tokens are attended to.\ninput_mask = [1] * len(input_ids)\n\n# Zero-pad up to the sequence length.\nwhile len(input_ids) < max_seq_length:\n    input_ids.append(0)\n    input_mask.append(0)\n    segment_ids.append(0)\n\nassert len(input_ids) == max_seq_length\nassert len(input_mask) == max_seq_length\nassert len(segment_ids) == max_seq_length\n\nlabel_id = label_map[example.label]\nif ex_index < 5:\n    tf.logging.info(\"*** Example ***\")\n    tf.logging.info(\"guid: %s\" % (example.guid))\n    tf.logging.info(\"tokens: %s\" % \" \".join(\n        [tokenization.printable_text(x) for x in tokens]))\n    tf.logging.info(\"input_ids: %s\" % \" \".join([str(x) for x in input_ids]))\n    tf.logging.info(\"input_mask: %s\" % \" \".join([str(x) for x in input_mask]))\n    tf.logging.info(\"segment_ids: %s\" % \" \".join([str(x) for x in segment_ids]))\n    tf.logging.info(\"label: %s (id = %d)\" % (example.label, label_id))\n\nfeature = InputFeatures(\n    input_ids=input_ids,\n    input_mask=input_mask,\n    segment_ids=segment_ids,\n    label_id=label_id)\nreturn feature\n<\/code><\/pre>\n\n

    And then extend Bert model with next code<\/p>\n\n

    def create_model(bert_config, is_training, input_ids, input_mask, segment_ids,\n             labels, num_labels, use_one_hot_embeddings):\n\"\"\"Creates a classification model.\"\"\"\nmodel = modeling.BertModel(\n    config=bert_config,\n    is_training=is_training,\n    input_ids=input_ids,\n    input_mask=input_mask,\n    token_type_ids=segment_ids,\n    use_one_hot_embeddings=use_one_hot_embeddings)\n\n# In the demo, we are doing a simple classification task on the entire\n# segment.\n#\n# If you want to use the token-level output, use model.get_sequence_output()\n# instead.\noutput_layer = model.get_pooled_output()\n\nhidden_size = output_layer.shape[-1].value\n\nwith tf.variable_scope(\"cls\/seq_relationship\"):\n    output_weights = tf.get_variable(\n        \"output_weights\", [num_labels, hidden_size])\n\n    output_bias = tf.get_variable(\n        \"output_bias\", [num_labels])\n\nwith tf.variable_scope(\"loss\"):\n    if is_training:\n        # I.e., 0.1 dropout\n        output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)\n\n    logits = tf.matmul(output_layer, output_weights, transpose_b=True)\n    logits = tf.nn.bias_add(logits, output_bias)\n    probabilities = tf.nn.softmax(logits, axis=-1)\n    log_probs = tf.nn.log_softmax(logits, axis=-1)\n\n    one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)\n\n    per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)\n    loss = tf.reduce_mean(per_example_loss)\n\n    return (loss, per_example_loss, logits, probabilities)\n<\/code><\/pre>\n\n

    probabilities - is what you need, its nextSentence preditions<\/p>\n"},{"AnswerId":"56303636","CreationDate":"2019-05-25T09:40:29.500","ParentId":null,"OwnerUserId":"6268910","Title":null,"Body":"

    I'm not sure how you can do it in tensorflow. But in the pythorch implementation by hugging face https:\/\/github.com\/huggingface\/pytorch-pretrained-BERT\/blob\/master\/pytorch_pretrained_bert\/modeling.py#L854<\/a> there is a model BertForNextSentencePrediction.<\/p>\n"}]} {"QuestionId":54262380,"AnswerCount":0,"Tags":"","CreationDate":"2019-01-18T22:44:57.843","AcceptedAnswerId":null,"OwnerUserId":4641482.0,"Title":"Cast string to float is not supported","Body":"

    I am working on a tensorflow course and am trying to apply what I am learning to my own data. I am getting a \"Cast string to float is not supported\". Using the pandas dataframe INFO(), I confirm that all columns that are OBJECTS I have turned to a feature column using categorical_column_with_hash_bucket, all INT64 or FLOAT64 I have used numeric_column. Why is this error popping up?<\/p>\n\n

    Here is my code and error:<\/p>\n\n

    <\/pre>\n","answers":[]}
    {"QuestionId":54262455,"AnswerCount":0,"Tags":"","CreationDate":"2019-01-18T22:54:37.183","AcceptedAnswerId":null,"OwnerUserId":10326474.0,"Title":"\"Expected Long but got Int\" while running PyTorch script","Body":"

    I am facing this error while running a pytorch script. <\/p>\n\n

    Can anyone help me?<\/p>\n\n

    <\/pre>\n","answers":[]}
    {"QuestionId":54262599,"AnswerCount":0,"Tags":"","CreationDate":"2019-01-18T23:12:32.957","AcceptedAnswerId":null,"OwnerUserId":7886651.0,"Title":"Training Loss suddenly increases while validation loss continues decreasing in tensorflow","Body":"

    I have trained the dense net model on the FER+ dataset; then I tried fine tuning the model on the SEWA database (Here in this case I have regression). So I removed the last dense layer from the original model and replaced it with a new dense layer of 2 outputs instead of 8. <\/p>\n\n

    Anyways, while fine tuning the model I used AdamOptimizer, and suddenly after around 50 epochs, the training loss start increasing, while the validation loss continued decreasing, until epoch 80 approximately, and then raised again. Here are the figures that I got:<\/p>\n\n

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

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

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

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

    I wonder how I got this sudden increase in the training loss...Please note that the reported loss is the MSE. Also, in total, the model was trained for 6 hours and 11 mins. <\/p>\n\n

    The optimizer I used is AdamOptimizer with learning rate of 0.0005<\/p>\n\n

    Any help is much appreciated!!!<\/p>\n","answers":[]} {"QuestionId":54262689,"AnswerCount":2,"Tags":"","CreationDate":"2019-01-18T23:26:31.497","AcceptedAnswerId":54361530.0,"OwnerUserId":10935797.0,"Title":"How does the parameter 'dim' in torch.unique() work?","Body":"

    I am trying to extract the unique values in each row of a matrix and returning them into the same matrix (with repeated values set to say, 0) For example, I would like to transform<\/p>\n\n

    <\/pre>\n\n

    to<\/p>\n\n

    <\/pre>\n\n

    or <\/p>\n\n

    <\/pre>\n\n

    I.e. the order does not matter in the rows. I have tried using and in the documentation it is mentioned that the dimension to take the unique values can be specified with the parameter . However, It doesn't seem to work for this case. <\/p>\n\n

    I've tried:<\/p>\n\n

    <\/pre>\n\n

    Which gives<\/p>\n\n

    <\/pre>\n\n

    Does anyone have a particular fix for this? If possible, I'm trying to avoid for loops. <\/p>\n","answers":[{"AnswerId":"57634779","CreationDate":"2019-08-24T03:01:30.463","ParentId":null,"OwnerUserId":"8301681","Title":null,"Body":"

    I was confused when using torch.unique<\/a> the first time. After doing some experiments I have finally figured out how the dim<\/code> argument works.\nDocs of torch.unique<\/a> says that:<\/p>\n\n

    \n

    counts (Tensor): (optional) if return_counts is True, there will be an additional returned tensor (same shape as output or output.size(dim), if dim was specified) representing the number of occurrences for each unique value or tensor<\/strong>.<\/p>\n<\/blockquote>\n\n

    For example, if your input tensor is a 3D tensor of size n x m x k and dim=2<\/code>, unique<\/code> will compare k matrices of size n x m. In other words, it will treat all dimensions other than the dim 2 as tensors and compare them.<\/p>\n"},{"AnswerId":"54361530","CreationDate":"2019-01-25T08:28:25.467","ParentId":null,"OwnerUserId":"9049053","Title":null,"Body":"

    One must admit the unique<\/code> function can sometimes be very confusing without given proper examples and explanations.<\/p>\n\n

    The dim<\/code> parameter specifies which dimension on the matrix tensor you want to apply on. <\/p>\n\n

    For instance, in a 2D matrix, dim=0<\/code> will let operation perform vertically where dim=1<\/code> means horizontally.<\/p>\n\n

    Example, let's consider a 4x4 matrix with dim=1<\/code>. As you can see from my code below, the unique<\/code> operation is applied row by row. <\/p>\n\n

    You notice the double occurrence of the number 11<\/code> in the first and last row. Numpy and Torch does this to preserve the shape of the final matrix. <\/p>\n\n

    However, if you do not specify any dimension, torch will automatically flatten your matrix and then apply unique<\/code> to it and you will get a 1D array that contains unique data.<\/p>\n\n

    import torch\n\nm = torch.Tensor([\n    [11, 11, 12,11], \n    [13, 11, 12,11], \n    [16, 11, 12, 11],  \n    [11, 11, 12, 11]\n])\n\noutput, indices = torch.unique(m, sorted=True, return_inverse=True, dim=1)\nprint(\"Ori \\n{}\".format(m.numpy()))\nprint(\"Sorted \\n{}\".format(output.numpy()))\nprint(\"Indices \\n{}\".format(indices.numpy()))\n\n# without specifying dimension\noutput, indices = torch.unique(m, sorted=True, return_inverse=True)\nprint(\"Sorted (no dim) \\n{}\".format(output.numpy()))\n<\/code><\/pre>\n\n
    \n\n

    Result (dim=1)<\/strong><\/p>\n\n

    Ori\n[[11. 11. 12. 11.]\n [13. 11. 12. 11.]\n [16. 11. 12. 11.]\n [11. 11. 12. 11.]]\nSorted\n[[11. 11. 12.]\n [11. 13. 12.]\n [11. 16. 12.]\n [11. 11. 12.]]\nIndices\n[1 0 2 0]\n<\/code><\/pre>\n\n

    Result (no dimension)<\/strong><\/p>\n\n

    Sorted (no dim)\n[11. 12. 13. 16.]\n<\/code><\/pre>\n"}]}
    {"QuestionId":54262831,"AnswerCount":0,"Tags":"","CreationDate":"2019-01-18T23:49:56.713","AcceptedAnswerId":null,"OwnerUserId":3380501.0,"Title":"How to handle dynamic shape in tf.contrib.image.dense_image_warp","Body":"

    It seems like tf.contrib.image.dense_image_warp, the API to do 2D warping, only supports static shape. The implementation assumes that the size of the input image is known.<\/p>\n\n

    Any suggestions on how to make it support dynamic shape, aka, the size the image is only known in runtime?<\/p>\n\n

    update on 01\/22\/2019:<\/p>\n\n

    The PR described in github<\/a> solved the problem. The PR was merged around 11\/2018. If you use the latest TensorFlow (master branch build), the function should support dynamic shape.<\/p>\n","answers":[]} {"QuestionId":54263155,"AnswerCount":1,"Tags":"","CreationDate":"2019-01-19T00:46:50.567","AcceptedAnswerId":null,"OwnerUserId":8285122.0,"Title":"Unity - Running a Neural Network","Body":"

    I trained a model using PyTorch. In Unity, I am using a to display a live video. How can I feed the webcam frames into the PyTorch model, then perform actions in Unity with the output of the model? <\/p>\n\n

    I found Unity ML-agents, but it doesn't seem like it would help with this situation.<\/p>\n","answers":[{"AnswerId":"54263643","CreationDate":"2019-01-19T02:39:36.397","ParentId":null,"OwnerUserId":"9094803","Title":null,"Body":"

    You can capture cam data on each update, then run your pytorch model by feeding it the data you just captured. I haven't tried and not sure how pytorch works, but for generic python scripts you can do something like:<\/p>\n\n

    ...\nvoid Start()\n{\n    ...\n    data = new Color32[webcamTexture.width * webcamTexture.height];\n    ...\n}\n...\nvoid FixedUpdate ()\n{\n    ...\n    webCamTexture.GetPixels32(data); \/\/this is faster than returning a Color32 object\n    ...\n} \n\n...\n\nprivate void runPython(string pathToPythonExecutable, string pyTorchScript, Color32[] data)\n{\n     var startInfo = new ProcessStartInfo();\n     var pyTorchArgs = convertDataToYourPyTorchInputFormat (data)\n     startInfo.Arguments = string.Format(\"{0} {1}\", pyTorchScript, pyTorchArgs);\n     startInfo.FileName = pathToPythonExecutable;\n     startInfo.UseShellExecute = false;\n     var process = Process.Start(start));\n     process.WaitForExit();\n     \/\/do stuff in unity with the return value of process (process.ExitCode) or whatever.\n}\n<\/code><\/pre>\n\n

    Mind you, this may create significant overhead to create and end processes using an external executable file. There are some libraries that allow you to run python scripts inside c#. I can think of 2: IronPython (http:\/\/ironpython.net<\/a>) and Python for .Net (http:\/\/pythonnet.github.io<\/a>) I have never tried them though.<\/p>\n"}]} {"QuestionId":54263308,"AnswerCount":0,"Tags":"","CreationDate":"2019-01-19T01:16:13.833","AcceptedAnswerId":null,"OwnerUserId":1738210.0,"Title":"why GPU is inactive during implementation in keras?","Body":"

    I have installed CUDA 9 on windows 10 and anaconda. before my programs were implemented on GPU but recently I add theano to my keras and after that all of my programs did not work. I reinstall anaconda with python 3.6.8, tensorflow 1.8, tensorflow_gpu 1.8 but it does not use GPU and only use CPU. what should I do now? I really need your help. Thank you.<\/p>\n","answers":[]} {"QuestionId":54263624,"AnswerCount":1,"Tags":"","CreationDate":"2019-01-19T02:35:56.660","AcceptedAnswerId":54335759.0,"OwnerUserId":3595278.0,"Title":"Combining flat_map and zip when reading TensorFlow Dataset from multiple files: Are files being read from disk a second time?","Body":"

    Following up on a previous question<\/a>, I am using to generate a dataset of successive items. I am doing this since I want my model_fn to be fed two successive frames at a time from which it calculates the difference.<\/p>\n\n

    When reading from multiple files on disk, I have run into the problem that the correct order of records in my dataset is sometimes not maintained in my current implementation. The simplified problem can be reproduced as:<\/p>\n\n

    file1.txt<\/em> (file2.txt looks the same with etc.)<\/p>\n\n

    <\/pre>\n\n

    My code<\/p>\n\n

    <\/pre>\n\n

    If I execute this code, I get one of<\/em> the following results, seemingly at random:<\/p>\n\n

    Option 1.1: Order maintained (file1.txt read first)<\/p>\n\n

    <\/pre>\n\n

    Option 1.2: Order maintained (file2.txt read first)<\/p>\n\n

    <\/pre>\n\n

    Option 2.1: Order not maintained (file1.txt read first)<\/p>\n\n

    <\/pre>\n\n

    Option 2.2: Order not maintained (file2.txt read first)<\/p>\n\n

    <\/pre>\n\n

    It seems to me like the zip function causes the dataset to be read from disk a second time independently. Is there any way that I can consistently achieve Option 1?<\/p>\n","answers":[{"AnswerId":"54335759","CreationDate":"2019-01-23T21:15:12.960","ParentId":null,"OwnerUserId":"3595278","Title":null,"Body":"

    I still think that this is confusing because I wouldn't expect zip to cause files to be read a second time. <\/p>\n\n

    However, in my case, it turns out all I needed to do was adding shuffle=False<\/code> argument to tf.data.Dataset.list_files<\/code> to achieve Option 1 consistently.<\/p>\n"}]} {"QuestionId":54263637,"AnswerCount":1,"Tags":"","CreationDate":"2019-01-19T02:39:12.043","AcceptedAnswerId":null,"OwnerUserId":10873443.0,"Title":"keras can not detect gpu","Body":"

    I have problem with my keras-gpu.<\/p>\n\n

    I install keras-gpu with Anaconda. \nMy laptop have two gpus. One is nVidia GTX950M, the other is Intel integrated graphics.When I run these testing codes,<\/p>\n\n

    <\/pre>\n\n

    the console shows:<\/p>\n\n

    <\/pre>\n\n

    It seems that my nVidia gpu is working.\nBut I use my keras-gpu, and run the following codes.<\/p>\n\n

    <\/pre>\n\n

    I check the task manager, and only my Intel Integrated Graphics works.\nI have tried <\/p>\n\n

    <\/pre>\n\n

    but it's still not working. And I tried to add these lines to my codes,<\/p>\n\n

    <\/pre>\n\n

    the console shows:<\/p>\n\n

    <\/pre>\n\n

    The gpu0 is my Intel graphics. So it turns out that my keras-gpu can not detect my nvidia gpu. \nIt doesn't make sense. How can it be that my tensorflow can detect the gpu but keras can not.\nI have working with this problem for so many days and it drives me crazy.\nPlease help me out.<\/p>\n","answers":[{"AnswerId":"54268827","CreationDate":"2019-01-19T15:55:17.557","ParentId":null,"OwnerUserId":"349130","Title":null,"Body":"

    What you are trying to do makes no sense, TensorFlow does not support Intel GPUs, only NVIDIA CUDA GPUs, your Intel GPU is not usable in TensorFlow, so it will always only see one GPU.<\/p>\n\n

    To use multi GPU, you need at least 2 NVIDIA CUDA GPUs.<\/p>\n"}]} {"QuestionId":54263733,"AnswerCount":1,"Tags":"","CreationDate":"2019-01-19T03:08:29.467","AcceptedAnswerId":null,"OwnerUserId":10887556.0,"Title":"No module named 'tensorflow' when running train.py in conda environment","Body":"

    I try to run the train.py file to train my object detector, but I get a error. I'm running this in my conda environment, and I can import and use tensorflow in that environment just fine. Anyone know why this happens? Thanks<\/p>\n\n

    <\/pre>\n","answers":[{"AnswerId":"54273554","CreationDate":"2019-01-20T04:23:07.800","ParentId":null,"OwnerUserId":"10887556","Title":null,"Body":"

    I couldn't figure out how to run it, so I just decided to create a jupyter notebook to run the cell in the fastai-audio kernel and it worked.<\/p>\n"}]} {"QuestionId":54264338,"AnswerCount":0,"Tags":"","CreationDate":"2019-01-19T05:30:13.390","AcceptedAnswerId":null,"OwnerUserId":874380.0,"Title":"Why does PyTorch not find my NVDIA drivers for CUDA support?","Body":"

    I've added an GeForce GTX 1080 Ti into my machine (Running Ubuntu 18.04 and Anaconda with Python 3.7) to utilize the GPU when using PyTorch. Both cards a correctly identified:<\/p>\n\n

    <\/pre>\n\n

    The NVS 310 handles my 2-monitor setup, I only want to utilize the 1080 for PyTorch. I also installed the latest NVIDIA drivers that are currently in the repository and that seems to be fine:<\/p>\n\n

    <\/pre>\n\n

    Driver version 390.xx allows to run CUDA 9.1 (9.1.85) according the the NVIDIA docs<\/a>. Since this is also the version in the Ubuntu repositories, I simple installed the CUDA Toolkit with:<\/p>\n\n

    <\/pre>\n\n

    And again, this seems be alright:<\/p>\n\n

    <\/pre>\n\n

    and<\/p>\n\n

    <\/pre>\n\n

    Lastly, I've installed PyTorch from scratch with conda<\/p>\n\n

    <\/pre>\n\n

    Also error as far as I can tell:<\/p>\n\n

    <\/pre>\n\n

    However, PyTorch doesn't seem to find CUDA:<\/p>\n\n

    <\/pre>\n\n

    In more detail, if I force PyTorch to convert a tensor to CUDA with I get the error:<\/p>\n\n

    <\/pre>\n\n

    What am I'm missing here? I'm new to this, but I think I've checked the Web already quite a bit to find any caveats like NVIDIA driver and CUDA toolkit versions?<\/p>\n\n

    EDIT:<\/strong> Some more outputs from PyTorch:<\/p>\n\n

    <\/pre>\n","answers":[]}
    {"QuestionId":54264358,"AnswerCount":0,"Tags":"","CreationDate":"2019-01-19T05:34:03.410","AcceptedAnswerId":null,"OwnerUserId":6224352.0,"Title":"how to use keras and pandas to duplicate similar arrays","Body":"

    I have a array from my teacher, he gave me an array like below:<\/p>\n\n

    array contains 0,1,none<\/p>\n\n

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

    and asked me to duplicate the array ten times but however each column must have similar percent distribution say each column have no more than 8% percent compared with the origin array.<\/p>\n\n

    how should i achieve the goal?<\/p>\n","answers":[]} {"QuestionId":54264617,"AnswerCount":1,"Tags":"","CreationDate":"2019-01-19T06:22:38.243","AcceptedAnswerId":null,"OwnerUserId":10323453.0,"Title":"How to save a modal and load again to use?","Body":"

    I have no more knowledge of python. This is my ANN modal code in python. This code contains to predict customers situation in binary output. Which is customers leave or not. <\/p>\n\n

    Code:<\/p>\n\n

    <\/pre>\n\n

    I want to know how to save this modal as h5 using keras. After I saved it how to load again in another project to predict the data. <\/p>\n","answers":[{"AnswerId":"54264742","CreationDate":"2019-01-19T06:46:31.690","ParentId":null,"OwnerUserId":"9999035","Title":null,"Body":"

    Inorder to save the model, You can do the one below:<\/p>\n\n

    from keras.models import load_model\nmodel.save('model_file.h5')\n<\/code><\/pre>\n\n

    And to load the model back use:<\/p>\n\n

    my_model = load_model('model_file.h5')\n<\/code><\/pre>\n"}]}
    {"QuestionId":54265153,"AnswerCount":1,"Tags":"","CreationDate":"2019-01-19T07:57:06.880","AcceptedAnswerId":54266897.0,"OwnerUserId":7528024.0,"Title":"Embedding an object detection model into iOS app, and deploy it on a UIView's content instead of camera stream?","Body":"

    I've retrained an ssd_mobilenet_v2 via tensorflow object detection API on my custom class. I've now got a frozen_inference_graph.pb file, which is ready to be embedded into my app. \nThe tutorials on tensorflow's github<\/a> and website only show how to use it for the iOS built-in camera stream. Instead, I have an external camera for my iPhone, which streams to an UIView component. I want my network to detect objects in this, but my research doesn't point to any obvious implementations\/tutorials. <\/p>\n\n

    My question: Does anyone know whether this is possible? If so, what's the best way to implement such a thing? tensorflow-lite? tensorflow mobile? Core ML? Metal?<\/p>\n\n

    Thanks!<\/p>\n","answers":[{"AnswerId":"54266897","CreationDate":"2019-01-19T12:04:12.523","ParentId":null,"OwnerUserId":"7501629","Title":null,"Body":"

    In that TensorFlow source code, in the file CameraExampleViewController.mm<\/strong> is a method runCNNOnFrame<\/code> that takes a CVPixelBuffer<\/code> object as input (from the camera) and copies its contents into image_tensor_mapped.data()<\/code>. Then it runs the TF graph on that image_tensor<\/code> object.<\/p>\n\n

    To use a different image source, such as the contents of a UIView<\/code>, you need to first read the contents of that view into some kind of memory buffer (typically a CGImage<\/code>) and then copy that memory buffer into image_tensor_mapped.data()<\/code>.<\/p>\n\n

    It might be easier to convert the TF model to Core ML (if possible), then use the Vision framework to run the model as that can directly use a CGImage<\/code> as input. This saves you from having to convert that image into a tensor first.<\/p>\n"}]} {"QuestionId":54265374,"AnswerCount":1,"Tags":"","CreationDate":"2019-01-19T08:37:49.790","AcceptedAnswerId":54265703.0,"OwnerUserId":10936710.0,"Title":"tensorflow ValueError: No gradients provided for any variable, check your graph for ops that do not support gradients","Body":"

    I got an error on tensorflow. \nThe code is like this:\n

    \r\n
    \r\n
    <\/pre>\r\n<\/div>\r\n<\/div>\r\n\nand the error is:<\/p>\n\n
    \n

    ValueError: No gradients provided for any variable, check your graph for ops that do not support gradients, between variables\n [\"\",\n \"\",\n \"\",\n \"\"] and loss\n Tensor(\"Mean:0\", shape=(), dtype=float32).<\/strong><\/p>\n<\/blockquote>\n\n

    My tensorflow version is 1.2.1, and I'm using python3.6.<\/p>\n","answers":[{"AnswerId":"54265703","CreationDate":"2019-01-19T09:27:25.913","ParentId":null,"OwnerUserId":"10651567","Title":null,"Body":"

    You got this problem because the arguments you passed into tf.nn.softmax_cross_entropy_with_logits<\/code> are not what it wants. From the doc of tf.nn.softmax_cross_entropy_with_logits<\/a>:<\/p>\n\n

    \n

    A common use case is to have logits and labels of shape [batch_size,\n num_classes], but higher dimensions are supported, with the dim\n argument specifying the class dimension.<\/p>\n<\/blockquote>\n\n

    So you should make your target one-hot encoded before feeding it to a neural network. Following is the runnable code:<\/p>\n\n

    from sklearn import datasets\nimport random\nimport tensorflow as tf\nimport numpy as np\nfrom sklearn.preprocessing import OneHotEncoder\n\nwine=datasets.load_wine()\nwine_data = wine.data\nonehotencoder = OneHotEncoder()\nwine_target = onehotencoder.fit_transform(wine.target[...,np.newaxis]).toarray()\n\ndef generate_batch(batch_size,wine):\n    batch_x=[]\n    batch_y=[]\n    for _ in range(batch_size):\n        index=random.randint(0,177)\n        batch_y.append(wine_target[index])\n        batch_x.append(wine_data[index])\n    return batch_x,batch_y\n\ndef inference(x):\n    with tf.variable_scope('layer1'):\n        weight1 = tf.get_variable('weight', [13, 7], initializer=tf.truncated_normal_initializer(stddev=0.1))\n        bias1 = tf.get_variable('bias', [7], initializer=tf.constant_initializer(0.1))\n        layer1 = tf.nn.relu(tf.matmul(x, weight1) + bias1)\n    weight2 =tf.get_variable('weight', [7, 3], initializer=tf.truncated_normal_initializer(stddev=0.1))\n    bias2 = tf.get_variable('bias', [3], initializer=tf.constant_initializer(0.1))\n    logit = tf.matmul(layer1, weight2) + bias2\n    return logit\n\nx=tf.placeholder(tf.float32,[None,13])\ny_=tf.placeholder(tf.float32,[None, 3])\ny=inference(x)\n\ncross_entropy=tf.nn.softmax_cross_entropy_with_logits(labels=y_,logits=y)\ncross_entropy_mean=tf.reduce_mean(cross_entropy)\n\ntrain_step=tf.train.GradientDescentOptimizer(0.001).minimize(cross_entropy_mean)\ncorrect_prediction = tf.equal(y ,y_)\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\"))\n\nwith tf.Session() as sess:\n    tf.global_variables_initializer().run()\n    for i in range(2000):\n        data,target=generate_batch(20,wine)\n        sess.run(train_step,feed_dict={x:data,y_:target})\n<\/code><\/pre>\n"}]}
    {"QuestionId":54265661,"AnswerCount":0,"Tags":"","CreationDate":"2019-01-19T09:22:21.383","AcceptedAnswerId":null,"OwnerUserId":3128349.0,"Title":"PyTorch: CrossEntropyLoss, changing class weight does not change the computed loss","Body":"

    According to Doc<\/a> for cross entropy loss, the weighted loss is calculated by multiplying the weight for each class and the original loss.<\/p>\n\n

    However, in the pytorch implementation, the class weight seems to have no effect on the final loss value unless it is set to zero. Following is the code:<\/p>\n\n

    <\/pre>\n\n

    As illustrated in the code, the class weight seems to have no effect unless it is set to 0, this behavior contradicts to the documentation.<\/p>\n\n

    Updates<\/strong>
    \nI implemented a version of weighted cross entropy which is in my eyes the \"correct\" way to do it.<\/p>\n\n

    <\/pre>\n\n

    What I did is to multiply each instance in the batch with its associated class weight. The result is still different from the original pytorch implementation, which makes me wonder how pytorch actually implement this.<\/p>\n","answers":[]} {"QuestionId":54265959,"AnswerCount":1,"Tags":"","CreationDate":"2019-01-19T10:02:45.180","AcceptedAnswerId":54266102.0,"OwnerUserId":10291015.0,"Title":"predicting my own image in cnn using keras","Body":"

    \n

    how to predict my own image(in the directory)using cnn in keras after\n training on MNIST dataset?\n I know I can use 'model.predict(X_test[:])' to make prediction on test set images but how do I predict my own image?<\/p>\n<\/blockquote>\n\n

    <\/pre>\n","answers":[{"AnswerId":"54266102","CreationDate":"2019-01-19T10:22:32.857","ParentId":null,"OwnerUserId":"10651567","Title":null,"Body":"

    You should first read in your image by cv2<\/code> and resize it to (28,28). Finally add the batch dimension(0th dimension) and channel dimension(last dimension) before feeding it into the keras model.<\/p>\n\n

    import cv2\nimport numpy as np\n\nimg = cv2.imread(\"your_image.png\",0)\nimg = cv2.resize(img, (28, 28))\nimg = np.reshape(img, [1, 28, 28, 1])\nprint(np.argmax(model.predict(img)))\n<\/code><\/pre>\n"}]}
    {"QuestionId":54265998,"AnswerCount":1,"Tags":"","CreationDate":"2019-01-19T10:08:12.643","AcceptedAnswerId":null,"OwnerUserId":10928672.0,"Title":"How to extract the weights and bias from tensorflow neural network and how to compute the prediction on your own in python?","Body":"

    I'm using tensorflow in python for building a simple neural network for regression and I would like to extract the weights and the bias in order to use them in another program. Can somebody maybe point out how to extract the weights from the tf neural network and compute the prediction from the same weights, with simple matrix multiplication and addition once the tensorflow NN is trained. Also will this computation improve the prediction time(since tf.predict does some additional computations)?<\/p>\n","answers":[{"AnswerId":"54270039","CreationDate":"2019-01-19T18:17:33.707","ParentId":null,"OwnerUserId":"10048953","Title":null,"Body":"

    You can use the tf.train.Saver<\/code> class to save your model as a ckpt file and use it later: <\/p>\n\n

    saver = tf.train.Saver()\n with tf.Session() as sess:\n    #your code here\n    save_path = saver.save(sess, \"\/model_path\/model.ckpt\")\n<\/code><\/pre>\n\n

    To restore the variables:<\/p>\n\n

    saver.restore(sess, \"\/your_path\/model.ckpt\") \n<\/code><\/pre>\n\n

    Complete documentation: https:\/\/www.tensorflow.org\/guide\/saved_model<\/a><\/p>\n"}]} {"QuestionId":54266176,"AnswerCount":0,"Tags":"","CreationDate":"2019-01-19T10:33:47.260","AcceptedAnswerId":null,"OwnerUserId":10927469.0,"Title":"Loss value becomes constant after some training steps while training a CNN in Tensorflow","Body":"

    I'm trying to develop a convolutional neural network for image classification.\nCurrently I am working on classifying a set from about 1000 cats and dogs images.\nHowever, I\u00b4m stuck in the training process.<\/p>\n\n

    Firstly, I tried to develop my own network, preprocessing and labeling the images myself, testing with different architectures and hyperparameters using Tensorflow.\nAs I didn't obtain good results, I tried to create a similar network with keras, obtainig better results.<\/p>\n\n

    In the following code I create the trainig and validation sets for the tensorflow network:<\/p>\n\n

    <\/pre>\n\n

    And the code that I used to build and train my model in tensorflow:<\/p>\n\n

    <\/pre>\n\n

    When I run the model, after some iterations, the gradients always became zero an the loss got stuck in a constant value.\nAt first I thought the network stopped learning because of the lack of images, but when I tried to train the same dataset with a network built in Keras, the results were pretty good.\nI used the same number of layers, the same hiperparameters and I processed the images the same way in both cases. Although the weigth's initialization may differ, the results make me think that there is some error in the code I added.\nCould someone help me with this issue?<\/p>\n","answers":[]} {"QuestionId":54266320,"AnswerCount":1,"Tags":"","CreationDate":"2019-01-18T16:29:03.390","AcceptedAnswerId":null,"OwnerUserId":10934085.0,"Title":"Calculating the gradient used by the Jacobian-based Dataset Augmentation in Keras","Body":"

    I am trying to understand my mistake when calculating the sign of the gradient used by the jacobian-based dataset augmentation published in https:\/\/arxiv.org\/abs\/1602.02697<\/a><\/p>\n\n

    \n

    \" the sign of the Jacobian matrix dimension corresponding to the label assigned to input $\\vec{x}$<\/span> by the oracle $\\tilde{O}$<\/span>: $sgn(J_F(\\vec{x})[\\tilde{O}(\\vec{x})])$<\/span> \"<\/p>\n<\/blockquote>\n\n

    For the calculation you can ignore the oracle O and simply treat it like a classification result Y.<\/p>\n\n

    As I understand the term correctly I have to calculate the gradient of the function that the neural network has learned w.r.t the inputs and then evaluate it with the current input vector x. The result should then be an array which contains the gradients for the input vector for each class.<\/p>\n\n

    For demonstration purposes I trained a keras model with the Iris data set according to https:\/\/www.kaggle.com\/lavajiit\/deep-learning-iris-dataset-keras\/notebook<\/a> \nand then calculated the sign of the gradients in the following way:<\/p>\n\n

    <\/pre>\n\n

    Unfortunately I do not get the desired results:<\/p>\n\n

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

    As you can see it only contains the gradients for the 4 features of the 120 input vectors, hence the shape (120,4) but it should calculate them for each class.\nE.g 3 x (120,4)<\/p>\n\n

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

    Additionally the gradients are mostly zero but in between there are some rows that seem to be correctly calculated.<\/p>\n\n

    I very much appreciate any help.<\/p>\n","answers":[{"AnswerId":"54277282","CreationDate":"2019-01-20T14:09:31.010","ParentId":null,"OwnerUserId":"10934085","Title":null,"Body":"

    The gradient needs to be computed for each of the 3 outputs separately:<\/p>\n\n

    tf.gradients(out[:, class_i], in)\n<\/code><\/pre>\n\n

    \"enter<\/p>\n"}]} {"QuestionId":54266402,"AnswerCount":0,"Tags":"","CreationDate":"2019-01-19T11:03:45.023","AcceptedAnswerId":null,"OwnerUserId":6224352.0,"Title":"what is the problem with my keras vae model,the acc is very bad","Body":"

    i have an 2-D array that contains only number 1,0 ,or 2. the array has 150 rows and 124 columns, i tried use VAE to modify the array slightly.\nbut the result and acc is very bad, please help<\/p>\n\n

    <\/pre>\n\n

    Epoch 35\/50\n500\/500 [==============================] - 0s 24us\/step - loss: 0.4306 - acc: 0.0000e+00 - val_loss: 0.4308 - val_acc: 0.0000e+00\nEpoch 36\/50\n500\/500 [==============================] - 0s 24us\/step - loss: 0.4293 - acc: 0.0000e+00 - val_loss: 0.4294 - val_acc: 0.0000e+00\nEpoch 37\/50\n500\/500 [==============================] - 0s 24us\/step - loss: 0.4292 - acc: 0.0000e+00 - val_loss: 0.4287 - val_acc: 0.0000e+00\nEpoch 38\/50\n500\/500 [==============================] - 0s 24us\/step - loss: 0.4282 - acc: 0.0000e+00 - val_loss: 0.4285 - val_acc: 0.0000e+00\nEpoch 39\/50\n500\/500 [==============================] - 0s 24us\/step - loss: 0.4262 - acc: 0.0000e+00 - val_loss: 0.4265 - val_acc: 0.0000e+00\nEpoch 40\/50\n500\/500 [==============================] - 0s 24us\/step - loss: 0.4250 - acc: 0.0000e+00 - val_loss: 0.4256 - val_acc: 0.0000e+00\nEpoch 41\/50\n500\/500 [==============================] - 0s 24us\/step - loss: 0.4271 - acc: 0.0000e+00 - val_loss: 0.4247 - val_acc: 0.0000e+00\nEpoch 42\/50\n500\/500 [==============================] - 0s 24us\/step - loss: 0.4226 - acc: 0.0000e+00 - val_loss: 0.4252 - val_acc: 0.0000e+00\nEpoch 43\/50\n500\/500 [==============================] - 0s 25us\/step - loss: 0.4214 - acc: 0.0000e+00 - val_loss: 0.4233 - val_acc: 0.0000e+00\nEpoch 44\/50\n500\/500 [==============================] - 0s 25us\/step - loss: 0.4237 - acc: 0.0000e+00 - val_loss: 0.4209 - val_acc: 0.0000e+00\nEpoch 45\/50\n500\/500 [==============================] - 0s 24us\/step - loss: 0.4203 - acc: 0.0000e+00 - val_loss: 0.4179 - val_acc: 0.0000e+00\nEpoch 46\/50\n500\/500 [==============================] - 0s 24us\/step - loss: 0.4211 - acc: 0.0000e+00 - val_loss: 0.4209 - val_acc: 0.0000e+00\nEpoch 47\/50\n500\/500 [==============================] - 0s 25us\/step - loss: 0.4220 - acc: 0.0000e+00 - val_loss: 0.4179 - val_acc: 0.0000e+00\nEpoch 48\/50\n500\/500 [==============================] - 0s 24us\/step - loss: 0.4172 - acc: 0.0000e+00 - val_loss: 0.4180 - val_acc: 0.0000e+00\nEpoch 49\/50\n500\/500 [==============================] - 0s 24us\/step - loss: 0.4166 - acc: 0.0000e+00 - val_loss: 0.4154 - val_acc: 0.0000e+00\nEpoch 50\/50\n500\/500 [==============================] - 0s 25us\/step - loss: 0.4173 - acc: 0.0000e+00 - val_loss: 0.4176 - val_acc: 0.0000e+00<\/p>\n","answers":[]} {"QuestionId":54267186,"AnswerCount":0,"Tags":"","CreationDate":"2019-01-19T12:40:00.263","AcceptedAnswerId":null,"OwnerUserId":10935710.0,"Title":"What is the source code for Keras function model.fit()?","Body":"

    I'm building a simple neural network in Python using Tensorflow and Keras. I need to implement this code to work on a GPU, using PyCuda. I plan on parallelizing learning all the epochs, however since Keras is very minimalistic, all epoch training (at least from my understanding) is done with one line:<\/p>\n\n

    model.fit(train_images, train_labels, epochs=100)<\/p>\n\n

    How would it be possible to \"extract\" something from this function, that could be fed to a PyCuda kernel function? This is my code so far:<\/p>\n\n

    <\/pre>\n","answers":[]}
    {"QuestionId":54267290,"AnswerCount":1,"Tags":"","CreationDate":"2019-01-19T12:53:50.243","AcceptedAnswerId":null,"OwnerUserId":988709.0,"Title":"TensorRT with TensorFlow get no result when infering","Body":"

    I want to use tensorrt to speedup tensorflow model infering. But i got none result when do that, the following is my code. The return boxes and scores are all None. Am i use TensorRT and tensorflow the wrong way?<\/p>\n\n

    <\/pre>\n","answers":[{"AnswerId":"57093262","CreationDate":"2019-07-18T11:18:11.710","ParentId":null,"OwnerUserId":"11802541","Title":null,"Body":"

    The problem is in the definition of output_node. The return_elements should be defined as return_elments=[\"detection_boxes:0\", \"detection_classes:0\"]<\/code><\/p>\n"}]} {"QuestionId":54267383,"AnswerCount":0,"Tags":"","CreationDate":"2019-01-19T13:03:49.153","AcceptedAnswerId":null,"OwnerUserId":3905169.0,"Title":"Is it possible to train keras models on many training sets in a multiprocessed way?","Body":"

    I run python v=3.6.7 with PyCharm using a conda virtual environment. My tensorflow version is 1.12.0.\nI want to train many keras models on various training sets. Since the training on one single training set is already quite slow, I would like to run the for loop using the Pool function of the multiprocessing library.\nI provide below a minimal example that reproduces the problem.<\/p>\n\n

    fit_model is the function on which I want to run multiprocessing: it takes as an input a numpy array which is a training set and train a simple keras neural network on it (dummy settings).\nI read already that one important aspect when performing multiprocessing with tensorflow is to make sure the function that we want to multiprocess has the tensorflow imports on the top, which is what I did. \nIf I add the following instruction (below the \"normal\" imports)<\/p>\n\n

    <\/pre>\n\n

    on top of the fit_model function, I have the error message (truncated):<\/p>\n\n

    <\/pre>\n\n

    Without the \"enable_eager_execution\" instruction, I get the following:<\/p>\n\n

    <\/pre>\n\n

    Please see below my code. You can add little dummy training sets provided below: just drop the data in txt files 'ts1.txt', 'ts2.txt', 'ts3.txt' and save them where you run the code.<\/p>\n\n

    Training set 1:<\/p>\n\n

    <\/pre>\n\n

    Training set 2:<\/p>\n\n

    <\/pre>\n\n

    Training set 3:<\/p>\n\n

    <\/pre>\n\n

    Code:<\/p>\n\n

    <\/pre>\n\n

    The code above does not work and I start to wonder if I what I am trying to do is actually possible.<\/p>\n","answers":[]} {"QuestionId":54267623,"AnswerCount":1,"Tags":"","CreationDate":"2019-01-19T13:31:41.780","AcceptedAnswerId":null,"OwnerUserId":2906838.0,"Title":"How To Measure The Performance Of Map Function In Tensorflow's New DataSet API?","Body":"

    I've been using Tensorflow version 1.12 in my GPU instance, I have around 130 TfRecords file containing the ImageNet data which is 1.2 million. First I apply a map function and then to augment the dataset, which will ultimately be 1.2 million x 2048 images. <\/p>\n\n

    <\/pre>\n\n

    Here decode function returns the flattened array of the image and the one-hot encoded label. However, the function passed in does quite a heavy thing, which is like: two loops to create the slices and reverse of them each producing 1024 tensors. The final output for a single image would be the tensor. The function looks like this: <\/p>\n\n

    <\/pre>\n\n

    Now the problem is that the training process is very slow. I've read that is quite bad with this kind of need. But I think there are lots of things which can be improved here. For that I need to visualize the performance of each of this operation. Mainly of the function. \nI'm using RunTime Statistic of tensorflow like this: <\/p>\n\n

    <\/pre>\n\n

    Which does logs the time taken to prepare the dataset, however it doesn't log the time taken to perform the operation, which is my concern here as I suspect, that is the place where the performance is lagging. \n\"enter<\/a><\/p>\n\n

    I would appreciate your help regarding both the Performance suggessation<\/strong> as well as the measurement of the time taken in flat_map function<\/strong>. <\/p>\n\n

    Thanks in advance. <\/p>\n","answers":[{"AnswerId":"54269071","CreationDate":"2019-01-19T16:22:39.413","ParentId":null,"OwnerUserId":"2641587","Title":null,"Body":"

    Try to use the TensorFlow's timeline: HowTo profile TensorFlow<\/a><\/p>\n"}]} {"QuestionId":54267750,"AnswerCount":1,"Tags":"","CreationDate":"2019-01-19T13:48:12.960","AcceptedAnswerId":null,"OwnerUserId":10843708.0,"Title":"Jupyter kernel crashing when executing an RNN fitting","Body":"

    After loading and cleaning the dataset in the Jupyter notebook, I tried to run following code:<\/p>\n\n

    <\/pre>\n\n

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

    <\/pre>\n\n

    Any of the previous operation give me problems, including adding 4 LSTM layers, the output layer and compiling the RNN.<\/p>\n\n

    And then the kernel stops working and I can't go on.<\/p>\n\n

    Any suggestion or a way to understand what is going wrong?
    \nThanks!<\/p>\n","answers":[{"AnswerId":"54267947","CreationDate":"2019-01-19T14:11:10.930","ParentId":null,"OwnerUserId":"10843708","Title":null,"Body":"

    Ok, solved.\nThe dataset was too large for my local memory (around 3.5 million entries, lol).\nI'd to split it in smaller chunks!<\/p>\n"}]} {"QuestionId":54267919,"AnswerCount":0,"Tags":"","CreationDate":"2019-01-19T14:07:00.107","AcceptedAnswerId":null,"OwnerUserId":4002012.0,"Title":"How can I add a feature using torchtext?","Body":"

    is able to read a file with some columns, each one corresponding to a field. What if I want to create a new column (which I will use as a feature)? For example, imagine the file has two columns, text and target, and I want to extract some information from the text and generate a new feature (e.g. if it contains certain words), can I do this directly with or do I need to do it in the file before?<\/p>\n\n

    Thanks!<\/p>\n","answers":[]} {"QuestionId":54267982,"AnswerCount":0,"Tags":"","CreationDate":"2019-01-19T14:14:30.443","AcceptedAnswerId":null,"OwnerUserId":6038900.0,"Title":"Proper way for creating mask for segmentation","Body":"

    Im creating the mask as follows for the sake of segmentation task.<\/p>\n\n

    <\/pre>\n\n

    I'm trying to segment three attributes so there are three different pixel values. Is this still a correct way of creating mask? because the training loss tends to be less than 50. <\/p>\n","answers":[]} {"QuestionId":54268029,"AnswerCount":3,"Tags":"","CreationDate":"2019-01-19T14:21:21.710","AcceptedAnswerId":54268111.0,"OwnerUserId":913098.0,"Title":"How to convert a pytorch tensor into a numpy array?","Body":"

    I have a torch tensor<\/p>\n\n

    <\/pre>\n\n

    How can I get it in numpy?<\/strong><\/p>\n\n

    Something like<\/p>\n\n

    <\/pre>\n\n

    output should be the same as if I did<\/p>\n\n

    <\/pre>\n","answers":[{"AnswerId":"56551106","CreationDate":"2019-06-11T20:14:02.857","ParentId":null,"OwnerUserId":"8534788","Title":null,"Body":"

    Another useful way :<\/p>\n\n

    a = torch(0.1, device: cuda)\n\na.cpu().data.numpy()\n\nAnswer: array(0.1, dtype=float32)\n<\/code><\/pre>\n"},{"AnswerId":"54268111","CreationDate":"2019-01-19T14:30:21.763","ParentId":null,"OwnerUserId":"913098","Title":null,"Body":"

    copied from pytorch doc<\/a>:<\/p>\n\n

    a = torch.ones(5)\nprint(a)\n<\/code><\/pre>\n\n
    \n

    tensor([1., 1., 1., 1., 1.])<\/p>\n<\/blockquote>\n\n

    b = a.numpy()\nprint(b)\n<\/code><\/pre>\n\n
    \n

    [1. 1. 1. 1. 1.]<\/p>\n<\/blockquote>\n"},{"AnswerId":"54268639","CreationDate":"2019-01-19T15:32:16.640","ParentId":null,"OwnerUserId":"5352399","Title":null,"Body":"

    You may find the following two functions useful.<\/p>\n\n

      \n
    1. torch.Tensor.numpy()<\/a><\/li>\n
    2. torch.from_numpy()<\/a><\/li>\n<\/ol>\n"}]} {"QuestionId":54268613,"AnswerCount":0,"Tags":"","CreationDate":"2019-01-19T15:29:14.810","AcceptedAnswerId":null,"OwnerUserId":10559457.0,"Title":"How to copy values of one LSTM to another in tensorflow","Body":"

      For a bit of background: I have to LSTM networks, each predicts different things and are trained on different data. LSTM1 is trained on a lot of data, LSTM2 trained on less data. In production, both networks will run at the same time.<\/p>\n\n

      The idea is to use LSTM1 as initial values for LSTM2.<\/p>\n\n

      I built the networks like this.<\/p>\n\n

      <\/pre>\n\n

      I thought that before training LSTM2 there must be a way to just copy the values from LSTM1 to LSTM2. I can't figure out how this works. I can see the variables and know how to access their values, but can't figure out how to transfer the values from one variable to the other.<\/p>\n\n

      Here the variables I'm talking about.<\/p>\n\n

      <\/pre>\n\n

      I want to set rnn\/LSTM2\/kernel:0 = rnn\/LSTM1\/kernel:0<\/p>\n","answers":[]} {"QuestionId":54268879,"AnswerCount":2,"Tags":"","CreationDate":"2019-01-19T16:02:04.340","AcceptedAnswerId":null,"OwnerUserId":9417884.0,"Title":"Reading a large pre trained fastext word embedding file in python","Body":"

      I am doing sentiment analysis and I want to use pre-trained fasttext embeddings, however the file is very large(6.7 GB) and the program takes ages to compile.<\/p>\n\n

      <\/pre>\n\n

      Is there any way to speedup the process?<\/p>\n","answers":[{"AnswerId":"54269230","CreationDate":"2019-01-19T16:43:46.693","ParentId":null,"OwnerUserId":"10921263","Title":null,"Body":"

      You can load the pretrained embeddings with gensim instead. At least for me this was much faster. First you need to pip install gensim and then you can load the model with the following line of code:<\/p>\n\n

      from gensim.models import FastText\n\nmodel = FastText.load_fasttext_format('cc.en.300.bin')\n<\/code><\/pre>\n\n

      (I'm not sure if you need the .bin file for this, maybe the .vec file also works.)<\/p>\n\n

      To get the embedding of a word with this model, simply use model[word]<\/code>.<\/p>\n"},{"AnswerId":"55870895","CreationDate":"2019-04-26T15:39:39.120","ParentId":null,"OwnerUserId":"3261292","Title":null,"Body":"

      I recommend you to use .bin models, but if it doesn't exist and you only have .vec or .txt, try to parallelize the process using Joblib:<\/p>\n\n

      from joblib import Parallel, delayed\nfrom tqdm import tqdm\n\nif __name__ == '__main__':\n    embeddings_index = {}\n\n    f = open(os.path.join('D:\/multi_lingual', 'wiki.en.align.vec'), 'r', encoding='utf-8')\n    def loading(line):\n        values = line.rstrip().rsplit(' ')\n        word = values[0]\n        coefs = np.asarray(values[1:], dtype='float32')\n        return word, coefs\n\n    embeddings_index = dict(Parallel(n_jobs=-1)(delayed(loading)(line) for line in tqdm(f)))\n    f.close()\n    print(len(embeddings_index))\n<\/code><\/pre>\n\n

      by monitoring tqdm progress bar, I noticed the amount of improvement:<\/p>\n\n

      \n

      without parallelization: 10208.44it\/s <\/p>\n \n

      with parallelization: 23155.08it\/s<\/p>\n<\/blockquote>\n\n

      I'm using 4 cores CPUz .. The results are not totally precise because I was using the processor on other stuff. Maybe you can notice better improvements. <\/p>\n\n

      The other point is, I recommend you after reading the required words to save them where you can load them in the next time instead of loading the whole embeddings file each time.<\/p>\n"}]} {"QuestionId":54268896,"AnswerCount":1,"Tags":"","CreationDate":"2019-01-19T16:04:21.470","AcceptedAnswerId":54269776.0,"OwnerUserId":10937834.0,"Title":"What strategy should I use in my CNN to go from a 3D volume to a 2D plane?","Body":"

      What strategy should I use in my CNN to go from a 3D volume to a 2D plane as the output layer. Can I even have a 2D layer as output?<\/p>\n\n

      I am trying to develop a network which input is a 320x320x3 image and output should be 68x2.<\/p>\n\n

      I know one way to do it would be to start from 320x320x3 and after a few layer I could flatten my 3D layers and then shorten it down to a 1D array of 136. But I am trying to understand if I could somehow go down to a desired 2d dimension at the final layer.<\/p>\n\n

      Thanks,\nShubham<\/p>\n","answers":[{"AnswerId":"54269776","CreationDate":"2019-01-19T17:48:48.067","ParentId":null,"OwnerUserId":"5495381","Title":null,"Body":"

      Edit<\/strong>: I might have misread your question initially. If your intention is to have 136 output nodes that can be arranged in a 68x2 matrix (and not to have a 68x68x2 image in the output, as I though at first<\/em>), then you can use a Reshape<\/code> layer after your final dense layer with 136 units:<\/p>\n\n

      import keras\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, Flatten, Dense, Reshape\n\nmodel = Sequential()\nmodel.add(Conv2D(32, 3, input_shape=(320, 320, 3)))\nmodel.add(Flatten())\nmodel.add(Dense(136))\nmodel.add(Reshape((68, 2)))\n\nmodel.summary()\n<\/code><\/pre>\n\n

      This will give you the following model, with the desired shape in the output:<\/p>\n\n

      Layer (type)                 Output Shape              Param #   \n=================================================================\nconv2d_2 (Conv2D)            (None, 318, 318, 32)      896       \n_________________________________________________________________\nflatten_2 (Flatten)          (None, 3235968)           0         \n_________________________________________________________________\ndense_2 (Dense)              (None, 136)               440091784 \n_________________________________________________________________\nreshape_1 (Reshape)          (None, 68, 2)             0         \n=================================================================\nTotal params: 440,092,680\nTrainable params: 440,092,680\nNon-trainable params: 0\n<\/code><\/pre>\n\n

      Make sure to provide your training labels in the same shape when fitting the model. <\/p>\n\n


      \n\n

      (original answer, might still be relevant)<\/em><\/p>\n\n

      Yes, this is commonly done in semantic segmentation models, where the inputs are images and the outputs are tensors of the same height and width of the images, and with the number of channels equal to the number of classes in the output. If you want to do this in TensorFlow or Keras, you can look up existing implementations<\/a>, for instance of U-Net architectures. <\/p>\n\n

      A core feature of these models is that these networks are fully convolutional: they only consist of convolutional layers. Typically, the feaure maps in these models go from 'wide and shallow' (big feature maps in the spatial dimensions with few channels) at first, to 'small and deep' (small spatial dimensions, high-dimensional channel dimension) and back to the desired output dimension. Hence the U-shape:<\/p>\n\n

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

      There are a lot of ways to go from 320x320x3 to 68x2 with a fully convolutional network, but the input and output of your model would basically look like this:<\/p>\n\n

      import keras\nfrom keras import Sequential\nfrom keras.layers import Conv2D\n\nmodel = Sequential()\n\nmodel.add(Conv2D(32, 3, activation='relu', input_shape=(320,320,3)))\n# Include more convolutional layers, pooling layers, upsampling layers etc\n...\n# At the end of the model, add your final Conv2dD layer with 2 filters\n# and the required activation function\nmodel.add(Conv2D(2, 3, activation='softmax'))\n<\/code><\/pre>\n"}]}
      {"QuestionId":54268970,"AnswerCount":1,"Tags":"","CreationDate":"2019-01-19T16:12:07.393","AcceptedAnswerId":54269383.0,"OwnerUserId":10648778.0,"Title":"Wrong dense layer output shape after moving from TF 1.12 to 1.10","Body":"

      I'm migrating from Tensorflow 1.12 to Tensorflow 1.10 (Collaboratory -> AWS sagemaker), the code seems to be working fine in Tensorflow 1.12 but in 1.10 i get an error <\/p>\n\n

      Input example - strings with no whitespaces: <\/p>\n\n

      <\/pre>\n\n

      which I preprocess by changing small letters into 1, capital letters 2, digits - 3, '-' - 4, '_' - 5 and padding so they are equal length with 0s<\/p>\n\n

      and 4 labels a - 0, b - 1, c - 2, d - 3<\/p>\n\n

      Assuming max length for each word is 10 (in my code it's 20):<\/p>\n\n

      features - [[1 1 1 1 2 1 1 0 0 0][1 1 2 2 0 0 0 0 0 0][1 1 1 1 0 0 0 0 0 0]]<\/p>\n\n

      labels - [1, 1, 2, 3]<\/p>\n\n

      expected output: [a: 0%, b: 0%, c: 1%, d: 99%] (example)<\/p>\n\n

      <\/pre>\n\n

      Shapes of train and evale - 2D arrays<\/p>\n\n

      <\/pre>\n\n

      Shapes:<\/p>\n\n

      <\/pre>\n","answers":[{"AnswerId":"54269383","CreationDate":"2019-01-19T17:02:45.403","ParentId":null,"OwnerUserId":"10921263","Title":null,"Body":"

      Probably your labels vector needs to be of shape (batch_size, 1)<\/code> instead of just (batch_size,)<\/code>. <\/p>\n\n

      Note:<\/strong> Since you are using sparse_categorical_crossentropy<\/code> as loss function instead of categorical_crossentropy<\/code>, it is correct to not one-hot encode the labels. <\/p>\n"}]} {"QuestionId":54269051,"AnswerCount":0,"Tags":"","CreationDate":"2019-01-19T16:20:57.457","AcceptedAnswerId":null,"OwnerUserId":10858431.0,"Title":"How to Create LSTM or RNN N-GRAM language model in Tensorflow C++ api","Body":"

      How can I create an LSTM or RNN N-Gram language model in Tensorflow C++ API? \nMy goal is to get the number of occurrence of a word (ngram) using an LSTM or RNN model. <\/p>\n","answers":[]} {"QuestionId":54269091,"AnswerCount":5,"Tags":"","CreationDate":"2019-01-19T16:24:42.693","AcceptedAnswerId":null,"OwnerUserId":10291015.0,"Title":"Google Colab can't access drive content","Body":"

      Even though I defined my Google Drive(and my dataset in it) to google colab but when I run my code I give this error:FileNotFoundError: [Errno 2] No such file or directory: 'content\/drive\/My Drive\/....<\/p>\n\n

      I already defined google drive in google colab and I can access to it through google colab but when I run my code I give this error <\/p>\n\n

      <\/pre>\n","answers":[{"AnswerId":"58826391","CreationDate":"2019-11-12T20:44:44.643","ParentId":null,"OwnerUserId":"11366468","Title":null,"Body":"

      So, I started by the default commands of Colab <\/p>\n\n

      from google.colab import drive\ndrive.mount('\/gdrive', force_remount=True)\n<\/code><\/pre>\n\n

      And the main changes that I did was here <\/p>\n\n

      img_width, img_height = 64, 64\ntrain_data_dir = '\/gdrive\/My Drive\/Colab Notebooks\/dataset\/training_set'\nvalidation_data_dir = '\/gdrive\/My Drive\/Colab Notebooks\/dataset\/test_set'\n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\ntrain_datagen = ImageDataGenerator(\n    rescale=1.\/255,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True)\n\ntest_datagen = ImageDataGenerator(rescale=1.\/255)\n\ntrain_generator = train_datagen.flow_from_directory(\n train_data_dir,\n target_size=(64, 64),\n batch_size=32,\n class_mode='binary')\n\nvalidation_generator = test_datagen.flow_from_directory(\n validation_data_dir,\n target_size=(64, 64),\n batch_size=32,\n class_mode='binary')\n\nclassifier.fit_generator(\n train_generator,\n steps_per_epoch=8000, # Number of images in train set\n epochs=25,\n validation_data=validation_generator,\n validation_steps=2000)\n<\/code><\/pre>\n\n

      This worked for me and I hope this helps someone.\nP.s. Ignore the indentation.<\/p>\n"},{"AnswerId":"58259525","CreationDate":"2019-10-06T17:08:13.757","ParentId":null,"OwnerUserId":"12118247","Title":null,"Body":"

      from google.colab import drive\ndrive.mount('\/content\/drive')<\/p>\n\n

      using above code you can load your drive in colab,\nwhen to load images use:<\/p>\n\n

      directory='drive\/My Drive\/Convolutional_Neural_Networks\/dataset\/test_set',\n<\/code><\/pre>\n\n

      not this :<\/p>\n\n

      directory='content\/drive\/My Drive\/Convolutional_Neural_Networks\/dataset\/test_set',\n<\/code><\/pre>\n\n

      for keras imagedatagenerator dataset strcut:<\/p>\n\n

      \n<\/code><\/pre>\n"},{"AnswerId":"54269326","CreationDate":"2019-01-19T16:55:29.100","ParentId":null,"OwnerUserId":"8841057","Title":null,"Body":"

      I think you are missing a leading \/<\/code> in your \/content\/drive...<\/code> path.<\/p>\n\n

      It's typical to mount you Drive files via<\/p>\n\n

      from google.colab import drive\ndrive.mount('\/content\/drive')\n<\/code><\/pre>\n\n

      https:\/\/colab.research.google.com\/notebooks\/io.ipynb#scrollTo=u22w3BFiOveA<\/a><\/p>\n"},{"AnswerId":"55675184","CreationDate":"2019-04-14T12:20:33.030","ParentId":null,"OwnerUserId":"9869300","Title":null,"Body":"

      I have been trying, and for those curious, it has not been possible for me to use flow from directory with a folder inside google drive. The collab file environment does not read the path and gives a \"Folder does not exist\" error. I have been trying to solve the problem and searching stack, similar questions have been posted here Google collaborative<\/a> and here Deep learnin on Google Colab: loading large image dataset is very long, how to accelerate the process?<\/a> , with no effective solution and for some reason, many downvotes to those who ask.<\/p>\n\n

      The only solution I find to reading 20k images in google colab, is uploading them and then processing them, wasting two sad hours to do so. It makes sense, google identifies things inside the drive with ids, flow from directory requires it to be identified both the dataset, and the classes with folder absolute paths, not being compatible with google drives identification method. Alternative might be using a google cloud enviroment instead I suppose and paying.We are getting quite a lot for free as it is. This is my novice understanding of the situation, please correct me if wrong.<\/p>\n\n

      edit1: I was able to use flow from directory on google collab, google does identify things with path also, the thing is that if you use os.getcwd(), it does not work properly, if you use it it will give you that the current working directory is \"\/content\", when in truth is \"\/content\/drive\/My Drive\/foldersinsideyourdrive\/.....\/folderthathasyourcollabnotebook\/. If you change in the traingenerator the path so that it includes this setting, and ignore os, it works. I had however, problems with the ram even when using flow from directory, not being able to train my cnn anyway, might be something that just happens to me though.<\/p>\n"},{"AnswerId":"56513306","CreationDate":"2019-06-09T09:04:20.027","ParentId":null,"OwnerUserId":"8125345","Title":null,"Body":"

      After mounting, move into the dataset folder.<\/p>\n\n

      cd content\/drive\/My Drive\/Convolutional_Neural_Networks\/dataset\/\n<\/code><\/pre>\n\n

      Don't use the !.\nThen set your directory as .\/training_set<\/code><\/p>\n"}]} {"QuestionId":54269389,"AnswerCount":1,"Tags":"","CreationDate":"2019-01-19T17:03:45.053","AcceptedAnswerId":54273502.0,"OwnerUserId":1075708.0,"Title":"Tensorflow warning: two cells provided to MultiRNNCell are the same object","Body":"

      I have been consistently receiving the following warning while executing tensorflow scripts<\/p>\n\n

      \n

      WARNING:tensorflow:At least two cells provided to MultiRNNCell are the\n same object and will share weights.<\/p>\n<\/blockquote>\n\n

      <\/pre>\n\n

      However, the RNNs in question appear to be running fine, and are making accurate predictions.<\/p>\n\n

      What are the implications in relation to the warning message? Can it be safely ignored? If it is potential serious, how might its impact be evaluated?<\/p>\n","answers":[{"AnswerId":"54273502","CreationDate":"2019-01-20T04:10:20.493","ParentId":null,"OwnerUserId":"7389608","Title":null,"Body":"

      You use [lstm_layer] * num_layers<\/code> to create multiple RNN layers that actually refer to a same object in python. This usage is normal in some versions of tensorflow, and some versions will report errors. <\/p>\n\n

      As the warning says, since all RNN layers are the same object, their weights will remain the same. All errors are fed back to an RNN layer. It is equivalent to reducing the parameters of the model and reducing the complexity of the model.<\/p>\n\n

      If you want to create multiple different RNN layers and complex models, you can use the following usage. The effectiveness evaluation of these two different methods depends on the specific application scenarios and results. If your model results are good enough, more complex models don't make much sense.<\/p>\n\n

      rnn_layers = []\nfor _ in range(num_layers):\n    lstm_layer = rnn.LSTMBlockCell(num_units, forget_bias=1)\n    lstm_layer = rnn.DropoutWrapper(lstm_layer, output_keep_prob=output_keep_prob)\n    rnn_layers.append(lstm_layer)\n\nstacked_lstm = rnn.MultiRNNCell(rnn_layers)\n<\/code><\/pre>\n"}]}
      {"QuestionId":54269610,"AnswerCount":1,"Tags":"","CreationDate":"2019-01-19T17:28:50.153","AcceptedAnswerId":54269648.0,"OwnerUserId":8128438.0,"Title":"Error when checking target: expected activation_1 to have shape (1,) but got array with shape (10,)","Body":"

      I'm having issues with this model, which is trying to forecast stock market 10 days in the future:<\/p>\n\n

      <\/pre>\n\n

      The error:<\/p>\n\n

      \n

      ValueError: Error when checking target: expected activation_1 to have\n shape (1,) but got array with shape (10,)<\/p>\n<\/blockquote>\n\n

      Shapes of the numpy arrays:<\/p>\n\n

      \n

      x_train (1968, 50, 3), y_train (1968, 10), x_test (450, 50, 3), y_test\n (450, 10)<\/p>\n<\/blockquote>\n\n

      <\/pre>\n","answers":[{"AnswerId":"54269648","CreationDate":"2019-01-19T17:33:36.160","ParentId":null,"OwnerUserId":"5495381","Title":null,"Body":"

      Your outputs are not sparsely encoded so you should use categorical_crossentropy<\/code> as a loss function instead of sparse_categorical_crossentropy<\/code>. Also, the Linear<\/code> activation at the end of your model can be removed, it does nothing here. <\/p>\n"}]} {"QuestionId":54270188,"AnswerCount":1,"Tags":"","CreationDate":"2019-01-19T18:36:33.693","AcceptedAnswerId":54270249.0,"OwnerUserId":2084944.0,"Title":"tensorflow\/keras utils module confusion between _api\/v1\/keras\/ and python\/keras","Body":"

      I just try to import vis_utils<\/a> from but it gives me<\/p>\n\n

      <\/pre>\n\n

      Checking the location of utils tells me that it points to the wrong (?) directory:<\/p>\n\n

      <\/pre>\n\n

      But it should actually point to \nI've installed everything via pip and tf version is 1.12 on my vanilla Ubuntu 16.04. Is the installation tainted or how do tell python to load the correct module?<\/p>\n","answers":[{"AnswerId":"54270249","CreationDate":"2019-01-19T18:43:05.557","ParentId":null,"OwnerUserId":"5495381","Title":null,"Body":"

      import tensorflow.python.keras.utils.vis_utils<\/code> should work.<\/p>\n"}]} {"QuestionId":54270971,"AnswerCount":1,"Tags":"","CreationDate":"2019-01-19T20:11:16.067","AcceptedAnswerId":null,"OwnerUserId":2035790.0,"Title":"The initial state or constants of an RNN layer cannot be specified with a mix of Keras tensors and non-Keras tensors","Body":"

      As we know the decoder takes the encoder hidden states as the initial state ...<\/p>\n\n

      <\/pre>\n\n

      Assume I want to replace the initial state of the decoder to be encoder_output and features from me from other resources <\/p>\n\n

      <\/pre>\n\n

      But I face the following error:<\/p>\n\n

      \n

      ValueError: The initial state or constants of an RNN layer cannot be\n specified with a mix of Keras tensors and non-Keras tensors (a \"Keras\n tensor\" is a tensor that was returned by a Keras layer, or by )<\/p>\n<\/blockquote>\n\n

      Although I print state_h & stat_c & encoder_output & my_state, all have the same type and shape, example:<\/p>\n\n

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

      What am I understanding that it will not accept inputs not produced from the previous layer, and as Keras tensor? <\/p>\n\n

      Update<\/strong><\/p>\n\n

      After convert tensor to Keras tensor, The new error:<\/p>\n\n

      \n

      ValueError: Input tensors to a Model must come from\n . Received: Tensor(\"Reshape_18:0\", shape=(?, 128),\n dtype=float32) (missing previous layer metadata).<\/p>\n<\/blockquote>\n","answers":[{"AnswerId":"54273319","CreationDate":"2019-01-20T03:20:34.117","ParentId":null,"OwnerUserId":"7389608","Title":null,"Body":"

      I guess you mixed tensorflow tensor and keras tensor. Although the results of state_h<\/code> and my_state<\/code> are tensor, they are actually different. You can use K.is_keras_tensor()<\/code> to distinguish them. An example:<\/p>\n\n

      import tensorflow as tf\nimport keras.backend as K\nfrom keras.layers import LSTM,Input,Lambda\n\nmy_state = Input(shape=(128,))\nprint('keras input layer type:')\nprint(my_state)\nprint(K.is_keras_tensor(my_state))\n\nmy_state = tf.placeholder(shape=(None,128),dtype=tf.float32)\n\nprint('\\ntensorflow tensor type:')\nprint(my_state)\nprint(K.is_keras_tensor(my_state))\n\n# you may need it\nmy_state = Lambda(lambda x:x)(my_state)\nprint('\\nconvert tensorflow to keras tensor:')\nprint(my_state)\nprint(K.is_keras_tensor(my_state))\n\n# print\nkeras input layer type:\nTensor(\"input_3:0\", shape=(?, 128), dtype=float32)\nTrue\n\ntensorflow tensor type:\nTensor(\"Placeholder:0\", shape=(?, 128), dtype=float32)\nFalse\n\nconvert tensorflow to keras tensor:\nTensor(\"lambda_1\/Identity:0\", shape=(?, 128), dtype=float32)\nTrue\n<\/code><\/pre>\n"}]}
      {"QuestionId":54271005,"AnswerCount":0,"Tags":"","CreationDate":"2019-01-19T20:15:25.110","AcceptedAnswerId":null,"OwnerUserId":2665416.0,"Title":"Keras LSTM - time series data input, binary data output","Body":"

      This is a follow up to my previous question and might seem a bit redundant, but please bear with me.<\/p>\n\n

      previous question<\/a><\/p>\n\n

      I am trying to create a Keras LSTM model which uses a sequence of time series data. The data is formatted as follows with input:<\/strong> time, value1, value2 and output(s):<\/strong> Y1 and Y2<\/p>\n\n

      <\/pre>\n\n

      I have calculated outputs Y1<\/strong> and Y2<\/strong> to train the LSTM on which is a binary value for each time instance. However, the LSTM is supposed to take a sequence of data, ex: (time, value1, value2) between rows 1-3 and then predict the binary output which corresponds to row 3 which I have calculated. Thus X and Y as follow:<\/p>\n\n

      Input X:<\/p>\n\n

      <\/pre>\n\n

      Output Y:<\/p>\n\n

      <\/pre>\n\n

      Thus far I have tried using keras.sequence.timeseriesgenerator to make the LSTM data. The code is as follows (dn is a numpy array with the first three columns corresponding to the input described above and the 4th column (Y1) the output):<\/p>\n\n

      <\/pre>\n\n

      This gives the Output:<\/p>\n\n

      <\/pre>\n\n

      I was expecting y0 to be [ 1. ], but the sequence generator is giving an output for each row in input. Am i right to pressume that if I provide this to the LSTM then it will attempt to predict the output for all the inputs instead of considering all the inputs and giving one output prediction?<\/p>\n\n

      I found another thread asking for something very similar here: similar question<\/a>. I copied the code and get the following output:<\/p>\n\n

      <\/pre>\n\n

      In the question asked it was informed that there was only one expected output, but this clearly gives one output for each row as well. I'm not sure these two methods are formatting x an y equal. It is difficult to visualize with all these brackets.<\/p>\n\n

      I hope I managed to convey my problem. How is the input and output formatted to a LSTM neural network that should consider a sequence of time data and provide a binary output(s)? I see many time series forcasting, but have not been able to translate their methods to a binary output.<\/p>\n\n

      --- UPDATE -----<\/strong><\/p>\n\n

      So I experimented some more with the timeseriesgenerator and managed to create an output formatted as I have explained. I changed the code to this:<\/p>\n\n

      <\/pre>\n\n

      The Output:<\/p>\n\n

      <\/pre>\n\n

      And the shuffle = True command will select three consequtive time instances from a random index. This is perfect. I would however like to get the other method running as well as I would get even more control of the data and as far as I understand, tf.data is supposed to be quite effective. So if anyone can assist with getting it working that would be much appreciated. <\/p>\n","answers":[]} {"QuestionId":54271094,"AnswerCount":4,"Tags":"","CreationDate":"2019-01-19T20:27:51.220","AcceptedAnswerId":54404511.0,"OwnerUserId":5066083.0,"Title":"conda install -c conda-forge tensorflow just stuck in Solving environment","Body":"

      I am trying to run this statement in MacOS.<\/p>\n\n

      <\/pre>\n\n

      It just stuck at the <\/p>\n\n

      <\/pre>\n\n

      Never finish.<\/p>\n\n

      <\/pre>\n","answers":[{"AnswerId":"54404511","CreationDate":"2019-01-28T14:51:38.527","ParentId":null,"OwnerUserId":"6161705","Title":null,"Body":"

      On win10 I waited about 5-6 minutes but it depends of the number of installed python packages and your internet connection.\nAlso you can install it via Anaconda Navigator<\/p>\n"},{"AnswerId":"54319801","CreationDate":"2019-01-23T03:55:11.033","ParentId":null,"OwnerUserId":"5066083","Title":null,"Body":"

      Follow the instruction by nekomatic.<\/p>\n\n

      I left it running for 1 hour. Yes. it is finally finished.<\/p>\n\n

      But now I got the conflicts<\/p>\n\n

      Solving environment: failed<\/p>\n\n

      UnsatisfiableError: The following specifications were found to be in conflict:\n  - anaconda==2018.12=py37_0 -> bleach==3.0.2=py37_0\n  - anaconda==2018.12=py37_0 -> html5lib==1.0.1=py37_0\n  - anaconda==2018.12=py37_0 -> numexpr==2.6.8=py37h7413580_0\n  - anaconda==2018.12=py37_0 -> scikit-learn==0.20.1=py37h27c97d8_0\n  - tensorflow\n Use \"conda info <package>\" to see the dependencies for each package.\n<\/code><\/pre>\n"},{"AnswerId":"56111916","CreationDate":"2019-05-13T12:01:52.397","ParentId":null,"OwnerUserId":"11027404","Title":null,"Body":"

      The same error happens with me .I've tried to install tensorboard with anaconda prompt but it was stuck on the environment solving .So i've added these paths to my environment variables:<\/p>\n\n

      C:\\Anaconda3 \n\nC:\\Anaconda3\\Library\\mingw-w64\\bin\n\nC:\\Anaconda3\\Library\\usr\\bin\n\nC:\\Anaconda3\\Library\\bin\n\nC:\\Anaconda3\\Scripts\n<\/code><\/pre>\n\n

      and it worked well.<\/p>\n"},{"AnswerId":"55398716","CreationDate":"2019-03-28T13:21:36.850","ParentId":null,"OwnerUserId":"11153552","Title":null,"Body":"

      Nothing worked untill i ran this in conda terminal:<\/p>\n\n

      conda upgrade conda\n<\/code><\/pre>\n\n

      Note that this was for poppler (conda install -c conda-forge poppler)<\/p>\n"}]} {"QuestionId":54271098,"AnswerCount":2,"Tags":"","CreationDate":"2019-01-19T20:28:11.333","AcceptedAnswerId":null,"OwnerUserId":4943253.0,"Title":"How should I store metadata in a TensorFlow SavedModel?","Body":"

      We train lots of variations of our model with different configuration and requiring different preprocessing of inputs (where the preprocessing is done outside of TensorFlow). I would like to export our models as SavedModels, and I am thinking that we will have an API server that will provide access to the models and handle preprocessing and talking to the TensorFlow server using config that it will retrieve from the model metadata via the TensorFlow server. The model metatdata might be a structured as a JSON, or possibly it could use a protocol buffer. I am unclear what best practices are around this. In particular, the MetaInfoDef protocol buffer has three different fields that seem designed to hold metadata (, , and ). But I couldn't find any examples in the wild of the use of any but the field. <\/p>\n\n

      <\/pre>\n\n

      (although I am not sure that these three fields can all be retrieved in the same way using the client API to TensorFlow serving?)<\/p>\n","answers":[{"AnswerId":"55811382","CreationDate":"2019-04-23T12:36:25.360","ParentId":null,"OwnerUserId":"11253331","Title":null,"Body":"

      @gmr,\nAdding the proto to a collection via tf.add_to_collection<\/em>, along with builder.add_meta_graph_and_variables<\/em> should resolve your issue.<\/p>\n\n

      Code for the same is mentioned below:<\/strong><\/p>\n\n

      # Mention the path below where you want the model to be stored\nexport_dir = \"\/usr\/local\/google\/home\/abc\/Jupyter_Notebooks\/export\"\n\ntf.gfile.DeleteRecursively(export_dir)\n\ntf.reset_default_graph()\n\n# Check below for other ways of adding Proto to Collection\ntf.add_to_collection(\"my_proto_collection\", \"my_proto_serialized\")\n\nbuilder = tf.saved_model.builder.SavedModelBuilder(export_dir)\nwith tf.Session() as session:\n  builder.add_meta_graph_and_variables(\n      session,\n      tags=[tf.saved_model.tag_constants.SERVING])\n  builder.save()\n<\/code><\/pre>\n\n

      Code for other ways of adding proto to collection are shown below:<\/p>\n\n

      tf.add_to_collection(\"your_collection_name\", str(your_proto))<\/code> or<\/p>\n\n

      any_buf = any_pb2.Any()\n\ntf.add_to_collection(\"your_collection_name\",\n         any_buf.Pack(your_proto))\n<\/code><\/pre>\n\n

      The .pb file, saved_model.pb, which is saved in the path you mentioned (export_dir) looks something like mentioned below:<\/p>\n\n

      {   # (tensorflow.SavedModel) size=89B\n  saved_model_schema_version: 1\n  meta_graphs: {    # (tensorflow.MetaGraphDef) size=85B\n    meta_info_def: {    # (tensorflow.MetaGraphDef.MetaInfoDef) size=29B\n      stripped_op_list: {   # (tensorflow.OpList) size=0B\n      } # meta_graphs[0].meta_info_def.stripped_op_list\n      tags    : [ \"serve\" ] # size=5\n      tensorflow_version    : \"1.13.1\"  # size=9\n      tensorflow_git_version: \"unknown\" # size=7\n    }   # meta_graphs[0].meta_info_def\n    graph_def: {    # (tensorflow.GraphDef) size=4B\n      versions: {   # (tensorflow.VersionDef) size=2B\n        producer     : 23\n      } # meta_graphs[0].graph_def.versions\n    }   # meta_graphs[0].graph_def\n    collection_def: {   # (tensorflow.MetaGraphDef.CollectionDefEntry) size=46B\n      key  : \"my_proto_collection\"  # size=19\n      value: {  # (tensorflow.CollectionDef) size=23B\n        bytes_list: {   # (tensorflow.CollectionDef.BytesList) size=21B\n          value: [ \"my_proto_serialized\" ]  # size=19\n        }   # meta_graphs[0].collection_def[0].value.bytes_list\n      } # meta_graphs[0].collection_def[0].value\n    }   # meta_graphs[0].collection_def[0]\n  } # meta_graphs[0]\n}\n<\/code><\/pre>\n"},{"AnswerId":"55399300","CreationDate":"2019-03-28T13:52:10.623","ParentId":null,"OwnerUserId":"11253331","Title":null,"Body":"

      The command for extracting MetaData using Client API (REST) is shown below<\/p>\n\n

      GET http:\/\/host:port\/v1\/models\/<\/a>${MODEL_NAME}[\/versions\/${MODEL_VERSION}]\/metadata<\/em><\/strong><\/p>\n\n

      \/versions\/${MODEL_VERSION} is optional. If omitted the model metadata for the latest version is returned in the response.<\/p>\n\n

      You can find more details in the link, https:\/\/www.tensorflow.org\/tfx\/serving\/api_rest\/<\/a> => Model Metadata API<\/p>\n"}]} {"QuestionId":54271124,"AnswerCount":0,"Tags":"","CreationDate":"2019-01-19T20:31:27.027","AcceptedAnswerId":null,"OwnerUserId":1273987.0,"Title":"TensorFlow: how to make a component of vector untrainable?","Body":"

      Is there a way of making a component of a of shape untrainable without having to define three distinct parts and concatenate them? At the moment the only way that I can think of is:<\/p>\n\n

      <\/pre>\n\n

      which in my case is very cumbersome, because the position of the untrainable element can vary given some conditions in other parts of the code...<\/p>\n","answers":[]} {"QuestionId":54271159,"AnswerCount":1,"Tags":"","CreationDate":"2019-01-19T20:35:09.210","AcceptedAnswerId":54273052.0,"OwnerUserId":3849781.0,"Title":"Variable size mismatch between x.shape and tf.shape(x)?","Body":"

      I am trying to understand tf code and for this I am printing out shapes of tensors. For the following code<\/p>\n\n

      <\/pre>\n\n

      I get output<\/p>\n\n

      <\/pre>\n\n

      It does not make a lot of sense. Based on what I found online tf.shape(x) can be used to dynamically get the size for the batch. But it gives rather wrong output - 4. I am not sure where this is coming from and how to get the right value for my tensor.<\/p>\n","answers":[{"AnswerId":"54273052","CreationDate":"2019-01-20T02:21:28.607","ParentId":null,"OwnerUserId":"7389608","Title":null,"Body":"

      In fact, the two results are the same. 4<\/code> is the shape of (?,32,32,3)<\/code>.<\/p>\n\n

      x.shape()<\/code> returns a tuple, and you can get shape without sess.run()<\/code>. You can use as_list()<\/code> to convert it into a list.<\/p>\n\n

      tf.shape(x)<\/code> returns a tensor, and you need to run sess.run()<\/code> to get the the actual number.<\/p>\n\n

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

      import tensorflow as tf\nimport numpy as np\n\nx = tf.placeholder(shape=(None,32,32,3),dtype=tf.float32)\nprint(x.shape)\nprint(tf.shape(x))\n\ndim = tf.shape(x)\ndim0 = tf.shape(x)[0]\n\nwith tf.Session()as sess:\n    dim,dim0 = sess.run([dim,dim0],feed_dict={x:np.random.uniform(size=(100,32,32,3))})\n    print(dim)\n    print(dim0)\n\n#print\n(?, 32, 32, 3)\nTensor(\"Shape:0\", shape=(4,), dtype=int32)\n[100  32  32   3]\n100\n<\/code><\/pre>\n"}]}
      {"QuestionId":54271273,"AnswerCount":1,"Tags":"","CreationDate":"2019-01-19T20:49:05.843","AcceptedAnswerId":54275376.0,"OwnerUserId":859227.0,"Title":"Builing TensorFlow for specific GPU architecture","Body":"

      I see for building TensorFlow on a GPU. I would like to know if there is any way to specify a compute compatibility number? For example, I want to build for SM_50.<\/p>\n\n

      I didn't find a clear answer for that in the documents. Any idea?<\/p>\n","answers":[{"AnswerId":"54275376","CreationDate":"2019-01-20T10:07:42.973","ParentId":null,"OwnerUserId":"4834515","Title":null,"Body":"

      There is an option about the compute capability after .\/configure<\/code> (view sample configuration session from https:\/\/www.tensorflow.org\/install\/source?hl=en#configure_the_build<\/a>): <\/p>\n\n

      \n

      Please specify a list of comma-separated Cuda compute capabilities you\n want to build with. You can find the compute capability of your device\n at: https:\/\/developer.nvidia.com\/cuda-gpus<\/a>. Please note that each\n additional compute capability significantly increases your build time\n and binary size. [Default is: 3.5,7.0] 6.1<\/p>\n<\/blockquote>\n"}]} {"QuestionId":54271706,"AnswerCount":1,"Tags":"","CreationDate":"2019-01-19T21:51:01.693","AcceptedAnswerId":54275189.0,"OwnerUserId":7114447.0,"Title":"How to make ROI line in open cv movable or let user draw it with his mouse","Body":"

      i am using this<\/a> as base for making a better vehicle counter but the roi line is hard coded in the middle of the screen: \nlike this and i am looking for a way two make it dynamic or by letting user draw which if find only tutorials and answers for rectangles<\/a> or make it movable by mouse clicks for going up and down in the screen.\nThank you in advance.<\/p>\n","answers":[{"AnswerId":"54275189","CreationDate":"2019-01-20T09:41:02.953","ParentId":null,"OwnerUserId":"10938631","Title":null,"Body":"

      Take a look here<\/a> \nYou need to capture your mouse coordinates and then use cv.line<\/p>\n\n

      def click_and_crop(event, x, y, flags, param):\n# grab references to the global variables\nglobal refPt, cropping\n\n# if the left mouse button was clicked, record the starting\n# (x, y) coordinates and indicate that cropping is being\n# performed\nif event == cv2.EVENT_LBUTTONDOWN:\n    refPt = [(x, y)]\n    cropping = True\n\n# check to see if the left mouse button was released\nelif event == cv2.EVENT_LBUTTONUP:\n    # record the ending (x, y) coordinates and indicate that\n    # the cropping operation is finished\n    # y = height x = width\n    refPt.append((x, y))\n    cropping = False\n    # draw a rectangle around the region of interest\n    #cv.line(input_frame, (0, int(height\/2)), (int (width), int(height\/2)), (0, 0xFF, 0), 5)\n    cv2.line(image,(0, int(y)), (int(width), int(y)), (0, 255, 0), 2)\n    cv2.imshow(\"image\", image)\n<\/code><\/pre>\n"}]}
      {"QuestionId":54271737,"AnswerCount":0,"Tags":"","CreationDate":"2019-01-19T21:56:34.607","AcceptedAnswerId":null,"OwnerUserId":10382003.0,"Title":"ImageAI code does not run after logging Using Tensorflow Backend","Body":"

      I am using ImageAI to detect vehicles in vid.mp4<\/p>\n\n

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

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

      The code is supposed to log the path of the output video with detection boxes. <\/p>\n\n

      The result is a message 'Using Tensorflow Backend.' and the code does not proceed further. I can't seem to figure out why. Please help.<\/p>\n\n

      I am using tensorflow version - 1.5.0 and keras - 2.2.4<\/p>\n\n

      In the anaconda prompt, when I type import keras a similar thing happens and it logs 'Using Tensorflow Backend' and exits the python terminal.<\/p>\n\n

      To recreate this problem:<\/p>\n\n

      Install ImageAI on anaconda as showed in the link above and then follow this:procedure<\/a><\/p>\n","answers":[]} {"QuestionId":54271942,"AnswerCount":1,"Tags":"","CreationDate":"2019-01-19T22:32:27.823","AcceptedAnswerId":54272785.0,"OwnerUserId":687412.0,"Title":"How to Create a Trained Keras Model Through Setting the Weights","Body":"

      I am trying to convert a trained chainer model into a trained keras model in hopes of converting it into coreml. My attempt at doing so is through directly setting the weights of an instantiated keras model with the same architecture as that of the chainer model. Through debugging, I noted that the shape of the weight matrices are transposed when setting them in Keras. The issue is that the ouputs of the two models differ. In the keras model, the first layer gets some of the outputs correct, but most are zeroed out in an unpredictable fashion. Are there other parameters to a trained keras model that i'm missing?<\/p>\n\n

      <\/pre>\n\n

      Sample Output from the first layer:<\/p>\n\n

      Chainer (correct model):<\/p>\n\n

      0.012310047, -0.0038410246, 0.019623855, 0.01872946, -0.010116328, ...<\/p>\n\n

      Keras:<\/p>\n\n

      0.012310054, 0.0, 0.0, 0.01872946, 0.0, ...<\/p>\n","answers":[{"AnswerId":"54272785","CreationDate":"2019-01-20T01:19:20.797","ParentId":null,"OwnerUserId":"5215416","Title":null,"Body":"

      In keras, layer is defined together with the activation function. While chainer L.Linear<\/code> layer is only for linear operation, without any activation function.<\/p>\n\n

      As you define first layer as l1 = Dense(1024, activation='relu')(inputs)<\/code>, this is the linear operation followed by relu operation<\/strong>, which converts negative value to 0.<\/p>\n\n

      That is why your keras model's first layer output have non-negative value.<\/p>\n\n

      Image AI<\/a><\/p>\n\n