{"QuestionId":48127178,"AnswerCount":1,"Tags":"","CreationDate":"2018-01-06T12:06:54.063","AcceptedAnswerId":null,"OwnerUserId":4877104.0,"Title":"How to import TensorFlow model with flatten layer in OpenCV?","Body":"

I have created a CNN with Keras. The code of the net is:<\/p>\n\n

<\/pre>\n\n

Then, using this script<\/a>, I have converted the .h5 file, created by Keras, in .pb.<\/p>\n\n

Now I want to import the model using OpenCV (3.4), but when I execute the following code<\/p>\n\n

<\/pre>\n\n

I get this error:<\/p>\n\n

<\/pre>\n\n

It seems that OpenCV can't handle flatten layer, am I right? Is there a way to import my net?<\/p>\n\n

Thanks for your help.<\/p>\n","answers":[{"AnswerId":"49613827","CreationDate":"2018-04-02T15:14:21.050","ParentId":null,"OwnerUserId":"5103762","Title":null,"Body":"

Yes, for now it looks like Opencv has a problem handling the flatten layer.\nYou can see more on this here: https:\/\/github.com\/opencv\/opencv_contrib\/issues\/1241<\/a><\/p>\n\n

A workaround suggested there is to use directly tf.reshape<\/code> on the network. But I'm also working on how to do that on keras layers.<\/p>\n"}]} {"QuestionId":48127205,"AnswerCount":0,"Tags":"","CreationDate":"2018-01-06T12:11:02.067","AcceptedAnswerId":null,"OwnerUserId":6333915.0,"Title":"Tensorflow File Operations with Tensor String Input","Body":"

I was trying to use tensorflow tf.gfile<\/a> functions such as, ListDirectory, walk<\/a> etc..\nI was wondering why they cannot have tensor string input? Am I missing something?<\/p>\n\n

I am trying to read all images from a folder and stack a tensor as an input data.<\/p>\n\n

<\/pre>\n\n

I want my mapping function to read files in given location and stack them into tensor. <\/p>\n","answers":[]} {"QuestionId":48127347,"AnswerCount":0,"Tags":"","CreationDate":"2018-01-06T12:30:58.110","AcceptedAnswerId":null,"OwnerUserId":2191652.0,"Title":"Pytorch: Randomly subsample loss tensors using `torch.randperm`","Body":"

I'm trying to randomly subsample the and array for my loss calculation. <\/p>\n\n

<\/pre>\n\n

However I'm getting this error message.<\/p>\n\n

<\/pre>\n\n

Does anyone know how to fix this?<\/p>\n\n

Edit:<\/strong>\nI got one step closer. It seems like torch.randperm does not return a torch variable, so one has to explicitly convert the output:<\/p>\n\n

<\/pre>\n\n

only problem is now that the backpropagation fails. Seems like the operation of randomly subsampling is causing an issue with the dimensions. \nHowever the dimensions seem to be fine when calculating the loss: <\/p>\n\n

<\/pre>\n\n

Unfortunately when calling I get this error message: <\/p>\n\n

<\/pre>\n","answers":[]}
{"QuestionId":48127550,"AnswerCount":4,"Tags":"","CreationDate":"2018-01-06T12:54:02.470","AcceptedAnswerId":48139341.0,"OwnerUserId":3744784.0,"Title":"Early stopping with Keras and sklearn GridSearchCV cross-validation","Body":"

I wish to implement early stopping with Keras and sklean's .<\/p>\n\n

The working code example below is modified from How to Grid Search Hyperparameters for Deep Learning Models in Python With Keras<\/a>. The data set may be downloaded from here<\/a>.<\/p>\n\n

The modification adds the Keras callback class to prevent over-fitting. For this to be effective it requires the argument for monitoring validation accuracy. For to be available requires the to generate validation accuracy, else raises . Note the code comment!<\/p>\n\n

Note we could replace by ! <\/p>\n\n

Question:<\/strong> How can I use the cross-validation data set generated by the k-fold algorithm instead of wasting 10% of the training data for an early stopping validation set? <\/p>\n\n

<\/pre>\n","answers":[{"AnswerId":"48133556","CreationDate":"2018-01-07T01:29:11.047","ParentId":null,"OwnerUserId":"4685471","Title":null,"Body":"

[Old answer, before the question was edited & clarified - see updated & accepted answer above]<\/p>\n\n

I am not sure I have understood your exact issue (your question is quite unclear, and you include many unrelated details, which is never good when asking a SO question - see here<\/a>).<\/p>\n\n

You don't have to<\/em> (and actually should not) include any arguments about validation data in your model = KerasClassifier()<\/code> function call (it is interesting why you don't feel the same need for training<\/em> data here, too). Your grid.fit()<\/code> will take care of both the training and<\/em> validation folds. So provided that you want to keep the hyperparameter values as included in your example, this function call should be simply<\/p>\n\n\n\n

model = KerasClassifier(build_fn=create_model, \n                        epochs=100, batch_size=32,\n                        shuffle=True,\n                        verbose=1)\n<\/code><\/pre>\n\n

You can see some clear and well-explained examples regarding the use of GridSearchCV<\/code> with Keras here<\/a>.<\/p>\n"},{"AnswerId":"54841542","CreationDate":"2019-02-23T12:21:58.967","ParentId":null,"OwnerUserId":"1721082","Title":null,"Body":"

I disagree with desertnaut (but lack reputation for commenting). With early stopping it is true that for a set of epoch counts you cannot tell which of them contributed to the best hyperparameter set found. But this was not the question to begin with. What the method did ask was \"Given at maximum<\/strong> n epochs and using early stopping, what are the best hyperparameters?\". Yes, early stopping will introduce further hyper parameters that you might or might not want to optimize with grid search, but this is true for any hyperparameter in your model. In fact I think early stopping during grid search makes way more sense than not doing so first but after grid search, since you can (at least mildly) reason about the hyperparameters it introduces.<\/p>\n"},{"AnswerId":"48309278","CreationDate":"2018-01-17T20:13:59.823","ParentId":null,"OwnerUserId":"4525474","Title":null,"Body":"

Here is how to do it with only a single split.<\/p>\n\n

fit_params['cl__validation_data'] = (X_val, y_val)\nX_final = np.concatenate((X_train, X_val))\ny_final = np.concatenate((y_train, y_val))\nsplits = [(range(len(X_train)), range(len(X_train), len(X_final)))]\n\nGridSearchCV(estimator=model, param_grid=param_grid, cv=splits)I\n<\/code><\/pre>\n\n

If you want more splits, you can use 'cl__validation_split' with a fixed ratio and construct splits that meet that criteria.<\/p>\n\n

It might be too paranoid, but I don't use the early stopping data set as a validation data set since it was indirectly used to create the model.<\/p>\n\n

I also think if you are using early stopping with your final model, then it should also be done when you are doing hyper-parameter search.<\/p>\n"},{"AnswerId":"48139341","CreationDate":"2018-01-07T16:42:33.013","ParentId":null,"OwnerUserId":"4685471","Title":null,"Body":"

[Answer after the question was edited & clarified:]<\/p>\n\n

Before rushing into implementation issues, it is always a good practice to take some time to think about the methodology and the task itself; arguably, intermingling early stopping with the cross validation procedure is not<\/strong> a good idea.<\/p>\n\n

Let's make up an example to highlight the argument.<\/p>\n\n

Suppose that you indeed use early stopping with 100 epochs, and 5-fold cross validation (CV) for hyperparameter selection. Suppose also that you end up with a hyperparameter set X giving best performance, say 89.3% binary classification accuracy.<\/p>\n\n

Now suppose that your second-best hyperparameter set, Y, gives 89.2% accuracy. Examining closely the individual CV folds, you see that, for your best case X, 3 out of the 5 CV folds exhausted the max 100 epochs, while in the other 2 early stopping kicked in, say in 89 and 93 epochs respectively.<\/p>\n\n

Now imagine that, examining your second-best set Y, you see that 4 out of the 5 CV folds exhausted the 100 epochs, while the 5th stopped early at ~ 80 epochs.<\/p>\n\n

What would be your conclusion from such an experiment?<\/p>\n\n

Arguably, you would have found yourself in an inconclusive<\/em> situation; further experiments might reveal which is actually the best hyperparameter set, provided of course that you would have thought to look into these details of the results in the first place. And needless to say, if all this was automated through a callback, you might have missed your best model despite the fact that you would have actually tried it<\/em>.<\/p>\n\n


\n\n

The whole CV idea is implicitly based on the \"all other being equal\" argument (which of course is never true in practice, only approximated in the best possible way). If you feel that the number of epochs should be a hyperparameter, just include it explicitly in your CV as such, rather than inserting it through the back door of early stopping, thus possibly compromising the whole process (not to mention that early stopping has itself a hyperparameter<\/em>, patience<\/code>).<\/p>\n\n

Not intermingling these two techniques doesn't mean of course that you cannot use them sequentially<\/em>: once you have obtained your best hyperparameters through CV, you can always employ early stopping when fitting the model in your whole training set (provided of course that you do have a separate validation set).<\/p>\n\n


\n\n

The field of deep neural nets is still (very) young, and it is true that it has yet to establish its \"best practice\" guidelines; add the fact that, thanks to an amazing community, there are all sort of tools available in open source implementations, and you can easily find yourself into the (admittedly tempting) position of mixing things up just because they happen to be available. I am not necessarily saying that this is what you are attempting to do here - I am just urging for more caution when combining ideas that may have not been designed to work along together...<\/p>\n"}]} {"QuestionId":48127701,"AnswerCount":1,"Tags":"","CreationDate":"2018-01-06T13:14:39.367","AcceptedAnswerId":null,"OwnerUserId":9181032.0,"Title":"TypeError: Value passed to parameter 'ref' has DataType int64 not in list of allowed values: float32, int32, qint8, quint8, qint32","Body":"

I'm on Raspberry Pi 3 and after installing Tensorflow with https:\/\/github.com\/samjabrahams\/tensorflow-on-raspberry-pi\/blob\/master\/GUIDE.md#3-build-bazel<\/a> indication, I'm trying to run a script in Python.<\/p>\n\n

\n

Python version : Python 2.7.9 <\/p>\n \n

tensorflow._ version<\/em> _ : '1.5.0-rc0'<\/p>\n<\/blockquote>\n\n

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

<\/pre>\n\n

After running script, I have :<\/p>\n\n

<\/pre>\n\n

I saw some questions with similar error messages, but I my case don't know how fixe it.<\/p>\n\n

Thank you for your answers !<\/p>\n","answers":[{"AnswerId":"48632075","CreationDate":"2018-02-05T21:50:28.577","ParentId":null,"OwnerUserId":"5708323","Title":null,"Body":"

Have you looked at the official Raspberry Pi images that are now available?<\/p>\n\n

https:\/\/petewarden.com\/2017\/08\/20\/cross-compiling-tensorflow-for-the-raspberry-pi\/<\/a><\/p>\n\n

That avoids the Bazel on-device compilation step.<\/p>\n"}]} {"QuestionId":48127811,"AnswerCount":1,"Tags":"","CreationDate":"2018-01-06T13:27:19.973","AcceptedAnswerId":48127962.0,"OwnerUserId":6444384.0,"Title":"How to get the class probabilities during the evaluation of CIFAR-10 in TensorFlow?","Body":"

I try to modify the code<\/a> from the Convolutional Neural Network TensorFlow Tutorial<\/a> to get the single probabilities for each class from each test-images.<\/p>\n\n

What alternative to <\/a> can I use? Because this method returns only one boolean tensor. But I want to preserve the individual values.<\/p>\n\n

I use Tensorflow 1.4 and Python 3.5, I think lines 62-82 and 121-129 \/ 142 are probably the lines to be modified. Somebody have a hint for me?<\/p>\n\n

Lines 62-82:<\/p>\n\n

<\/pre>\n\n

Lines 121-129 + 142<\/p>\n\n

<\/pre>\n","answers":[{"AnswerId":"48127962","CreationDate":"2018-01-06T13:42:46.360","ParentId":null,"OwnerUserId":"712995","Title":null,"Body":"

You can compute the class probabilities from the raw logits<\/code>:<\/p>\n\n\n\n

# The vector of probabilities per each example in a batch\nprediction = tf.nn.softmax(logits)\n<\/code><\/pre>\n\n

As a bonus, here's how to get the exact accuracy:<\/p>\n\n

correct_pred = tf.equal(tf.argmax(logits, 1), tf.argmax(labels, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n<\/code><\/pre>\n"}]}
{"QuestionId":48128724,"AnswerCount":0,"Tags":"","CreationDate":"2018-01-06T15:18:55.960","AcceptedAnswerId":null,"OwnerUserId":6930972.0,"Title":"Who changed my weight initialization?","Body":"

I know it is the reset_parameters() in conv.py that is responsible for the default weight initialization,<\/p>\n\n

I changed the function to<\/p>\n\n

<\/pre>\n\n

and after my model was created, I apply the follow manual weights_init() to change the weight initialization method of my conv layer<\/p>\n\n

<\/pre>\n\n

I think they are same , but I found it print below info in reset_params function.<\/p>\n\n

\n

reset w, stdv= 0.19245008972987526 reset b, stdv= 0.19245008972987526\n w: 4.651364750286455 b: 0.9658572124243059 reset w, stdv=\n 0.041666666666666664 reset b, stdv= 0.041666666666666664 w: 4.60668514079571 b: 0.19021859795685142 reset w, stdv= 0.041666666666666664 reset b, stdv= 0.041666666666666664 w: 6.529658534196003 b: 0.24801288097906313 reset w, stdv= 0.029462782549439483 reset b, stdv= 0.029462782549439483 w: 6.544403663970284 b: 0.20246035190569983 reset w, stdv= 0.029462782549439483 reset b, stdv= 0.029462782549439483 w: 9.237618805061214 b: 0.2699324704165474 reset w, stdv= 0.020833333333333332 reset b, stdv= 0.020833333333333332 w: 9.240560902888104 b: 0.18776950085546212 reset w, stdv= 0.020833333333333332 reset b, stdv= 0.020833333333333332 w: 9.23323252375467 b: 0.19598698034213305 reset w, stdv= 0.020833333333333332 reset b, stdv= 0.020833333333333332 w: 9.247914516750834 b: 0.19991090497324737 reset w, stdv= 0.020833333333333332 reset b, stdv= 0.020833333333333332 w: 13.062441360447233 b: 0.2709608856088436 reset w, stdv= 0.014731391274719742 reset b, stdv= 0.014731391274719742 w: 13.058955297303523 b: 0.19297756771652977 reset w, stdv= 0.014731391274719742 reset b, stdv= 0.014731391274719742 w: 13.064573213326009 b: 0.19342352625500445 reset w, stdv= 0.014731391274719742 reset b, stdv= 0.014731391274719742 w: 13.060771314609305 b: 0.1931597201764238 reset w, stdv= 0.014731391274719742 reset b, stdv= 0.014731391274719742 w: 13.068217941106957 b: 0.1944194648771781 reset w, stdv= 0.014731391274719742 reset b, stdv= 0.014731391274719742 w: 13.064472494773318 b: 0.1871614021517605 reset w, stdv= 0.014731391274719742 reset b, stdv= 0.014731391274719742 w: 13.065174600640301 b: 0.19473828458164352 reset w, stdv= 0.014731391274719742 reset b, stdv= 0.014731391274719742 w: 13.064107007871193 b: 0.18669129860732317<\/p>\n<\/blockquote>\n\n

but during my weights_init() ,it print below info:<\/p>\n\n

\n

Conv2d (3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n 2.5413928031921387\n 0.0\n 4.599651336669922\n 0.8222851753234863<\/p>\n \n

Conv2d (64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n 11.280376434326172\n 0.0\n 4.624712944030762\n 0.18499651551246643<\/p>\n \n

Conv2d (64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n 11.323299407958984\n 0.0\n 6.527068614959717\n 0.2626609206199646<\/p>\n \n

Conv2d (128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n 16.010761260986328\n 0.0\n 6.516138553619385\n 0.18262024223804474<\/p>\n \n

Conv2d (128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n 16.00145149230957\n 0.0\n 9.22119426727295\n 0.2743944823741913 etc \u2026<\/p>\n<\/blockquote>\n\n

Obviously, it has been changed somewhere, for example, the bias was changed to 0 at least.\nI don\u2019t know if there another point in the source code which modify the conv weight initialization, who can explain this question to me will be much appreciated! My English is poor, hoping you can understand it :smile:<\/p>\n","answers":[]} {"QuestionId":48128934,"AnswerCount":2,"Tags":"","CreationDate":"2018-01-06T15:42:33.037","AcceptedAnswerId":null,"OwnerUserId":9094009.0,"Title":"Compute gradients w.r.t. the values of embedding vectors in PyTorch","Body":"

I am trying to train a dual encoder LSTM model for a chatbot using PyTorch.<\/p>\n\n

I defined two classes: the Encoder class defines the LSTM itself and the Dual_Encoder class applies the Encoder to both context and response utterances that I am trying to train on: <\/p>\n\n

<\/pre>\n\n

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

<\/pre>\n\n

I do understand why the problem occurs (surely it makes no sense to compute the gradient w.r.t. the indices).\nBut I do not understand how to adjust the code so that it computes the gradients w.r.t. the content values of the embedding vectors.<\/p>\n\n

All help highly appreciated!<\/p>\n\n

(Also see the thread in the PyTorch<\/a> forum)<\/p>\n","answers":[{"AnswerId":"48134087","CreationDate":"2018-01-07T03:30:21.180","ParentId":null,"OwnerUserId":"5352399","Title":null,"Body":"

I don't know why you are deleting the weights of the embedding layer. If you want to initialize the embedding weights, you should do:<\/p>\n\n

self.embedding.weight.data.copy_(torch.from_numpy(self.embedding_weights))\n<\/code><\/pre>\n\n

You have commented out the above line but that is the best way to initialize the embedding weights.<\/p>\n"},{"AnswerId":"48172828","CreationDate":"2018-01-09T16:41:01.677","ParentId":null,"OwnerUserId":"9094009","Title":null,"Body":"

After some extensive adjustments, the code works now. The problem was not only the embedding initialization. See my github repo<\/a> for the improved code.<\/p>\n"}]} {"QuestionId":48129527,"AnswerCount":1,"Tags":"","CreationDate":"2018-01-06T16:46:03.330","AcceptedAnswerId":null,"OwnerUserId":4134377.0,"Title":"What is the most effective and efficient method of encoding text at the char level for input into a tensorflow model?","Body":"

What would be the most effective and efficient method of character level input into a Tensorflow model (yes, char level input is necessary).<\/p>\n\n

For a given string \"hello\", \nand a char embedding \"abcdefghijklmnop...\" (~150 chars omitted for brevity), I have tried the following methods:<\/p>\n\n

1) direct translation example: <\/p>\n\n

<\/pre>\n\n

2) one hot encoding example:<\/p>\n\n

<\/pre>\n\n

Which method would be best for achieving efficient and effective char level encoding on large textual inputs (with numerous characters), or is there a better alternative to the aforementioned solutions I have presented?<\/p>\n","answers":[{"AnswerId":"48129846","CreationDate":"2018-01-06T17:17:50.503","ParentId":null,"OwnerUserId":"712995","Title":null,"Body":"

Since character vocabulary (i.e., alphabet) is relatively small, one-hot encoding is a viable solution. For example, this is exactly what's done in min-char-rnn<\/a> by Andrew Karpathy (see this post<\/a>). <\/p>\n\n

Speaking of the large corpus applications, take a look at CS 20SI<\/a> example that analyzes and then generates Shakespeare-like text, character by character. Here<\/a> you can find a script: it encodes chars in one-hot and feeds to the RNN, and it works pretty well. <\/p>\n\n

Character embeddings would have been more useful if there were semantic similarities between characters, like there are between words. But character 'a' is equally similar to 'b' and to 'z', so they aren't very useful for this task.<\/p>\n"}]} {"QuestionId":48129804,"AnswerCount":3,"Tags":"","CreationDate":"2018-01-06T17:12:54.383","AcceptedAnswerId":48143350.0,"OwnerUserId":9181865.0,"Title":"I'm Trying to Get Keras to Load vgg16.h5 Wheights Locally Instead of Downloading","Body":"

I've tried modifying this code serveral different ways,
\nfrom trying to change the last lines to my vgg16.h5 file on my local disk,
\nto importing load_weights from Keras and trying to get it to grab the weights that way instead. <\/p>\n\n

This code is from lesson 1 of the fast.ai course. I've asked on their forum but got no response. <\/p>\n\n

The files running this are in this link.
\n
https:\/\/github.com\/fastai\/courses\/tree\/master\/deeplearning1\/nbs<\/a>
\nlesson1.ipynb calls on the file vgg16.py to download the weights.
\nThe code below starts at line 117 in the vgg16.py file. <\/p>\n\n

<\/pre>\n\n

The above code is the code out of the box that downloads the weights.
\nWhen I change that last line and get rid of everything in the parenthesis except for 'fname' like this... <\/p>\n\n

<\/pre>\n\n

I get the error below. <\/p>\n\n

<\/pre>\n","answers":[{"AnswerId":"51742406","CreationDate":"2018-08-08T08:49:52.537","ParentId":null,"OwnerUserId":"6805186","Title":null,"Body":"

Copying the .h5<\/code> file to .keras\/models\/<\/code> and modifying the vgg16.py<\/code> at line 30 to<\/p>\n\n

WEIGHTS_PATH_NO_TOP = ('.keras\/models\/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5')<\/code> seems to work fine<\/p>\n"},{"AnswerId":"53643230","CreationDate":"2018-12-06T01:18:59.460","ParentId":null,"OwnerUserId":"10328434","Title":null,"Body":"

The path in different system:\nLinux:<\/p>\n\n

~\/.keras\/models\/\n<\/code><\/pre>\n\n

Win:<\/p>\n\n

settings\/.keras\/models\/ of Python\n<\/code><\/pre>\n\n

Anaconda on Win<\/p>\n\n

D:\\Anaconda3\\Lib\\site-packages\\tensorflow\\contrib\\keras\\api\\keras\\applications\\vgg16\n<\/code><\/pre>\n\n

Putting the downloaded .h5 file to these local folder seems to work.<\/p>\n"},{"AnswerId":"48143350","CreationDate":"2018-01-08T01:57:31.053","ParentId":null,"OwnerUserId":"9181865","Title":null,"Body":"

I found the folder Keras is\/ or would store this weight file and dropped it in there with the following line in Terminal. <\/p>\n\n

mv \/home\/mine\/fastai\/courses-master\/deeplearning1\/nbs\/vgg16.h5 ~\/.keras\/models\/vgg16.h5\n<\/code><\/pre>\n\n

The first path is the path with my fully downloaded weights .h5 file. The second path is where I put said weights and the path Keras looks at to find the weights.<\/p>\n"}]} {"QuestionId":48129814,"AnswerCount":1,"Tags":"","CreationDate":"2018-01-06T17:14:01.583","AcceptedAnswerId":48136137.0,"OwnerUserId":1385975.0,"Title":"Keras LSTM Converges on the Dataset's Mean Value","Body":"

Snippet of data:<\/p>\n\n

\n

[ 1., 0.52916667 0.55, 0.5375 0.55714286 0.54285714 0.09395973]<\/p>\n \n

[ 0., 0.59285714 0.55, 0.5, 0.53076923 0.5, 0.09395973]<\/p>\n \n

[ 0., 0.53076923 0.5375 0., 0.5375 0.5, 0.08277405]<\/p>\n \n

[ 0., 0.55625 0.55833333 1., 0.53888889 0.52777778 0.08137584]<\/p>\n \n

[ 1., 0.52222222 0.52857143 0.54, 0.55, 0.55, 0.10834132]<\/p>\n \n

[ 1., 0.6875 0.6125 0.575 0.53, 0.52, 0.09395973]<\/p>\n \n

[ 0., 0.55666667 0.55, 0.55833333 0.52647059 0.52058824 0.08137584]<\/p>\n \n

[ 0., 0.53529412 0.5, 0.5, 0.5, 0.5, 0.02205177]<\/p>\n \n

[ 0., 0.52083333 1., 1., 0.54, 0.58, 0.34563758]<\/p>\n \n

[ 0., 0.55, 0.6, 0.5, 0.58, 0.5, 0.09395973]<\/p>\n \n

[ 0., 0.67, 0.5, 0., 0.5, 0.5, 0.07957814]<\/p>\n \n

[ 0., 0.51764706 1., 1., 0.54166667 0.55, 0.16107383]<\/p>\n<\/blockquote>\n\n

Each row in this timeseries dataframe contains 7 features and I'm trying to predict whether the first feature of the next time step will be a 1 or a 0.<\/p>\n\n

To achieve this I have shifted everything forward one time step to create the labels, like so:<\/p>\n\n

<\/pre>\n\n

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

<\/pre>\n\n

If I run 10,000 rows of data through the model, after 10 epochs I get the following:<\/p>\n\n

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

Looks okay... but my dataset is actually 4 million rows. When I ran the full 4 million rows through training it just predicts the mean of the Y values (0.5):<\/p>\n\n

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

The results are the same after 1 or 10 epochs. I can't figure out what's going on here. Any ideas?<\/p>\n","answers":[{"AnswerId":"48136137","CreationDate":"2018-01-07T10:10:17.360","ParentId":null,"OwnerUserId":"1977527","Title":null,"Body":"

First of all there are many different ways, why this could be.<\/p>\n\n

    \n
  1. In the past I had similar problems, where the output was also just the average. I worked there with stock price prediction. For Machine Learning algorithm it is just very difficult to extract meaningful information from stock information, that is why it starts predicting either random results or just the average like in your case. And this is probably the best a model can get (in predicting stock prices),because the stock prices go up and down random as well. Unfortunately, in this case there is not much you can do.<\/p><\/li>\n

  2. Second scenario is that you have too little data. Although you have 4 million rows of data, this sometimes is not enough to generalize a problem and you still need to get more data.<\/p><\/li>\n

  3. This is the most likely scenario. Your model architecture is wrong. Your true data is either 0 or 1, therefore it should be a classification problem. Change your model architecture to something like this:<\/p><\/li>\n<\/ol>\n\n

    You still need to do the fine tuning, I have not tested this.<\/p>\n\n

    x = CuDNNLSTM(128)(inputs)\nx = Dropout(0.5)(x)\npredictions = Dense(1, kernel_initializer='normal', activation='sigmoid')(x)\n\nmodel.compile(loss='binary_crossentropy', optimizer='adam')\n<\/code><\/pre>\n\n

    Additional your model probably has still too much noise in it. You can try a model with layers 64-64-1 instead of your model 128-128-128 or even try 32-1. And you can adjust the Dropout layer as well to like 0.3, 0.4, 0.5 or even more. If your model has to much noise, then it is just try and error, trying to get the noise out.<\/p>\n\n

    Recourses: <\/p>\n\n

    Machine Learning Mastery<\/a><\/p>\n\n

    Binary Classification<\/a><\/p>\n"}]} {"QuestionId":48130702,"AnswerCount":0,"Tags":"","CreationDate":"2018-01-06T18:50:59.117","AcceptedAnswerId":null,"OwnerUserId":6494707.0,"Title":"How to load a multi-channel (5 channel) into FCN which has been already trained on RGB images?","Body":"

    I am using FCN8s and its pre-trained model for semantic segmentation on my data. Since vanilla-fcn<\/a> models accept three channels images (RGB), I do not know how can I give 5 channel images to the model. Could someone please explain how can I give an input to a model that is using a pre-trained model? Thanks<\/p>\n","answers":[]} {"QuestionId":48131057,"AnswerCount":1,"Tags":"","CreationDate":"2018-01-06T19:28:02.340","AcceptedAnswerId":null,"OwnerUserId":1948893.0,"Title":"How to restore a tensorflow model that only has one file with extension \".model\"","Body":"

    I want to use a pretrained tensorflow model provided by an unknown author. I do not know how he\/she managed to save the tensorflow model (he\/she used tensorflow version >= 1.2) to only one file with the extension '.model<\/strong>', as normally I get either three files '.meta', '.data', '.index' or one file with '.ckpt'.<\/p>\n\n

    How can I restore this pretrained model? How can I save a model to this format later? <\/p>\n\n

    Thanks.<\/p>\n","answers":[{"AnswerId":"49912823","CreationDate":"2018-04-19T04:36:56.917","ParentId":null,"OwnerUserId":"3901871","Title":null,"Body":"

    I have also asked this question on a number of platforms with no assistance yet. So I decided to do some experimental work and this is what I found. This may be long but please bear with me.<\/p>\n\n

    To import a model in Tensor-flow we use<\/p>\n\n

    with tf.Session() as sess:\n  new_saver = tf.train.import_meta_graph('my_test_model-1000.meta')\n  new_saver.restore(sess, tf.train.latest_checkpoint('.\/'))\n<\/code><\/pre>\n\n

    The .meta<\/code> file contains all the variables, operations, collections, etc, of the trained model. What tf.train.latest_checkpoint('.\/')<\/code> does is to use the checkpoint file (which simply keeps a record of latest checkpoint files saved) to import the xxxx_model.data-00000-of-00001<\/code>. This .data-00000-of-00001<\/code> contains all the weights, biases, gradients, etc, that must be loaded into the variables contained in my_test_model-1000.meta<\/code>.<\/p>\n\n

    Summary [Semi-complete code]<\/h2>\n\n
    with tf.Session() as sess:\n    new_saver = tf.train.import_meta_graph('my_test_model-1000.meta')\n    #new_saver.restore(sess, tf.train.latest_checkpoint('.\/'))\n    tensor_variable = tf.trainable_variables()\n    for tensor_var in tensor_variable:\n        #print(sess.run(tensor_var))\n        print(tensor_var)\n<\/code><\/pre>\n\n

    This initial code will print out all the variables from .meta<\/code> that are trainable. If you try to run print(sess.run(tensor_var))<\/code> you will get an error. This is because, the variables have not been initialized. How ever, if you un-comment new_saver.restore(sess, tf.train.latest_checkpoint('.\/'))<\/code> and run print(sess.run(tensor_var))<\/code>, you will get all the variables alongside values loaded into the variables. <\/p>\n\n


    \n\n

    Now to \u201c.model\u201d<\/h2>\n\n

    My best guess is that xxxxxx.model<\/code> works a much like xxxx_model.data-00000-of-00001<\/code> from tensorflow. It does not contain variables and so if you try to do <\/p>\n\n

    with tf.Session() as sess:\n          new_saver = tf.train.import_meta_graph('xxx.model')\n<\/code><\/pre>\n\n

    you will get an error. Remember, the reason is that, this .model<\/code> file does not contain any variables nor operation graph of any form. If you also try to do <\/p>\n\n

    with tf.Session() as sess:\n          new_saver = tf.train.Saver()\n          new_saver.restore(sess, \"xxxx.model\")\n<\/code><\/pre>\n\n

    you will similarly get an error. This is because, there are no corresponding variables to load values into. Therefore, if you ever obtain a xxx.model<\/code> file, you will have to go through the pain of replicating all the variables and operations before trying to run new_saver.restore(sess, \"xxxx.model\")<\/code>. If you are able to replicate the architecture, this will run smoothly with no issues, hopefully. <\/p>\n\n

    I am sorry this was long, but considering that there is almost no answer on the internet, I had to make a lecture out of it. :)<\/p>\n"}]} {"QuestionId":48131106,"AnswerCount":1,"Tags":"","CreationDate":"2018-01-06T19:33:27.423","AcceptedAnswerId":48135788.0,"OwnerUserId":8027995.0,"Title":"Invalid array shape with neural network using Keras?","Body":"

    Currently studying the 'Deep Learning with Python' book by Francios Chollet. I am very new to this and I am getting this error code despite following his code verbatim. Can anyone interpret the error message or what needs to be done to solve it? Any help would be greatly appreciated!<\/p>\n\n

    <\/pre>\n\n

    Edit: Here is an image of the error code that I am getting:\n\"enter<\/a><\/p>\n","answers":[{"AnswerId":"48135788","CreationDate":"2018-01-07T09:10:33.397","ParentId":null,"OwnerUserId":"1977527","Title":null,"Body":"

    I tested your Code and found, that x_test was not defined. I think you meant to vectorize it as follows. With this Code it worked: <\/p>\n\n

    x_train = vectorize_sequences(train_data)\nx_test = vectorize_sequences(test_data)\ny_train = np.asarray(train_labels).astype('float32')\ny_test = np.asarray(test_labels).astype('float32')\n<\/code><\/pre>\n"}]}
    {"QuestionId":48131255,"AnswerCount":2,"Tags":"","CreationDate":"2018-01-06T19:49:02.547","AcceptedAnswerId":48131558.0,"OwnerUserId":9071615.0,"Title":"Tensorflow error concerning the shape of placeholders","Body":"

    I'm very new to TensorFlow and I try to understand the concept of Placeholders.\nLet's say I have a feature set with the shape of 100x4. So I have a 100 rows of 4 different features. The target is then of a 100x1 shape. If I want to use both matrices as a training set. What I do is:<\/p>\n\n

    <\/pre>\n\n

    Which then results into a \"ValueError: Cannot feed value of shape (...,) for Tensor 'Placeholder:0', which has shape '(..., ...)'\". More specifically, the dimensions are not equal for 'sub' in cost function.<\/p>\n\n

    Could someone explain how to proceed and why?\nThanks in advance<\/p>\n","answers":[{"AnswerId":"48131370","CreationDate":"2018-01-06T20:02:51.710","ParentId":null,"OwnerUserId":"6689249","Title":null,"Body":"

    \n

    understand the concept of Placeholders<\/p>\n<\/blockquote>\n\n

    Placeholders are needed to hold a place for real data that you will feed in future:<\/p>\n\n

    x = tf.placeholder(tf.float32, shape=X_train.shape)\nlogits = nn(x)  # making some operations with x in order to calculate logits\n\ns = tf.Session()\nlogits = s.run(logits, feed_dict={x: X_train})\n<\/code><\/pre>\n\n

    because we used placeholder to make logits we need to place real data instead of placeholder in order to compute logits<\/code><\/p>\n\n

    \n

    \"ValueError: Cannot feed value of shape (...,) for Tensor 'Placeholder:0', which has shape '(..., ...)'\"<\/p>\n<\/blockquote>\n\n

    looks like in feed_dict={x: X_train}<\/code> your placeholder x<\/code> has 2nd rank but X_train<\/code> is 1st rank. Better to double-check your data.<\/p>\n"},{"AnswerId":"48131558","CreationDate":"2018-01-06T20:23:45.623","ParentId":null,"OwnerUserId":"5668710","Title":null,"Body":"

    You should use placeholders if you want to train your data in batches<\/strong>. <\/p>\n\n

    Why?<\/strong>
    \nThis is done when you have a large dataset<\/strong>, for example if you want to train your classifier on an image classification problem but can't load all of your training images on your memory. What is done instead, is training your model through
    batch gradient descent<\/a>. Through this technique only a single batch of images is loaded each time and backpropagation is performed only on that batch. This requires more epochs to converge to a minima but each epoch is faster to train.<\/p>\n\n

    How?<\/strong>
    \nYou first define two placeholders one for the training examples X<\/code> and one for their labels Y<\/code>, with respective shapes (batch_size, 4)<\/code> and (batch_size, 1)<\/code> in your case.
    \nThen when you want to train your model you should feed<\/strong> your data into the placeholders through a feed dictionary:<\/p>\n\n

    with tf.Session() as sess:\n    sess.run(train_op, feed_dict={X:x_batch, Y:y_batch}) # train_op is the operation that minimizes your cost function\n<\/code><\/pre>\n\n

    where x_batch<\/code> and y_batch<\/code> should be random batches from your X_train<\/code> and Y_train<\/code> arrays, but instead of 100<\/code> examples they should have batch_size<\/code> examples (so that their dimensions match the placeholders' dimensions).<\/p>\n\n

    Why you shouldn't do this in your case?<\/strong>
    \nSince you have a small dataset<\/strong>, that is already loaded in your memory you could use regular gradient descent.<\/p>\n\n

    How?<\/strong>
    \nJust use variables (tf.Variable()<\/code>) instead of placeholders.<\/p>\n\n

    X = tf.Variable(X_train)\nY = tf.Variable(Y_train)\n<\/code><\/pre>\n\n

    This will create two Variable type tensors which, when initialized will take the shape and values of X_train<\/code> and Y_train<\/code> respectively.<\/p>\n\n

    Just don't forget to initialize<\/strong> them in your session:<\/p>\n\n

    with tf.Session() as sess:\n     sess.run(tf.global_variables_initializer()) # initialize variables\n     sess.run(train_op) # no need for a feed_dict\n<\/code><\/pre>\n"}]}
    {"QuestionId":48131965,"AnswerCount":2,"Tags":"","CreationDate":"2018-01-06T21:13:59.130","AcceptedAnswerId":null,"OwnerUserId":null,"Title":"Keras segmentation fault on load_model on Linux and not on Windows","Body":"

    I prototyped a Python deep learning piece of code working on Windows and I can't make it work on Linux. I identified that the problem comes from load_model.\nHere is the piece of Python code that behaves differently on Windows and in Linux.<\/p>\n\n

    Both Keras installations were made from the github source repository from Keras Team because the model format is not recognized by the standard Keras package, a patch was done very recently for the characters format in the Github source code.<\/p>\n\n

    Do you have an idea of what's going on?<\/p>\n\n

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

    <\/pre>\n\n

    Windows output:<\/p>\n\n

    <\/pre>\n\n

    Linux output:<\/p>\n\n

    <\/pre>\n\n

    The french Erreur de segmentation<\/strong> means Segmentation fault<\/strong><\/p>\n\n

    Thank you for your help!<\/p>\n\n

    Glassfrog<\/p>\n","answers":[{"AnswerId":"48150238","CreationDate":"2018-01-08T12:23:27.653","ParentId":null,"OwnerUserId":null,"Title":null,"Body":"

    I only found a workaround. <\/p>\n\n

    As the model file was a data conversion from another weights file in another format, I went and regenerated the Keras model for the latest version of Keras.<\/p>\n\n

    Now It works.<\/p>\n\n

    But I still don't know what caused the segmentation fault.<\/p>\n"},{"AnswerId":"56593862","CreationDate":"2019-06-14T07:57:19.093","ParentId":null,"OwnerUserId":"446140","Title":null,"Body":"

    From what I can tell, the segfault happens at the model creation, but I have no idea why.\nI could debug this by saving the model and weights independently:<\/p>\n\n

    from keras.models import load_model\nx = load_model('combined_model.h5')  # runs only on the source machine\nwith open('model.json', 'w') as fp:\n     fp.write(x.to_json())\nx.save_weights('weights.h5')\n<\/code><\/pre>\n\n

    on the other machine I tried to load the model from the JSON file, but got the segmentation fault<\/code> as well:<\/p>\n\n

    from keras.models import model_from_json\nwith open('model.json', 'r') as fp:\n    model = model_from_json(fp.read())  # segfaults here\n<\/code><\/pre>\n\n

    If it is possible to simply re-create the model on the target machine by creating the Sequential model again, you can simply load the weights in the model:<\/p>\n\n

    from keras import Sequential\n# ...\nnew_model = Sequential()\n# [...] run your model creation here...\nnew_model.load_weights('weights.h5')\n\nnew_model.predict(...)  # this should work now\n<\/code><\/pre>\n"}]}
    {"QuestionId":48132420,"AnswerCount":0,"Tags":"","CreationDate":"2018-01-06T22:12:08.193","AcceptedAnswerId":null,"OwnerUserId":7155735.0,"Title":"Unable to load tensorflow model in Java","Body":"

    I have created a servable LSTM model in Python but when I try to use the model in Java I get an error. <\/p>\n\n

    Here is my Java code to load the model:<\/p>\n\n

    <\/pre>\n\n

    Here is the error I encounter:<\/p>\n\n

    <\/pre>\n\n

    I have checked the saved_model.pbtxt for servable model and find quite a few references to 'type: DT_VARIANT'<\/p>\n\n

    My python code uses tensorflow tf-nightly 1.5x build. I have also tried this with tf1.4 library. In Java, I am using libtensorflow-1.5.0-rc0.jar. I have also tried unsuccessfully loading the model alongwith libtensorflow-1.4.0.jar and libtensorflow-1.3.0.jar jar files.<\/p>\n\n

    When I look at the history of tensorflow\/tensorflow\/core\/framework\/types.proto in github, I notice that DT_VARIANT and uint32\/uint64 were added in July 2017 and Oct 2017 respectively so maybe thats why the jar files are not able to recognize them. I have checked in tensorflow\/tensorflow\/java\/src\/ and havent noticed any reference to these types. So maybe that is the problem.<\/p>\n\n

    Sorry if Im missing something obvious, I have tried looking around for an answer. Does anyone have any suggestions I can try to get around this problem?<\/p>\n","answers":[]} {"QuestionId":48132740,"AnswerCount":1,"Tags":"","CreationDate":"2018-01-06T22:59:20.277","AcceptedAnswerId":null,"OwnerUserId":439929.0,"Title":"Tensorflow:using results of one operation in other","Body":"

    I am trying to replace a piece of numpy in my code. I have something like this<\/p>\n\n

    <\/pre>\n\n

    I would like to use tf.unqiue, but the result of returning tensor wont be available until I evaluate the graph. I want to build one single graph so I can evaluate all ops together. Is it possible to do something like this in TensorFlow. If not, is this the advantage dynamically generated graphs like pyTorch and others provide ? <\/p>\n","answers":[{"AnswerId":"48533132","CreationDate":"2018-01-31T01:31:34.277","ParentId":null,"OwnerUserId":"8581827","Title":null,"Body":"

    If you knew the number of unique values, then something like this could work:<\/p>\n\n

    array = <ndarray>\nnum_unique = <# of unique values>\ny, idx = tf.unique(array)\nidx = tf.reshape(idx, (-1, 1))\neq_tensors = tf.transpose(tf.equal(idx, tf.range(num_unique)))\n<\/code><\/pre>\n"}]}
    {"QuestionId":48132807,"AnswerCount":1,"Tags":"","CreationDate":"2018-01-06T23:11:38.043","AcceptedAnswerId":48133079.0,"OwnerUserId":7015035.0,"Title":"Why does tensor flow return NaN when running variables after training?","Body":"

    I can't really understand why this is not working, basically I'm trying to retrieve values for m and q just to print them but I always get [nan, nan]<\/p>\n\n

    <\/pre>\n\n

    train.csv and test.csv are both files with a header line and two columns of values, x and y<\/p>\n\n

    First 10 lines of train.csv<\/p>\n\n

    <\/pre>\n","answers":[{"AnswerId":"48133079","CreationDate":"2018-01-06T23:50:59.710","ParentId":null,"OwnerUserId":"7015035","Title":null,"Body":"

    Solved, the error was that train.csv was missing the y value at line 215<\/p>\n"}]} {"QuestionId":48133160,"AnswerCount":1,"Tags":"","CreationDate":"2018-01-07T00:07:42.157","AcceptedAnswerId":null,"OwnerUserId":6175691.0,"Title":"ValueError Tensor is not an element of this graph","Body":"

    I am having a bad time. While I was able to solve the problem<\/a> I had with the dimensionality... new error appeared. <\/p>\n\n

    The task is still binary image segmentation. I have images of size WxH as well as labels of the same size (0, 255). I rescale images and labels to the values between (0,1) in the imageDataGenerator. <\/p>\n\n

    I followed the advice<\/a> and reshaped my labels into using this<\/a> nice blog entry as a reference. <\/p>\n\n

    For the up-sampling I used BilinearUpsampling2D<\/a>.<\/p>\n\n

    SO. My labels and the output of the network are of the same shape.<\/p>\n\n

    The error I am getting now is:<\/p>\n\n

    <\/pre>\n\n

    I am again posting the entire code and ask you if you notice any stupid things I am doing. I can't seem to figure it out.\nUsing Python3.5, Keras (2.1.2) with tensorflow (1.4.0) backend. <\/p>\n\n

    <\/pre>\n\n

    Adding complete traceback: <\/p>\n\n

    <\/pre>\n","answers":[{"AnswerId":"48446981","CreationDate":"2018-01-25T15:54:22.403","ParentId":null,"OwnerUserId":"6175691","Title":null,"Body":"

    For people having similar problems. I found the error from Keras very unintuitive. In my case there was no bug or errors with the layers. <\/p>\n\n

    My mentor pointed out, that this might be a problem of feeding the network with data of improper shape. This was not the case, since the outputs and inputs were ok.<\/p>\n\n

    The problem was in the choice of loss function and the shape it expects. I am still trying to figure out which loss function to use, but what I found to be working is either dice coefficient loss<\/code> or mean_pairwise_squared_error<\/code>.<\/p>\n"}]} {"QuestionId":48133855,"AnswerCount":0,"Tags":"","CreationDate":"2018-01-07T02:38:22.647","AcceptedAnswerId":null,"OwnerUserId":8797405.0,"Title":"Visualizing weights of trained Tensorflow model","Body":"

    I trained a model in TF an I would like to visualize its weights. Below is the code that I used to train the model. It looks like a lot of code but it's very straight forward. I just build the network, define the placeholders and train it with the optimize() function.<\/p>\n\n

    <\/pre>\n\n

    With this code I'm able to train the model successfully.\nNow, I would like to get the weights of the convolutional layer. To do so, I use this code snippet:<\/p>\n\n

    <\/pre>\n\n

    However with the code above I only get an image object that I cannot visualize. I'm not even sure if this is the right way to get the weights. I've seen that other people have asked this question but most answers lead to Tensorboard and I want to do this is in an iPython shell.<\/p>\n\n

    Below is an example of what I would like to see.<\/p>\n\n

    Conv Layer Weights 1<\/a><\/p>\n\n

    Conv Layer Weights 2<\/a><\/p>\n","answers":[]} {"QuestionId":48134099,"AnswerCount":0,"Tags":"","CreationDate":"2018-01-07T03:33:47.750","AcceptedAnswerId":null,"OwnerUserId":459519.0,"Title":"CNN performs worse than fully connected net - how to spot mistakes?","Body":"

    I'm experimenting with CNNs and I'm baffled, because model I've built actually learns slower and performs worse than fully connected NN. Here are two models:<\/p>\n\n

    fully connected:<\/p>\n\n

    <\/pre>\n\n

    CNN:<\/p>\n\n

    <\/pre>\n\n

    Basically CNN have a little more shallow fully connected net, but added conv layers vs just fully connected. CNN arrives to accuracy ~88% vs 92% of deep nn after same number of epochs and same dataset. How to debug issues like that? What are good practices in designing conv layers?<\/p>\n","answers":[]} {"QuestionId":48134179,"AnswerCount":1,"Tags":"","CreationDate":"2018-01-07T03:56:40.310","AcceptedAnswerId":48134756.0,"OwnerUserId":9137521.0,"Title":"Trained model detects almost everything as one class after a long training","Body":"

    I trained a custom person detector using Tensorflow and Inception's pretrained model then after a few thousands of step and an average of 2-1 loss, I've stopped the training and tested it with a live video. The result was quite good and only gets few false positives. It can detect some person but not everyone so I decided to continue on training the model until I get an average loss of below 1 then tested it again. It now detects almost everything as a person even the whole frame of the video even when there is no object present. The models seems to work great on pictures but not on videos. Is that an overfitting?<\/p>\n\n

    Sorry I forgot how many steps it is. I accidentally deleted the training folder that contains the ckpt and tfevents.<\/p>\n\n

    edit: I forgot that I am also training the same model with same dataset but higher batch size on a cloud as a backup which is now on a higher step. I'll edit the post later and will provide the infos from tensorboard once I've finished downloading and testing the model from the cloud.<\/p>\n\n

    edit2: I downloaded the trained model on 200k steps from the cloud and it is working, it detects persons but sometimes recognizes the whole frame as \"person\" for less than a second when I am moving the camera. I guess this could be improved by continuing on training the model. \nTotal Loss on tensorboard<\/a><\/p>\n\n

    For now, I'll just continue the training on the cloud and try to document every results of my test. I'll also try to resize some images on my dataset and train it on my local machine using mobilenet and compare the results from two models.<\/p>\n","answers":[{"AnswerId":"48134756","CreationDate":"2018-01-07T06:06:19.370","ParentId":null,"OwnerUserId":"5330223","Title":null,"Body":"

    As you are saying the model did well when there were less training iterations, I guess the pre-trained model could already detect the person object and your training set made the detection worse. <\/p>\n\n

    \n

    The models seems to work great on pictures but not on videos<\/p>\n<\/blockquote>\n\n

    If your single pictures are detected fine, then videos should work too. the only difference can be from video image resolution and quality. So, compare the image resolution and the video.<\/p>\n\n

    \n

    Is that an overfitting?<\/p>\n<\/blockquote>\n\n

    The images and the videos, you are talking about, If the images were used in training you should not use them to evaluate the model<\/strong>. If the model is over fitted it will detect the training images but not any other ones.<\/p>\n\n

    As you are saying, the model detects too many detections, I think this is not because of overfitting, it can be about your dataset. I think <\/p>\n\n

      \n
    1. You have too little amount of data to train.<\/p><\/li>\n

    2. The network model is too big and complicated for the amount of data. Try smaller network like VGG, inception_v1(ssd mobile net) etc.<\/p><\/li>\n

    3. The image resolution used in training set is very different from the evaluation images.<\/li>\n
    4. Learning rate is important, but I think in your case it's fine.<\/li>\n<\/ol>\n\n

      I think you can check carefully the dataset you used for training and use as many data as you can for the training. These are the things I generally experienced and wasted time.<\/p>\n"}]} {"QuestionId":48134194,"AnswerCount":4,"Tags":"","CreationDate":"2018-01-07T03:59:46.053","AcceptedAnswerId":null,"OwnerUserId":8518156.0,"Title":"Machine learning: why the cost function does not need to be derivable?","Body":"

      I was playing around with Tensorflow creating a customized loss function and this question about general machine learning arose to my head.<\/p>\n\n

      My understanding is that the optimization algorithm needs a derivable cost function to find\/approach a minimum, however we can use functions that are non-derivable such as the absolute function (there is no derivative when x=0). A more extreme example, I defined my cost function like this:<\/p>\n\n

      <\/pre>\n\n

      and I expected an error when running the code, but it actually worked (it didn't learn anything but it didn't crash).<\/p>\n\n

      Am I missing something?<\/p>\n","answers":[{"AnswerId":"48136091","CreationDate":"2018-01-07T10:02:50.863","ParentId":null,"OwnerUserId":"288875","Title":null,"Body":"

      If it didn't learn anything, what have you gained ? Your loss function is differentiable almost everywhere but it is flat almost anywhere so the minimizer can't figure out the direction towards the minimum. <\/p>\n\n

      If you start out with a positive value, it will most likely be stuck at a random value on the positive side even though the minima on the left side are better (have a lower value). <\/p>\n\n

      Tensorflow can be used to do calculations in general and it provides a mechanism to automatically find the derivative of a given expression and can do so across different compute platforms (CPU, GPU) and distributed over multiple GPUs and servers if needed. <\/p>\n\n

      But what you implement in Tensorflow does not necessarily have to be a goal function to be minimized. You could use it e.g. to throw random numbers and perform Monte Carlo integration of a given function.<\/p>\n"},{"AnswerId":"48136023","CreationDate":"2018-01-07T09:52:35.870","ParentId":null,"OwnerUserId":"2891324","Title":null,"Body":"

      You're missing the fact that the gradient of the sign<\/code> function is somewhere manually defined in the Tensorflow source code.<\/p>\n\n

      As you can see here<\/a>:<\/p>\n\n

      def _SignGrad(op, _):\n  \"\"\"Returns 0.\"\"\"\n  x = op.inputs[0]\n  return array_ops.zeros(array_ops.shape(x), dtype=x.dtype)\n<\/code><\/pre>\n\n

      the gradient of tf.sign<\/code> is defined to be always zero. This, of course, is the gradient where the derivate exists, hence everywhere but not in zero.<\/p>\n\n

      The tensorflow authors decided to do not check if the input is zero and throw an exception in that specific case<\/p>\n"},{"AnswerId":"48136026","CreationDate":"2018-01-07T09:53:15.957","ParentId":null,"OwnerUserId":"1306026","Title":null,"Body":"

      In order to prevent TensorFlow from throwing an error, the only real requirement is that you cost function evaluates to a number for any value of your input variables. From a purely \"will it run\" perspective, it doesn't know\/care about the form of the function its trying to minimize.<\/p>\n\n

      In order for your cost function to provide you a meaningful<\/em> result when TensorFlow uses it to train a model, it additionally needs to 1) get smaller as your model does better and 2) be bounded from below (i.e. it can't go to negative infinity). It's not generally necessary for it to be smooth (e.g. abs(x) has a kink where the sign flips). Tensorflow is always able to compute gradients at any location using automatic differentiation (https:\/\/en.wikipedia.org\/wiki\/Automatic_differentiation<\/a>, https:\/\/www.tensorflow.org\/versions\/r0.12\/api_docs\/python\/train\/gradient_computation<\/a>).<\/p>\n\n

      Of course, those gradients are of more use if you've chose a meaningful cost function isn't isn't too flat.<\/p>\n"},{"AnswerId":"48136037","CreationDate":"2018-01-07T09:55:34.917","ParentId":null,"OwnerUserId":"712995","Title":null,"Body":"

      Ideally, the cost function needs to be smooth everywhere to apply gradient based optimization methods (SGD, Momentum, Adam, etc). But nothing's going to crash if it's not, you can just have issues with convergence to a local minimum.<\/p>\n\n

      When the function is non-differentiable at a certain point x<\/code>, it's possible to get large oscillations if the neural network converges to this x<\/code>. E.g., if the loss function is tf.abs(x)<\/code>, it's possible that the network weights are mostly positive, so the inference x > 0<\/code> at all times, so the network won't notice tf.abs<\/code>. However, it's more likely that x<\/code> will bounce around 0<\/code>, so that the gradient is arbitrarily positive and negative. If the learning rate is not decaying, the optimization won't converge to the local minimum, but will bound around it.<\/p>\n\n

      In your particular case, the gradient is zero all the time, so nothing's going to change at all.<\/p>\n"}]} {"QuestionId":48135221,"AnswerCount":1,"Tags":"","CreationDate":"2018-01-07T07:33:51.573","AcceptedAnswerId":48135863.0,"OwnerUserId":5718092.0,"Title":"How to do matrix-wise multiply in Tensorflow?","Body":"

      I would appreciate some help with the following:<\/p>\n\n

      Given two tensors of<\/p>\n\n

      A = bsz x a_len x dim <\/p>\n\n

      B = bsz x b_len x dim<\/p>\n\n

      I would like to do a matrix-wise element-wise multiply such that each vector of length dim is multiplied with each vector (dim length) of B<\/p>\n\n

      The output should be:<\/p>\n\n

      bsz x a_len x b_len x dim<\/p>\n\n

      How can I do this in Tensorflow?<\/p>\n\n

      Thanks in advance!<\/p>\n","answers":[{"AnswerId":"48135863","CreationDate":"2018-01-07T09:24:08.113","ParentId":null,"OwnerUserId":"1306026","Title":null,"Body":"

      Have you looked at tf.einsum? <\/p>\n\n

      https:\/\/www.tensorflow.org\/versions\/r1.0\/api_docs\/python\/tf\/einsum<\/a><\/p>\n\n

      Does tf.einsum('abd,acd->abcd', A, B)<\/code> give you what you're looking for?<\/p>\n"}]} {"QuestionId":48135310,"AnswerCount":1,"Tags":"","CreationDate":"2018-01-07T07:50:25.953","AcceptedAnswerId":null,"OwnerUserId":8175904.0,"Title":"Tensorflow on Raspberry Pi Error","Body":"

      I have a python script that works without any errors on my desktop. When I try to run it on my raspberry pi, I encounter an error.<\/p>\n\n

      To install tensorflow on the raspberry pi for python 3.5, I followed this tutorial: https:\/\/petewarden.com\/2017\/08\/20\/cross-compiling-tensorflow-for-the-raspberry-pi\/<\/a> There is no offical binary for tensorflow and python 3.5 and I had errors when I tried to compile it myself. The tutorial suggest to just install tensorflow from the Python 3.4 binary.<\/p>\n\n

      \n

      If you\u2019re running Python 3.5, you can use the Python 3.4 wheel but with a\n slight change to the file name, since that encodes the version. You\n will see a couple of warnings every time you import tensorflow, but it\n should work correctly.<\/p>\n<\/blockquote>\n\n

      Here is the error I am encountering:<\/p>\n\n

      <\/pre>\n\n

      Line 93 attempts to create an Estimator which causes the error.<\/p>\n\n

      <\/pre>\n\n

      I found a similar error on github but it was no help: https:\/\/github.com\/tensorflow\/serving\/issues\/684<\/a><\/p>\n","answers":[{"AnswerId":"48164079","CreationDate":"2018-01-09T08:29:19.767","ParentId":null,"OwnerUserId":"8175904","Title":null,"Body":"

      I installed an older build. It doesn't cause this error. http:\/\/ci.tensorflow.org\/view\/Nightly\/job\/nightly-pi\/78\/artifact\/output-artifacts\/tensorflow-1.3.0-cp27-none-any.whl<\/a><\/p>\n"}]} {"QuestionId":48135452,"AnswerCount":0,"Tags":"","CreationDate":"2018-01-07T08:12:49.753","AcceptedAnswerId":null,"OwnerUserId":7750721.0,"Title":"ubuntu GNOME : tensorflow-gpu installation error","Body":"

      I'm trying to install tensorflow-gpu on my ubuntu GNOME machine.<\/p>\n\n

      I think I installed CUDA 8.0 and cudnn v5.1 correctly, but when I open up my tensorflow environment and run<\/p>\n\n

      <\/pre>\n\n

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

      <\/pre>\n\n

      To make the long story short, I get two <\/p>\n\n

      <\/pre>\n\n

      Is that a cudnn v6.x file? Do I need to install the cudnn 6.x instead of the 5.1? I'm totally new to Linux and having some trouble. Please do help.<\/p>\n","answers":[]} {"QuestionId":48136804,"AnswerCount":1,"Tags":"","CreationDate":"2018-01-07T11:47:55.267","AcceptedAnswerId":null,"OwnerUserId":3831845.0,"Title":"tf.Estimator.train throws as_list() is not defined on an unknown TensorShape","Body":"

      I created a custom and converted a keras model into for training. However, it keeps throwing me error. <\/p>\n\n