{"QuestionId":36586712,"AnswerCount":1,"Tags":"","CreationDate":"2016-04-13T00:59:42.600","AcceptedAnswerId":36586822.0,"OwnerUserId":5982966.0,"Title":"Cannot differentiate image functions","Body":"

In Tensorflow, I'm restricted from differentiating values that had operations like hsv_to_rgb applied. This is because of this code, I assume:<\/p>\n\n

<\/pre>\n\n

What is the rationale for this? Are the subgradients that uninformative?<\/p>\n","answers":[{"AnswerId":"36586822","CreationDate":"2016-04-13T01:12:21.260","ParentId":null,"OwnerUserId":"419116","Title":null,"Body":"

That reflects the fact that gradients have not been implemented for these ops<\/p>\n"}]} {"QuestionId":36586916,"AnswerCount":0,"Tags":"","CreationDate":"2016-04-13T01:24:07.677","AcceptedAnswerId":null,"OwnerUserId":6998621.0,"Title":"Discrepancy in results when using batch size 1 in prototxt versus coercing batch size to 1 in pycaffe","Body":"

I am running the MNIST<\/a> example with some manual changes to the layers. While training everything works great and I reach a final test accuracy of ~99%. I am now trying to work with the generated model in python using pycaffe and am following the steps as given here<\/a>. I want to compute the confusion matrix so I'm looping through the test images one by one from LMDB and then running the network. Here is the code :<\/p>\n\n

<\/pre>\n\n

Here is my network definition prototxt<\/p>\n\n

<\/pre>\n\n

Note that test batch size is 100 which is why I need that reshape in python code. Now, suppose I change the test batch size to 1, the exact same python code prints different (and mostly correct) predicted class labels. Thus, the code being run with batch size 1 produces expected result with ~99% accuracy while batch size 100 is horrible.\nHowever, based on the Imagenet pycaffe tutorial, I don't see what I'm doing wrong. As a last resort I can create a copy of my prototxt with batch size 1 for test and use that in my python code and use the original one while training, but that is not ideal. <\/p>\n\n

Also, I don't think it should be an issue with preprocessing since it doesn't explain why it works well with batch size 1.<\/p>\n\n

Any pointers appreciated!<\/p>\n","answers":[]} {"QuestionId":36587399,"AnswerCount":1,"Tags":"","CreationDate":"2016-04-13T02:19:52.407","AcceptedAnswerId":36610187.0,"OwnerUserId":5607962.0,"Title":"how to use android camera's flash in Android Studio","Body":"

I am working on a kind of torch application in android Studio environment. I want to use a pulse waves modulated(PWM) to make the flash light be adapted to the ambient light. I made lot of research about that, but i didn't find any tutorial about how to manage the camera's flash alone in android studio. \nIs there any solution? <\/p>\n","answers":[{"AnswerId":"36610187","CreationDate":"2016-04-13T21:48:32.430","ParentId":null,"OwnerUserId":"1344825","Title":null,"Body":"

An Android device's camera flash can be controlled with the setTorchMode()<\/a> method starting with Android M. <\/p>\n\n

Prior to that, you have to open a camera device with either the deprecated camera API, or the new camera2 API, and change the flash state to TORCH.<\/p>\n\n

However, even with camera2, you won't be able to modulate the flash at a high rate - I'd be surprised if you could reach 30Hz, and certainly not faster. <\/p>\n\n

So without building your own Android ROM, and modifying the flash LED driver code, you're unlikely to be able to do this.<\/p>\n"}]} {"QuestionId":36590720,"AnswerCount":1,"Tags":"","CreationDate":"2016-04-13T06:53:20.713","AcceptedAnswerId":36601443.0,"OwnerUserId":4776256.0,"Title":"Error loading module when using lua","Body":"

I'm new to lua and recently learning DL with Torch.\nI have installed torch just following instructions: http:\/\/torch.ch\/docs\/getting-started.html#_<\/a> and added some packages using . Then I wrote a test file:<\/p>\n\n

<\/pre>\n\n

when running with (Ubuntu 14.04), it errs as followed:<\/p>\n\n

\n

error loading module 'libpaths' from file\n '\/home\/user1\/torch\/install\/lib\/lua\/5.1\/libpaths.so':\n \/home\/user1\/torch\/install\/lib\/lua\/5.1\/libpaths.so: undefined symbol:\n luaL_register<\/p>\n<\/blockquote>\n\n

It seems something wrong with path settings or so. However, when I run test with command , it works fine.\nI searched and examined these answers: Error loading module (Lua)<\/a>\nTorch7 Lua, error loading module 'libpaths' (Linux)<\/a>\nnot fully answered my question though.
\nSo I wonder where exactly the error comes from, and how to fix it. Even though I can use torch with .<\/p>\n\n

ADD:\nI find that the reason maybe API is not supported in ver 5.2 which is what I am using, while calls a lua shell in ver 5.1? So does this mean I can only use to run my files?<\/p>\n","answers":[{"AnswerId":"36601443","CreationDate":"2016-04-13T14:25:01.263","ParentId":null,"OwnerUserId":"1442917","Title":null,"Body":"

You are likely using your system Lua (probably version 5.2), but Torch requires LuaJIT it comes with. Run your script as luajit test.lua<\/code> (it's probably in \/home\/user1\/torch\/install\/bin\/luajit<\/code>).<\/p>\n"}]} {"QuestionId":36591078,"AnswerCount":2,"Tags":"","CreationDate":"2016-04-13T07:11:42.313","AcceptedAnswerId":null,"OwnerUserId":4035713.0,"Title":"One Hot Encoding giving same number for different words in keras","Body":"

Why I am getting same results for different words?<\/p>\n\n

<\/pre>\n","answers":[{"AnswerId":"43446164","CreationDate":"2017-04-17T06:18:07.560","ParentId":null,"OwnerUserId":"1647894","Title":null,"Body":"

From the Keras source code<\/a>, you can see that the words are hashed modulo the output dimension (43, in your case):<\/p>\n\n

def one_hot(text, n,\n        filters='!\"#$%&()*+,-.\/:;<=>?@[\\\\]^_`{|}~\\t\\n',\n        lower=True,\n        split=' '):\n    seq = text_to_word_sequence(text,\n                            filters=filters,\n                            lower=lower,\n                            split=split)\n    return [(abs(hash(w)) % (n - 1) + 1) for w in seq]\n<\/code><\/pre>\n\n

So it is very likely that there will be a collision.<\/p>\n"},{"AnswerId":"36594559","CreationDate":"2016-04-13T09:45:05.250","ParentId":null,"OwnerUserId":"5876383","Title":null,"Body":"

unicity non-guaranteed in one hot encoding<\/p>\n\n

see one hot keras documentation<\/a> <\/p>\n"}]} {"QuestionId":36593228,"AnswerCount":0,"Tags":"","CreationDate":"2016-04-13T08:51:50.563","AcceptedAnswerId":null,"OwnerUserId":2846915.0,"Title":"Torch nn. Current error always is nan","Body":"

I've wrote the following code:<\/p>\n\n

<\/pre>\n\n

And it must works good (At least I think so), and it works correct when . But when current error always is . At first I've thought that file reading part is incorrect. I've recheck it some times but it is working great. Also I found that sometimes too small or too big learning rate may affect on it. I've tried learning rate from 0.00001 up to 0.8, but still the same result. What I'm doing wrong?<\/p>\n\n

Thanks,\nIgor<\/p>\n","answers":[]} {"QuestionId":36597519,"AnswerCount":1,"Tags":"","CreationDate":"2016-04-13T11:51:59.043","AcceptedAnswerId":36605314.0,"OwnerUserId":3761534.0,"Title":"Adding regularizer to skflow","Body":"

I recently switched form tensorflow to skflow. In tensorflow we would add our lambda*tf.nn.l2_loss(weights) to our loss. Now I have the following code in skflow:<\/p>\n\n

<\/pre>\n\n

How and where do I add a regularizer here? Illia hints something here<\/a> but I couldn't figure it out.<\/p>\n","answers":[{"AnswerId":"36605314","CreationDate":"2016-04-13T17:17:03.793","ParentId":null,"OwnerUserId":"884962","Title":null,"Body":"

You can still add additional components to loss, you just need to retrieve weights from dnn \/ logistic_regression and add them to the loss:<\/p>\n\n

def regularize_loss(loss, weights, lambda):\n    for weight in weights:\n        loss = loss + lambda * tf.nn.l2_loss(weight)\n    return loss    \n\n\ndef deep_psi(X, y):\n    layers = skflow.ops.dnn(X, [5, 10, 20, 10, 5], keep_prob=0.5)\n    preds, loss = skflow.models.logistic_regression(layers, y)\n\n    weights = []\n    for layer in range(5): # n layers you passed to dnn\n        weights.append(tf.get_variable(\"dnn\/layer%d\/linear\/Matrix\" % layer))\n        # biases are also available at dnn\/layer%d\/linear\/Bias\n    weights.append(tf.get_variable('logistic_regression\/weights'))\n\n    return preds, regularize_loss(loss, weights, lambda)\n<\/code><\/pre>\n\n

```<\/p>\n\n

Note, the path to variables can be found here<\/a>.<\/p>\n\n

Also, we want to add regularizer support to all layers with variables (like dnn<\/code>, conv2d<\/code> or fully_connected<\/code>) so may be next week's night build of Tensorflow should have something like this dnn(.., regularize=tf.contrib.layers.l2_regularizer(lambda))<\/code>. I'll update this answer when this happens.<\/p>\n"}]} {"QuestionId":36598331,"AnswerCount":1,"Tags":"","CreationDate":"2016-04-13T12:26:03.517","AcceptedAnswerId":null,"OwnerUserId":2902280.0,"Title":"Queue input data with tensorflow or skflow","Body":"

I am training a neural net with a which is a bit slow (because it reads non-contiguous data from a h5 file); so the GPU satays idle (GPU-Util is at 0 %) half of the time.<\/p>\n\n

Is there a way, in either TensorFlow or skflow, to have multiple s running in parallel, to avoid this bottleneck?<\/p>\n","answers":[{"AnswerId":"36606061","CreationDate":"2016-04-13T17:57:00.573","ParentId":null,"OwnerUserId":"884962","Title":null,"Body":"

Tensorflow has reader library<\/a> that can in parallel (and in C++) read and queue data. This should remove bottleneck you are talking about.<\/p>\n\n

We are currently (this\/next week) adding it's support to tf.learn (new name for skflow) to make it easy to use. You will still need to convert your data into one of the formats readers support (fixed len vectors, Example proto).<\/p>\n\n

If you want to try make it work yourself - you can create a separate DataFeeder, that would use the ops from reader library in input_builder<\/code> function and return no-op in the get_feed_dict_fn<\/code>.<\/p>\n"}]} {"QuestionId":36599237,"AnswerCount":1,"Tags":"","CreationDate":"2016-04-13T13:01:42.730","AcceptedAnswerId":36973018.0,"OwnerUserId":6198808.0,"Title":"Keras. ValueError: I\/O operation on closed file","Body":"

I use jupyter notebook with anaconda. I use kerast firstly, and i can't do tutorial. About this issues are two themes in stackoverflow, but solve not found.<\/p>\n\n

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

<\/pre>\n\n

And I have error, it's some random and sometimes one or two epoch competed:<\/p>\n\n

\n

Epoch 1\/5 4352\/17500 [======>.......................]<\/p>\n \n

--------------------------------------------------------------------------- ValueError Traceback (most recent call\n last) in ()\n 2 # of 32 samples\n 3 #sleep(0.1)\n ----> 4 model.fit(X_train, Y_train, nb_epoch=5, batch_size=32)\n 5 #sleep(0.1)<\/p>\n \n

C:\\Anaconda3\\envs\\py27\\lib\\site-packages\\keras\\models.pyc in fit(self,\n x, y, batch_size, nb_epoch, verbose, callbacks, validation_split,\n validation_data, shuffle, class_weight, sample_weight, **kwargs)\n 395 shuffle=shuffle,\n 396 class_weight=class_weight,\n --> 397 sample_weight=sample_weight)\n 398 \n 399 def evaluate(self, x, y, batch_size=32, verbose=1,<\/p>\n \n

C:\\Anaconda3\\envs\\py27\\lib\\site-packages\\keras\\engine\\training.pyc in\n fit(self, x, y, batch_size, nb_epoch, verbose, callbacks,\n validation_split, validation_data, shuffle, class_weight,\n sample_weight) 1009 verbose=verbose,\n callbacks=callbacks, 1010
\n val_f=val_f, val_ins=val_ins, shuffle=shuffle,\n -> 1011 callback_metrics=callback_metrics) 1012 1013 def\n evaluate(self, x, y, batch_size=32, verbose=1, sample_weight=None):<\/p>\n \n

C:\\Anaconda3\\envs\\py27\\lib\\site-packages\\keras\\engine\\training.pyc in\n _fit_loop(self, f, ins, out_labels, batch_size, nb_epoch, verbose, callbacks, val_f, val_ins, shuffle, callback_metrics)\n 753 batch_logs[l] = o\n 754 \n --> 755 callbacks.on_batch_end(batch_index, batch_logs)\n 756 \n 757 epoch_logs = {}<\/p>\n \n

C:\\Anaconda3\\envs\\py27\\lib\\site-packages\\keras\\callbacks.pyc in\n on_batch_end(self, batch, logs)\n 58 t_before_callbacks = time.time()\n 59 for callback in self.callbacks:\n ---> 60 callback.on_batch_end(batch, logs)\n 61 self._delta_ts_batch_end.append(time.time() - t_before_callbacks)\n 62 delta_t_median = np.median(self._delta_ts_batch_end)<\/p>\n \n

C:\\Anaconda3\\envs\\py27\\lib\\site-packages\\keras\\callbacks.pyc in\n on_batch_end(self, batch, logs)\n 187 # will be handled by on_epoch_end\n 188 if self.verbose and self.seen < self.params['nb_sample']:\n --> 189 self.progbar.update(self.seen, self.log_values)\n 190 \n 191 def on_epoch_end(self, epoch, logs={}):<\/p>\n \n

C:\\Anaconda3\\envs\\py27\\lib\\site-packages\\keras\\utils\\generic_utils.pyc\n in update(self, current, values)\n 110 info += ((prev_total_width - self.total_width) * \" \")\n 111 \n --> 112 sys.stdout.write(info)\n 113 sys.stdout.flush()\n 114 <\/p>\n \n

C:\\Anaconda3\\envs\\py27\\lib\\site-packages\\ipykernel\\iostream.pyc in\n write(self, string)\n 315 \n 316 is_child = (not self._is_master_process())\n --> 317 self._buffer.write(string)\n 318 if is_child:\n 319 # newlines imply flush in subprocesses<\/p>\n \n

ValueError: I\/O operation on closed file<\/p>\n<\/blockquote>\n","answers":[{"AnswerId":"36973018","CreationDate":"2016-05-01T23:10:41.993","ParentId":null,"OwnerUserId":"1536437","Title":null,"Body":"

Change your verbose level in \nmodel.fit()<\/code>\nto \n verbose=0.<\/code>
\nSee
github.com\/fchollet\/keras\/issues\/2110<\/a><\/p>\n\n

It's not a straight-on \"fix\", but it should help alleviate a race condition associated with updating of the iPython console.<\/p>\n"}]} {"QuestionId":36601019,"AnswerCount":1,"Tags":"","CreationDate":"2016-04-13T14:09:56.517","AcceptedAnswerId":36603279.0,"OwnerUserId":6151595.0,"Title":"Datatype class: H5T_FLOAT F0413 08:54:40.661201 17769 hdf5_data_layer.cpp:53] Check failed: hdf_blobs_[i] ->shape(0) == num (1 vs. 1024)","Body":"

My data set is a HDF5 file consists of with shape and of shape .
\nBut when I run solver.prototxt, I get the error message:<\/p>\n\n

\n
<\/pre>\n<\/blockquote>\n","answers":[{"AnswerId":"36603279","CreationDate":"2016-04-13T15:37:59.767","ParentId":null,"OwnerUserId":"1714410","Title":null,"Body":"

It looks like you saved your hdf5 from matlab, rather than python (judging by your previous question<\/a>).
\nWhen saving data from Matlab one has to remember that Matlab stores multi-dimensions arrays in memory in colums-first fashion (fortran style), while python, caffe and many other applications expects multi-dimension arrays in row-first fashion (C style).
\nThus, you need to permute<\/code> the data in matlab before saving it to hdf5 for caffe. See
this answer<\/a> for more details.<\/p>\n\n

I suspect that if you run h5ls<\/code> in shell on the hdf5 file you stored you'll notice that the shape of the stored arrays are actually<\/p>\n\n

data   [1024, 12, 1, 129028]\nlabel  [1, 1, 1, 129028]\n<\/code><\/pre>\n"}]}
{"QuestionId":36601526,"AnswerCount":0,"Tags":"","CreationDate":"2016-04-13T14:27:48.923","AcceptedAnswerId":null,"OwnerUserId":6199244.0,"Title":"Tensorflow Memory Issues with GPU","Body":"

I am completely new to Tensorflow. I have installed on RHEL7\/CUDA 7.5.18\/libcudnn\/4. <\/p>\n\n

When attempting to test the installation, I continue to get out of memory\/memory allocation errors <\/p>\n\n

<\/pre>\n\n

The install appears to work properly when I limit the processing to CPU's only () but, regardless of what memory limits I set, when executing with GPU's, I get memory errors.<\/p>\n\n


\n\n

I am attempting to test MINST demo model dataset get these memory issues (models\/image\/mnist\/convolutional.py)<\/p>\n\n

I humbly realize that this is most likely some naive config issue and would greatly appreciate any assistance anyone is willing to offer.<\/p>\n","answers":[]} {"QuestionId":36604815,"AnswerCount":1,"Tags":"","CreationDate":"2016-04-13T16:49:59.910","AcceptedAnswerId":null,"OwnerUserId":6185028.0,"Title":"Labels as a matrix in LMDB data using python","Body":"

I want to create a lmdb data in python where the labels are not scalars but each label is (1,K) vector and K is the number of classes. More specifically, the label vector has zeros everywhere except in the corresponding class index you have 1.<\/p>\n\n

I tested the following code in python:<\/p>\n\n

<\/pre>\n\n

But I got the this error where is a numpy (1,k) vector as described above.<\/p>\n\n

I am also wondering if caffe would accept such format of labels.<\/p>\n\n

Any help would be very appreciated<\/p>\n","answers":[{"AnswerId":"36614868","CreationDate":"2016-04-14T05:59:27.127","ParentId":null,"OwnerUserId":"4095689","Title":null,"Body":"

Yes, caffe supports transformation of numpy arrays to datum, then you can put the datum to lmdb.<\/p>\n\n

Using caffe.io.array_to_datum(numpy_array)<\/code> to transform a numpy_array to datum, NOTE that the numpy_array must have 4 axes, so if you want to put a vecttor into lmdb, you should initialize a numpy_array with shape [1,1,1,M], while M is the length of your vector.<\/p>\n\n

here<\/a> is a tool to write image\/map pairs to lmdb which can be feed to caffe networks.<\/p>\n"}]} {"QuestionId":36606885,"AnswerCount":1,"Tags":"","CreationDate":"2016-04-13T18:40:41.883","AcceptedAnswerId":null,"OwnerUserId":null,"Title":"Theano : Can we reuse compile files generated by theano?","Body":"

Uisng compile, Theano generates C++ code along with Cuda code and compiled lib.\nCan we reuse those ones after ?<\/p>\n","answers":[{"AnswerId":"36829111","CreationDate":"2016-04-24T21:30:33.773","ParentId":null,"OwnerUserId":"3688908","Title":null,"Body":"

You could<\/em> load them as a python module from the cache or just copy the code somewhere else and modify it to have a friendlier name.<\/p>\n\n

Also there is a project to have Theano produce a some C code for a library that I know works for some situations but has never really been finished. If you are interested in that I would ask on the theano-dev mailing list.<\/p>\n"}]} {"QuestionId":36609273,"AnswerCount":2,"Tags":"","CreationDate":"2016-04-13T20:47:04.597","AcceptedAnswerId":null,"OwnerUserId":815539.0,"Title":"TypeError: Inconsistency in the inner graph of scan 'scan_fn' .... 'TensorType(float64, col)' and 'TensorType(float64, matrix)'","Body":"

I'm getting the following error when I try to run my LSTM program (for variable length inputs). <\/p>\n\n

\n

TypeError: Inconsistency in the inner graph of scan 'scan_fn' : an\n input and an output are associated with the same recurrent state and\n should have the same type but have type 'TensorType(float64, col)' and\n 'TensorType(float64, matrix)' respectively.<\/p>\n<\/blockquote>\n\n

My program is based on the LSTM example for imdb sentiment analysis problem as in here: http:\/\/deeplearning.net\/tutorial\/lstm.html<\/a> . My data is not of imdb but it is sensor data.<\/p>\n\n

I shared my source code: lstm_var_length.py<\/strong><\/a> and data: data.npz<\/a><\/strong>. (Click on the files)<\/p>\n\n

From the error above and a few google searches made me understand that I have some issue with the vector\/matrix dimensions in my function. Below are the function definitions where this problem occurs: <\/p>\n\n

<\/pre>\n\n

The error above is caused when trying to compile f_pred_prob<\/strong> theano function.<\/p>\n\n

Exception and call stack is below: <\/p>\n\n

<\/pre>\n\n

I have been doing all the debugging for a week, but could not find the issue. I doubt the initializations at outputs_info in theano.scan to be the problem but when I delete the second dimension (1) I get an error in slice function even before getting to f_pred_prob<\/strong> function (near lstm_result<\/em>). I'm not sure where the problem lies.<\/p>\n\n

A simple execution of this program by placing the data file in the same directory as the python source file can recreate this issue.<\/p>\n\n

Please help me out.<\/p>\n\n

Thanks & Regards, \ninblueswithu<\/p>\n","answers":[{"AnswerId":"39955633","CreationDate":"2016-10-10T09:51:25.367","ParentId":null,"OwnerUserId":"6945117","Title":null,"Body":"

use<\/p>\n\n

outputs_info=[tensor.unbroadcast(tensor.alloc(numpy.asarray(0., dtype=floatX),\n                                              options['hidden_dim'], 1),1),\n              tensor.unbroadcast(tensor.alloc(numpy.asarray(0., dtype=floatX),\n                                              options['hidden_dim'], 1),1)]\n<\/code><\/pre>\n\n

instead of the original outputs_info.<\/p>\n\n

This is because the second dim of tensor.alloc(numpy.asarray(0., dtype=floatX),options['hidden_dim'], 1)<\/code> is 1, then theano automatically make it broadcastable, and wrap the tensor variable as col instead of matrix. This this the 'TensorType(float64, col)'<\/code> in the error message<\/p>\n\n

TypeError: Inconsistency in the inner graph of scan 'scan_fn' : an input and an output are associated with the same recurrent state and should have the same type but have type 'TensorType(float64, col)' and 'TensorType(float64, matrix)' respectively. \n<\/code><\/pre>\n\n

And theano.unbroadcast<\/code> avoids this problem.<\/p>\n"},{"AnswerId":"36632966","CreationDate":"2016-04-14T20:06:59.277","ParentId":null,"OwnerUserId":"815539","Title":null,"Body":"

I think, I found the issue. I had to recheck all the dimensions of the matrices. I still have to double check my code. Once I'm finished I'll put the new code.<\/p>\n\n

Thankyou.<\/p>\n"}]} {"QuestionId":36609309,"AnswerCount":0,"Tags":"","CreationDate":"2016-04-13T20:49:30.393","AcceptedAnswerId":null,"OwnerUserId":6198754.0,"Title":"TensorFlow optimization proceeds non-deterministically on GPU","Body":"

I'm using Google TensorFlow to fit a small, 2-layer net. I've noticed that when I use a GPU with AdamOptimizer or RMSPropOptimizer, the optimization proceeds non-deterministically. Even if I seed the graph with set_random_seed, the opt produces substantially different weights each time.<\/p>\n\n

The problem does not occur if I use other optimizers (e.g. GradientDescentOptimizer) or configure the graph to run on a CPU.<\/p>\n\n

Has anyone encountered similar behavior in TensorFlow or have any ideas on debugging the problem?<\/p>\n\n

I'm using TensorFlow 0.7.1 with a Nvidia Grid K520 GPU.<\/p>\n","answers":[]} {"QuestionId":36609920,"AnswerCount":2,"Tags":"","CreationDate":"2016-04-13T21:30:08.860","AcceptedAnswerId":null,"OwnerUserId":1624415.0,"Title":"TensorFlow using LSTMs for generating text","Body":"

I would like to use tensorflow to generate text and have been modifying the LSTM tutorial (https:\/\/www.tensorflow.org\/versions\/master\/tutorials\/recurrent\/index.html#recurrent-neural-networks<\/a>) code to do this, however my initial solution seems to generate nonsense, even after training for a long time, it does not improve. I fail to see why. The idea is to start with a zero matrix and then generate one word at a time.<\/p>\n\n

This is the code, to which I've added the two functions below\nhttps:\/\/tensorflow.googlesource.com\/tensorflow\/+\/master\/tensorflow\/models\/rnn\/ptb\/ptb_word_lm.py<\/a><\/p>\n\n

The generator looks as follows<\/p>\n\n

<\/pre>\n\n

I have added the variable \"probabilities\" to the ptb_model and it is simply a softmax over the logits.<\/p>\n\n

<\/pre>\n\n

And the sampling:<\/p>\n\n

<\/pre>\n","answers":[{"AnswerId":"37478520","CreationDate":"2016-05-27T08:26:34.017","ParentId":null,"OwnerUserId":"6389953","Title":null,"Body":"

I use your code, it seems not right. So I modify it a little, it seems work.\nHere is my code, and I'm not sure it is right:<\/p>\n\n

def generate_text(session,m,eval_op, word_list):\noutput = []\nfor i in xrange(20):\n    state = m.initial_state.eval()\n    x = np.zeros((1,1), dtype=np.int32)\n    y = np.zeros((1,1), dtype=np.int32)\n    output_str = \"\"\n    for step in xrange(100):\n        if True:\n            # Run the batch \n            # targets have to bee set but m is the validation model, thus it should not train the neural network\n            cost, state, _, probabilities = session.run([m.cost, m.final_state, eval_op, m.probabilities],\n                                                        {m.input_data: x, m.targets: y, m.initial_state: state})\n            # Sample a word-id and add it to the matrix and output\n            word_id = sample(probabilities[0,:])\n            if (word_id<0) or (word_id > len(word_list)):\n                continue\n            #print(word_id)\n            output_str = output_str + \" \" + word_list[word_id]\n            x[0][0] = word_id\n    print(output_str)\n    output.append(output_str)\nreturn output\n<\/code><\/pre>\n"},{"AnswerId":"38729349","CreationDate":"2016-08-02T19:53:15.393","ParentId":null,"OwnerUserId":"6332561","Title":null,"Body":"

I have been working toward the exact same goal, and just got it to work. You have many of the right modifications here, but I think you've missed a few steps.<\/p>\n\n

First, for generating text you need to create a different version of the model which represents only a single timestep. The reason is that we need to sample each output y before we can feed it into the next step of the model. I did this by making a new config which sets num_steps<\/code> and batch_size<\/code> both equal to 1.<\/p>\n\n

class SmallGenConfig(object):\n  \"\"\"Small config. for generation\"\"\"\n  init_scale = 0.1\n  learning_rate = 1.0\n  max_grad_norm = 5\n  num_layers = 2\n  num_steps = 1 # this is the main difference\n  hidden_size = 200\n  max_epoch = 4\n  max_max_epoch = 13\n  keep_prob = 1.0\n  lr_decay = 0.5\n  batch_size = 1\n  vocab_size = 10000\n<\/code><\/pre>\n\n

I also added a probabilities to the model with these lines:<\/p>\n\n

self._output_probs = tf.nn.softmax(logits)\n<\/code><\/pre>\n\n

and<\/p>\n\n

@property\ndef output_probs(self):\n  return self._output_probs\n<\/code><\/pre>\n\n

Then, there are a few differences in my generate_text()<\/code> function. The first one is that I load saved model parameters from disk using the tf.train.Saver()<\/code> object. Note that we do this after instantiating the PTBModel with the new config from above.<\/p>\n\n

def generate_text(train_path, model_path, num_sentences):\n  gen_config = SmallGenConfig()\n\n  with tf.Graph().as_default(), tf.Session() as session:\n    initializer = tf.random_uniform_initializer(-gen_config.init_scale,\n                                                gen_config.init_scale)    \n    with tf.variable_scope(\"model\", reuse=None, initializer=initializer):\n      m = PTBModel(is_training=False, config=gen_config)\n\n    # Restore variables from disk.\n    saver = tf.train.Saver() \n    saver.restore(session, model_path)\n    print(\"Model restored from file \" + model_path)\n<\/code><\/pre>\n\n

The second difference is that I get the lookup table from ids to word strings (I had to write this function, see the code below).<\/p>\n\n

    words = reader.get_vocab(train_path)\n<\/code><\/pre>\n\n

I set up the initial state the same way you do, but then I set up the initial token in a different manner. I want to use the \"end of sentence\" token so that I'll start my sentence with the right types of words. I looked through the word index and found that <eos><\/code> happens to have index 2 (deterministic) so I just hard-coded that in. Finally, I wrap it in a 1x1 Numpy Matrix so that it is the right type for the model inputs.<\/p>\n\n

    state = m.initial_state.eval()\n    x = 2 # the id for '<eos>' from the training set\n    input = np.matrix([[x]])  # a 2D numpy matrix \n<\/code><\/pre>\n\n

Finally, here's the part where we generate sentences. Note that we tell session.run()<\/code> to compute the output_probs<\/code> and the final_state<\/code>. And we give it the input and the state. In the first iteration the input is <eos><\/code> and the state is the initial_state<\/code>, but on subsequent iterations we give as input our last sampled output, and we pass the state along from the last iteration. Note also that we use the words<\/code> list to look up the word string from the output index.<\/p>\n\n

    text = \"\"\n    count = 0\n    while count < num_sentences:\n      output_probs, state = session.run([m.output_probs, m.final_state],\n                                   {m.input_data: input,\n                                    m.initial_state: state})\n      x = sample(output_probs[0], 0.9)\n      if words[x]==\"<eos>\":\n        text += \".\\n\\n\"\n        count += 1\n      else:\n        text += \" \" + words[x]\n      # now feed this new word as input into the next iteration\n      input = np.matrix([[x]]) \n<\/code><\/pre>\n\n

Then all we have to do is print out the text we accumulated.<\/p>\n\n

    print(text)\n  return\n<\/code><\/pre>\n\n

That's it for the generate_text()<\/code> function. <\/p>\n\n

Finally, let me show you the function definition for get_vocab()<\/code>, which I put in reader.py.<\/p>\n\n

def get_vocab(filename):\n  data = _read_words(filename)\n\n  counter = collections.Counter(data)\n  count_pairs = sorted(counter.items(), key=lambda x: (-x[1], x[0]))\n\n  words, _ = list(zip(*count_pairs))\n\n  return words\n<\/code><\/pre>\n\n

The last thing you need to do is to be able to save the model after training it, which looks like<\/p>\n\n

save_path = saver.save(session, \"\/tmp\/model.ckpt\")\n<\/code><\/pre>\n\n

And that's the model that you'll load from disk later when generating text.<\/p>\n\n

There was one more problem: I found that sometimes the probability distribution produced by the Tensorflow softmax function didn't sum exactly to 1.0. When the sum was larger than 1.0, np.random.multinomial()<\/code> throws an error. So I had to write my own sampling function, which looks like this<\/p>\n\n

def sample(a, temperature=1.0):\n  a = np.log(a) \/ temperature\n  a = np.exp(a) \/ np.sum(np.exp(a))\n  r = random.random() # range: [0,1)\n  total = 0.0\n  for i in range(len(a)):\n    total += a[i]\n    if total>r:\n      return i\n  return len(a)-1 \n<\/code><\/pre>\n\n

When you put all this together, the small model was able to generate me some cool sentences. Good luck.<\/p>\n"}]} {"QuestionId":36610290,"AnswerCount":2,"Tags":"","CreationDate":"2016-04-13T21:54:48.880","AcceptedAnswerId":null,"OwnerUserId":3691859.0,"Title":"Tensorflow and Multiprocessing: Passing Sessions","Body":"

I have recently been working on a project that uses a neural network for virtual robot control. I used tensorflow to code it up and it runs smoothly. So far, I used sequential simulations to evaluate how good the neural network is, however, I want to run several simulations in parallel<\/strong> to reduce the amount of time it takes to get data.<\/p>\n\n

To do this I am importing python's package. Initially I was passing the sess variable () to a function that would run the simulation. However, once I get to any statement that uses this variable, the process quits without a warning. After searching around for a bit I found these two posts:\nTensorflow: Passing a session to a python multiprocess<\/a>\nand Running multiple tensorflow sessions concurrently<\/a><\/p>\n\n

While they are highly related I haven't been able to figure out how to make it work. I tried creating a session for each individual process and assigning the weights of the neural net to its trainable parameters without success. I've also tried saving the session into a file and then loading it within a process, but no luck there either.<\/p>\n\n

Has someone been able to pass a session (or clones of sessions) to several processes?<\/p>\n\n

Thanks.<\/p>\n","answers":[{"AnswerId":"54562773","CreationDate":"2019-02-06T21:26:01.070","ParentId":null,"OwnerUserId":"7858504","Title":null,"Body":"

You can't use Python multiprocessing to pass a TensorFlow Session<\/code> into a multiprocessing.Pool<\/code> in the straightfoward way because the Session<\/code> object can't be pickled (it's fundamentally not serializable because it may manage GPU memory and state like that).<\/p>\n\n

I'd suggest parallelizing the code using actors<\/a>, which are essentially the parallel computing analog of \"objects\" and use used to manage state in the distributed setting.<\/p>\n\n

Ray<\/a> is a good framework for doing this. You can define a Python class which manages the TensorFlow Session<\/code> and exposes a method for running your simulation.<\/p>\n\n

import ray\nimport tensorflow as tf\n\nray.init()\n\n@ray.remote\nclass Simulator(object):\n    def __init__(self):\n        self.sess = tf.Session()\n        self.simple_model = tf.constant([1.0])\n\n    def simulate(self):\n        return self.sess.run(self.simple_model)\n\n# Create two actors.\nsimulators = [Simulator.remote() for _ in range(2)]\n\n# Run two simulations in parallel.\nresults = ray.get([s.simulate.remote() for s in simulators])\n<\/code><\/pre>\n\n

Here are a few more examples of parallelizing TensorFlow with Ray<\/a>.<\/p>\n\n

See the Ray documentation<\/a>. Note that I'm one of the Ray developers.<\/p>\n"},{"AnswerId":"46779776","CreationDate":"2017-10-16T22:05:03.393","ParentId":null,"OwnerUserId":"5683778","Title":null,"Body":"

I use keras as a wrapper with tensorflow as a backed, but the same general principal should apply.<\/p>\n\n

If you try something like this:<\/p>\n\n

import keras\nfrom functools import partial\nfrom multiprocessing import Pool\n\ndef ModelFunc(i,SomeData):\n    YourModel = Here\n    return(ModelScore)\n\npool = Pool(processes = 4)\nfor i,Score in enumerate(pool.imap(partial(ModelFunc,SomeData),range(4))):\n    print(Score)\n<\/code><\/pre>\n\n

It will fail. However, if you try something like this: <\/p>\n\n

from functools import partial\nfrom multiprocessing import Pool\n\ndef ModelFunc(i,SomeData):\n    import keras\n    YourModel = Here\n    return(ModelScore)\n\npool = Pool(processes = 4)\nfor i,Score in enumerate(pool.imap(partial(ModelFunc,SomeData),range(4))):\n    print(Score)\n<\/code><\/pre>\n\n

It should work. Try calling tensorflow separately for each process.<\/p>\n"}]} {"QuestionId":36610789,"AnswerCount":1,"Tags":"","CreationDate":"2016-04-13T22:38:01.450","AcceptedAnswerId":36636014.0,"OwnerUserId":2662629.0,"Title":"Decoding multiple sentences in tensorflow with respect to the sentence dependencies","Body":"

the function in the file from the github<\/a> contains the line <\/p>\n\n

In this example I want to decode not one, but three sentences:<\/p>\n\n

    \n
  1. This is todays MovieWorld cinema schedule.<\/li>\n
  2. Look for the special offers available for gold member.<\/li>\n
  3. After your visit, please return the 3D glasses.<\/li>\n<\/ol>\n\n

    Now, how can I make sure that the decoding function takes the dependencies among the sentences into account? I want the model to take sentence 1 into account, when decoding sentence 2 and 3.<\/p>\n\n

    Do I only have to change the or anything else as well?<\/p>\n","answers":[{"AnswerId":"36636014","CreationDate":"2016-04-14T23:53:34.387","ParentId":null,"OwnerUserId":"2878004","Title":null,"Body":"

    Neural translation models are usually trained to do one sentence at a time. That means that there would be little advantage in decoding the three sentences all together. If you wnat to do that though you can try concatenating them into a single string comprised of three sentences and then decoding it.<\/p>\n"}]} {"QuestionId":36612247,"AnswerCount":0,"Tags":"","CreationDate":"2016-04-14T01:21:56.473","AcceptedAnswerId":null,"OwnerUserId":378469.0,"Title":"Is it possible to make tensorflow raise an error on invalid flag?","Body":"

    I can't find any documentation for tf.app.flags, but I see that the command line parser will happily accept invalid syntax, flags that have never been defined, etc. Is there a way to configure it to raise an error in these cases? I wasted a lot of time trying to figure out why decreasing my learning rate didn't help when the problem was just that I had typed \"-learning_rate\" instead of \"--learning_rate\".<\/p>\n","answers":[]} {"QuestionId":36612512,"AnswerCount":3,"Tags":"","CreationDate":"2016-04-14T01:56:13.247","AcceptedAnswerId":36784246.0,"OwnerUserId":3618299.0,"Title":"Tensorflow: How to get a tensor by name?","Body":"

    I'm having trouble recovering a tensor by name, I don't even know if it's possible.<\/p>\n\n

    I have a function that creates my graph:<\/p>\n\n

    <\/pre>\n\n

    I want to access the variable S1_conv1 outside this function. I tried:<\/p>\n\n

    <\/pre>\n\n

    But that is giving me an error:<\/p>\n\n

    ValueError: Under-sharing: Variable scale_1\/Scale1_first_relu does not exist, disallowed. Did you mean to set reuse=None in VarScope?<\/p>\n\n

    But this works:<\/p>\n\n

    <\/pre>\n\n

    I can get around this with<\/p>\n\n

    <\/pre>\n\n

    but I don't want to do that.<\/p>\n\n

    I think my problem is that S1_conv1 is not really a variable, it's just a tensor. Is there a way to do what I want?<\/p>\n","answers":[{"AnswerId":"36784246","CreationDate":"2016-04-22T03:22:56.553","ParentId":null,"OwnerUserId":"6238570","Title":null,"Body":"

    There is a function tf.Graph.get_tensor_by_name(). For instance:<\/p>\n\n

    import tensorflow as tf\n\nc = tf.constant([[1.0, 2.0], [3.0, 4.0]])\nd = tf.constant([[1.0, 1.0], [0.0, 1.0]])\ne = tf.matmul(c, d, name='example')\n\nwith tf.Session() as sess:\n    test =  sess.run(e)\n    print e.name #example:0\n    test = tf.get_default_graph().get_tensor_by_name(\"example:0\")\n    print test #Tensor(\"example:0\", shape=(2, 2), dtype=float32)\n<\/code><\/pre>\n"},{"AnswerId":"36613748","CreationDate":"2016-04-14T04:12:14.507","ParentId":null,"OwnerUserId":"419116","Title":null,"Body":"

    All tensors have string names which you can see as follows<\/p>\n\n

    [tensor.name for tensor in tf.get_default_graph().as_graph_def().node]\n<\/code><\/pre>\n\n

    Once you know the name you can fetch the Tensor using <name>:0<\/code> (0 refers to endpoint which is somewhat redundant)<\/p>\n\n

    For instance if you do this<\/p>\n\n

    tf.constant(1)+tf.constant(2)\n<\/code><\/pre>\n\n

    You have the following Tensor names<\/p>\n\n

    [u'Const', u'Const_1', u'add']\n<\/code><\/pre>\n\n

    So you can fetch output of addition as<\/p>\n\n

    sess.run('add:0')\n<\/code><\/pre>\n\n

    Note, this is part not part of public API. Automatically generated string tensor names are an implementation detail and may change.<\/p>\n"},{"AnswerId":"52700081","CreationDate":"2018-10-08T10:16:48.367","ParentId":null,"OwnerUserId":"8584587","Title":null,"Body":"

    All you gotta do in this case is:<\/p>\n\n

    ft=tf.get_variable('scale1\/Scale1_first_relu:0')\n<\/code><\/pre>\n"}]}
    {"QuestionId":36615004,"AnswerCount":3,"Tags":"","CreationDate":"2016-04-14T06:08:49.490","AcceptedAnswerId":36705471.0,"OwnerUserId":3781180.0,"Title":"Tensorflow visualizer \"Tensorboard\" not working under Anaconda","Body":"

    I'm currently using tensorflow and I want to visualize the effect of the convolutional neural network that I'm writing. However, I can't use tensorboard. I see the tensorboard underneath my conda env as envs\/tensorenv\/bin\/tensorboard (python file). It imports this thing called tensorflow.tensorboard.tensorboard that it can't find.<\/p>\n\n\n\n

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