{"QuestionId":53549352,"AnswerCount":1,"Tags":"","CreationDate":"2018-11-30T00:00:58.870","AcceptedAnswerId":53549555.0,"OwnerUserId":9650073.0,"Title":"minimize a function in Tensorflow","Body":"

How can I get the gradients of a function using tf.gradients? the below is working when I use GradientDescentOptimizer.minimize(), tf.gradients seems to be evaluating 1 at the deriv of x^2+2 which is 2x<\/p>\n\n

What am I missing ?<\/p>\n\n

<\/pre>\n","answers":[{"AnswerId":"53549555","CreationDate":"2018-11-30T00:25:34.227","ParentId":null,"OwnerUserId":"5495304","Title":null,"Body":"

If I understand your question correctly, you want to find the value of x<\/code> which minimizes x^2 + 2<\/code>. <\/p>\n\n

To do so, you need to repeatedly call GradientDescentOptimizer<\/code> until x<\/code> converges to the value which minimizes the function. This is because gradient descent is an iterative technique. <\/p>\n\n

Also, in tensorflow, the method minimize<\/code> of GradientDescentOptimizer<\/code> does both computing the gradients and then applying them to the relevant variables (x<\/code> in your case). So the code should look like this (Notice I commented the grad<\/code> variable, which is not required unless you want to look at the gradient values): <\/p>\n\n

x = tf.Variable(1.0, trainable=True)\ny = x**2 + 2\n\n# grad = tf.gradients(y, x)\ngrad_op = tf.train.GradientDescentOptimizer(0.2).minimize(y)\n\ninit = tf.global_variables_initializer()\n\nn_iterations = 10\nwith tf.Session() as sess:\n    sess.run(init)\n    for i in range(n_iterations):\n        _, new_x = sess.run([grad_op, x])\n        print('Iteration:', i,', x:', new_x)\n<\/code><\/pre>\n\n

and you get: <\/p>\n\n

Iteration: 0 , x: 1.0\nIteration: 1 , x: 0.6\nIteration: 2 , x: 0.36\nIteration: 3 , x: 0.216\nIteration: 4 , x: 0.07776\nIteration: 5 , x: 0.07776\nIteration: 6 , x: 0.046656\nIteration: 7 , x: 0.01679616\nIteration: 8 , x: 0.010077696\nIteration: 9 , x: 0.010077696\n<\/code><\/pre>\n\n

which you see in converging to the true answer which is 0.<\/p>\n\n

If you increase the learning rate of GradientDescentOptimizer<\/code>, from 0.2 to 0.4, it will converge to 0 much faster.<\/p>\n\n

EDIT<\/strong><\/p>\n\n

OK, based on my new understanding of the question, to manually implement gradient descent, you cannot do x = x - alpha * gradient<\/code> because this is python operation which simply replaces the object x<\/code>. You need to tell tensorflow to add the op to the graph, and this can be done using x.assign<\/code>. It will look like: <\/p>\n\n

x = tf.Variable(1.0, trainable=True)\ny = x**2 + 2\n\ngrad = tf.gradients(y, x)\n# grad_op = tf.train.GradientDescentOptimizer(0.5).minimize(y)\n\nupdate_op = x.assign(x - 0.2*grad[0])\n\ninit = tf.global_variables_initializer()\n\nwith tf.Session() as sess:\n    sess.run(init)\n    for i in range(10):\n        new_x = sess.run([update_op, x])\n        print('Iteration:', i,', x:', new_x)\n<\/code><\/pre>\n\n

and we get the same answer as the native GradientDescentOptimizer<\/code>:<\/p>\n\n

Iteration: 0 , x: 1.0\nIteration: 1 , x: 0.6\nIteration: 2 , x: 0.36\nIteration: 3 , x: 0.1296\nIteration: 4 , x: 0.1296\nIteration: 5 , x: 0.077759996\nIteration: 6 , x: 0.046655998\nIteration: 7 , x: 0.027993599\nIteration: 8 , x: 0.01679616\nIteration: 9 , x: 0.010077696\n<\/code><\/pre>\n"}]}
{"QuestionId":53549714,"AnswerCount":1,"Tags":"","CreationDate":"2018-11-30T00:50:19.987","AcceptedAnswerId":null,"OwnerUserId":3869972.0,"Title":"Can deep learning TensorFlow models be trained in Python, pickled and used for prediction in C++?","Body":"

I have learnt a neural net based model using TensorFlow in Python. <\/p>\n\n

\n

I would like to store this model in a file and be able to load it into\n memory in a C++ program for prediction later.<\/p>\n<\/blockquote>\n\n

I am doing a comparative study of my machine learning model versus a standard algorithm written in C++. For this reason, I would like to load the model and do the prediction in C++ since I don't want the internals of the programming language to cause differences in the runtimes of the implementations.<\/p>\n\n

\n

Are there other ways to keep the comparisons language-neutral?<\/p>\n<\/blockquote>\n","answers":[{"AnswerId":"53563987","CreationDate":"2018-11-30T19:49:27.733","ParentId":null,"OwnerUserId":"10481010","Title":null,"Body":"

Yes. I think you can do it using bazel (google's tool for TF). Once you make sure that you are saving checkpoints, build the project. It would create executable file for you to use in c++.<\/p>\n"}]} {"QuestionId":53549717,"AnswerCount":1,"Tags":"","CreationDate":"2018-11-30T00:50:38.363","AcceptedAnswerId":53550240.0,"OwnerUserId":5348713.0,"Title":"Pytorch Loading two Images from Dataloader","Body":"

I'm trying to make a GAN which takes a lo-res image, and tries to create a hi-res image from it. To do this, I need to user a Dataloader which has both the hi-res and low-res training images stored in it.<\/p>\n\n

<\/pre>\n\n

I've tried using two separate data loaders (shown above) but when they are shuffled, I cant enumerate through them both because the hi-res and low-res images are not matched up. How can I make it so I can enumerate and shuffle both with pytorch?<\/p>\n","answers":[{"AnswerId":"53550240","CreationDate":"2018-11-30T02:09:39.507","ParentId":null,"OwnerUserId":"10597864","Title":null,"Body":"

Assuming you have similar names for hi & low resolution images (say img01_hi & img01_low), one option is to create a custom Dataloader that returns both images by overriding __getitem__<\/code> method.<\/p>\n\n

As both images are returned in one call, you can make sure they match by appending _hi & _low to the filename.<\/p>\n\n

You may need to create a \"cue\" text file containing list of all your image file names to make sure you are processing each image file only once.<\/p>\n"}]} {"QuestionId":53550031,"AnswerCount":1,"Tags":"","CreationDate":"2018-11-30T01:39:12.873","AcceptedAnswerId":null,"OwnerUserId":10631580.0,"Title":"How to slice some specific value in tensorflow by fixing step just like in numpy arrays?","Body":"

In the following code I want to slice [[[3,30]]]. Can I perform numpy like slicing in tensorflow?<\/p>\n\n

<\/pre>\n","answers":[{"AnswerId":"53551002","CreationDate":"2018-11-30T03:54:43.297","ParentId":null,"OwnerUserId":"4502035","Title":null,"Body":"

You can modified it slightly using tf.strided_slice()<\/code><\/a> instead of tf.slice()<\/code><\/p>\n\n

s = tf.strided_slice(t, begin=[1,0,0],end=[2,1,3],strides=[1,1,2])\n<\/code><\/pre>\n\n

The end<\/code> is the value of size<\/code> parameter + begin<\/code> parameter. While strides<\/code> describes whether to skip any element in every iteration while slicing (1<\/code> means not skipping anything, 2<\/code> means skip 1 element, etc). Use 1, 1, 2<\/code> to skip 1 element in every iteration, which will skip the 2th, 4th, etc. This will give you [[[3, 30]]]<\/code> instead of [[[3, 31, 30]]]<\/code><\/p>\n"}]} {"QuestionId":53550046,"AnswerCount":0,"Tags":"","CreationDate":"2018-11-30T01:41:14.197","AcceptedAnswerId":null,"OwnerUserId":10714928.0,"Title":"tensorflow object detection in google colab","Body":"

recently trained my ssd_mobilenet model using tensorflow object detection API and I run the model in the google colab. If my trainging was stopped due to the time of the use of the colab. Is there any solution to restore my model ?<\/p>\n","answers":[]} {"QuestionId":53550959,"AnswerCount":0,"Tags":"","CreationDate":"2018-11-30T03:49:22.767","AcceptedAnswerId":null,"OwnerUserId":10328434.0,"Title":"How can I get the score I wanted by using KerasRegressor and sklearn pipeline?","Body":"

I want to insert Keras model into scikit-learn pipeline, but when I use pipeline.score, I am comfused. Here is the code:<\/p>\n\n

<\/pre>\n\n

The model score is:<\/p>\n\n

<\/pre>\n\n

What's the score is? I want to get the result like the output of evaluate function, How can I do? <\/p>\n\n

<\/pre>\n\n

Thank you for your attention.<\/p>\n","answers":[]} {"QuestionId":53551235,"AnswerCount":1,"Tags":"","CreationDate":"2018-11-30T04:25:39.783","AcceptedAnswerId":53551309.0,"OwnerUserId":8011482.0,"Title":"Keras Convolutional Autoencoder blank output","Body":"

Quick disclaimer: I'm pretty new to Keras, machine learning, and programming in general. <\/p>\n\n

I'm trying to create a basic autoencoder for (currently) a single image. While it seems to run just fine, the output is just a white image. Here's what I've got:<\/p>\n\n

<\/pre>\n\n

I've looked at a handful of tutorials for reference, but I still can't figure out what my issue is.<\/p>\n\n

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

Thanks!<\/p>\n","answers":[{"AnswerId":"53551309","CreationDate":"2018-11-30T04:33:10.950","ParentId":null,"OwnerUserId":"10669112","Title":null,"Body":"

this<\/a> solved the problem. The code was just missing<\/p>\n\n

x = x.astype('float32') \/ 255.\n<\/code><\/pre>\n\n

This is a numpy built-in function to convert the values contained in that vector to floats. <\/p>\n\n

This allows us to get decimal values, where the values are divided by 255. RGB values are stored as 8 bit integers, so we divide the values in the vector by 255 (2^8 - 1), to represent the colour as a decimal value between 0.0 and 1.0.<\/p>\n"}]} {"QuestionId":53551368,"AnswerCount":1,"Tags":"","CreationDate":"2018-11-30T04:41:57.367","AcceptedAnswerId":null,"OwnerUserId":10486968.0,"Title":"ImportError: cannot import name 'delf_config_pb2'","Body":"

Installed DELF through Ubuntu terminal on a Google Cloud instance for image recognition using these instructions: https:\/\/github.com\/tensorflow\/models\/blob\/master\/research\/delf\/INSTALL_INSTRUCTIONS.md<\/a><\/p>\n\n

The last step to test installation says \"should just return without complaints. This indicates that the DELF package is loaded successfully.\" I run that but it gives me <\/p>\n\n

<\/pre>\n\n

So, not sure if this means DELF was installed successfully or not.<\/p>\n\n

Then, when trying the example to run delf (https:\/\/github.com\/tensorflow\/models\/blob\/master\/research\/delf\/EXTRACTION_MATCHING.md<\/a>) when I run <\/p>\n\n

<\/pre>\n\n

it returns the error <\/p>\n\n

<\/pre>\n\n

So it is importing delf, but not 'delf_config_pb2'.<\/p>\n\n

It worked when I followed the exact same instructions on my local ubuntu, but is failing on google cloud ubuntu instance.<\/p>\n\n

Also, when I stop the instance and then restart it, it says delf is not installed and fails to even import delf; so I have to follow the installation instructions again each time.<\/p>\n","answers":[{"AnswerId":"54144205","CreationDate":"2019-01-11T10:01:37.750","ParentId":null,"OwnerUserId":"8638548","Title":null,"Body":"

Protoc complier generates delf_config_pb2<\/code> file<\/p>\n\n

so make sure that you installed it correctly<\/p>\n\n

wget https:\/\/github.com\/google\/protobuf\/releases\/download\/v3.3.0\/protoc-3.3.0-linux-x86_64.zip\nunzip protoc-3.3.0-linux-x86_64.zip\necho 'export PATH=\/path\/to\/protoc\/bin:$PATH' >> ~\/.bashrc\nsource ~\/.bashrc\n<\/code><\/pre>\n\n

or check out here how to install protoc compiler<\/p>\n\n

[http:\/\/google.github.io\/proto-lens\/installing-protoc.html][1]<\/a><\/p>\n\n

check that protoc complier is installed.<\/p>\n\n

type protoc<\/code> on terminal and see if the command works.<\/p>\n\n

After installing protoc, type this command<\/p>\n\n

# From tensorflow\/models\/research\/delf\/\nprotoc delf\/protos\/*.proto --python_out=.\n<\/code><\/pre>\n\n

and you can add the path into .bashrc file in google cloud not to reinstall delf.<\/p>\n\n

In google cloud. (check the location of the tensorflow model folder you've installed)<\/p>\n\n

echo 'export PYTHONPATH=$PYTHONPATH:tensorflow\/models\/research' >> ~\/.bashrc \n<\/code><\/pre>\n"}]}
{"QuestionId":53551400,"AnswerCount":1,"Tags":"","CreationDate":"2018-11-30T04:46:59.490","AcceptedAnswerId":null,"OwnerUserId":1031417.0,"Title":"How can I plot AUC and ROC while using fit_generator and evaluate_generator to train my network?","Body":"
<\/pre>\n\n

My question how can I create AUC and ROC<\/a> when I use ?<\/p>\n","answers":[{"AnswerId":"53552619","CreationDate":"2018-11-30T06:48:43.830","ParentId":null,"OwnerUserId":"5495304","Title":null,"Body":"

I think your best bet in this case is to define AUC as a new metric. To do this, you have to define the metric in tensorflow (I am assuming you are using tensorflow backend). <\/p>\n\n

One way which I have experimented with previously (however, I don't recall I tested it for correctness of results) is something like this:<\/p>\n\n

def as_keras_metric(method):\n    \"\"\"\n    This is taken from:\n    https:\/\/stackoverflow.com\/questions\/45947351\/how-to-use-tensorflow-metrics-in-keras\/50527423#50527423\n    \"\"\"\n    @functools.wraps(method)\n    def wrapper(*args, **kwargs):\n        \"\"\" Wrapper for turning tensorflow metrics into keras metrics \"\"\"\n        value, update_op = method(*args, **kwargs)\n        tf.keras.backend.get_session().run(tf.local_variables_initializer())\n        with tf.control_dependencies([update_op]):\n            value = tf.identity(value)\n        return value\n    return wrapper\n<\/code><\/pre>\n\n

and then define the metric when the model is compiled:<\/p>\n\n

model.compile(metrics=['accuracy', as_keras_metric(tf.metrics.auc)], optimizer='adam', loss='categorical_crossentropy')\n<\/code><\/pre>\n\n

Although this spits out numbers, I have yet to find out if they are correct. If you are able to test this, and it gives the correct results, or not, please let me know, I would be interested to find out.<\/p>\n\n

A second way to go around this is to use a callback class<\/a> and define at least the on_epoch_end<\/code> function, and then then you can call sklearn<\/code> roc_auc_score<\/code> from there and either print out or save to a log. <\/p>\n\n

However, what I have found out so far, is that you need to provide it the training data through __init__<\/code>, and thus with generators, you need to make sure the callback's generator is supplying the same data as the model's fitting generator. On the other hand, for the validation generator, it can be accessed from a callback class using self.validation_data<\/code>, which is the same as the one supplied to fit_generator<\/code>.<\/p>\n"}]} {"QuestionId":53551612,"AnswerCount":1,"Tags":"","CreationDate":"2018-11-30T05:14:50.860","AcceptedAnswerId":53554229.0,"OwnerUserId":9901493.0,"Title":"TensorFlow Importing error ( Using Anaconda)","Body":"

I have installed anaconda in my system, Python version is (3.7), I want to install TensorFlow as well. Since \"python3.7\" needed in my system,i created a environment for TensorFlow (Using conda promt) and installed \"python 3.6\". Installation and everything was fine, But now when i am importing TensorFlow, i am getting following error.<\/p>\n\n

<\/p>\n\n

System info():<\/p>\n\n

    \n
  1. i5 HP Inspiron, AMD graphics<\/li>\n<\/ol>\n\n

    tried downloading DLL files and pasting in system folder. but not helping.\nOther solutions i found are through CUDA, which are only applicable if nvidia graphics available.<\/p>\n","answers":[{"AnswerId":"53554229","CreationDate":"2018-11-30T08:56:53.813","ParentId":null,"OwnerUserId":"10389198","Title":null,"Body":"

    Could you please try out the following steps which worked fine for us.<\/p>\n\n

    For Linux Machine:<\/strong><\/p>\n\n

    1)Create a virtual environment using the below command<\/p>\n\n

    conda create -n env_tensor -c intel python=3.6\n<\/code><\/pre>\n\n

    2)Activate the environment<\/p>\n\n

    source activate env_tensor\n<\/code><\/pre>\n\n

    3)Install tensorflow in the activated environment<\/p>\n\n

    pip install tensorflow\n<\/code><\/pre>\n\n

    For Windows Machine<\/strong><\/p>\n\n

    1)Create a virtual environment using the below command<\/p>\n\n

    conda create -n env_tensor python=3.6\n<\/code><\/pre>\n\n

    2)Activate the environment<\/p>\n\n

    conda activate env_tensor\n<\/code><\/pre>\n\n

    3)Install tensorflow in the activated environment<\/p>\n\n

    pip install tensorflow\n<\/code><\/pre>\n\n

    (Here \"env_tensor\" is the environment name.You can use any name instead).<\/p>\n\n

    After executing the above steps please try to import tensorflow.<\/p>\n"}]} {"QuestionId":53551975,"AnswerCount":2,"Tags":"","CreationDate":"2018-11-30T05:53:37.610","AcceptedAnswerId":53556218.0,"OwnerUserId":2508660.0,"Title":"How to know what Tensorflow actually \"see\"?","Body":"

    I'm using cnn built by keras(tensorflow) to do visual recognition.\nI wonder if there is a way to know what my own tensorflow model \"see\".\nGoogle had a news showing the cat face in the AI brain.<\/p>\n\n

    https:\/\/www.smithsonianmag.com\/innovation\/one-step-closer-to-a-brain-79159265\/<\/a><\/p>\n\n

    Can anybody tell me how to take out the image in my own cnn networks.\nFor example, what my own cnn model recognize a car?<\/p>\n","answers":[{"AnswerId":"53554378","CreationDate":"2018-11-30T09:07:56.320","ParentId":null,"OwnerUserId":"7981988","Title":null,"Body":"

    When you are building a model to perform visual recognition, you actually give it similar kinds of labelled data or pictures in this case to it to recognize so that it can modify its weights according to the training data. If you wish to build a model that can recognize a car, you have to perform training on a large train data containing labelled pictures. This type of recognition is basically a categorical recognition. <\/p>\n\n

    You can experiment with the MNIST dataset which provides with a dataset of pictures of digits for image recognition.<\/p>\n"},{"AnswerId":"53556218","CreationDate":"2018-11-30T10:59:56.947","ParentId":null,"OwnerUserId":"4592059","Title":null,"Body":"

    We have to distinguish between what Tensorflow actually see<\/a>:<\/p>\n\n

    \n

    As we go deeper into the network, the feature maps look less like the\n original image and more like an abstract representation of it. As you\n can see in block3_conv1 the cat is somewhat visible, but after that it\n becomes unrecognizable. The reason is that deeper feature maps encode\n high level concepts like \u201ccat nose\u201d or \u201cdog ear\u201d while lower level\n feature maps detect simple edges and shapes. That\u2019s why deeper feature\n maps contain less information about the image and more about the class\n of the image. They still encode useful features, but they are less\n visually interpretable by us.<\/p>\n<\/blockquote>\n\n

    and what we can reconstruct<\/a> from it as a result of some kind of reverse deconvolution (which is not a real math deconvolution in fact) process.<\/p>\n\n

    To answer to your real question, there is a lot of good example solution out there, one you can study it with success: Visualizing output of convolutional layer in tensorflow<\/a>.<\/p>\n"}]} {"QuestionId":53552115,"AnswerCount":1,"Tags":"","CreationDate":"2018-11-30T06:04:33.377","AcceptedAnswerId":53552375.0,"OwnerUserId":8234464.0,"Title":"Error when checking target: expected conv2d to have 4 dimensions, but got array with shape","Body":"

    I have built a Keras ConvLSTM neural network, and I want to predict one frame ahead based on a sequence of 10-time steps:<\/p>\n\n

    <\/pre>\n\n

    Training:<\/p>\n\n

    <\/pre>\n\n

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

    <\/pre>\n\n

    And this is the results of 'model.summary()':<\/p>\n\n

    <\/pre>\n\n

    This model is a revised version of another model which was compiled without error, what is changed from the previous model is just the last two layers. Previously was like:<\/p>\n\n

    <\/pre>\n\n

    I made this change because I want to get a 4-dimensional output of the form (samples, output_row, output_col, filters)<\/p>\n","answers":[{"AnswerId":"53552375","CreationDate":"2018-11-30T06:26:52.553","ParentId":null,"OwnerUserId":"5825953","Title":null,"Body":"

    The error message is clear. The model expects the output rank to be four, but you are passing output of rank 5. Squeeze the second dimension of data_train_y before feeding it to the model. <\/p>\n\n

    data_train_y = tf.squeeze(data_train_y, axis=1)\n<\/code><\/pre>\n"}]}
    {"QuestionId":53553643,"AnswerCount":0,"Tags":"","CreationDate":"2018-11-30T08:13:06.493","AcceptedAnswerId":null,"OwnerUserId":10726448.0,"Title":"tensorflow: distillation from resnet based model to VGG based model","Body":"

    The model given by https:\/\/github.com\/iro-cp\/FCRN-DepthPrediction<\/a> shows good result in depth prediction. It basically contains of down-sampling layers(resnet50 based) and up-sampling layers(up-projection). In order to customize the model, I want to distill the knowledge to train a small network (VGG16 + up-projection).<\/p>\n\n

    I import the teacher net and student net in one script. I start up one session and calculate the mse loss between the teacher's soft target and the student's soft target, and use the tf's SGD optimizer to do the back propagation. However, the loss doesn't converge. I think it is due to my usage of tensorflow.<\/p>\n\n

    Anyone can tell me whether only one session is enough to run the teacher net and student net at the same time in tensorflow. If so, what kind of problem it may be to result in these failure.<\/p>\n\n

    <\/pre>\n\n

    This is an incomplete code.<\/p>\n","answers":[]} {"QuestionId":53553797,"AnswerCount":3,"Tags":"","CreationDate":"2018-11-30T08:25:28.847","AcceptedAnswerId":null,"OwnerUserId":5677268.0,"Title":"Usage of sigmoid activation function in Keras","Body":"

    I have a big dataset composed of 18260 input field with 4 outputs. I am using Keras and Tensorflow to build a neural network that can detect the possible output.<\/p>\n\n

    However I tried many solutions but the accuracy is not getting above 55% unless I use activation function in all model layers except the first one as below:<\/p>\n\n

    <\/pre>\n\n

    Is using for activation correct in all layers? The accuracy is reaching 99.9% when using sigmoid as shown above. So I was wondering if there is something wrong in the model implementation.<\/p>\n","answers":[{"AnswerId":"53553965","CreationDate":"2018-11-30T08:37:26.260","ParentId":null,"OwnerUserId":"10454790","Title":null,"Body":"

    Neural networks require non-linearity at each layer to work. Without non-linear activation no matter how many layers you have, you could write the same thing with only one layer. <\/p>\n\n

    Linear functions are limited in complexity and if \"g\" and \"f\" are linear functions g(f(x)) could be written as z(x) where z is also a linear function. It is pointless to stack them without adding non-linearity. <\/p>\n\n

    And that's why we use non-linear activation functions. sigmoid(g(f(x))) cannot be written as a linear function. <\/p>\n"},{"AnswerId":"53554042","CreationDate":"2018-11-30T08:42:14.453","ParentId":null,"OwnerUserId":"5825953","Title":null,"Body":"

    The sigmoid might work. But I suggest using relu activation for hidden layers' activation. The problem is, your output layer's activation is sigmoid but it should be softmax(because you are using sparse_categorical_crossentropy loss).<\/p>\n\n

    model.add(Dense(4, activation=\"softmax\", kernel_initializer=init))\n<\/code><\/pre>\n\n

    Edit after discussion on comments<\/h3>\n\n

    Your output's are integers for class labels. Sigmoid logistic function outputs values in range (0,1). The output of the softmax is also in range (0,1), but the softmax function adds another constraint on outputs:- the sum of outputs must be 1. Therefore the output of softmax can be interpreted as probability of the input for each class. <\/p>\n\n

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

    \ndef sigmoid(x): \n    return 1.0\/(1 + np.exp(-x))\n\ndef softmax(a): \n    return np.exp(a-max(a))\/np.sum(np.exp(a-max(a))) \n\na = np.array([0.6, 10, -5, 4, 7])\nprint(sigmoid(a))\n# [0.64565631, 0.9999546 , 0.00669285, 0.98201379, 0.99908895]\nprint(softmax(a))\n# [7.86089760e-05, 9.50255231e-01, 2.90685280e-07, 2.35544722e-03,\n       4.73104222e-02]\nprint(sum(softmax(a))\n# 1.0\n<\/code><\/pre>\n"},{"AnswerId":"53553929","CreationDate":"2018-11-30T08:34:51.323","ParentId":null,"OwnerUserId":"10355465","Title":null,"Body":"

    You got to use one or the other activation, as activations are the source to bring non-linearity into the model. If the model doesn't have any activation, then it basically behaves like a single layer network. Read more about 'Why to use activations here<\/a>'. You can check various activations here<\/a>.<\/p>\n\n

    Although it seems like your model is overfitting when using sigmoid, so try techniques to overcome it like creating train\/dev\/test sets, reducing complexity of the model, dropouts, etc.<\/p>\n"}]} {"QuestionId":53553799,"AnswerCount":1,"Tags":"","CreationDate":"2018-11-30T08:25:30.247","AcceptedAnswerId":null,"OwnerUserId":10696125.0,"Title":"Tensorflow error: An initializer for variable dense_1\/kernel of dtype: 'complex64' is required","Body":"

    I am getting the following error when the code comes to the dense layer -> second line (...)<\/p>\n\n

    \n

    Tensorflow error: An initializer for variable dense_1\/kernel of dtype:'complex64' is required<\/p>\n<\/blockquote>\n\n

    My variable has a complex value and it seems I have to initialize my dense layer with the same variable type (complex64) but I don't know how to do it.<\/p>\n\n

    Any ideas?<\/p>\n\n

    <\/pre>\n\n

    Thank you very much.<\/p>\n","answers":[{"AnswerId":"53554563","CreationDate":"2018-11-30T09:20:39.000","ParentId":null,"OwnerUserId":"5343439","Title":null,"Body":"

    You have not specified your own custom kernel_initializer<\/code><\/a>, and the standard initializers in TensorFlow do not support complex weights yet. See this ticket<\/a> for the details and possible solutions.<\/p>\n"}]} {"QuestionId":53554281,"AnswerCount":1,"Tags":"","CreationDate":"2018-11-30T09:00:39.877","AcceptedAnswerId":null,"OwnerUserId":10709131.0,"Title":"Installing Tensorflow problem : pip doesn't upgraded","Body":"

    \n

    (tensorflow) C:\\Users>python -m pip install --upgrade pip\n Collecting pip\n Using cached https:\/\/files.pythonhosted.org\/packages\/c2\/d7\/90f34cb0d83a6c5631cf71dfe64cc1054598c843a92b400e55675cc2ac37\/pip-18.1-py2.py3-none-any.whl<\/a>\n twisted 18.7.0 requires PyHamcrest>=1.9.0, which is not installed.\n Installing collected packages: pip\n Found existing installation: pip 10.0.1\n Uninstalling pip-10.0.1:\n Could not install packages due to an EnvironmentError: [WinError 5] \uc561\uc138\uc2a4\uac00 \uac70\ubd80\ub418\uc5c8\uc2b5\ub2c8\ub2e4: 'c:\\programdata\\anaconda3\\lib\\site-packages\\pip\\_internal\\basecommand.py'\n Consider using the option or check the permissions.<\/p>\n<\/blockquote>\n\n

    You are using pip version 10.0.1, however version 18.1 is available.\nYou should consider upgrading via the 'python -m pip install --upgrade pip' command.<\/p>\n\n

    I installed Anaconda3.7 and now I'm trying to install the tensorflow, but it seems the version of pip is problem. \nSo I typed 'python -m pip install --upgrade pip' command several times but it didn't work at all. Is there a way to install it?<\/strong> <\/p>\n","answers":[{"AnswerId":"53554974","CreationDate":"2018-11-30T09:46:48.380","ParentId":null,"OwnerUserId":"10177402","Title":null,"Body":"

    I'm sorry. You messed Anaconda up with your pip install.<\/p>\n\n

    I had to reset my machine to factory settings, as reinstalling Anaconda gave me some conflict errors.<\/p>\n\n

    Once I reset my machine the command I typed was:<\/p>\n\n

    conda install tensorflow<\/p>\n\n

    you might also look into keras and theano.<\/p>\n\n

    Good luck buddy. You are not the only one to have done this. Anaconda is tricky like that.<\/p>\n"}]} {"QuestionId":53554291,"AnswerCount":1,"Tags":"","CreationDate":"2018-11-30T09:01:19.447","AcceptedAnswerId":53558309.0,"OwnerUserId":10294457.0,"Title":"Keras: cannot access training images inside on_batch_end callback","Body":"

    I am training a CNN using Keras with TensorFlow backend, using imgaug for image augmentation.<\/p>\n\n

    I am also using Tensorboard to visualize training progress and results.<\/p>\n\n

    Since imgaug is applying (random) transformations to the input images, I would like to send (some of) the augmented images over to Tensorboard, so that I can visualize them and verify that everything is correct (eg: to check if I am applying too large translations, or blurring the images too much).<\/p>\n\n

    For this I created a custom Keras callback and am trying to input my logic in the on_batch_end method. I can send images to tensorboard alright, but can't find where I can access the augmented input images. Any tips on how to achieve this?<\/p>\n\n

    Thanks in advance<\/p>\n","answers":[{"AnswerId":"53558309","CreationDate":"2018-11-30T13:15:52.547","ParentId":null,"OwnerUserId":"2097240","Title":null,"Body":"

    Better to do that outside training by simply getting images from your generator. <\/p>\n\n\n\n

    If it's a regular generator<\/code>:<\/p>\n\n

    for i in range(numberOfBatches):\n    x,y = next(generator)\n    #plot, print, etc. with the batches    \n<\/code><\/pre>\n\n

    If it's a keras.utils.Sequence<\/code>:<\/p>\n\n

    for i in range(len(generator)):\n    x,y = generator[i]\n    #plot, print, etc. with the batches    \n<\/code><\/pre>\n"}]}
    {"QuestionId":53554441,"AnswerCount":2,"Tags":"","CreationDate":"2018-11-30T09:12:21.443","AcceptedAnswerId":null,"OwnerUserId":9713319.0,"Title":"AttributeError:'InputLayer' object has no attribute 'W'","Body":"

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

    <\/pre>\n\n

    While running this code I am getting the following error:<\/p>\n\n

    <\/pre>\n\n

    What does this error mean here? How to overcome this?<\/p>\n\n

    Python:3.6, Keras: 2.2.4 & 2.2.0, backend: Theano.<\/p>\n","answers":[{"AnswerId":"53554552","CreationDate":"2018-11-30T09:19:45.097","ParentId":null,"OwnerUserId":"4844311","Title":null,"Body":"

    Your last line reads embeddings = predict_green.layers[0].W.get_values()<\/code>. \nThis implies that you expect the InputLayer from predict_green.layers[0]<\/code> to have an attribute W<\/code>. The error is saying this is not the case - your InputLayer object does not have an attribute W<\/code>.<\/p>\n\n

    You can read more about class attributes here: https:\/\/www.geeksforgeeks.org\/class-instance-attributes-python\/<\/a><\/p>\n"},{"AnswerId":"53554604","CreationDate":"2018-11-30T09:23:30.407","ParentId":null,"OwnerUserId":"2099607","Title":null,"Body":"

    If you want to get the embeddings after training, then you need to use get_weights()<\/code> method of the Embedding<\/code> layer (which is the second layer not the first one):<\/p>\n\n

    embeddings = predict_green.layers[1].get_weights()\n<\/code><\/pre>\n"}]}
    {"QuestionId":53555018,"AnswerCount":0,"Tags":"","CreationDate":"2018-11-30T09:49:17.397","AcceptedAnswerId":null,"OwnerUserId":3534616.0,"Title":"Is tf.constant_initializer value stored in graph like how constants are stored in tensorflow ? If not where is the constant value stored?","Body":"

    In tensorflow, if we create a variable with initial value as a constant, then the constant value will be stored in tensorflow graph and therefore you can't have large constant values, as the limit for tensorflow graph proto is 2GB. \nsee eg:<\/p>\n\n

    <\/pre>\n\n

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

    <\/pre>\n\n

    But when a constant initializer with the same value is used as the initial value, no errors are raised. eg:<\/p>\n\n

    <\/pre>\n\n

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

    <\/pre>\n\n

    Where is this constant numpy array saved in the second scenario if not in the graph? Wouldn't the variable have an initial state in this scenario?<\/p>\n","answers":[]} {"QuestionId":53555616,"AnswerCount":0,"Tags":"","CreationDate":"2018-11-30T10:25:28.923","AcceptedAnswerId":null,"OwnerUserId":10675469.0,"Title":"How to handle the predict_signature_def","Body":"

    I am developping a CNN to classify the image to 4 results.\nI have some problem to understand how the input and output to the tensorflow\/serving can be declared, in particular to save the model.\nBelow you can see my code but I cannot save the model for some issue I guess due to the wrong predict_signature_def.\nIn general I would appreciate an explanation how to link the model input\/output to the SavedModel declaration as tensors input\/output.<\/p>\n\n

    Here the code to show the model is sequential and the input shape is [64,64,3]<\/p>\n\n

    <\/pre>\n\n

    the 4 classes outputs:<\/p>\n\n

    <\/pre>\n\n

    the SavedModel is like this:<\/p>\n\n

    <\/pre>\n\n

    When I compile the model I got the following errors, but I cannot have any clue wy the model has not been saved<\/p>\n\n

    <\/pre>\n","answers":[]}
    {"QuestionId":53556558,"AnswerCount":1,"Tags":"","CreationDate":"2018-11-30T11:22:16.170","AcceptedAnswerId":null,"OwnerUserId":8388707.0,"Title":"AWS Sagemaker | How to debug docker image | What the parameter we pass","Body":"

    We want to upload a docker image which have our custom code for tensorflow, now we followed this standard code \nhttps:\/\/github.com\/awslabs\/amazon-sagemaker-examples\/blob\/master\/advanced_functionality\/tensorflow_bring_your_own\/tensorflow_bring_your_own.ipynb<\/a><\/p>\n\n

    We are able to upload docker there with our dependency but we are not able to pass the S3 location to their method, now we are not sure if the S3 location is passing to the container or not so added print which is not printing on sagemaker. Can someone please help how to debug the docker as the custom log is also not available on cloudwatch.<\/p>\n\n

    <\/pre>\n","answers":[{"AnswerId":"53754201","CreationDate":"2018-12-13T02:27:06.123","ParentId":null,"OwnerUserId":"9090582","Title":null,"Body":"

    Looking at your error message, this seems to be a problem that isn't in the original example that you followed.<\/p>\n\n

    Diagnosing and debugging this might require a bit more details in regards to your cifar10.py file, as the stack trace provided doesn't seem to match the original cifar10.py file in the example:\nhttps:\/\/github.com\/awslabs\/amazon-sagemaker-examples\/blob\/master\/advanced_functionality\/tensorflow_bring_your_own\/container\/cifar10\/cifar10.py<\/a><\/p>\n\n

    Also, I understand that iteration can be incredibly slow, so I recommend making use of local mode to speed up iterations before productionizing on SageMaker. The example notebook cited above cites this and this can be done by using 'local' as the value for train_instance_type or instance_type for training\/hosting.<\/p>\n\n

    Does your example work with your dataset provided from a local directory(file:\/\/\/)?<\/p>\n\n

    If it does, however doesn't work in SageMaker, that might be because your not expecting your dataset to be in the right directory. SageMaker will push your data to a specific channel as specified here:\nhttps:\/\/docs.aws.amazon.com\/sagemaker\/latest\/dg\/your-algorithms-training-algo.html#your-algorithms-training-algo-running-container-trainingdata<\/a><\/p>\n\n

    Please let me know if there is anything I can clarfiy.<\/p>\n"}]} {"QuestionId":53556666,"AnswerCount":1,"Tags":"","CreationDate":"2018-11-30T11:28:15.033","AcceptedAnswerId":null,"OwnerUserId":10581547.0,"Title":"Error importing tensorflow on windows with anaconda navigator","Body":"

    I'm trying to import tensorflow and I have already tried everything and in the cmd prompt, I succeeded to install tensorflow with PIP. <\/p>\n\n

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

    But when I'm trying to import tensorflow in Python, I get the following error:<\/p>\n\n

    <\/pre>\n\n

    I have tried everything on the internet, but nothing seems to fix it. I have Python version 3.7.1<\/p>\n\n

    What is the problem and more important: how can I fix this??<\/p>\n","answers":[{"AnswerId":"53556745","CreationDate":"2018-11-30T11:33:54.263","ParentId":null,"OwnerUserId":"5003756","Title":null,"Body":"

    First, if you have already installed tensorflow with pip, trying to install it again with conda is a bad idea. Before running the conda command, first uninstall the pip version.<\/p>\n\n

    pip uninstall tensorflow\n<\/code><\/pre>\n\n

    That is an odd error you are seeing. Try to specify the channel you are installing from. It is available from both the anaconda and conda-forge channels<\/p>\n\n

    conda isntall tensorflow --channel anaconda\n<\/code><\/pre>\n"}]}
    {"QuestionId":53556895,"AnswerCount":1,"Tags":"","CreationDate":"2018-11-30T11:43:37.187","AcceptedAnswerId":null,"OwnerUserId":6949375.0,"Title":"Problem Converting Caffe model to dlc using SNPE","Body":"

    I am facing an issue in converting my caffe model to dlc using SNPE.<\/p>\n\n

    Specifically in the \"Scale\" layer. <\/p>\n\n

    The first two layers are as follows<\/p>\n\n

    <\/pre>\n\n

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

    <\/pre>\n","answers":[{"AnswerId":"57086244","CreationDate":"2019-07-18T02:19:28.077","ParentId":null,"OwnerUserId":"2745495","Title":null,"Body":"

    Here is the documentation for the Scale layer limitation of SNPE:<\/p>\n\n

    https:\/\/developer.qualcomm.com\/docs\/snpe\/limitations.html<\/a><\/p>\n\n

    \n

    Batch normalization (+ Scaling)<\/strong><\/p>\n \n

I am using generator to train and predict classification on my data. Here is an example of ImageDataGenerator<\/a> <\/p>\n\n