diff --git "a/data.json" "b/data.json" --- "a/data.json" +++ "b/data.json" @@ -3304,5 +3304,1655 @@ "input": "", "output": "

len(dataloader) returns the total number of batches. It depends on the __len__ function of your dataset, so make sure it is set correctly.

\n", "system": "" + }, + { + "instruction": "What does TensorFlow's `conv2d_transpose()` operation do?", + "input": "", + "output": "

This is the best explanation I've seen online how convolution transpose works is here.

\n\n

I'll give my own short description. It applies convolution with a fractional stride. In other words spacing out the input values (with zeroes) to apply the filter over a region that's potentially smaller than the filter size.

\n\n

As for the why one would want to use it. It can be used as a sort of upsampling with learned weights as opposed to bilinear interpolation or some other fixed form of upsampling.

\n", + "system": "" + }, + { + "instruction": "How can I visualize the weights(variables) in cnn in Tensorflow?", + "input": "", + "output": "

To visualize the weights, you can use a tf.image_summary() op to transform a convolutional filter (or a slice of a filter) into a summary proto, write them to a log using a tf.train.SummaryWriter, and visualize the log using TensorBoard.

\n\n

Let's say you have the following (simplified) program:

\n\n
filter = tf.Variable(tf.truncated_normal([8, 8, 3]))\nimages = tf.placeholder(tf.float32, shape=[None, 28, 28])\n\nconv = tf.nn.conv2d(images, filter, strides=[1, 1, 1, 1], padding=\"SAME\")\n\n# More ops...\nloss = ...\noptimizer = tf.GradientDescentOptimizer(0.01)\ntrain_op = optimizer.minimize(loss)\n\nfilter_summary = tf.image_summary(filter)\n\nsess = tf.Session()\nsummary_writer = tf.train.SummaryWriter('/tmp/logs', sess.graph_def)\nfor i in range(10000):\n  sess.run(train_op)\n  if i % 10 == 0:\n    # Log a summary every 10 steps.\n    summary_writer.add_summary(filter_summary, i)\n
\n\n

After doing this, you can start TensorBoard to visualize the logs in /tmp/logs, and you will be able to see a visualization of the filter.

\n\n

Note that this trick visualizes depth-3 filters as RGB images (to match the channels of the input image). If you have deeper filters, or they don't make sense to interpret as color channels, you can use the tf.split() op to split the filter on the depth dimension, and generate one image summary per depth.

\n", + "system": "" + }, + { + "instruction": "Error while importing Tensorflow in Python 2.7 in Ubuntu 12.04. 'GLIBC_2.17 not found'", + "input": "", + "output": "

I've just managed to install tensorflow 0.12rc0 on CentOS 6.5 with glibc 2.12, without having root privileges. Simply installing tensorflow binary via pip was giving me an error, related to GLIBC version as well.

\n\n

Basically, you have 4 options how to deal with this (each with some advantages and disadvantages):

\n\n

Option 1 - Upgrade your system GLIBC globally.

\n\n

This is, probably, the best option, if your system supports this, you have root privileges, and you are confident that this upgrade won't break anything for some weird reason. Ultimately, this goes up to upgrading the whole Linux distribution. Here's a nice short list of default GLIBC versions on popular distributions.

\n\n

Option 2 - Add second GLIBC to your system

\n\n

Compile or download binary. The most simple&straightforward option. Especially if you only need to run few simple scripts.

\n\n\n\n

Option 3 - Patch tensorflow

\n\n

This may work for TF 0.6.0, but you would probably have to start again from scratch, when each new tensorflow version is released. E.g. here's a fix for 0.9.0.

\n\n

Option 4 - Compile tensorflow from source

\n\n

If you re-compile it from source and link against your existing GLIBC, newer GLIBC would be no longer needed. Somehow, this option was not mentioned in any answer here yet. Imho, this is the best option, both \"in general\", and \"specifically for tensorflow\".

\n\n\n\n

A quick summary of \"building tensorflow on outdated system\":

\n\n

Although the official guide provides a \"installing from sources\" section, there are few tricks you need to do to build it on an outdated system. Here I assume, that you do not have root privileges (if you do - you probably would be able to install the same pre-requestities with a package manager, rather them manually building them from source).

\n\n

I found two well-documented success stories: #1, #2 and a number of useful posts on the official github (mostly about a set of libraries to link inside the binary): #1, #2, #3, #4. I had to combine tricks, described there to successfully compile TF in my case.

\n\n
    \n
  1. First of all, check your gcc --version, and verify that it supports c++11. Mine was 4.4.7, so it won't work. I've downloaded gcc-4.9.4 source code, and compiled it. This step is pretty straightforward, but the compilation itself may take few hours. As a workaround for an issue in bazel, I've compiled gcc with hardcoded paths to as,ld and nm. However, you may try another workarounds: (1, 2).

    \n\n
    #!/bin/sh\n\nunset LIBRARY_PATH CPATH C_INCLUDE_PATH \nunset PKG_CONFIG_PATH CPLUS_INCLUDE_PATH INCLUDE LD_LIBRARY_PATH\n\ncd gcc-4.9.4\n./contrib/download_prerequisites\n\nmkdir objdir\ncd objdir\n\n\n# I've added --disable-multilib to fix the following error:\n# /usr/bin/ld: crt1.o: No such file: No such file or directory\n# collect2: ld returned 1 exit status\n# configure: error: I suspect your system does not have 32-bit \n# developement libraries (libc and headers). If you have them,\n# rerun configure with --enable-multilib. If you do not have them, \n# and want to build a 64-bit-only compiler, rerun configure \n# with --disable-multilib.           \n\n../configure --prefix=$HOME/opt/gcc-4.9.4 \\\n             --disable-multilib \\\n             --disable-nls \\\n             --enable-languages=c,c++ \\\n             --with-ld=/usr/bin/ld \\\n             --with-nm=/usr/bin/nm \\\n             --with-as=/usr/bin/as\n\nmake        \nmake install\n
  2. \n
  3. Check your java --version. Bazel requires JDK 8, install it if necessary. (They still provide some jdk7 related downloads, for bazel-0.4.1 but it looks like they consider it deprecated)

  4. \n
  5. I've created a separate use_gcc_4.9.4.sh file, with necessary environment variables. I use source ./use_gcc_4.9.4.sh when I need to so something related to this newer compiler.

    \n\n
    #!/bin/sh\nthis=$HOME/opt/gcc-4.9.4\nexport PATH=$this/bin:$PATH\nexport CPATH=$this/include:$CPATH\nexport LIBRARY_PATH=$this/lib:$LIBRARY_PATH\nexport LIBRARY_PATH=$this/lib64:$LIBRARY_PATH\nexport LD_LIBRARY_PATH=$this/lib:$LD_LIBRARY_PATH\nexport LD_LIBRARY_PATH=$this/lib64:$LD_LIBRARY_PATH\n
  6. \n
  7. The current bazel binary (0.4.1) requires GLIBC 2.14, so we have to compile bazel from source as well (with our new gcc). Works OK, unless you are only allowed to run a very limited number of threads on the target machine. (This post describes some additional workarounds, but in my case they were not needed, maybe due to recent updates in bazel code.)

  8. \n
  9. Obtain tensorflow source code git clone https://github.com/tensorflow/tensorflow, and install prerequisites you need (CUDA,cuDNN,python, etc). See official guide.

  10. \n
  11. If you're not using default system gcc (e.g. if you had to compile newer gcc, like discussed above), add the following linker flags to tensorflow/third_party/gpus/crosstool/CROSSTOOL.tpl, line 59:

    \n\n
    linker_flag: \"-L/home/username/localinst/opt/gcc-4.9.4/lib64\"\nlinker_flag: \"-Wl,-rpath,/home/username/localinst/opt/gcc-4.9.4/lib64\"\n
    \n\n

    Without this step, you would likely run into error messages like this:

    \n\n
    # ERROR: /home/username/localdistr/src/tensorflow/tensorflow/tensorflow/core/debug/BUILD:33:1: null failed: protoc failed: error executing command bazel-out/host/bin/external/protobuf/protoc '--cpp_out=bazel-out/local_linux-py3-opt/genfiles/' '--plugin=protoc-gen-grpc=bazel-out/host/bin/external/grpc/grpc_cpp_plugin' ... (remaining 8 argument(s) skipped): com.google.devtools.build.lib.shell.BadExitStatusException: Process exited with status 1.\n# bazel-out/host/bin/external/protobuf/protoc: /usr/lib64/libstdc++.so.6: version `GLIBCXX_3.4.20' not found (required by bazel-out/host/bin/external/protobuf/protoc)\n# bazel-out/host/bin/external/protobuf/protoc: /usr/lib64/libstdc++.so.6: version `CXXABI_1.3.8' not found (required by bazel-out/host/bin/external/protobuf/protoc)\n# bazel-out/host/bin/external/protobuf/protoc: /usr/lib64/libstdc++.so.6: version `GLIBCXX_3.4.18' not found (required by bazel-out/host/bin/external/protobuf/protoc)\n
  12. \n
  13. Finally, to avoid GLIBC dependencies, we have to statically link some libraries, by adding the -lrt linker flag (maybe -lm as well). I found multiple posts, suggesting to add this in a different manner:

    \n\n\n\n

    Without -lrt I ran into GLIBC-version-specific error again, trying to import tensorflow:

    \n\n
    # ImportError: /lib64/libc.so.6: version `GLIBC_2.14' not found (required by /home/username/anaconda3/envs/myenvname/lib/python3.5/site-packages/tensorflow/python/_pywrap_tensorflow.so)\n
    \n\n

    Without -lm you may run into this (for me, it turned out to be not necessary).

  14. \n
  15. Run the build process.

  16. \n
\n\n
    source ./use_gcc_4.9.4.sh\n    ./configure\n    bazel build -c opt --config=cuda //tensorflow/tools/pip_package:build_pip_package\n    bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg\n    pip install --upgrade /tmp/tensorflow_pkg/tensorflow-0.12.0rc0-cp35-cp35m-linux_x86_64.whl\n
\n\n
    \n
  1. Try to run the following simple python script to test if the most basic stuff is functioning:

    \n\n
    import tensorflow as tf\nhello = tf.constant('Hello, TensorFlow!')\nsess = tf.Session()\nprint(sess.run(hello))\n\na = tf.constant(10)\nb = tf.constant(32)\nprint(sess.run(a + b))\n
  2. \n
\n", + "system": "" + }, + { + "instruction": "Error importing tensorflow "AlreadyExistsError: Another metric with the same name already exists."", + "input": "", + "output": "

TL;DR: Ensure the Keras version matches the Tensorflow version

\n

I am experiencing the same thing with:

\n\n

The core issue appears to be that there are two Keras packages installed:

\n
<site-packages>/keras\n<site-packages/tensorflow/python/keras\n
\n

If you look at the release notes for 2.6:\nhttps://github.com/tensorflow/tensorflow/releases/tag/v2.6.0

\n
\n

Keras been split into a separate PIP package (keras), and its code has\nbeen moved to the GitHub repositorykeras-team/keras. The API endpoints\nfor tf.keras stay unchanged, but are now backed by the keras PIP\npackage. The existing code in tensorflow/python/keras is a staled copy\nand will be removed in future release (2.7). Please remove any imports\nto tensorflow.python.keras and replace them with public tf.keras API\ninstead.

\n
\n

For some reason, it is still importing from both packages which is triggering the valid exception (only one Keras instance should be imported)

\n

Digging a bit further, it looks like Keras-2.7 was being installed, reverting to Keras-2.6 resolved the issue:

\n
pip install keras==2.6.*\n
\n

For some reason:\nhttps://github.com/tensorflow/tensorflow/blob/v2.6.1/tensorflow/tools/pip_package/setup.py#L106

\n

Is not working, maybe a bug in PIP?

\n", + "system": "" + }, + { + "instruction": "Difference between installation libraries of Tensorflow GPU vs CPU", + "input": "", + "output": "

Updated answer 2023 (Tensorflow 2.x and above:)

\n

Verify the CPU setup:

\n
python3 -c "import tensorflow as tf; print(tf.reduce_sum(tf.random.normal([100, 100])))"\n
\n

If a tensor is returned, you've installed TensorFlow successfully.

\n

Verify the GPU setup:

\n
python3 -c "import tensorflow as tf; print(tf.config.list_physical_devices('GPU'))"\n
\n

If a list of GPU devices is returned, you've installed TensorFlow successfully.

\n

Source: Tensorflow installation guide

\n

Old answer(Tensorflow 1.x):

\n

One thing to Note: CUDA can be installed even if you don't have a GPU in your system.

\n

For packages tensorflow and tensorflow-gpu I hope this clears the confusion. yes/no means "Will the package work out of the box when executing import tensorflow as tf"? Here are the differences:

\n
| Support for TensorFlow libraries | tensorflow | tensorflow-gpu  |\n| for hardware type:               |    tf      |     tf-gpu      |\n|----------------------------------|------------|-----------------|\n| cpu-only                         |    yes     |   no (~tf-like) |\n| gpu with cuda+cudnn installed    |    yes     |   yes           |\n| gpu without cuda+cudnn installed |    yes     |   no (~tf-like) |\n
\n

Edit: Confirmed the no answers on a cpu-only system and the gpu without cuda+cudnn installed (by removing CUDA+CuDNN env variables).

\n

~tf-like means even though the library is tensorflow-gpu, it would behave like tensorflow library.

\n", + "system": "" + }, + { + "instruction": "Tensorflow : logits and labels must have the same first dimension", + "input": "", + "output": "

The problem is in your target shape and is related to the correct choice of an appropriate loss function. you have 2 possibilities:

\n

1. possibility: if you have 1D integer encoded target, you can use sparse_categorical_crossentropy as loss function

\n
n_class = 3\nn_features = 100\nn_sample = 1000\n\nX = np.random.randint(0,10, (n_sample,n_features))\ny = np.random.randint(0,n_class, n_sample)\n\ninp = Input((n_features,))\nx = Dense(128, activation='relu')(inp)\nout = Dense(n_class, activation='softmax')(x)\n\nmodel = Model(inp, out)\nmodel.compile(loss='sparse_categorical_crossentropy',optimizer='adam',metrics=['accuracy'])\nhistory = model.fit(X, y, epochs=3)\n
\n

2. possibility: if you have one-hot encoded your target in order to have 2D shape (n_samples, n_class), you can use categorical_crossentropy

\n
n_class = 3\nn_features = 100\nn_sample = 1000\n\nX = np.random.randint(0,10, (n_sample,n_features))\ny = pd.get_dummies(np.random.randint(0,n_class, n_sample)).values\n\ninp = Input((n_features,))\nx = Dense(128, activation='relu')(inp)\nout = Dense(n_class, activation='softmax')(x)\n\nmodel = Model(inp, out)\nmodel.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])\nhistory = model.fit(X, y, epochs=3)\n
\n", + "system": "" + }, + { + "instruction": "Use shared GPU memory with TensorFlow?", + "input": "", + "output": "

Shared memory is an area of the main system RAM reserved for graphics. References:

\n\n

https://en.wikipedia.org/wiki/Shared_graphics_memory

\n\n

https://www.makeuseof.com/tag/can-shared-graphics-finally-compete-with-a-dedicated-graphics-card/

\n\n

https://youtube.com/watch?v=E5WyJY1zwcQ

\n\n

This type of memory is what integrated graphics eg Intel HD series typically use.

\n\n

This is not on your NVIDIA GPU, and CUDA can't use it. Tensorflow can't use it when running on GPU because CUDA can't use it, and also when running on CPU because it's reserved for graphics.

\n\n

Even if CUDA could use it somehow. It won't be useful because system RAM bandwidth is around 10x less than GPU memory bandwidth, and you have to somehow get the data to and from the GPU over the slow (and high latency) PCIE bus.

\n\n

Bandwidth numbers for reference :\nGeForce GTX 980: 224 GB/s\nDDR4 on desktop motherboard: approx 25GB/s\nPCIe 16x: 16GB/s

\n\n

This doesn't take into account latency. In practice, running a GPU compute task on data which is too big to fit in GPU memory and has to be transferred over PCIe every time it is accessed is so slow for most types of compute that doing the same calculation on CPU would be much faster.

\n\n

Why do you see that kind of memory being allocated when you have a NVIDIA card in your machine? Good question. I can think of a couple of possibilities:

\n\n

(a) You have both NVIDIA and Intel graphics drivers active (eg as happens when running different displays on both). Uninstaller the Intel drivers and/or disable Intel HD graphics in the BIOS and shared memory will disappear.

\n\n

(b) NVIDIA is using it. This may be eg extra texture memory, etc. It could also not be real memory but just a memory mapped area that corresponds to GPU memory. Look in the advanced settings of the NVIDIA driver for a setting that controls this.

\n\n

In any case, no, there isn't anything that Tensorflow can use.

\n", + "system": "" + }, + { + "instruction": "Where should pre-processing and post-processing steps be executed when a TF model is served using TensorFlow serving?", + "input": "", + "output": "

I'm running over the same issue here, even if I'm not 100% sure yet on how to use the wordDict variable (I guess you use one too to map the words with its ids), the main pre-process and post-process functions are defined here:

\n\n

https://www.tensorflow.org/programmers_guide/saved_model

\n\n

as export_outputs and serving_input_receiver_fn.

\n\n\n\n

Needs to be defined in EstimatorSpec if you are using estimators. Here is an example for a classification algorithm

\n\n
  predicted_classes = tf.argmax(logits, 1)\n  categories_tensor = tf.convert_to_tensor(CATEGORIES, tf.string)\n  export_outputs = { \"categories\": export_output.ClassificationOutput(classes=categories_tensor) }\n  if mode == tf.estimator.ModeKeys.PREDICT:\n    return tf.estimator.EstimatorSpec(\n        mode=mode,\n        predictions={\n            'class': predicted_classes,\n            'prob': tf.nn.softmax(logits)\n        },\n        export_outputs=export_outputs)\n
\n\n\n\n

It needs to be defined on before exporting the trained estimator model, it assumes the input is a raw string and parses your input from there, you can write your own function but I'm unsure whenever you can use external variables. Here is a simple example for a classification algorithm:

\n\n
def serving_input_receiver_fn():\n    feature_spec = { \"words\": tf.FixedLenFeature(dtype=tf.int64, shape=[4]) }\n    return tf.estimator.export.build_parsing_serving_input_receiver_fn(feature_spec)()\n\n  export_dir = classifier.export_savedmodel(export_dir_base=args.job_dir,\n                                            serving_input_receiver_fn=serving_input_receiver_fn)\n
\n\n

hope it helps.

\n", + "system": "" + }, + { + "instruction": "How to disable printing reports after each epoch in Keras?", + "input": "", + "output": "

Set verbose=0 to the fit method of your model.

\n", + "system": "" + }, + { + "instruction": "What is the relationship between steps and epochs in TensorFlow?", + "input": "", + "output": "

TL;DR: An epoch is when your model goes through your whole training data once. A step is when your model trains on a single batch (or a single sample if you send samples one by one). Training for 5 epochs on a 1000 samples 10 samples per batch will take 500 steps.

\n\n

The contrib.learn.io module is not documented very well, but it seems that numpy_input_fn() function takes some numpy arrays and batches them together as input for a classificator. So, the number of epochs probably means \"how many times to go through the input data I have before stopping\". In this case, they feed two arrays of length 4 in 4 element batches, so it will just mean that the input function will do this at most a 1000 times before raising an \"out of data\" exception. The steps argument in the estimator fit() function is how many times should estimator do the training loop. This particular example is somewhat perverse, so let me make up another one to make things a bit clearer (hopefully).

\n\n

Lets say you have two numpy arrays (samples and labels) that you want to train on. They are a 100 elements each. You want your training to take batches with 10 samples per batch. So after 10 batches you will go through all of your training data. That is one epoch. If you set your input generator to 10 epochs, it will go through your training set 10 times before stopping, that is it will generate at most a 100 batches.

\n\n

Again, the io module is not documented, but considering how other input related APIs in tensorflow work, it should be possible to make it generate data for unlimited number of epochs, so the only thing controlling the length of training are going to be the steps. This gives you some extra flexibility on how you want your training to progress. You can go a number of epochs at a time or a number of steps at a time or both or whatever.

\n", + "system": "" + }, + { + "instruction": "Faster RCNN for TensorFlow", + "input": "", + "output": "

Tensorflow has just released an official Object Detection API here, that can be used for instance with their various slim models.

\n\n

This API contains implementation of various Pipelines for Object Detection, including popular Faster RCNN, with their pre-trained models as well.

\n", + "system": "" + }, + { + "instruction": "Tensor flow toggle between CPU/GPU", + "input": "", + "output": "

To make GPU invisible

\n\n
export CUDA_VISIBLE_DEVICES=\"\"\n
\n\n

To return to normal

\n\n
unset CUDA_VISIBLE_DEVICES\n
\n", + "system": "" + }, + { + "instruction": "Choosing between GeForce or Quadro GPUs to do machine learning via TensorFlow", + "input": "", + "output": "

I think GeForce TITAN is great and is widely used in Machine Learning (ML). In ML, single precision is enough in most of cases.

\n\n

More detail on the performance of the GTX line (currently GeForce 10) can be found in Wikipedia, here.

\n\n

Other sources around the web support this claim. Here is a quote from doc-ok in 2013 (permalink).

\n\n
\n

For comparison, an \u201centry-level\u201d $700 Quadro 4000 is significantly slower than a $530 high-end GeForce GTX 680, at least according to my measurements using several Vrui applications, and the closest performance-equivalent to a GeForce GTX 680 I could find was a Quadro 6000 for a whopping $3660.

\n
\n\n

Specific to ML, including deep learning, there is a Kaggle forum discussion dedicated to this subject (Dec 2014, permalink), which goes over comparisons between the Quadro, GeForce, and Tesla series:

\n\n
\n

Quadro GPUs aren't for scientific computation, Tesla GPUs are. Quadro\n cards are designed for accelerating CAD, so they won't help you to\n train neural nets. They can probably be used for that purpose just\n fine, but it's a waste of money.

\n \n

Tesla cards are for scientific computation, but they tend to be pretty\n expensive. The good news is that many of the features offered by Tesla\n cards over GeForce cards are not necessary to train neural networks.

\n \n

For example, Tesla cards usually have ECC memory, which is nice to\n have but not a requirement. They also have much better support for\n double precision computations, but single precision is plenty for\n neural network training, and they perform about the same as GeForce\n cards for that.

\n \n

One useful feature of Tesla cards is that they tend to have is a lot\n more RAM than comparable GeForce cards. More RAM is always welcome if\n you're planning to train bigger models (or use RAM-intensive\n computations like FFT-based convolutions).

\n \n

If you're choosing between Quadro and GeForce, definitely pick\n GeForce. If you're choosing between Tesla and GeForce, pick GeForce,\n unless you have a lot of money and could really use the extra RAM.

\n
\n\n

NOTE: Be careful what platform you are working on and what the default precision is in it. For example, here in the CUDA forums (August 2016), one developer owns two Titan X's (GeForce series) and doesn't see a performance gain in any of their R or Python scripts. This is diagnosed as a result of R being defaulted to double precision, and has a worse performance on new GPU than their CPU (a Xeon processor). Tesla GPUs are cited as the best performance for double precision. In this case, converting all numbers to float32 increases performance from 12.437s with nvBLAS 0.324s with gmatrix+float32s on one TITAN X (see first benchmark). Quoting from this forum discussion:

\n\n
\n

Double precision performance of Titan X is pretty low.

\n
\n", + "system": "" + }, + { + "instruction": "Where is the folder for Installing tensorflow with pip, Mac OSX?", + "input": "", + "output": "

Installing with pip, installs the packages to the directory \"site-packages\".

\n\n

The following code shows the location of tensorflow as well as where pip installs the packages:

\n\n
$ pip show tensorflow\n
\n\n

Which return:

\n\n
Metadata-Version: 2.0\nName: tensorflow\nVersion: 0.5.0\nSummary: TensorFlow helps the tensors flow\nHome-page: http://tensorflow.com/\nAuthor: Google Inc.\nAuthor-email: opensource@google.com\nLicense: Apache 2.0\nLocation: /usr/local/lib/python2.7/site-packages\nRequires: six, numpy\n
\n\n

here Location: shows where the package is installed with

\n\n
$ cd /usr/local/lib/python2.7/site-packages/tensorflow\n
\n\n
\n\n

EDIT:

\n\n

As some people pointed out in the newer versions of tensorflow and depending on the $ echo $TENSORFLOW you need to look in either

\n\n
$ cd /usr/local/lib/python{2,3}.X/{site,dist}-packages/tensorflow\n
\n\n

Or

\n\n
$ cd /usr/local/lib/python2.7/dist-packages/tensorflow/include/tensorflow/core/framework\n
\n", + "system": "" + }, + { + "instruction": "AttributeError: module 'setuptools._distutils' has no attribute 'version'", + "input": "", + "output": "

This is a known bug which has been patched: https://github.com/pytorch/pytorch/pull/69904

\n

You can either use the nightly-release of PyTorch, or otherwise downgrade setup tools to setuptools version 59.5.0:

\n

pip install setuptools==59.5.0

\n", + "system": "" + }, + { + "instruction": "Tensorflow tf.data AUTOTUNE", + "input": "", + "output": "

tf.data builds a performance model of the input pipeline and runs an optimization algorithm to find a good allocation of its CPU budget across all parameters specified as AUTOTUNE. While the input pipeline is running, tf.data tracks the time spent in each operation, so that these times can be fed into the optimization algorithm.

\n

The OptimizationOptions object gives some control over how autotune will behave.

\n", + "system": "" + }, + { + "instruction": "Machine Learning : Tensorflow v/s Tensorflow.js v/s Brain.js", + "input": "", + "output": "

The speeds are different: Tensorflow > tfjs > brainjs. Python can be directly compiled to machine code and directly use the CPU and GPU, whereas tfjs is a script-language which is being compiled on the client and has to use the <canvas> in the browser to access the GPU the same as brain.js (I am not sure if brain.js is GPU-accelerated)

\n\n

Another thing is that tensorflow is a whole ecosystem, which is kept in sync with each different version for the different platforms, so it is really easy to port your python(keras) model to tfjs and if you know how to code a tensorflow-model you can do it in any language.

\n\n

And if you're using nodejs the only reason to stay with tfjs and not switch to python is that you like the JavaScript language better or you are forced to use because you are working in a JS backend.

\n\n

PS:\nA new library was just released (ML5), which is a wrapper for tfjs and adds a lot of stuff, which helps you to build and use models without having a deep machine learning background.

\n", + "system": "" + }, + { + "instruction": "What is the definition of a non-trainable parameter?", + "input": "", + "output": "

In keras, non-trainable parameters (as shown in model.summary()) means the number of weights that are not updated during training with backpropagation.

\n\n

There are mainly two types of non-trainable weights:

\n\n\n\n

Weights are the values inside the network that perform the operations and can be adjusted to result in what we want. The backpropagation algorithm changes the weights towards a lower error at the end.

\n\n

By default, all weights in a keras model are trainable.

\n\n

When you create layers, internally it creates its own weights and they're trainable. (The backpropagation algorithm will update these weights)

\n\n

When you make them untrainable, the algorithm will not update these weights anymore. This is useful, for instance, when you want a convolutional layer with a specific filter, like a Sobel filter, for instance. You don't want the training to change this operation, so these weights/filters should be kept constant.

\n\n

There is a lot of other reasons why you might want to make weights untrainable.

\n\n
\n\n

Changing parameters:

\n\n

For deciding whether weights are trainable or not, you take layers from the model and set trainable:

\n\n
model.get_layer(layerName).trainable = False #or True\n
\n\n

This must be done before compilation.

\n", + "system": "" + }, + { + "instruction": "What is the difference between model.fit() an model.evaluate() in Keras?", + "input": "", + "output": "

fit() is for training the model with the given inputs (and corresponding training labels).

\n\n

evaluate() is for evaluating the already trained model using the validation (or test) data and the corresponding labels. Returns the loss value and metrics values for the model.

\n\n

predict() is for the actual prediction. It generates output predictions for the input samples.

\n\n

Let us consider a simple regression example:

\n\n
# input and output\nx = np.random.uniform(0.0, 1.0, (200))\ny = 0.3 + 0.6*x + np.random.normal(0.0, 0.05, len(y))\n
\n\n

\"enter

\n\n

Now lets apply a regression model in keras:

\n\n
# A simple regression model\nmodel = Sequential()\nmodel.add(Dense(1, input_shape=(1,)))\nmodel.compile(loss='mse', optimizer='rmsprop')\n\n# The fit() method - trains the model\nmodel.fit(x, y, nb_epoch=1000, batch_size=100)\n\nEpoch 1000/1000\n200/200 [==============================] - 0s - loss: 0.0023\n\n# The evaluate() method - gets the loss statistics\nmodel.evaluate(x, y, batch_size=200)     \n# returns: loss: 0.0022612824104726315\n\n# The predict() method - predict the outputs for the given inputs\nmodel.predict(np.expand_dims(x[:3],1)) \n# returns: [ 0.65680361],[ 0.70067143],[ 0.70482892]\n
\n", + "system": "" + }, + { + "instruction": "Keras: How to get layer shapes in a Sequential model", + "input": "", + "output": "

If you want the output printed in a fancy way:

\n\n
model.summary()\n
\n\n

If you want the sizes in an accessible form

\n\n
for layer in model.layers:\n    print(layer.get_output_at(0).get_shape().as_list())\n
\n\n

There are probably better ways to access the shapes than this. Thanks to Daniel for the inspiration.

\n", + "system": "" + }, + { + "instruction": "After building TensorFlow from source, seeing libcudart.so and libcudnn errors", + "input": "", + "output": "

First, for the following error:

\n\n
\n

ImportError: libcudart.so.8.0: cannot open shared object file: No such file or directory

\n
\n\n

make sure your LD_LIBRARY_PATH includes your lib64 directory in whichever path you installed your cuda package in. You can do this by adding an export line in your .bashrc. For Omar, it looked like the following:

\n\n
\n

I fixed this just adding the cuda path to my .bashrc

\n \n
\n

export LD_LIBRARY_PATH=/usr/local/cuda/lib64/

\n
\n
\n\n
\n\n

For me, I had to do Omar's line and also:\n export LD_LIBRARY_PATH=/usr/local/cuda-8.0/lib64/\nbecause I have two directories involving cuda (probably not the best).

\n\n
\n\n

Second, are you sure you installed cuDNN? Note that this is different from the regular cuda package. You will need to register, then download and install the package from the following page:\nhttps://developer.nvidia.com/cudnn

\n\n
\n\n

Third, I had this same problem:

\n\n
\n

ImportError: libcudnn.5: cannot open shared object file: No such file or directory

\n
\n\n

It turns out there is no libcudnn.5 in my /usr/local/cuda/lib64 or /usr/local/cuda-8.0/lib64 directories. However, I do have a libcudnn.so.6.* file. To solve the problem, I created a soft link:

\n\n
ln -s libcudnn.so.6.* libcudnn.so.5\n
\n\n

in my /usr/local/cuda/lib64 directory. Now everything works for me. Your directory might be different if you already had cuDNN, and your libcudnn.so.6.* might be a different version, so check that.

\n", + "system": "" + }, + { + "instruction": "How does Keras define "accuracy" and "loss"?", + "input": "", + "output": "

Have a look at metrics.py, there you can find definition of all available metrics including different types of accuracy. Accuracy is not printed unless you add it to the list of desired metrics when you compile your model.

\n\n

Regularizers are by definition added to the loss. For example, see add_loss method of the Layerclass.

\n\n

Update

\n\n

The type of accuracy is determined based on the objective function, see training.py. The default choice is categorical_accuracy. Other types like binary_accuracy and sparse_categorical_accuracy are selected when the objective function is either binary or sparse.

\n", + "system": "" + }, + { + "instruction": "TensorFlow: numpy.repeat() alternative", + "input": "", + "output": "

You can achieve the effect of np.repeat() using a combination of tf.tile() and tf.reshape():

\n\n
idx = tf.range(len(yp))\nidx = tf.reshape(idx, [-1, 1])    # Convert to a len(yp) x 1 matrix.\nidx = tf.tile(idx, [1, len(yp)])  # Create multiple columns.\nidx = tf.reshape(idx, [-1])       # Convert back to a vector.\n
\n\n

You can simply compute jdx using tf.tile():

\n\n
jdx = tf.range(len(yp))\njdx = tf.tile(jdx, [len(yp)])\n
\n\n

For the indexing, you could try using tf.gather() to extract non-contiguous slices from the yp tensor:

\n\n
s = tf.gather(yp, idx) - tf.gather(yp, jdx)\n
\n", + "system": "" + }, + { + "instruction": "After building TensorFlow from source, seeing libcudart.so and libcudnn errors", + "input": "", + "output": "

First, for the following error:

\n\n
\n

ImportError: libcudart.so.8.0: cannot open shared object file: No such file or directory

\n
\n\n

make sure your LD_LIBRARY_PATH includes your lib64 directory in whichever path you installed your cuda package in. You can do this by adding an export line in your .bashrc. For Omar, it looked like the following:

\n\n
\n

I fixed this just adding the cuda path to my .bashrc

\n \n
\n

export LD_LIBRARY_PATH=/usr/local/cuda/lib64/

\n
\n
\n\n
\n\n

For me, I had to do Omar's line and also:\n export LD_LIBRARY_PATH=/usr/local/cuda-8.0/lib64/\nbecause I have two directories involving cuda (probably not the best).

\n\n
\n\n

Second, are you sure you installed cuDNN? Note that this is different from the regular cuda package. You will need to register, then download and install the package from the following page:\nhttps://developer.nvidia.com/cudnn

\n\n
\n\n

Third, I had this same problem:

\n\n
\n

ImportError: libcudnn.5: cannot open shared object file: No such file or directory

\n
\n\n

It turns out there is no libcudnn.5 in my /usr/local/cuda/lib64 or /usr/local/cuda-8.0/lib64 directories. However, I do have a libcudnn.so.6.* file. To solve the problem, I created a soft link:

\n\n
ln -s libcudnn.so.6.* libcudnn.so.5\n
\n\n

in my /usr/local/cuda/lib64 directory. Now everything works for me. Your directory might be different if you already had cuDNN, and your libcudnn.so.6.* might be a different version, so check that.

\n", + "system": "" + }, + { + "instruction": "How to convert keras(h5) file to a tflite file?", + "input": "", + "output": "
from tensorflow.contrib import lite\nconverter = lite.TFLiteConverter.from_keras_model_file( 'model.h5')\ntfmodel = converter.convert()\nopen (\"model.tflite\" , \"wb\") .write(tfmodel)\n
\n\n

You can use the TFLiteConverter to directly convert .h5 files to .tflite file.\nThis does not work on Windows.

\n\n

For Windows, use this Google Colab notebook to convert. Upload the .h5 file and it will convert it .tflite file.

\n\n

Follow, if you want to try it yourself :

\n\n
    \n
  1. Create a Google Colab Notebook. In the left top corner, click the \"UPLOAD\" button and upload your .h5 file.
  2. \n
  3. Create a code cell and insert this code.

    \n\n
    from tensorflow.contrib import lite\nconverter = lite.TFLiteConverter.from_keras_model_file( 'model.h5' ) # Your model's name\nmodel = converter.convert()\nfile = open( 'model.tflite' , 'wb' ) \nfile.write( model )\n
  4. \n
  5. Run the cell. You will get a model.tflite file. Right click on the file and select \"DOWNLOAD\" option.

  6. \n
\n", + "system": "" + }, + { + "instruction": "Tensorflow: ImportError: libcusolver.so.8.0: cannot open shared object file: No such file or directory", + "input": "", + "output": "

Found the solution:

\n\n

I reinstalled nvidia-381, CUDA-8.0 (using the runfile) and cuDNN 6.0. Then I added the following in my .bashrc:

\n\n
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda/lib64/\n
\n", + "system": "" + }, + { + "instruction": "ImportError: cannot import name 'get_config' from 'tensorflow.python.eager.context'", + "input": "", + "output": "

Instead of:

\n
import keras\n
\n

Try:

\n
from tensorflow import keras \n
\n", + "system": "" + }, + { + "instruction": "Why Bert transformer uses [CLS] token for classification instead of average over all tokens?", + "input": "", + "output": "

BERT is designed primarily for transfer learning, i.e., finetuning on task-specific datasets. If you average the states, every state is averaged with the same weight: including stop words or other stuff that are not relevant for the task. The [CLS] vector gets computed using self-attention (like everything in BERT), so it can only collect the relevant information from the rest of the hidden states. So, in some sense the [CLS] vector is also an average over token vectors, only more cleverly computed, specifically for the tasks that you fine-tune on.

\n

Also, my experience is that when I keep the weights fixed and do not fine-tune BERT, using the token average yields better results.

\n", + "system": "" + }, + { + "instruction": "parallelising tf.data.Dataset.from_generator", + "input": "", + "output": "

\nTurns out I can use Dataset.map if I make the generator super lightweight (only generating meta data) and then move the actual heavy lighting into a stateless function. This way I can parallelise just the heavy lifting part with .map using a py_func.

\n\n

Works; but feels a tad clumsy... Would be great to be able to just add num_parallel_calls to from_generator :)

\n\n
def pure_numpy_and_pil_complex_calculation(metadata, label):\n  # some complex pil and numpy work nothing to do with tf\n  ...\n\ndataset = tf.data.Dataset.from_generator(lightweight_generator,\n                                         output_types=(tf.string,   # metadata\n                                                       tf.string))  # label\n\ndef wrapped_complex_calulation(metadata, label):\n  return tf.py_func(func = pure_numpy_and_pil_complex_calculation,\n                    inp = (metadata, label),\n                    Tout = (tf.uint8,    # (H,W,3) img\n                            tf.string))  # label\ndataset = dataset.map(wrapped_complex_calulation,\n                      num_parallel_calls=8)\n\ndataset = dataset.batch(64)\niter = dataset.make_one_shot_iterator()\nimgs, labels = iter.get_next()\n
\n", + "system": "" + }, + { + "instruction": "CUDA_HOME path for Tensorflow", + "input": "", + "output": "

Run the following command in the terminal:

\n\n
export CUDA_HOME=/usr/local/cuda-X.X\n
\n\n

Where you replace X.X by the first two digits of your version number (can be found out e.g. via nvcc --version).

\n", + "system": "" + }, + { + "instruction": "LSTM Autoencoder", + "input": "", + "output": "

Models can be any way you want. If I understood it right, you just want to know how to create models with LSTM?

\n\n

Using LSTMs

\n\n

Well, first, you have to define what your encoded vector looks like. Suppose you want it to be an array of 20 elements, a 1-dimension vector. So, shape (None,20). The size of it is up to you, and there is no clear rule to know the ideal one.

\n\n

And your input must be three-dimensional, such as your (1200,10,5). In keras summaries and error messages, it will be shown as (None,10,5), as \"None\" represents the batch size, which can vary each time you train/predict.

\n\n

There are many ways to do this, but, suppose you want only one LSTM layer:

\n\n
from keras.layers import *\nfrom keras.models import Model\n\ninpE = Input((10,5)) #here, you don't define the batch size   \noutE = LSTM(units = 20, return_sequences=False, ...optional parameters...)(inpE)\n
\n\n

This is enough for a very very simple encoder resulting in an array with 20 elements (but you can stack more layers if you want). Let's create the model:

\n\n
encoder = Model(inpE,outE)   \n
\n\n

Now, for the decoder, it gets obscure. You don't have an actual sequence anymore, but a static meaningful vector. You may want to use LTSMs still, they will suppose the vector is a sequence.

\n\n

But here, since the input has shape (None,20), you must first reshape it to some 3-dimensional array in order to attach an LSTM layer next.

\n\n

The way you will reshape it is entirely up to you. 20 steps of 1 element? 1 step of 20 elements? 10 steps of 2 elements? Who knows?

\n\n
inpD = Input((20,))   \noutD = Reshape((10,2))(inpD) #supposing 10 steps of 2 elements    \n
\n\n

It's important to notice that if you don't have 10 steps anymore, you won't be able to just enable \"return_sequences\" and have the output you want. You'll have to work a little. Acually, it's not necessary to use \"return_sequences\" or even to use LSTMs, but you may do that.

\n\n

Since in my reshape I have 10 timesteps (intentionally), it will be ok to use \"return_sequences\", because the result will have 10 timesteps (as the initial input)

\n\n
outD1 = LSTM(5,return_sequences=True,...optional parameters...)(outD)    \n#5 cells because we want a (None,10,5) vector.   \n
\n\n

You could work in many other ways, such as simply creating a 50 cell LSTM without returning sequences and then reshaping the result:

\n\n
alternativeOut = LSTM(50,return_sequences=False,...)(outD)    \nalternativeOut = Reshape((10,5))(alternativeOut)\n
\n\n

And our model goes:

\n\n
decoder = Model(inpD,outD1)  \nalternativeDecoder = Model(inpD,alternativeOut)   \n
\n\n

After that, you unite the models with your code and train the autoencoder. \nAll three models will have the same weights, so you can make the encoder bring results just by using its predict method.

\n\n
encoderPredictions = encoder.predict(data)\n
\n\n
\n\n

What I often see about LSTMs for generating sequences is something like predicting the next element.

\n\n

You take just a few elements of the sequence and try to find the next element. And you take another segment one step forward and so on. This may be helpful in generating sequences.

\n", + "system": "" + }, + { + "instruction": "Running Tensorflow in Jupyter Notebook", + "input": "", + "output": "

I came up with your case. This is how I sort it out

\n
    \n
  1. Install Anaconda
  2. \n
  3. Create a virtual environment - conda create -n tensorflow
  4. \n
  5. Go inside your virtual environment - (on macOS/Linux:) source activate tensorflow (on Windows: activate tensorflow)
  6. \n
  7. Inside that install tensorflow. You can install it using pip
  8. \n
  9. Finish install
  10. \n
\n

So then the next thing, when you launch it:

\n
    \n
  1. If you are not inside the virtual environment type - Source Activate Tensorflow
  2. \n
  3. Then inside this again install your Jupiter notebook and Pandas libraries, because there can be some missing in this virtual environment
  4. \n
\n

Inside the virtual environment just type:

\n
    \n
  1. pip install jupyter notebook
  2. \n
  3. pip install pandas
  4. \n
\n

Then you can launch jupyter notebook saying:

\n
    \n
  1. jupyter notebook
  2. \n
  3. Select the correct terminal python 3 or 2
  4. \n
  5. Then import those modules
  6. \n
\n", + "system": "" + }, + { + "instruction": "Update TensorFlow", + "input": "", + "output": "
(tensorflow)$ pip install --upgrade pip  # for Python 2.7\n(tensorflow)$ pip3 install --upgrade pip # for Python 3.n\n\n(tensorflow)$ pip install --upgrade tensorflow      # for Python 2.7\n(tensorflow)$ pip3 install --upgrade tensorflow     # for Python 3.n\n(tensorflow)$ pip install --upgrade tensorflow-gpu  # for Python 2.7 and GPU\n(tensorflow)$ pip3 install --upgrade tensorflow-gpu # for Python 3.n and GPU\n\n(tensorflow)$ pip install --upgrade tensorflow-gpu==1.4.1 # for a specific version\n
\n\n

Details on install tensorflow.

\n", + "system": "" + }, + { + "instruction": "How to convert one-hot encodings into integers?", + "input": "", + "output": "

You can use numpy.argmax or tf.argmax. Example:

\n\n
import numpy as np  \na  = np.array([[0,1,0,0],[1,0,0,0],[0,0,0,1]])\nprint('np.argmax(a, axis=1): {0}'.format(np.argmax(a, axis=1)))\n
\n\n

output:

\n\n
np.argmax(a, axis=1): [1 0 3]\n
\n\n

You may also want to look at sklearn.preprocessing.LabelBinarizer.inverse_transform.

\n", + "system": "" + }, + { + "instruction": "Linear vs nonlinear neural network?", + "input": "", + "output": "

For starters, a neural network can model any function (not just linear functions) Have a look at this - http://neuralnetworksanddeeplearning.com/chap4.html.

\n\n

A Neural Network has got non linear activation layers which is what gives the Neural Network a non linear element.

\n\n

The function for relating the input and the output is decided by the neural network and the amount of training it gets. If you supply two variables having a linear relationship, then your network will learn this as long as you don't overfit. Similarly, a complex enough neural network can learn any function.

\n", + "system": "" + }, + { + "instruction": "How do you read Tensorboard files programmatically?", + "input": "", + "output": "

You can use TensorBoard's Python classes or script to extract the data:

\n

How can I export data from TensorBoard?

\n
\n

If you'd like to export data to visualize elsewhere (e.g. iPython Notebook), that's possible too. You can directly depend on the underlying classes that TensorBoard uses for loading data: python/summary/event_accumulator.py (for loading data from a single run) or python/summary/event_multiplexer.py (for loading data from multiple runs, and keeping it organized). These classes load groups of event files, discard data that was "orphaned" by TensorFlow crashes, and organize the data by tag.

\n

As another option, there is a script (tensorboard/scripts/serialize_tensorboard.py) which will load a logdir just like TensorBoard does, but write all of the data out to disk as json instead of starting a server. This script is setup to make "fake TensorBoard backends" for testing, so it is a bit rough around the edges.

\n
\n

Using EventAccumulator:

\n
# In [1]: from tensorflow.python.summary import event_accumulator  # deprecated\nIn [1]: from tensorboard.backend.event_processing import event_accumulator\n\nIn [2]: ea = event_accumulator.EventAccumulator('events.out.tfevents.x.ip-x-x-x-x',\n   ...:  size_guidance={ # see below regarding this argument\n   ...:      event_accumulator.COMPRESSED_HISTOGRAMS: 500,\n   ...:      event_accumulator.IMAGES: 4,\n   ...:      event_accumulator.AUDIO: 4,\n   ...:      event_accumulator.SCALARS: 0,\n   ...:      event_accumulator.HISTOGRAMS: 1,\n   ...:  })\n\nIn [3]: ea.Reload() # loads events from file\nOut[3]: <tensorflow.python.summary.event_accumulator.EventAccumulator at 0x7fdbe5ff59e8>\n\nIn [4]: ea.Tags()\nOut[4]: \n{'audio': [],\n 'compressedHistograms': [],\n 'graph': True,\n 'histograms': [],\n 'images': [],\n 'run_metadata': [],\n 'scalars': ['Loss', 'Epsilon', 'Learning_rate']}\n\nIn [5]: ea.Scalars('Loss')\nOut[5]: \n[ScalarEvent(wall_time=1481232633.080754, step=1, value=1.6365480422973633),\n ScalarEvent(wall_time=1481232633.2001867, step=2, value=1.2162202596664429),\n ScalarEvent(wall_time=1481232633.3877788, step=3, value=1.4660096168518066),\n ScalarEvent(wall_time=1481232633.5749283, step=4, value=1.2405034303665161),\n ScalarEvent(wall_time=1481232633.7419815, step=5, value=0.897326648235321),\n ...]\n
\n

size_guidance:

\n
size_guidance: Information on how much data the EventAccumulator should\n  store in memory. The DEFAULT_SIZE_GUIDANCE tries not to store too much\n  so as to avoid OOMing the client. The size_guidance should be a map\n  from a `tagType` string to an integer representing the number of\n  items to keep per tag for items of that `tagType`. If the size is 0,\n  all events are stored.\n
\n", + "system": "" + }, + { + "instruction": "How to manually create a tf.Summary()", + "input": "", + "output": "

You can create a tf.Summary object in your Python program and write it to the same tf.summary.FileWriter object that takes your TensorFlow-produced summaries using the SummaryWriter.add_summary() method.

\n\n

The tf.Summary class is a Python protocol buffer wrapper for the Summary protocol buffer. Each Summary contains a list of tf.Summary.Value protocol buffers, which each have a tag and a either a \"simple\" (floating-point scalar) value, an image, a histogram, or an audio snippet. For example, you can generate a scalar summary from a Python object as follows:

\n\n
writer = tf.train.SummaryWriter(...)\nvalue = 37.0\nsummary = tf.Summary(value=[\n    tf.Summary.Value(tag=\"summary_tag\", simple_value=value), \n])\nwriter.add_summary(summary)\n
\n", + "system": "" + }, + { + "instruction": "Compute pairwise distance in a batch without replicating tensor in Tensorflow?", + "input": "", + "output": "

You can use some linear algebra to turn it into matrix ops. Note that what you need matrix D where a[i] is the ith row of your original matrix and

\n\n
D[i,j] = (a[i]-a[j])(a[i]-a[j])'\n
\n\n

You can rewrite that into

\n\n
D[i,j] = r[i] - 2 a[i]a[j]' + r[j]\n
\n\n

Where r[i] is squared norm of ith row of the original matrix.

\n\n

In a system that supports standard broadcasting rules you can treat r as a column vector and write D as

\n\n
D = r - 2 A A' + r'\n
\n\n

In TensorFlow you could write this as

\n\n
A = tf.constant([[1, 1], [2, 2], [3, 3]])\nr = tf.reduce_sum(A*A, 1)\n\n# turn r into column vector\nr = tf.reshape(r, [-1, 1])\nD = r - 2*tf.matmul(A, tf.transpose(A)) + tf.transpose(r)\nsess = tf.Session()\nsess.run(D)\n
\n\n

result

\n\n
array([[0, 2, 8],\n       [2, 0, 2],\n       [8, 2, 0]], dtype=int32)\n
\n", + "system": "" + }, + { + "instruction": "od_graph_def = tf.GraphDef() AttributeError: module 'tensorflow' has no attribute 'GraphDef'", + "input": "", + "output": "

Yeah, the syntax has changed in T2.0. Here's the correct piece:

\n\n
tf.compat.v1.GraphDef()   # -> instead of tf.GraphDef()\ntf.compat.v2.io.gfile.GFile()   # -> instead of tf.gfile.GFile()\n
\n", + "system": "" + }, + { + "instruction": "How do I split Tensorflow datasets?", + "input": "", + "output": "

You may use Dataset.take() and Dataset.skip():

\n\n
train_size = int(0.7 * DATASET_SIZE)\nval_size = int(0.15 * DATASET_SIZE)\ntest_size = int(0.15 * DATASET_SIZE)\n\nfull_dataset = tf.data.TFRecordDataset(FLAGS.input_file)\nfull_dataset = full_dataset.shuffle()\ntrain_dataset = full_dataset.take(train_size)\ntest_dataset = full_dataset.skip(train_size)\nval_dataset = test_dataset.skip(test_size)\ntest_dataset = test_dataset.take(test_size)\n
\n\n

For more generality, I gave an example using a 70/15/15 train/val/test split but if you don't need a test or a val set, just ignore the last 2 lines.

\n\n

Take:

\n\n
\n

Creates a Dataset with at most count elements from this dataset.

\n
\n\n

Skip:

\n\n
\n

Creates a Dataset that skips count elements from this dataset.

\n
\n\n

You may also want to look into Dataset.shard():

\n\n
\n

Creates a Dataset that includes only 1/num_shards of this dataset.

\n
\n", + "system": "" + }, + { + "instruction": "Choosing number of Steps per Epoch", + "input": "", + "output": "

Based on what you said it sounds like you need a larger batch_size, and of course there are implications with that which could impact the steps_per_epoch and number of epochs.

\n\n

To solve for jumping-around

\n\n\n\n

Implications of a larger batch-size

\n\n\n\n

When to reduce epochs

\n\n\n\n

When to adjust steps-per-epoch

\n\n\n", + "system": "" + }, + { + "instruction": "No module named 'absl' error when I import tensorflow", + "input": "", + "output": "

This was caused by a Python version issue for me. I had the absl package installed on my Python 2.x, but my Python 3.x didn't have it. So I just made sure that both Pythons on my machine had the package installed:

\n\n

pip install absl-py
\npip3 install absl-py

\n", + "system": "" + }, + { + "instruction": "How do I specify nvidia runtime from docker-compose.yml?", + "input": "", + "output": "

Currently (Aug 2018), NVIDIA container runtime for Docker (nvidia-docker2) supports Docker Compose.

\n\n
\n

Yes, use Compose format 2.3 and add runtime: nvidia to your GPU service. Docker Compose must be version 1.19.0 or higher.

\n
\n\n

Example docker-compose.yml:

\n\n
version: '2.3'\n\nservices:\n  nvsmi:\n    image: ubuntu:16.04\n    runtime: nvidia\n    environment:\n      - NVIDIA_VISIBLE_DEVICES=all\n    command: nvidia-smi\n
\n\n

More example from NVIDIA blog uses Docker Compose to show how to launch multiple GPU containers with the NVIDIA Container Runtime.

\n", + "system": "" + }, + { + "instruction": "Tensorflow import error: No module named 'tensorflow'", + "input": "", + "output": "

The reason Python 3.5 environment is unable to import Tensorflow is that Anaconda does not store the tensorflow package in the same environment.

\n\n

One solution is to create a new separate environment in Anaconda dedicated to TensorFlow with its own Spyder

\n\n
conda create -n newenvt anaconda python=3.5\nactivate newenvt\n
\n\n

and then install tensorflow into newenvt

\n\n

I found this primer helpful

\n", + "system": "" + }, + { + "instruction": "Tensorflow: loss decreasing, but accuracy stable", + "input": "", + "output": "

A decrease in binary cross-entropy loss does not imply an increase in accuracy. Consider label 1, predictions 0.2, 0.4 and 0.6 at timesteps 1, 2, 3 and classification threshold 0.5. timesteps 1 and 2 will produce a decrease in loss but no increase in accuracy.

\n\n

Ensure that your model has enough capacity by overfitting the training data. If the model is overfitting the training data, avoid overfitting by using regularization techniques such as dropout, L1 and L2 regularization and data augmentation.

\n\n

Last, confirm your validation data and training data come from the same distribution.

\n", + "system": "" + }, + { + "instruction": "looking for source code of from gen_nn_ops in tensorflow", + "input": "", + "output": "

You can't find this source because the source is automatically generated by bazel. If you build from source, you'll see this file inside bazel-genfiles. It's also present in your local distribution which you can find using inspect module. The file contains automatically generated Python wrappers to underlying C++ implementations, so it basically consists of a bunch of 1-line functions. A shortcut to find underlying C++ implementation of such generated Python op is to convert snake case to camel case, ie conv2d_backprop_input -> Conv2dBackpropInput

\n\n
# figure out where gen_nn_ops is\nprint(tf.nn.conv2d_transpose.__globals__['gen_nn_ops'])\n\nfrom tensorflow.python.ops import gen_nn_ops\nimport inspect\ninspect.getsourcefile('gen_nn_ops.conv2d_backprop_input')\n'/Users/yaroslav/anaconda/lib/python3.5/site-packages/tensorflow/python/ops/gen_nn_ops.py'\n
\n\n

If you cared to find out how this file really came about, you could follow the trail of bazel dependencies in BUILD files. It to find Bazel target that generated it from tensorflow source tree:

\n\n
fullname=$(bazel query tensorflow/python/ops/gen_nn_ops.py)\nbazel query \"attr('srcs', $fullname, ${fullname//:*/}:*)\"\n\n//tensorflow/python:nn_ops_gen\n
\n\n

So now going to BUILD file inside tensorflow/python you see that this is a target of type tf_gen_op_wrapper_private_py which is defined here and calls gen_op_wrapper_py from tensorflow/tensorflow.bzl which looks like this

\n\n
def tf_gen_op_wrapper_py(name, out=None, hidden=None, visibility=None, deps=[],\n....\n      native.cc_binary(\n      name = tool_name,\n
\n\n

This native.cc_binary construct is a way to have Bazel target that represents execution of an arbitrary command. In this case it calls tool_name with some arguments. With a couple more steps you can find that \"tool\" here is compiled from framework/python_op_gen_main.cc

\n\n

The reason for this complication is that TensorFlow was designed to be language agnostic. So in ideal world you would have each op described in ops.pbtxt, and then each op would have one implementation per hardware type using REGISTER_KERNEL_BUILDER, so all implementations would be done in C++/CUDA/Assembly and become automatically available to all language front-ends. There would be an equivalent translator op like \"python_op_gen_main\" for every language and all client library code would be automatically generated. However, because Python is so dominant, there was pressure to add features on the Python side. So now there are two kinds of ops -- pure TensorFlow ops seen in files like gen_nn_ops.py, and Python-only ops in files like nn_ops.py which typically wrap ops automatically generated files gen_nn_ops.py but add extra features/syntax sugar. Also, originally all names were camel-case, but it was decided that public facing release should be PEP compliant with more common Python syntax, so this is a reason for camel-case/snake-case mismatch between C++/Python interfaces of same op

\n", + "system": "" + }, + { + "instruction": "Tensorflow variable scope: reuse if variable exists", + "input": "", + "output": "

A ValueError is raised in get_variable() when creating a new variable and shape is not declared, or when violating reuse during variable creation. Therefore, you can try this:

\n\n
def get_scope_variable(scope_name, var, shape=None):\n    with tf.variable_scope(scope_name) as scope:\n        try:\n            v = tf.get_variable(var, shape)\n        except ValueError:\n            scope.reuse_variables()\n            v = tf.get_variable(var)\n    return v\n\nv1 = get_scope_variable('foo', 'v', [1])\nv2 = get_scope_variable('foo', 'v')\nassert v1 == v2\n
\n\n

Note that the following also works:

\n\n
v1 = get_scope_variable('foo', 'v', [1])\nv2 = get_scope_variable('foo', 'v', [1])\nassert v1 == v2\n
\n\n
\n\n

UPDATE. The new API supports auto-reusing now:

\n\n
def get_scope_variable(scope, var, shape=None):\n    with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n        v = tf.get_variable(var, shape)\n    return v\n
\n", + "system": "" + }, + { + "instruction": "How does TensorFlow name tensors?", + "input": "", + "output": "

Your observations on Tensor naming are absolutely correct: the name of a Tensor is the concatenation of

\n\n
    \n
  1. the name of the operation that produced it,
  2. \n
  3. a colon (:), and
  4. \n
  5. the index of that tensor in the outputs of the operation that produced it.
  6. \n
\n\n

Therefore the tensor named \"foo:2\" is the output of the op named \"foo\" at position 2 (with indices starting from zero).

\n\n

The naming of tf.Variable objects is slightly strange. Every tf.Variable contains a mutable tensor object that holds the state of the variable (and a few other tensors). A \"Variable\" op (which has the name \"variable_name\" in your example) \"produces\" this mutable tensor each time it is run as its 0th output, so the name of the mutable tensor is \"variable_name:0\".

\n\n

Since a tf.Variable is mostly indistinguishable from a tf.Tensor—in that it can be used in the same places—we took the decision to make variable names resemble tensor names, so the Variable.name property returns the name of the mutable tensor. (This contrasts with tf.QueueBase and tf.ReaderBase objects, which are not usable directly as tensors (instead you have to call methods on them to create ops that operate on their state), so these do not have a tensor-like name.)

\n", + "system": "" + }, + { + "instruction": "Tensorflow Precision / Recall / F1 score and Confusion matrix", + "input": "", + "output": "

You do not really need sklearn to calculate precision/recall/f1 score. You can easily express them in TF-ish way by looking at the formulas:

\n\n

\"enter

\n\n

Now if you have your actual and predicted values as vectors of 0/1, you can calculate TP, TN, FP, FN using tf.count_nonzero:

\n\n
TP = tf.count_nonzero(predicted * actual)\nTN = tf.count_nonzero((predicted - 1) * (actual - 1))\nFP = tf.count_nonzero(predicted * (actual - 1))\nFN = tf.count_nonzero((predicted - 1) * actual)\n
\n\n

Now your metrics are easy to calculate:

\n\n
precision = TP / (TP + FP)\nrecall = TP / (TP + FN)\nf1 = 2 * precision * recall / (precision + recall)\n
\n", + "system": "" + }, + { + "instruction": "Could not load dynamic library 'cudnn64_8.dll'; dlerror: cudnn64_8.dll not found", + "input": "", + "output": "

I think I can help you with providing a cudnn64_8.dll file (this is the download link: https://www.dll-files.com/cudnn64_8.dll.html). When you get the file, you can just put in your bin directory. For example, usually in windows platform, you can put it into C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v11.3\\bin.

\n", + "system": "" + }, + { + "instruction": "TensorFlow: How and why to use SavedModel", + "input": "", + "output": "

EDIT: I wrote this back at TensorFlow 1.4. As of today (TensorFlow 1.12 is stable, there's a 1.13rc and 2.0 is around the corner) the docs linked in the question are much improved.

\n\n
\n\n

I'm trying to use tf.saved_model and also found the Docs quite (too) abstract. Here's my stab at a full answer to your questions:

\n\n

1. signature_def_map:

\n\n

a. Format See Tom's answer to Tensorflow: how to save/restore a model. (Ctrl-F for \"tf.saved_model\" - currently, the only uses of the phrase on that question are in his answer).

\n\n

b. need It's my understanding that you do normally need it. If you intend to use the model, you need to know the inputs and outputs of the graph. I think it is akin to a C++ function signature: If you intend to define a function after it's called or in another C++ file, you need the signature in your main file (i.e. prototyped or in a header file).

\n\n

2. assets_collection:

\n\n

format: Couldn't find clear documentation, so I went to the builder source code. It appears that the argument is an iterable of Tensors of dtype=tf.string, where each Tensor is a path for the asset directory. So, a TensorFlow Graph collection should work. I guess that is the parameter's namesake, but from the source code I would expect a Python list to work too.

\n\n

(You didn't ask if you need to set it, but judging from Zoe's answer to What are assets in tensorflow? and iga's answer to the tangentially related Tensorflow serving: \u201cNo assets to save/writes\u201d when exporting models, it doesn't usually need set.)

\n\n

3. Tags:

\n\n

a. Why list I don't know why you must pass a list, but you may pass a list with one element. For instance, in my current project I only use the [tf...tag_constants.SERVING] tag.

\n\n

b. When to use multiple Say you're using explicit device placement for operations. Maybe you want to save a CPU version and a GPU version of your graph. Obviously you want to save a serving version of each, and say you want to save training checkpoints. You could use a CPU/GPU tag and a training/serving tag to manage all cases. The docs hint at it:

\n\n
\n

Each MetaGraphDef added to the SavedModel must be annotated with user-specified tags. The tags provide a means to identify the specific MetaGraphDef to load and restore, along with the shared set of variables and assets. These tags typically annotate a MetaGraphDef with its functionality (for example, serving or training), and optionally with hardware-specific aspects (for example, GPU).

\n
\n\n

c. Collision\nToo lazy to force a collision myself - I see two cases that would need addressed - I went to the loader source code. Inside def load, you'll see:

\n\n
saved_model = _parse_saved_model(export_dir)\nfound_match = False\nfor meta_graph_def in saved_model.meta_graphs:\n  if set(meta_graph_def.meta_info_def.tags) == set(tags):\n    meta_graph_def_to_load = meta_graph_def\n    found_match = True\n    break\n\nif not found_match:\n  raise RuntimeError(\n      \"MetaGraphDef associated with tags \" + str(tags).strip(\"[]\") +\n      \" could not be found in SavedModel. To inspect available tag-sets in\"\n      \" the SavedModel, please use the SavedModel CLI: `saved_model_cli`\"\n  )\n
\n\n

It appears to me that it's looking for an exact match. E.g. say you have a metagraph with tags \"GPU\" and \"Serving\" and a metagraph with tag \"Serving\". If you load \"Serving\", you'll get the latter metagraph. On the other hand, say you have a metagraph \"GPU\" and \"Serving\" and a metagraph \"CPU\" and \"Serving\". If you try to load \"Serving\", you'll get the error. If you try to save two metagraphs with the exact same tags in the same folder, I expect you'll overwrite the first one. It doesn't look like the build code handles such a collision in any special way.

\n\n

4. SavedModel or tf.train.Saver:

\n\n

This confused me too. wicke's answer to Should TensorFlow users prefer SavedModel over Checkpoint or GraphDef? cleared it up for me. I'll throw in my two cents:

\n\n

In the scope of local Python+TensorFlow, you can make tf.train.Saver do everything. But, it will cost you. Let me outline the save-a-trained-model-and-deploy use case. You'll need your saver object. It's easiest to set it up to save the complete graph (every variable). You probably don't want to save the .meta all the time since you're working with a static graph. You'll need to specify that in your training hook. You can read about that on cv-tricks. When your training finishes, you'll need convert your checkpoint file to a pb file. That usually means clearing the current graph, restoring the checkpoint, freezing your variables to constants with tf.python.framework.graph_util, and writing it with tf.gfile.GFile. You can read about that on medium. After that, you want to deploy it in Python. You'll need the input and output Tensor names - the string names in the graph def. You can read about that on metaflow (actually a very good blog post for the tf.train.Saver method). Some op nodes will let you feed data into them easily. Some not so much. I usually gave up on finding an appropriate node and added a tf.reshape that didn't actually reshape anything to the graph def. That was my ad-hoc input node. Same for the output. And then finally, you can deploy your model, at least locally in Python.

\n\n

Or, you could use the answer I linked in point 1 to accomplish all this with the SavedModel API. Less headaches thanks to Tom's answer . You'll get more support and features in the future if it ever gets documented appropriately . Looks like it's easier to use command line serving (the medium link covers doing that with Saver - looks tough, good luck!). It's practically baked in to the new Estimators. And according to the Docs,

\n\n
\n

SavedModel is a language-neutral, recoverable, hermetic serialization format.

\n
\n\n

Emphasis mine: Looks like you can get your trained models into the growing C++ API much easier.

\n\n

The way I see it, it's like the Datasets API. It's just easier than the old way!

\n\n

As far as concrete examples of SavedModel of tf.train.Saver: If \"basically, when you want to save or restore your model\" isn't clear enough for you: The correct time to use it is any time it makes your life easier. To me, that looks like always. Especially if you're using Estimators, deploying in C++, or using command line serving.

\n\n

So that's my research on your question. Or four enumerated questions. Err, eight question marks. Hope this helps.

\n", + "system": "" + }, + { + "instruction": "What are the differences between all these cross-entropy losses in Keras and TensorFlow?", + "input": "", + "output": "

There is just one cross (Shannon) entropy defined as:

\n\n
H(P||Q) = - SUM_i P(X=i) log Q(X=i)\n
\n\n

In machine learning usage, P is the actual (ground truth) distribution, and Q is the predicted distribution. All the functions you listed are just helper functions which accepts different ways to represent P and Q.

\n\n

There are basically 3 main things to consider:

\n\n\n\n

Depending on these three aspects, different helper function should be used:

\n\n
                                  outcomes     what is in Q    targets in P   \n-------------------------------------------------------------------------------\nbinary CE                                2      probability         any\ncategorical CE                          >2      probability         soft\nsparse categorical CE                   >2      probability         hard\nsigmoid CE with logits                   2      score               any\nsoftmax CE with logits                  >2      score               soft\nsparse softmax CE with logits           >2      score               hard\n
\n\n

In the end one could just use \"categorical cross entropy\", as this is how it is mathematically defined, however since things like hard targets or binary classification are very popular - modern ML libraries do provide these additional helper functions to make things simpler. In particular \"stacking\" sigmoid and cross entropy might be numerically unstable, but if one knows these two operations are applied together - there is a numerically stable version of them combined (which is implemented in TF).

\n\n

It is important to notice that if you apply wrong helper function the code will usually still execute, but results will be wrong. For example if you apply softmax_* helper for binary classification with one output your network will be considered to always produce \"True\" at the output.

\n\n

As a final note - this answer considers classification, it is slightly different when you consider multi label case (when a single point can have multiple labels), as then Ps do not sum to 1, and one should use sigmoid_cross_entropy_with_logits despite having multiple output units.

\n", + "system": "" + }, + { + "instruction": "How to apply Drop Out in Tensorflow to improve the accuracy of neural network?", + "input": "", + "output": "

In the graph, I'd suggest to move keep_prob = tf.placeholder(tf.float32) outside of the model function to make it global.

\n\n
with graph.as_default():\n    ...\n    x = tf.placeholder(\"float\", [None, n_input])\n    y = tf.placeholder(\"float\", [None, n_classes])\n    keep_prob = tf.placeholder(tf.float32)\n\n    def model(x, weights_hiden, weights_out, biases_hidden, biases_out, keep_prob):\n        # hidden layer with RELU activation\n        layer_1 = tf.nn.relu(tf.add(tf.matmul(x, weights_hiden), biases_hidden))\n        # apply DropOut to hidden layer\n        drop_out = tf.nn.dropout(layer_1, keep_prob)  # DROP-OUT here\n        # output layer with linear activation\n        out_layer = tf.matmul(drop_out, weights_out) + biases_out\n        return out_layer\n    ...\n
\n\n

When running session, feed a desired keep_prob value during training time, and feed 1.0 to keep_prob during reference (validation and/or testing) time.

\n\n
# run the graph\nwith tf.Session(graph=graph) as sess:\n    tf.initialize_all_variables().run()\n    ...\n    for epoch in range(training_epochs):\n        ...\n        for i in range(total_batch):\n            batch_x = ...\n            batch_y = ...\n            # Run optimization op (backprop) and cost op (to get loss value)\n            # Feed a value < 1.0 for keep prob during training\n            _, c = sess.run([optimizer, cost], feed_dict={x: batch_x, y: batch_y, keep_prob : 0.5})\n    ...\n    # Feed 1.0 for keep prob during testing\n    print(\"Test data accuracy:\", accuracy.eval({x: test_dataset, y: test_labels, keep_prob : 1.0}))\n    print(\"Valid data accuracy:\", accuracy.eval({x: valid_dataset, y: valid_labels, keep_prob : 1.0}))\n
\n", + "system": "" + }, + { + "instruction": "Tensorflow get all variables in scope", + "input": "", + "output": "

I think you want tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='my_scope'). This will get all variables in a scope.

\n\n

To pass to an optimizer you do not want all variables you would just want the trainable variables. Those are also kept in a default collection, which is tf.GraphKeys.TRAINABLE_VARIABLES.

\n", + "system": "" + }, + { + "instruction": "How to prefetch data using a custom python function in tensorflow", + "input": "", + "output": "

This is a common use case, and most implementations use TensorFlow's queues to decouple the preprocessing code from the training code. There is a tutorial on how to use queues, but the main steps are as follows:

\n\n
    \n
  1. Define a queue, q, that will buffer the preprocessed data. TensorFlow supports the simple tf.FIFOQueue that produces elements in the order they were enqueued, and the more advanced tf.RandomShuffleQueue that produces elements in a random order. A queue element is a tuple of one or more tensors (which can have different types and shapes). All queues support single-element (enqueue, dequeue) and batch (enqueue_many, dequeue_many) operations, but to use the batch operations you must specify the shapes of each tensor in a queue element when constructing the queue.

  2. \n
  3. Build a subgraph that enqueues preprocessed elements into the queue. One way to do this would be to define some tf.placeholder() ops for tensors corresponding to a single input example, then pass them to q.enqueue(). (If your preprocessing produces a batch at once, you should use q.enqueue_many() instead.) You might also include TensorFlow ops in this subgraph.

  4. \n
  5. Build a subgraph that performs training. This will look like a regular TensorFlow graph, but will get its input by calling q.dequeue_many(BATCH_SIZE).

  6. \n
  7. Start your session.

  8. \n
  9. Create one or more threads that execute your preprocessing logic, then execute the enqueue op, feeding in the preprocessed data. You may find the tf.train.Coordinator and tf.train.QueueRunner utility classes useful for this.

  10. \n
  11. Run your training graph (optimizer, etc.) as normal.

  12. \n
\n\n

EDIT: Here's a simple load_and_enqueue() function and code fragment to get you started:

\n\n
# Features are length-100 vectors of floats\nfeature_input = tf.placeholder(tf.float32, shape=[100])\n# Labels are scalar integers.\nlabel_input = tf.placeholder(tf.int32, shape=[])\n\n# Alternatively, could do:\n# feature_batch_input = tf.placeholder(tf.float32, shape=[None, 100])\n# label_batch_input = tf.placeholder(tf.int32, shape=[None])\n\nq = tf.FIFOQueue(100, [tf.float32, tf.int32], shapes=[[100], []])\nenqueue_op = q.enqueue([feature_input, label_input])\n\n# For batch input, do:\n# enqueue_op = q.enqueue_many([feature_batch_input, label_batch_input])\n\nfeature_batch, label_batch = q.dequeue_many(BATCH_SIZE)\n# Build rest of model taking label_batch, feature_batch as input.\n# [...]\ntrain_op = ...\n\nsess = tf.Session()\n\ndef load_and_enqueue():\n  with open(...) as feature_file, open(...) as label_file:\n    while True:\n      feature_array = numpy.fromfile(feature_file, numpy.float32, 100)\n      if not feature_array:\n        return\n      label_value = numpy.fromfile(feature_file, numpy.int32, 1)[0]\n\n      sess.run(enqueue_op, feed_dict={feature_input: feature_array,\n                                      label_input: label_value})\n\n# Start a thread to enqueue data asynchronously, and hide I/O latency.\nt = threading.Thread(target=load_and_enqueue)\nt.start()\n\nfor _ in range(TRAINING_EPOCHS):\n  sess.run(train_op)\n
\n", + "system": "" + }, + { + "instruction": "Logging training and validation loss in tensorboard", + "input": "", + "output": "

There are several different ways you could achieve this, but you're on the right track with creating different tf.summary.scalar() nodes. Since you must explicitly call SummaryWriter.add_summary() each time you want to log a quantity to the event file, the simplest approach is probably to fetch the appropriate summary node each time you want to get the training or validation accuracy:

\n\n
accuracy = tf.reduce_mean(correct)\n\ntraining_summary = tf.summary.scalar(\"training_accuracy\", accuracy)\nvalidation_summary = tf.summary.scalar(\"validation_accuracy\", accuracy)\n\n\nsummary_writer = tf.summary.FileWriter(...)\n\nfor step in xrange(NUM_STEPS):\n\n  # Perform a training step....\n\n  if step % LOG_PERIOD == 0:\n\n    # To log training accuracy.\n    train_acc, train_summ = sess.run(\n        [accuracy, training_summary], \n        feed_dict={images : training_set.images, labels : training_set.labels})\n    writer.add_summary(train_summ, step) \n\n    # To log validation accuracy.\n    valid_acc, valid_summ = sess.run(\n        [accuracy, validation_summary],\n        feed_dict={images : validation_set.images, labels : validation_set.labels})\n    writer.add_summary(valid_summ, step)\n
\n\n

Alternatively, you could create a single summary op whose tag is a tf.placeholder(tf.string, []) and feed the string \"training_accuracy\" or \"validation_accuracy\" as appropriate.

\n", + "system": "" + }, + { + "instruction": "How do I get the current value of a Variable?", + "input": "", + "output": "

The only way to get the value of the variable is by running it in a session. In the FAQ it is written that:

\n\n
\n

A Tensor object is a symbolic handle to the result of an operation,\n but does not actually hold the values of the operation's output.

\n
\n\n

So TF equivalent would be:

\n\n
import tensorflow as tf\n\nx = tf.Variable([1.0, 2.0])\n\ninit = tf.global_variables_initializer()\n\nwith tf.Session() as sess:\n    sess.run(init)\n    v = sess.run(x)\n    print(v)  # will show you your variable.\n
\n\n

The part with init = global_variables_initializer() is important and should be done in order to initialize variables.

\n\n

Also, take a look at InteractiveSession if you work in IPython.

\n", + "system": "" + }, + { + "instruction": "Why do we name variables in Tensorflow?", + "input": "", + "output": "

The name parameter is optional (you can create variables and constants with or without it), and the variable you use in your program does not depend on it. Names can be helpful in a couple of places:

\n\n

When you want to save or restore your variables (you can save them to a binary file after the computation). From docs:

\n\n
\n

By default, it uses the value of the Variable.name property for each\n variable

\n
\n\n
matrix_1 = tf.Variable([[1, 2], [2, 3]], name=\"v1\")\nmatrix_2 = tf.Variable([[3, 4], [5, 6]], name=\"v2\")\ninit = tf.initialize_all_variables()\n\nsaver = tf.train.Saver()\n\nsess = tf.Session()\nsess.run(init)\nsave_path = saver.save(sess, \"/model.ckpt\")\nsess.close()\n
\n\n

Nonetheless you have variables matrix_1, matrix_2 they are saves as v1, v2 in the file.

\n\n

Also names are used in TensorBoard to nicely show names of edges. You can even group them by using the same scope:

\n\n
import tensorflow as tf\n\nwith tf.name_scope('hidden') as scope:\n  a = tf.constant(5, name='alpha')\n  W = tf.Variable(tf.random_uniform([1, 2], -1.0, 1.0), name='weights')\n  b = tf.Variable(tf.zeros([1]), name='biases')\n
\n", + "system": "" + }, + { + "instruction": "tensorflow:Your input ran out of data", + "input": "", + "output": "

To make sure that you have "at least steps_per_epoch * epochs batches", set the steps_per_epoch to

\n
steps_per_epoch = len(X_train)//batch_size\n\nvalidation_steps = len(X_test)//batch_size # if you have validation data \n
\n

You can see the maximum number of batches that model.fit() can take by the progress bar when the training interrupts:

\n
5230/10000 [==============>...............] - ETA: 2:05:22 - loss: 0.0570\n
\n

Here, the maximum would be 5230 - 1

\n

Importantly, keep in mind that by default, batch_size is 32 in model.fit().

\n

If you're using a tf.data.Dataset, you can also add the repeat() method, but be careful: it will loop indefinitely (unless you specify a number).

\n", + "system": "" + }, + { + "instruction": "Install Tensorflow 2.0 in conda enviroment", + "input": "", + "output": "

TENSORFLOW 2.0 release version is out!

\n

Since 01/10/2019 I'm not talking beta but the release version.

\n

Using Anaconda

\n

Since 01/11/2019 Anaconda is supporting the Tensorflow 2.0.0.

\n

Option 1: For what the easiest way is just:

\n

conda install tensorflow or conda install tensorflow-gpu

\n

For the gpu mode, anaconda will take care of all the CUDA everything you need to install for the tensorflow gpu mode to work so I strongly recommend using this method.

\n

The only issue with this method is that anaconda might not have the last last version of TensorFlow. For example, at Feb 21 2021, conda has the version 2.3 whereas the PIP version is 2.4. You can check the current version of gpu or cpu.

\n

Option 2 (virtual env): It is strongly recommended to use an environment on where to install tensorflow, for which you need the following command that will create an environment first and then install tensorflow within:

\n\n

Change <your_env_name> by a meaningful name like tf-2

\n

To use tensorflow run first conda activate <your_env_name>

\n

Using pip

\n

Using pip the tensorflow official instructions are quite complete.

\n

Just install tensorflow using pip like:

\n
# Current stable release for CPU-only\npip install tensorflow\n
\n

I yet recommend before doing everything to install tensorflow in a new environment so the 3 steps would be (with anaconda):

\n
conda create --n <our_env_name> pip\nconda activate <your_env_name>\npip install tensorflow\n
\n

Now for the GPU version it's harder with pip, I recommend you this link that explains the extra things you need to install (CUDA and others).

\n", + "system": "" + }, + { + "instruction": "What's the purpose of keras.backend.function()", + "input": "", + "output": "

I have the following understanding of this function keras.backend.function. I will explain it with the help of a code snippet from this.

\n

The part of code snippet is as follows

\n
final_conv_layer = get_output_layer(model, "conv5_3")\nget_output = K.function([model.layers[0].input], \n                        [final_conv_layer.output, model.layers[-1].output])\n[conv_outputs, predictions] = get_output([img])\n    \n
\n

In this code, there is a model from which conv5_3 layer is extracted (line 1). In the function K.function(), the first argument is input to this model and second is set of 2 outputs - one for convolution and second for softmax output at the last layer.

\n

As per the Keras/Tensorflow manual, this function runs the computation graph that we have created in the code, taking input from the first parameter and extracting the number of outputs as per the layers mentioned in the second parameter. Thus, conv_outputs are output of final_conv_layer and predictions are output of model.layers[-1], i.e. the last layer of the model.

\n", + "system": "" + }, + { + "instruction": "What is y_true and y_pred when creating a custom metric in Keras?", + "input": "", + "output": "

y_true and y_pred

\n

The tensor y_true is the true data (or target, ground truth) you pass to the fit method.
\nIt's a conversion of the numpy array y_train into a tensor.

\n

The tensor y_pred is the data predicted (calculated, output) by your model.

\n

Usually, both y_true and y_pred have exactly the same shape. A few of the losses, such as the sparse ones, may accept them with different shapes.

\n
\n

The shape of y_true

\n

It contains an entire batch. Its first dimension is always the batch size, and it must exist, even if the batch has only one element.

\n

Two very easy ways to find the shape of y_true are:

\n\n

But its first dimension will be the batch size.

\n

So, if your last layer outputs (None, 1), the shape of y_true is (batch, 1). If the last layer outputs (None, 200,200, 3), then y_true will be (batch, 200,200,3).

\n
\n

Custom metrics and loss functions

\n

Unfotunately, printing custom metrics will not reveal their content (unless you are using eager mode on, and you have calculated every step of the model with data).
\nYou can see their shapes with print(K.int_shape(y_pred)), for instance.

\n

Remember that these libraries first "compile a graph", then later "runs it with data". When you define your loss, you're in the compile phase, and asking for data needs the model to run.

\n

But even if the result of your metric is multidimensional, keras will automatically find ways to output a single scalar for that metric. (Not sure what is the operation, but very probably a K.mean() hidden under the table - it's interesting to return the entire batch, so Keras applies other operations such as sample weights, for instance).

\n

Sources. After you get used to keras, this understanding gets natural from simply reading this part:

\n
\n

y_true: True labels. Theano/TensorFlow tensor.
\ny_pred: Predictions. Theano/TensorFlow tensor of the same shape as y_true.

\n
\n

True labels mean true/target data. Labels is a badly chosen word here, it is only really "labels" in classification models.
\nPredictions mean the results of your model.

\n", + "system": "" + }, + { + "instruction": "How to average summaries over multiple batches?", + "input": "", + "output": "

Do the averaging of your measure in Python and create a new Summary object for each mean. Here is what I do:

\n\n
accuracies = []\n\n# Calculate your measure over as many batches as you need\nfor batch in validation_set:\n  accuracies.append(sess.run([training_op]))\n\n# Take the mean of you measure\naccuracy = np.mean(accuracies)\n\n# Create a new Summary object with your measure\nsummary = tf.Summary()\nsummary.value.add(tag=\"%sAccuracy\" % prefix, simple_value=accuracy)\n\n# Add it to the Tensorboard summary writer\n# Make sure to specify a step parameter to get nice graphs over time\nsummary_writer.add_summary(summary, global_step)\n
\n", + "system": "" + }, + { + "instruction": "IOError: [Errno 28] No space left on device while installing TensorFlow", + "input": "", + "output": "

Usually, You can set the environment variable 'TMPDIR' to use a different directory other than /tmp or /var/tmp and most programs will honour that.

\n\n

You can perhaps try,

\n\n
\n

$ export TMPDIR=$HOME/tmp

\n
\n\n

and then start your 'pip install'

\n", + "system": "" + }, + { + "instruction": "Keras uses way too much GPU memory when calling train_on_batch, fit, etc", + "input": "", + "output": "

It is a very common mistake to forget that the activations, gradients and optimizer moment tracking variables also take VRRAM, not just the parameters, increasing memory usage quite a bit. The backprob calculations themselves make it so the training phase takes almost double the VRAM of forward / inference use of the neural net, and the Adam optimizer triples the space usage.

\n

So, in the beginning when the network is created, only the parameters are allocated. However, when the training starts. the model actiavtions, backprop computations and the optimizer's tracking variables get allocated, increasing memory use by a large factor.

\n

To allow the training of larger models, people:

\n\n

Tools to train very large models:

\n\n", + "system": "" + }, + { + "instruction": "Implementing contrastive loss and triplet loss in Tensorflow", + "input": "", + "output": "

Update (2018/03/19): I wrote a blog post detailing how to implement triplet loss in TensorFlow.

\n\n
\n\n

You need to implement yourself the contrastive loss or the triplet loss, but once you know the pairs or triplets this is quite easy.

\n\n
\n\n

Contrastive Loss

\n\n

Suppose you have as input the pairs of data and their label (positive or negative, i.e. same class or different class). For instance you have images as input of size 28x28x1:

\n\n
left = tf.placeholder(tf.float32, [None, 28, 28, 1])\nright = tf.placeholder(tf.float32, [None, 28, 28, 1])\nlabel = tf.placeholder(tf.int32, [None, 1]). # 0 if same, 1 if different\nmargin = 0.2\n\nleft_output = model(left)  # shape [None, 128]\nright_output = model(right)  # shape [None, 128]\n\nd = tf.reduce_sum(tf.square(left_output - right_output), 1)\nd_sqrt = tf.sqrt(d)\n\nloss = label * tf.square(tf.maximum(0., margin - d_sqrt)) + (1 - label) * d\n\nloss = 0.5 * tf.reduce_mean(loss)\n
\n\n
\n\n

Triplet Loss

\n\n

Same as with contrastive loss, but with triplets (anchor, positive, negative). You don't need labels here.

\n\n
anchor_output = ...  # shape [None, 128]\npositive_output = ...  # shape [None, 128]\nnegative_output = ...  # shape [None, 128]\n\nd_pos = tf.reduce_sum(tf.square(anchor_output - positive_output), 1)\nd_neg = tf.reduce_sum(tf.square(anchor_output - negative_output), 1)\n\nloss = tf.maximum(0., margin + d_pos - d_neg)\nloss = tf.reduce_mean(loss)\n
\n\n
\n\n

The real trouble when implementing triplet loss or contrastive loss in TensorFlow is how to sample the triplets or pairs. I will focus on generating triplets because it is harder than generating pairs.

\n\n

The easiest way is to generate them outside of the Tensorflow graph, i.e. in python and feed them to the network through the placeholders. Basically you select images 3 at a time, with the first two from the same class and the third from another class. We then perform a feedforward on these triplets, and compute the triplet loss.

\n\n

The issue here is that generating triplets is complicated. We want them to be valid triplets, triplets with a positive loss (otherwise the loss is 0 and the network doesn't learn).
\nTo know whether a triplet is good or not you need to compute its loss, so you already make one feedforward through the network...

\n\n

Clearly, implementing triplet loss in Tensorflow is hard, and there are ways to make it more efficient than sampling in python but explaining them would require a whole blog post !

\n", + "system": "" + }, + { + "instruction": "How to understand the term `tensor` in TensorFlow?", + "input": "", + "output": "

TensorFlow doesn't have first-class Tensor objects, meaning that there are no notion of Tensor in the underlying graph that's executed by the runtime. Instead the graph consists of op nodes connected to each other, representing operations. An operation allocates memory for its outputs, which are available on endpoints :0, :1, etc, and you can think of each of these endpoints as a Tensor. If you have tensor corresponding to nodename:0 you can fetch its value as sess.run(tensor) or sess.run('nodename:0'). Execution granularity happens at operation level, so the run method will execute op which will compute all of the endpoints, not just the :0 endpoint. It's possible to have an Op node with no outputs (like tf.group) in which case there are no tensors associated with it. It is not possible to have tensors without an underlying Op node.

\n\n

You can examine what happens in underlying graph by doing something like this

\n\n
tf.reset_default_graph()\nvalue = tf.constant(1)\nprint(tf.get_default_graph().as_graph_def())\n
\n\n

So with tf.constant you get a single operation node, and you can fetch it using sess.run(\"Const:0\") or sess.run(value)

\n\n

Similarly, value=tf.placeholder(tf.int32) creates a regular node with name Placeholder, and you could feed it as feed_dict={\"Placeholder:0\":2} or feed_dict={value:2}. You can not feed and fetch a placeholder in the same session.run call, but you can see the result by attaching a tf.identity node on top and fetching that.

\n\n

For variable

\n\n
tf.reset_default_graph()\nvalue = tf.Variable(tf.ones_initializer()(()))\nvalue2 = value+3\nprint(tf.get_default_graph().as_graph_def())\n
\n\n

You'll see that it creates two nodes Variable and Variable/read, the :0 endpoint is a valid value to fetch on both of these nodes. However Variable:0 has a special ref type meaning it can be used as an input to mutating operations. The result of Python call tf.Variable is a Python Variable object and there's some Python magic to substitute Variable/read:0 or Variable:0 depending on whether mutation is necessary. Since most ops have only 1 endpoint, :0 is dropped. Another example is Queue -- close() method will create a new Close op node which connects to Queue op. To summarize -- operations on python objects like Variable and Queue map to different underlying TensorFlow op nodes depending on usage.

\n\n

For ops like tf.split or tf.nn.top_k which create nodes with multiple endpoints, Python's session.run call automatically wraps output in tuple or collections.namedtuple of Tensor objects which can be fetched individually.

\n", + "system": "" + }, + { + "instruction": "Tensorflow: restoring a graph and model then running evaluation on a single image", + "input": "", + "output": "

There are two methods to feed a single new image to the cifar10 model. The first method is a cleaner approach but requires modification in the main file, hence will require retraining. The second method is applicable when a user does not want to modify the model files and instead wants to use the existing check-point/meta-graph files.

\n\n

The code for the first approach is as follows:

\n\n
import tensorflow as tf\nimport numpy as np\nimport cv2\n\nsess = tf.Session('', tf.Graph())\nwith sess.graph.as_default():\n    # Read meta graph and checkpoint to restore tf session\n    saver = tf.train.import_meta_graph(\"/tmp/cifar10_train/model.ckpt-200.meta\")\n    saver.restore(sess, \"/tmp/cifar10_train/model.ckpt-200\")\n\n    # Read a single image from a file.\n    img = cv2.imread('tmp.png')\n    img = np.expand_dims(img, axis=0)\n\n    # Start the queue runners. If they are not started the program will hang\n    # see e.g. https://www.tensorflow.org/programmers_guide/reading_data\n    coord = tf.train.Coordinator()\n    threads = []\n    for qr in sess.graph.get_collection(tf.GraphKeys.QUEUE_RUNNERS):\n        threads.extend(qr.create_threads(sess, coord=coord, daemon=True,\n                                         start=True))\n\n    # In the graph created above, feed \"is_training\" and \"imgs\" placeholders.\n    # Feeding them will disconnect the path from queue runners to the graph \n    # and enable a path from the placeholder instead. The \"img\" placeholder will be \n    # fed with the image that was read above.\n    logits = sess.run('softmax_linear/softmax_linear:0', \n                     feed_dict={'is_training:0': False, 'imgs:0': img})\n\n    #Print classifiction results.\n    print(logits) \n
\n\n

The script requires that a user creates two placeholders and a conditional execution statement for it to work.

\n\n

The placeholders and conditional execution statement are added in cifar10_train.py as shown below:

\n\n
def train():   \n\"\"\"Train CIFAR-10 for a number of steps.\"\"\"   \n    with tf.Graph().as_default():\n        global_step = tf.contrib.framework.get_or_create_global_step()\n\n    with tf.device('/cpu:0'):\n        images, labels = cifar10.distorted_inputs()\n\n    is_training = tf.placeholder(dtype=bool,shape=(),name='is_training')\n    imgs = tf.placeholder(tf.float32, (1, 32, 32, 3), name='imgs')\n    images = tf.cond(is_training, lambda:images, lambda:imgs)\n    logits = cifar10.inference(images)\n
\n\n

The inputs in cifar10 model are connected to queue runner object which is a multistage queue that can prefetch data from files in parallel. See a nice animation of queue runner here

\n\n

While queue runners are efficient in prefetching large dataset for training, they are an overkill for inference/testing where only a single file is needed to be classified, also they are a bit more involved to modify/maintain.\nFor that reason, I have added a placeholder \"is_training\", which is set to False while training as shown below:

\n\n
 import numpy as np\n tmp_img = np.ndarray(shape=(1,32,32,3), dtype=float)\n with tf.train.MonitoredTrainingSession(\n     checkpoint_dir=FLAGS.train_dir,\n     hooks=[tf.train.StopAtStepHook(last_step=FLAGS.max_steps),\n            tf.train.NanTensorHook(loss),\n            _LoggerHook()],\n     config=tf.ConfigProto(\n         log_device_placement=FLAGS.log_device_placement)) as mon_sess:\n   while not mon_sess.should_stop():\n     mon_sess.run(train_op, feed_dict={is_training: True, imgs: tmp_img})\n
\n\n

Another placeholder \"imgs\" holds a tensor of shape (1,32,32,3) for the image that will be fed during inference -- the first dimension is the batch size which is one in this case. I have modified cifar model to accept 32x32 images instead of 24x24 as the original cifar10 images are 32x32.

\n\n

Finally, the conditional statement feeds the placeholder or queue runner output to the graph. The \"is_training\" placeholder is set to False during inference and \"img\" placeholder is fed a numpy array -- the numpy array is reshaped from 3 to 4 dimensional vector to conform to the input tensor to inference function in the model.

\n\n

That is all there is to it. Any model can be inferred with a single/user defined test data like shown in the script above. Essentially read the graph, feed data to the graph nodes and run the graph to get the final output.

\n\n

Now the second method. The other approach is to hack cifar10.py and cifar10_eval.py to change batch size to one and replace the data coming from the queue runner with the one read from a file.

\n\n

Set batch size to 1:

\n\n
tf.app.flags.DEFINE_integer('batch_size', 1,\n                             \"\"\"Number of images to process in a batch.\"\"\")\n
\n\n

Call inference with an image file read.

\n\n
def evaluate():   with tf.Graph().as_default() as g:\n    # Get images and labels for CIFAR-10.\n    eval_data = FLAGS.eval_data == 'test'\n    images, labels = cifar10.inputs(eval_data=eval_data)\n    import cv2\n    img = cv2.imread('tmp.png')\n    img = np.expand_dims(img, axis=0)\n    img = tf.cast(img, tf.float32)\n\n    logits = cifar10.inference(img)\n
\n\n

Then pass logits to eval_once and modify eval once to evaluate logits:

\n\n
def eval_once(saver, summary_writer, top_k_op, logits, summary_op): \n    ...\n    while step < num_iter and not coord.should_stop():\n        predictions = sess.run([top_k_op])\n        print(sess.run(logits))\n
\n\n

There is no separate script to run this method of inference, just run cifar10_eval.py which will now read a file from the user defined location with a batch size of one.

\n", + "system": "" + }, + { + "instruction": "How to create only one copy of graph in tensorboard events file with custom tf.Estimator?", + "input": "", + "output": "

You need to use the TensorBoard tool for visualizing the contents of your summary logs.

\n

The event file log can be read and use it.\nYou can see the example from this link provides information about how to read events written to an event file.

\n
# This example supposes that the events file contains summaries with a\n# summary value tag 'loss'.  These could have been added by calling\n# `add_summary()`, passing the output of a scalar summary op created with\n# with: `tf.compat.v1.summary.scalar('loss', loss_tensor)`.\nfor e in tf.compat.v1.train.summary_iterator(path to events file):\n    for v in e.summary.value:\n        if v.tag == 'loss':\n            print(v.simple_value)\n
\n", + "system": "" + }, + { + "instruction": "Numpy is installed but still getting error", + "input": "", + "output": "

Run:

\n
pip3 uninstall numpy\n
\n

Until you receive a message stating no files available with numpy to uninstall and then you can freshly install numpy using

\n
pip install numpy\n
\n

And that will fix the issue.

\n", + "system": "" + }, + { + "instruction": "Is there an easy way to get something like Keras model.summary in Tensorflow?", + "input": "", + "output": "

Looks like you can use Slim

\n\n

Example:

\n\n
import numpy as np\n\nfrom tensorflow.python.layers import base\nimport tensorflow as tf\nimport tensorflow.contrib.slim as slim\n\nx = np.zeros((1,4,4,3))\nx_tf = tf.convert_to_tensor(x, np.float32)\nz_tf = tf.layers.conv2d(x_tf, filters=32, kernel_size=(3,3))\n\ndef model_summary():\n    model_vars = tf.trainable_variables()\n    slim.model_analyzer.analyze_vars(model_vars, print_info=True)\n\nmodel_summary()\n
\n\n

Output:

\n\n
---------\nVariables: name (type shape) [size]\n---------\nconv2d/kernel:0 (float32_ref 3x3x3x32) [864, bytes: 3456]\nconv2d/bias:0 (float32_ref 32) [32, bytes: 128]\nTotal size of variables: 896\nTotal bytes of variables: 3584\n
\n\n

Also here is an example of custom function to print model summary:\nhttps://github.com/NVlabs/stylegan/blob/f3a044621e2ab802d40940c16cc86042ae87e100/dnnlib/tflib/network.py#L507

\n\n

If you already have .pb tensorflow model you can use: inspect_pb.py to print model info or use tensorflow summarize_graph tool with --print_structure flag, also it's nice that it can detect input and output names.

\n", + "system": "" + }, + { + "instruction": "Adam optimizer goes haywire after 200k batches, training loss grows", + "input": "", + "output": "

Yes. This is a known problem of Adam.

\n\n

The equations for Adam are

\n\n
t <- t + 1\nlr_t <- learning_rate * sqrt(1 - beta2^t) / (1 - beta1^t)\n\nm_t <- beta1 * m_{t-1} + (1 - beta1) * g\nv_t <- beta2 * v_{t-1} + (1 - beta2) * g * g\nvariable <- variable - lr_t * m_t / (sqrt(v_t) + epsilon)\n
\n\n

where m is an exponential moving average of the mean gradient and v is an exponential moving average of the squares of the gradients. The problem is that when you have been training for a long time, and are close to the optimal, then v can become very small. If then all of a sudden the gradients starts increasing again it will be divided by a very small number and explode.

\n\n

By default beta1=0.9 and beta2=0.999. So m changes much more quickly than v. So m can start being big again while v is still small and cannot catch up.

\n\n

To remedy to this problem you can increase epsilon which is 10-8 by default. Thus stopping the problem of dividing almost by 0. \nDepending on your network, a value of epsilon in 0.1, 0.01, or 0.001 might be good.

\n", + "system": "" + }, + { + "instruction": "TensorFlow 'module' object has no attribute 'global_variables_initializer'", + "input": "", + "output": "

In older versions, it was called tf.initialize_all_variables.

\n", + "system": "" + }, + { + "instruction": "How can I make tensorflow run on a GPU with capability 2.x?", + "input": "", + "output": "

Recent GPU versions of tensorflow require compute capability 3.5 or higher (and use cuDNN to access the GPU.

\n\n

cuDNN also requires a GPU of cc3.0 or higher:

\n\n
\n

cuDNN is supported on Windows, Linux and MacOS systems with Pascal, Kepler, Maxwell, Tegra K1 or Tegra X1 GPUs.

\n
\n\n\n\n

Fermi GPUs (cc2.0, cc2.1) are not supported by cuDNN.

\n\n

Older GPUs (e.g. compute capability 1.x) are also not supported by cuDNN.

\n\n

Note that there has never been either a version of cuDNN or any version of TF that officially supported NVIDIA GPUs less than cc3.0. The initial version of cuDNN started out by requiring cc3.0 GPUs, and the initial version of TF started out by requiring cc3.0 GPUs.

\n", + "system": "" + }, + { + "instruction": "How do I find the variable names and values that are saved in a checkpoint?", + "input": "", + "output": "

Example usage:

\n\n
from tensorflow.python.tools.inspect_checkpoint import print_tensors_in_checkpoint_file\nimport os\ncheckpoint_path = os.path.join(model_dir, \"model.ckpt\")\n\n# List ALL tensors example output: v0/Adam (DT_FLOAT) [3,3,1,80]\nprint_tensors_in_checkpoint_file(file_name=checkpoint_path, tensor_name='')\n\n# List contents of v0 tensor.\n# Example output: tensor_name:  v0 [[[[  9.27958265e-02   7.40226209e-02   4.52989563e-02   3.15700471e-02\nprint_tensors_in_checkpoint_file(file_name=checkpoint_path, tensor_name='v0')\n\n# List contents of v1 tensor.\nprint_tensors_in_checkpoint_file(file_name=checkpoint_path, tensor_name='v1')\n
\n\n

Update: all_tensors argument was added to print_tensors_in_checkpoint_file since Tensorflow 0.12.0-rc0 so you may need to add all_tensors=False or all_tensors=True if required.

\n\n

Alternative method:

\n\n
from tensorflow.python import pywrap_tensorflow\nimport os\n\ncheckpoint_path = os.path.join(model_dir, \"model.ckpt\")\nreader = pywrap_tensorflow.NewCheckpointReader(checkpoint_path)\nvar_to_shape_map = reader.get_variable_to_shape_map()\n\nfor key in var_to_shape_map:\n    print(\"tensor_name: \", key)\n    print(reader.get_tensor(key)) # Remove this is you want to print only variable names\n
\n\n

Hope it helps.

\n", + "system": "" + }, + { + "instruction": "Getting the current learning rate from a tf.train.AdamOptimizer", + "input": "", + "output": "

All the optimizers have a private variable that holds the value of a learning rate.

\n\n

In adagrad and gradient descent it is called self._learning_rate. In adam it is self._lr.

\n\n

So you will just need to print sess.run(optimizer._lr) to get this value. Sess.run is needed because they are tensors.

\n", + "system": "" + }, + { + "instruction": "TensorFlow: getting variable by name", + "input": "", + "output": "

The get_variable() function creates a new variable or returns one created earlier by get_variable(). It won't return a variable created using tf.Variable(). Here's a quick example:

\n\n
>>> with tf.variable_scope(\"foo\"):\n...   bar1 = tf.get_variable(\"bar\", (2,3)) # create\n... \n>>> with tf.variable_scope(\"foo\", reuse=True):\n...   bar2 = tf.get_variable(\"bar\")  # reuse\n... \n\n>>> with tf.variable_scope(\"\", reuse=True): # root variable scope\n...   bar3 = tf.get_variable(\"foo/bar\") # reuse (equivalent to the above)\n... \n>>> (bar1 is bar2) and (bar2 is bar3)\nTrue\n
\n\n

If you did not create the variable using tf.get_variable(), you have a couple options. First, you can use tf.global_variables() (as @mrry suggests):

\n\n
>>> bar1 = tf.Variable(0.0, name=\"bar\")\n>>> bar2 = [var for var in tf.global_variables() if var.op.name==\"bar\"][0]\n>>> bar1 is bar2\nTrue\n
\n\n

Or you can use tf.get_collection() like so:

\n\n
>>> bar1 = tf.Variable(0.0, name=\"bar\")\n>>> bar2 = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=\"bar\")[0]\n>>> bar1 is bar2\nTrue\n
\n\n

Edit

\n\n

You can also use get_tensor_by_name():

\n\n
>>> bar1 = tf.Variable(0.0, name=\"bar\")\n>>> graph = tf.get_default_graph()\n>>> bar2 = graph.get_tensor_by_name(\"bar:0\")\n>>> bar1 is bar2\nFalse, bar2 is a Tensor througn convert_to_tensor on bar1. but bar1 equal \nbar2 in value.\n
\n\n

Recall that a tensor is the output of an operation. It has the same name as the operation, plus :0. If the operation has multiple outputs, they have the same name as the operation plus :0, :1, :2, and so on.

\n", + "system": "" + }, + { + "instruction": "import input_data MNIST tensorflow not working", + "input": "", + "output": "

So let's assume that you are in the directory: /somePath/tensorflow/tutorial (and this is your working directory).

\n

All you need to do is to download the input_data.py file and place it like this. Let's assume that the file name you invoke:

\n
import input_data\nmnist = input_data.read_data_sets("MNIST_data/", one_hot=True)\n...\n
\n

is main.py and it is also in the same directory.

\n

Once this is done, you can just start running main.py which will start downloading the files and will put them in the MNIST_data folder (once they are there the script will not be downloading them next time).

\n", + "system": "" + }, + { + "instruction": "Error in python after 'import tensorflow': TypeError: __init__() got an unexpected keyword argument 'syntax'", + "input": "", + "output": "

Several users have reported issues that arise when an older version of protobuf is installed.

\n\n

TensorFlow requires (and uses a copy of) protobuf-3.0.0a4. However it seems to be conflicting with your installed version (perhaps due to how the PYTHONPATH environment variable is configured on your system?). Can you try uninstalling the python-protobuf package if it is installed, and then seeing if TensorFlow starts correctly?

\n\n

Some users have had success when using a virtualenv. For instructions on installing TensorFlow into a virtualenv, see the getting started guide.

\n", + "system": "" + }, + { + "instruction": "ValueError: Layer sequential_20 expects 1 inputs, but it received 2 input tensors", + "input": "", + "output": "

it helped me when I changed:
\nvalidation_data=[X_val, y_val] into validation_data=(X_val, y_val)
\nActually still wonder why?

\n", + "system": "" + }, + { + "instruction": "Confusion about keras Model: __call__ vs. call vs. predict methods", + "input": "", + "output": "

Adding to @Dmitry Kabanov, they are similar yet they aren't exactly the same thing. If you care about performance, need to look in to critical differences between them.

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
model.predictmodel(x)
loops over the data in batches which means means that predict() calls can scale to very large arrays.happens in-memory and doesn't scale
not differentiabledifferentiable
use this if you just need the output valueuse this when you need to retrieve the gradients
Output is NumPy valueOutput is a Tensor
use this if you have batches of data to be predicteduse this for small dataset
relatively slower for small datarelatively faster for small data
\n
\n

Please check more detailed explanation in Keras FAQs

\n", + "system": "" + }, + { + "instruction": "Optimizing subgraph of large graph - slower than optimizing subgraph by itself", + "input": "", + "output": "

I am guessing that this is a generative adversarial network given by the relation between the losses and the parameters. It seems that the first group of parameters are the generative model and the second group make up the detector model.

\n

If my guesses are correct, then that would mean that the second model is using the output of the first model as its input. Admittedly, I am much more informed about PyTorch than TF. There is a comment which I believe is saying that the first model could be included in the second graph. I also think this is true. I would implement something similar to the following. The most important part is just creating a copy of the generated_tensor with no graph:

\n
// An arbitrary label\nlabel = torch.Tensor(1.0)\n\n// Treat GenerativeModel as the model with the first list of Variables/parameters\ngenerated_tensor = GenerativeModel(random_input_tensor)\n// Treat DetectorModel as the model with the second list of Variables/parameters\ndetector_prediction = DetectorModel(generated_tensor)\n\ngenerated_tensor_copy = torch.tensor(generated_tensor, requires_grad=False)\ndetector_prediction_copy = DetectorModel(generated_tensor_copy)\n\n//This is for optimizing the first model, but it has the second model in its graph\n// which is necessary.\nloss1 = loss_func1(detector_prediction, label)\n// This is for optimizing the second model. It will not have the first model in its graph\nloss2 = loss_func2(detector_prediction_copy, label)\n
\n

I hope this is helpful. If anyone knows how to do this in TF, that would probably be very invaluable.

\n", + "system": "" + }, + { + "instruction": "What is difference frozen_inference_graph.pb and saved_model.pb?", + "input": "", + "output": "

frozen_inference_graph.pb, is a frozen graph that cannot be trained anymore, it defines the graphdef and is actually a serialized graph and can be loaded with this code:

\n
def load_graph(frozen_graph_filename):\n    with tf.gfile.GFile(frozen_graph_filename, "rb") as f:\n        graph_def = tf.GraphDef()\n        graph_def.ParseFromString(f.read())\n        return graph_def\ntf.import_graph_def(load_graph("frozen_inference_graph.pb"))\n
\n

the saved model is a model generated by tf.saved_model.builder and is has to be imported into a session, this file contains the full graph with all training weights (just like the frozen graph) but here can be trained upon, and this one is not serialized and needs to be loaded by this snippet. The [] are tagconstants which can be read by the saved_model_cli. This model is also often served to predict on, like google ml engine par example:

\n
with tf.Session() as sess:\n    tf.saved_model.loader.load(sess, [], "foldername to saved_model.pb, only folder")\n
\n

model.ckpt files are checkpoints, generated during training, this is used to resume training or to have a back up when something goes wrong after along training. If you have a saved model and a frozen graph, then you can ignore this.

\n

.pbtxt files are basically the same as previous discussed models, but then human readable, not binary. These can be ignored as well.

\n

To answer your conversion question:\nsaved models can be transformed into a frozen graph and vice versa, although a saved_model extracted from a frozen graph is also no trainable, but the way it is stored is in saved model format. Checkpoints can be read in and loaded into a session, and there you can build a saved model from them.

\n

Hope I helped, any questions, ask away!

\n

ADDITION:

\n

How to freeze a graph, starting from a saved model folder structure.\nThis post is old, so the method I used before might not work anymore, it will most likely still work with Tensorflow 1.+.

\n

Start of by downloading this file from the tensorflow library, and then this code snippit should do the trick:

\n
    import freeze_graph # the file you just downloaded\n    from tensorflow.python.saved_model import tag_constants # might be unnecessary\n\n    freeze_graph.freeze_graph(\n        input_graph=None,\n        input_saver=None,\n        input_binary=None,\n        input_checkpoint=None,\n        output_node_names="dense_output/BiasAdd",\n        restore_op_name=None,\n        filename_tensor_name=None,\n        output_graph=os.path.join(path, "frozen_graph.pb"),\n        clear_devices=None,\n        initializer_nodes=None,\n        input_saved_model_dir=path,\n        saved_model_tags=tag_constants.SERVING\n    )\n
\n

output_node_names = Node name of the final operation, if you end on a dense layer, it will be dense layer_name/BiasAdd

\n

output_graph = output graph name

\n

input_saved_model_dir = root folder of the saved model

\n

saved_model_tags = saved model tags, in your case this can be None, I did however use a tag.

\n

ANOTHER ADDITION:

\n

The code to load models is already provided above. To actually predict you need a session, for a saved model this session is already created, for a frozen model, it's not.

\n

saved model:

\n
with tf.Session() as sess:\n    tf.saved_model.loader.load(sess, [], "foldername to saved_model.pb, only folder")\n    prediction = sess.run(output_tensor, feed_dict={input_tensor: test_images})\n
\n

Frozen model:

\n
tf.import_graph_def(load_graph("frozen_inference_graph.pb"))\nwith tf.Session() as sess:\n    prediction = sess.run(output_tensor, feed_dict={input_tensor: test_images})\n
\n

To further understand what your input and output layers are, you need to check them out with tensorboard, simply add the following line of code into your session:

\n
tf.summary.FileWriter("path/to/folder/to/save/logs", sess.graph)\n
\n

This line will create a log file that you can open with the cli/powershell, to see how to run tensorboard, check out this previously posted question

\n", + "system": "" + }, + { + "instruction": "Multivariate LSTM with missing values", + "input": "", + "output": "

As suggested by Fran\u00e7ois Chollet (creator of Keras) in his book, one way to handle missing values is to replace them with zero:

\n
\n

In general, with neural networks, it\u2019s safe to input missing values as\n0, with the condition that 0 isn\u2019t already a meaningful value. The\nnetwork will learn from exposure to the data that the value 0 means\nmissing data and will start ignoring the value. Note that if you\u2019re\nexpecting missing values in the test data, but the network was trained\non data without any missing values, the network won\u2019t have learned to\nignore missing values! In this situation, you should artificially\ngenerate training samples with missing entries: copy some training\nsamples several times, and drop some of the features that you expect\nare likely to be missing in the test data.

\n
\n

So you can assign zero to NaN elements, considering that zero is not used in your data (you can normalize the data to a range, say [1,2], and then assign zero to NaN elements; or alternatively, you can normalize all the values to be in range [0,1] and then use -1 instead of zero to replace NaN elements.)

\n

Another alternative way is to use a Masking layer in Keras. You give it a mask value, say 0, and it would drop any timestep (i.e. row) where all its features are equal to the mask value. However, all the following layers should support masking and you also need to pre-process your data and assign the mask value to all the features of a timestep which includes one or more NaN features. Example from Keras doc:

\n
\n

Consider a Numpy data array x of shape (samples, timesteps,features),\nto be fed to an LSTM layer. You want to mask timestep #3\nand #5 because you lack data for these timesteps. You can:

\n\n\n
model = Sequential()\nmodel.add(Masking(mask_value=0., input_shape=(timesteps, features)))\nmodel.add(LSTM(32))\n
\n
\n
\n

Update (May 2021): According to an updated suggestion from Fran\u00e7ois Cholle, it might be better to use a more meaningful or informative value (instead of using zero) for masking missing values. This value could be computed (e.g. mean, median, etc.) or predicted from the data itself.

\n", + "system": "" + }, + { + "instruction": "Illegal instruction (core dumped) after running import tensorflow", + "input": "", + "output": "

I would use older version. Looks like your CPU does not support AVX instructions.

\n\n

Quoting from their Release Page

\n\n
Breaking Changes\nPrebuilt binaries are now built against CUDA 9.0 and cuDNN 7.\nPrebuilt binaries will use AVX instructions. This may break TF on older CPUs.\n
\n\n

You have atleast two options:

\n\n
    \n
  1. Use tensorflow 1.5 or older

  2. \n
  3. Build from source

  4. \n
\n\n

Regarding your concern for differences, you will miss out on new features, but most basic features and documentations are not that different.

\n", + "system": "" + }, + { + "instruction": "Plot multiple graphs in one plot using Tensorboard", + "input": "", + "output": "

If you are using the SummaryWriter from tensorboardX or pytorch 1.2, you have a method called add_scalars:

\n\n

Call it like this:

\n\n
my_summary_writer.add_scalars(f'loss/check_info', {\n    'score': score[iteration],\n    'score_nf': score_nf[iteration],\n}, iteration)\n
\n\n

And it will show up like this:

\n\n

\"tensorboard

\n\n
\n\n

Be careful that add_scalars will mess with the organisation of your runs: it will add mutliple entries to this list (and thus create confusion):

\n\n

\"tensorboard

\n\n

I would recommend that instead you just do:

\n\n
my_summary_writer.add_scalar(f'check_info/score',    score[iter],    iter)\nmy_summary_writer.add_scalar(f'check_info/score_nf', score_nf[iter], iter)\n
\n", + "system": "" + }, + { + "instruction": "keras tensorboard: plot train and validation scalars in a same figure", + "input": "", + "output": "

To handle the validation logs with a separate writer, you can write a custom callback that wraps around the original TensorBoard methods.

\n\n\n\n
import os\nimport tensorflow as tf\nfrom keras.callbacks import TensorBoard\n\nclass TrainValTensorBoard(TensorBoard):\n    def __init__(self, log_dir='./logs', **kwargs):\n        # Make the original `TensorBoard` log to a subdirectory 'training'\n        training_log_dir = os.path.join(log_dir, 'training')\n        super(TrainValTensorBoard, self).__init__(training_log_dir, **kwargs)\n\n        # Log the validation metrics to a separate subdirectory\n        self.val_log_dir = os.path.join(log_dir, 'validation')\n\n    def set_model(self, model):\n        # Setup writer for validation metrics\n        self.val_writer = tf.summary.FileWriter(self.val_log_dir)\n        super(TrainValTensorBoard, self).set_model(model)\n\n    def on_epoch_end(self, epoch, logs=None):\n        # Pop the validation logs and handle them separately with\n        # `self.val_writer`. Also rename the keys so that they can\n        # be plotted on the same figure with the training metrics\n        logs = logs or {}\n        val_logs = {k.replace('val_', ''): v for k, v in logs.items() if k.startswith('val_')}\n        for name, value in val_logs.items():\n            summary = tf.Summary()\n            summary_value = summary.value.add()\n            summary_value.simple_value = value.item()\n            summary_value.tag = name\n            self.val_writer.add_summary(summary, epoch)\n        self.val_writer.flush()\n\n        # Pass the remaining logs to `TensorBoard.on_epoch_end`\n        logs = {k: v for k, v in logs.items() if not k.startswith('val_')}\n        super(TrainValTensorBoard, self).on_epoch_end(epoch, logs)\n\n    def on_train_end(self, logs=None):\n        super(TrainValTensorBoard, self).on_train_end(logs)\n        self.val_writer.close()\n
\n\n\n\n

Using the MNIST dataset as an example:

\n\n
from keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.datasets import mnist\n\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\nx_train = x_train.reshape(60000, 784)\nx_test = x_test.reshape(10000, 784)\nx_train = x_train.astype('float32')\nx_test = x_test.astype('float32')\nx_train /= 255\nx_test /= 255\n\nmodel = Sequential()\nmodel.add(Dense(64, activation='relu', input_shape=(784,)))\nmodel.add(Dense(10, activation='softmax'))\nmodel.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n\nmodel.fit(x_train, y_train, epochs=10,\n          validation_data=(x_test, y_test),\n          callbacks=[TrainValTensorBoard(write_graph=False)])\n
\n\n

You can then visualize the two curves on a same figure in TensorBoard.

\n\n

\"Screenshot\"

\n\n
\n\n

EDIT: I've modified the class a bit so that it can be used with eager execution.

\n\n

The biggest change is that I use tf.keras in the following code. It seems that the TensorBoard callback in standalone Keras does not support eager mode yet.

\n\n
import os\nimport tensorflow as tf\nfrom tensorflow.keras.callbacks import TensorBoard\nfrom tensorflow.python.eager import context\n\nclass TrainValTensorBoard(TensorBoard):\n    def __init__(self, log_dir='./logs', **kwargs):\n        self.val_log_dir = os.path.join(log_dir, 'validation')\n        training_log_dir = os.path.join(log_dir, 'training')\n        super(TrainValTensorBoard, self).__init__(training_log_dir, **kwargs)\n\n    def set_model(self, model):\n        if context.executing_eagerly():\n            self.val_writer = tf.contrib.summary.create_file_writer(self.val_log_dir)\n        else:\n            self.val_writer = tf.summary.FileWriter(self.val_log_dir)\n        super(TrainValTensorBoard, self).set_model(model)\n\n    def _write_custom_summaries(self, step, logs=None):\n        logs = logs or {}\n        val_logs = {k.replace('val_', ''): v for k, v in logs.items() if 'val_' in k}\n        if context.executing_eagerly():\n            with self.val_writer.as_default(), tf.contrib.summary.always_record_summaries():\n                for name, value in val_logs.items():\n                    tf.contrib.summary.scalar(name, value.item(), step=step)\n        else:\n            for name, value in val_logs.items():\n                summary = tf.Summary()\n                summary_value = summary.value.add()\n                summary_value.simple_value = value.item()\n                summary_value.tag = name\n                self.val_writer.add_summary(summary, step)\n        self.val_writer.flush()\n\n        logs = {k: v for k, v in logs.items() if not 'val_' in k}\n        super(TrainValTensorBoard, self)._write_custom_summaries(step, logs)\n\n    def on_train_end(self, logs=None):\n        super(TrainValTensorBoard, self).on_train_end(logs)\n        self.val_writer.close()\n
\n\n

The idea is the same --

\n\n\n\n

Again, you can use the MNIST data to test it,

\n\n
from tensorflow.keras.datasets import mnist\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.train import AdamOptimizer\n\ntf.enable_eager_execution()\n\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\nx_train = x_train.reshape(60000, 784)\nx_test = x_test.reshape(10000, 784)\nx_train = x_train.astype('float32')\nx_test = x_test.astype('float32')\nx_train /= 255\nx_test /= 255\ny_train = y_train.astype(int)\ny_test = y_test.astype(int)\n\nmodel = Sequential()\nmodel.add(Dense(64, activation='relu', input_shape=(784,)))\nmodel.add(Dense(10, activation='softmax'))\nmodel.compile(loss='sparse_categorical_crossentropy', optimizer=AdamOptimizer(), metrics=['accuracy'])\n\nmodel.fit(x_train, y_train, epochs=10,\n          validation_data=(x_test, y_test),\n          callbacks=[TrainValTensorBoard(write_graph=False)])\n
\n", + "system": "" + }, + { + "instruction": "How to set weights in Keras with a numpy array?", + "input": "", + "output": "

What is keras_layer in your code?

\n\n

You can set weights these ways:

\n\n
model.layers[i].set_weights(listOfNumpyArrays)    \nmodel.get_layer(layerName).set_weights(...)\nmodel.set_weights(listOfNumpyArrays)\n
\n\n

Where model is an instance of an existing model. \nYou can see the expected length of the list and its array shapes using the method get_weights() from the same instances above.

\n", + "system": "" + }, + { + "instruction": "Tensorflow: How to convert .meta, .data and .index model files into one graph.pb file", + "input": "", + "output": "

You can use this simple script to do that. But you must specify the names of the output nodes.

\n\n
import tensorflow as tf\n\nmeta_path = 'model.ckpt-22480.meta' # Your .meta file\noutput_node_names = ['output:0']    # Output nodes\n\nwith tf.Session() as sess:\n    # Restore the graph\n    saver = tf.train.import_meta_graph(meta_path)\n\n    # Load weights\n    saver.restore(sess,tf.train.latest_checkpoint('path/of/your/.meta/file'))\n\n    # Freeze the graph\n    frozen_graph_def = tf.graph_util.convert_variables_to_constants(\n        sess,\n        sess.graph_def,\n        output_node_names)\n\n    # Save the frozen graph\n    with open('output_graph.pb', 'wb') as f:\n      f.write(frozen_graph_def.SerializeToString())\n
\n\n

If you don't know the name of the output node or nodes, there are two ways

\n\n
    \n
  1. You can explore the graph and find the name with Netron or with console summarize_graph utility.

  2. \n
  3. You can use all the nodes as output ones as shown below.

  4. \n
\n\n
output_node_names = [n.name for n in tf.get_default_graph().as_graph_def().node]\n
\n\n

(Note that you have to put this line just before convert_variables_to_constants call.)

\n\n

But I think it's unusual situation, because if you don't know the output node, you cannot use the graph actually.

\n", + "system": "" + }, + { + "instruction": "Change images slider step in TensorBoard", + "input": "", + "output": "

I answered this question over there \"TensorBoard doesn't show all data points\", but this seems to be more popular so I will quote it here.

\n\n

You don't have to change the source code for this, there is a flag called --samples_per_plugin.

\n\n

Quoting from the help command

\n\n
\n

--samples_per_plugin: An optional comma separated list of plugin_name=num_samples pairs to explicitly\n specify how many samples to keep per tag for that plugin. For unspecified plugins, TensorBoard\n randomly downsamples logged summaries to reasonable values to prevent out-of-memory errors for long\n running jobs. This flag allows fine control over that downsampling. Note that 0 means keep all\n samples of that type. For instance, \"scalars=500,images=0\" keeps 500 scalars and all images. Most\n users should not need to set this flag.\n (default: '')

\n
\n\n

So if you want to have a slider of 100 images, use:

\n\n

tensorboard --samples_per_plugin images=100

\n", + "system": "" + }, + { + "instruction": "TensorBoard doesn't show all data points", + "input": "", + "output": "

You don't have to change the source code for this, there is a flag called --samples_per_plugin.

\n\n

Quoting from the help command

\n\n
\n

--samples_per_plugin: An optional comma separated list of plugin_name=num_samples pairs to explicitly\n specify how many samples to keep per tag for that plugin. For unspecified plugins, TensorBoard\n randomly downsamples logged summaries to reasonable values to prevent out-of-memory errors for long\n running jobs. This flag allows fine control over that downsampling. Note that 0 means keep all\n samples of that type. For instance, \"scalars=500,images=0\" keeps 500 scalars and all images. Most\n users should not need to set this flag.\n (default: '')

\n
\n\n

So if you want to have a slider of 100 images, use:

\n\n

tensorboard --samples_per_plugin images=100

\n", + "system": "" + }, + { + "instruction": "What does tf.gather_nd intuitively do?", + "input": "", + "output": "

Ok, so think about it like this:

\n\n

You are providing a list of index values to index the provided tensor to get those slices. The first dimension of the indices you provide is for each index you will perform. Let's pretend that tensor is just a list of lists.

\n\n

[[0]] means you want to get one specific slice(list) at index 0 in the provided tensor. Just like this:

\n\n
[tensor[0]]\n
\n\n

[[0], [1]] means you want get two specific slices at indices 0 and 1 like this:

\n\n
[tensor[0], tensor[1]]\n
\n\n

Now what if tensor is more than one dimensions? We do the same thing:

\n\n

[[0, 0]] means you want to get one slice at index [0,0] of the 0-th list. Like this:

\n\n
[tensor[0][0]]\n
\n\n

[[0, 1], [2, 3]] means you want return two slices at the indices and dimensions provided. Like this:

\n\n
[tensor[0][1], tensor[2][3]]\n
\n\n

I hope that makes sense. I tried using Python indexing to help explain how it would look in Python to do this to a list of lists.

\n", + "system": "" + }, + { + "instruction": "TensorFlow: questions regarding tf.argmax() and tf.equal()", + "input": "", + "output": "
tf.argmax(input, axis=None, name=None, dimension=None)\n
\n\n

Returns the index with the largest value across axis of a tensor.

\n\n

input is a Tensor and axis describes which axis of the input Tensor to reduce across. For vectors, use axis = 0.

\n\n

For your specific case let's use two arrays and demonstrate this

\n\n
pred = np.array([[31, 23,  4, 24, 27, 34],\n                [18,  3, 25,  0,  6, 35],\n                [28, 14, 33, 22, 20,  8],\n                [13, 30, 21, 19,  7,  9],\n                [16,  1, 26, 32,  2, 29],\n                [17, 12,  5, 11, 10, 15]])\n\ny = np.array([[31, 23,  4, 24, 27, 34],\n                [18,  3, 25,  0,  6, 35],\n                [28, 14, 33, 22, 20,  8],\n                [13, 30, 21, 19,  7,  9],\n                [16,  1, 26, 32,  2, 29],\n                [17, 12,  5, 11, 10, 15]])\n
\n\n

Evaluating tf.argmax(pred, 1) gives a tensor whose evaluation will give array([5, 5, 2, 1, 3, 0])

\n\n

Evaluating tf.argmax(y, 1) gives a tensor whose evaluation will give array([5, 5, 2, 1, 3, 0])

\n\n
tf.equal(x, y, name=None) takes two tensors(x and y) as inputs and returns the truth value of (x == y) element-wise. \n
\n\n

Following our example, tf.equal(tf.argmax(pred, 1),tf.argmax(y, 1)) returns a tensor whose evaluation will givearray(1,1,1,1,1,1).

\n\n

correct_prediction is a tensor whose evaluation will give a 1-D array of 0's and 1's

\n\n

y_test_prediction can be obtained by executing pred = tf.argmax(logits, 1)

\n\n

The documentation for tf.argmax and tf.equal can be accessed by following the links below.

\n\n

tf.argmax() https://www.tensorflow.org/api_docs/python/math_ops/sequence_comparison_and_indexing#argmax

\n\n

tf.equal() https://www.tensorflow.org/versions/master/api_docs/python/control_flow_ops/comparison_operators#equal

\n", + "system": "" + }, + { + "instruction": "Is it possible to make a trainable variable not trainable?", + "input": "", + "output": "

After looking at the documentation and the code, I was not able to find a way to remove a Variable from the TRAINABLE_VARIABLES.

\n\n

Here is what happens:

\n\n\n\n

First solution

\n\n

When calling the minimize method of the optimizer (see doc.), you can pass a var_list=[...] as argument with the variables you want to optimizer.

\n\n

For instance, if you want to freeze all the layers of VGG except the last two, you can pass the weights of the last two layers in var_list.

\n\n

Second solution

\n\n

You can use a tf.train.Saver() to save variables and restore them later (see this tutorial).

\n\n\n\n

Optionally, you can decide to save only some of the variables in your checkpoint file. See the doc for more info.

\n", + "system": "" + }, + { + "instruction": "Does tensorflow use automatic or symbolic gradients?", + "input": "", + "output": "

TF uses automatic differentiation and more specifically reverse-mode auto differentiation.

\n\n
\n\n

There are 3 popular methods to calculate the derivative:

\n\n
    \n
  1. Numerical differentiation
  2. \n
  3. Symbolic differentiation
  4. \n
  5. Automatic differentiation
  6. \n
\n\n

Numerical differentiation relies on the definition of the derivative: \"enter, where you put a very small h and evaluate function in two places. This is the most basic formula and on practice people use other formulas which give smaller estimation error. This way of calculating a derivative is suitable mostly if you do not know your function and can only sample it. Also it requires a lot of computation for a high-dim function.

\n\n

Symbolic differentiation manipulates mathematical expressions. If you ever used matlab or mathematica, then you saw something like this\n\"enter

\n\n

Here for every math expression they know the derivative and use various rules (product rule, chain rule) to calculate the resulting derivative. Then they simplify the end expression to obtain the resulting expression.

\n\n

Automatic differentiation manipulates blocks of computer programs. A differentiator has the rules for taking the derivative of each element of a program (when you define any op in core TF, you need to register a gradient for this op). It also uses chain rule to break complex expressions into simpler ones. Here is a good example how it works in real TF programs with some explanation.

\n\n
\n\n

You might think that Automatic differentiation is the same as Symbolic differentiation (in one place they operate on math expression, in another on computer programs). And yes, they are sometimes very similar. But for control flow statements (`if, while, loops) the results can be very different:

\n\n
\n

symbolic differentiation leads to inefficient code (unless carefully\n done) and faces the difficulty of converting a computer program into a\n single expression

\n
\n", + "system": "" + }, + { + "instruction": "TensorFlow operator overloading", + "input": "", + "output": "

If at least one of x or y is a tf.Tensor object, the expressions tf.add(x, y) and x + y are equivalent. The main reason you might use tf.add() is to specify an explicit name keyword argument for the created op, which is not possible with the overloaded operator version.

\n\n

Note that if neither x nor y is a tf.Tensor—for example if they are NumPy arrays—then x + y will not create a TensorFlow op. tf.add() always creates a TensorFlow op and converts its arguments to tf.Tensor objects. Therefore, if you are writing a library function that might accept both tensors and NumPy arrays, you might prefer to use tf.add().

\n\n

The following operators are overloaded in the TensorFlow Python API:

\n\n\n\n

Please note, __eq__ ( binary == ) is not overloaded. x == y will simply return a Python boolean whether x and y refer to the same tensor. You need to use tf.equal() explicitly to check for element-wise equality. Same goes for not equal, __ne__ ( binary != ).

\n", + "system": "" + }, + { + "instruction": "TensorFlow: Max of a tensor along an axis", + "input": "", + "output": "

The tf.reduce_max() operator provides exactly this functionality. By default it computes the global maximum of the given tensor, but you can specify a list of reduction_indices, which has the same meaning as axis in NumPy. To complete your example:

\n\n
x = tf.constant([[1, 220, 55], [4, 3, -1]])\nx_max = tf.reduce_max(x, reduction_indices=[1])\nprint sess.run(x_max)  # ==> \"array([220,   4], dtype=int32)\"\n
\n\n

If you compute the argmax using tf.argmax(), you could obtain the the values from a different tensor y by flattening y using tf.reshape(), converting the argmax indices into vector indices as follows, and using tf.gather() to extract the appropriate values:

\n\n
ind_max = tf.argmax(x, dimension=1)\ny = tf.constant([[1, 2, 3], [6, 5, 4]])\n\nflat_y = tf.reshape(y, [-1])  # Reshape to a vector.\n\n# N.B. Handles 2-D case only.\nflat_ind_max = ind_max + tf.cast(tf.range(tf.shape(y)[0]) * tf.shape(y)[1], tf.int64)\n\ny_ = tf.gather(flat_y, flat_ind_max)\n\nprint sess.run(y_) # ==> \"array([2, 6], dtype=int32)\"\n
\n", + "system": "" + }, + { + "instruction": "Visualizing output of convolutional layer in tensorflow", + "input": "", + "output": "

I don't know of a helper function but if you want to see all the filters you can pack them into one image with some fancy uses of tf.transpose.

\n\n

So if you have a tensor that's images x ix x iy x channels

\n\n
>>> V = tf.Variable()\n>>> print V.get_shape()\n\nTensorShape([Dimension(-1), Dimension(256), Dimension(256), Dimension(32)])\n
\n\n

So in this example ix = 256, iy=256, channels=32

\n\n

first slice off 1 image, and remove the image dimension

\n\n
V = tf.slice(V,(0,0,0,0),(1,-1,-1,-1)) #V[0,...]\nV = tf.reshape(V,(iy,ix,channels))\n
\n\n

Next add a couple of pixels of zero padding around the image

\n\n
ix += 4\niy += 4\nV = tf.image.resize_image_with_crop_or_pad(image, iy, ix)\n
\n\n

Then reshape so that instead of 32 channels you have 4x8 channels, lets call them cy=4 and cx=8.

\n\n
V = tf.reshape(V,(iy,ix,cy,cx)) \n
\n\n

Now the tricky part. tf seems to return results in C-order, numpy's default.

\n\n

The current order, if flattened, would list all the channels for the first pixel (iterating over cx and cy), before listing the channels of the second pixel (incrementing ix). Going across the rows of pixels (ix) before incrementing to the next row (iy).

\n\n

We want the order that would lay out the images in a grid.\nSo you go across a row of an image (ix), before stepping along the row of channels (cx), when you hit the end of the row of channels you step to the next row in the image (iy) and when you run out or rows in the image you increment to the next row of channels (cy). so:

\n\n
V = tf.transpose(V,(2,0,3,1)) #cy,iy,cx,ix\n
\n\n

Personally I prefer np.einsum for fancy transposes, for readability, but it's not in tf yet.

\n\n
newtensor = np.einsum('yxYX->YyXx',oldtensor)\n
\n\n

anyway, now that the pixels are in the right order, we can safely flatten it into a 2d tensor:

\n\n
# image_summary needs 4d input\nV = tf.reshape(V,(1,cy*iy,cx*ix,1))\n
\n\n

try tf.image_summary on that, you should get a grid of little images.

\n\n

Below is an image of what one gets after following all the steps here.

\n\n

\"enter

\n", + "system": "" + }, + { + "instruction": "Tensorflow: How to replace a node in a calculation graph?", + "input": "", + "output": "

TL;DR: If you can define the two computations as Python functions, you should do that. If you can't, there's more advanced functionality in TensorFlow to serialize and import graphs, which allows you to compose graphs from different sources.

\n\n

One way to do this in TensorFlow is to build the disjoint computations as separate tf.Graph objects, then convert them to serialized protocol buffers using Graph.as_graph_def():

\n\n
with tf.Graph().as_default() as g_1:\n  input = tf.placeholder(tf.float32, name=\"input\")\n  y = f(input)\n  # NOTE: using identity to get a known name for the output tensor.\n  output = tf.identity(y, name=\"output\")\n\ngdef_1 = g_1.as_graph_def()\n\nwith tf.Graph().as_default() as g_2:  # NOTE: g_2 not g_1       \n  input = tf.placeholder(tf.float32, name=\"input\")\n  z = g(input)\n  output = tf.identity(y, name=\"output\")\n\ngdef_2 = g_2.as_graph_def()\n
\n\n

Then you could compose gdef_1 and gdef_2 into a third graph, using tf.import_graph_def():

\n\n
with tf.Graph().as_default() as g_combined:\n  x = tf.placeholder(tf.float32, name=\"\")\n\n  # Import gdef_1, which performs f(x).\n  # \"input:0\" and \"output:0\" are the names of tensors in gdef_1.\n  y, = tf.import_graph_def(gdef_1, input_map={\"input:0\": x},\n                           return_elements=[\"output:0\"])\n\n  # Import gdef_2, which performs g(y)\n  z, = tf.import_graph_def(gdef_2, input_map={\"input:0\": y},\n                           return_elements=[\"output:0\"]\n
\n", + "system": "" + }, + { + "instruction": "pip installation error "No such file or directory: setup.py"", + "input": "", + "output": "

from https://github.com/tensorflow/tensorflow/issues/56

\n\n
\n

The command to type is \"pip install --upgrade pip\", and this should be\n added to the instructions right after where they tell the user to\n \"source bin/activate\"

\n
\n", + "system": "" + }, + { + "instruction": "Keras difference between generator and sequence", + "input": "", + "output": "

Those methods are roughly the same. It is correct to subclass\nSequence when your dataset doesn't fit in memory. But you shouldn't\nrun any preprocessing in any of the class' methods because that will\nbe reexecuted once per epoch wasting lots of computing resources.

\n\n

It is probably also easier to shuffle the samples rather than their\nindices. Like this:

\n\n

from random import shuffle

\n\n
class DataGen(Sequence):\n    def __init__(self, batch_size, preproc, type, x_set, y_set):\n        self.samples = list(zip(x, y))\n        self.batch_size = batch_size\n        shuffle(self.samples)\n        self.type = type\n        self.preproc = preproc\n\n    def __len__(self):\n        return int(np.ceil(len(self.samples) / self.batch_size))\n\n    def __getitem__(self, i):\n        batch = self.samples[i * self.batch_size:(i + 1) * self.batch_size]\n        return self.preproc.process(*zip(batch))\n\n    def on_epoch_end(self):\n        shuffle(self.samples)\n
\n\n

I think it is impossible to say why you run out of memory without\nknowing more about your data. My guess would be that your preproc\nfunction is doing something wrong. You can debug it by running:

\n\n
for e in DataGen(batch_size, preproc, *train):\n    print(e)\nfor e in DataGen(batch_size, preproc, *dev):\n    print(e)\n
\n\n

You will most likely run out of memory.

\n", + "system": "" + }, + { + "instruction": "Unknown initializer: GlorotUniform when loading Keras model", + "input": "", + "output": "

I ran into the same issue. After changing:

\n\n

from tensorflow import keras

\n\n

to:

\n\n

import keras

\n\n

life is once again worth living.

\n", + "system": "" + }, + { + "instruction": "'Tensor' object has no attribute 'lower'", + "input": "", + "output": "

The tensor must be passed to the layer when you are calling it, and not as an argument. Therefore it must be like this:

\n\n
x = Flatten()(x)  # first the layer is constructed and then it is called on x\n
\n\n

To make it more clear, it is equivalent to this:

\n\n
flatten_layer = Flatten()  # instantiate the layer\nx = flatten_layer(x)       # call it on the given tensor\n
\n", + "system": "" + }, + { + "instruction": "Tensorflow Keras Copy Weights From One Model to Another", + "input": "", + "output": "

Actually what you've done is much more than simply copying weights. You made these two models identical all the time. Every time you update one model - the second one is also updated - as both models have the same weights variables.

\n\n

If you want to just copy weights - the simplest way is by this command:

\n\n
target_model.set_weights(model.get_weights()) \n
\n", + "system": "" + }, + { + "instruction": "How to disable dropout while prediction in keras?", + "input": "", + "output": "

Keras does this by default. In Keras dropout is disabled in test mode. You can look at the code here and see that they use the dropped input in training and the actual input while testing.

\n\n

As far as I know you have to build your own training function from the layers and specify the training flag to predict with dropout (e.g. its not possible to specify a training flag for the predict functions). This is a problem in case you want to do GANs, which use the intermediate output for training and also train the network as a whole, due to a divergence between generated training images and generated test images.

\n", + "system": "" + }, + { + "instruction": "Tensorflow : What is the relationship between .ckpt file and .ckpt.meta and .ckpt.index , and .pb file", + "input": "", + "output": "\n\n

There are a lot of questions here about how to save and restore a graph. See the answer here for instance, but be careful that the two cited tutorials, though really helpful, are far from perfect, and a lot of people still seem to struggle to import a model in c++.

\n\n

EDIT:\nit looks like you can also use the .ckpt files in c++ now, so I guess you don't necessarily need the .pb file any more.

\n", + "system": "" + }, + { + "instruction": "What is the difference between Luong attention and Bahdanau attention?", + "input": "", + "output": "

I went through this Effective Approaches to Attention-based Neural Machine Translation. In the section 3.1 They have mentioned the difference between two attentions as follows,

\n
    \n
  1. Luong attention used top hidden layer states in both of encoder and decoder. But Bahdanau attention take concatenation of forward and backward source hidden state (Top Hidden Layer).

    \n
  2. \n
  3. In Luong attention they get the decoder hidden state at time t. Then calculate attention scores and from that get the context vector which will be concatenated with hidden state of the decoder and then predict.

    \n

    But in the Bahdanau at time t we consider about t-1 hidden state of the decoder. Then we calculate alignment , context vectors as above. But then we concatenate this context with hidden state of the decoder at t-1. So before the softmax this concatenated vector goes inside a GRU.

    \n
  4. \n
  5. Luong has diffferent types of alignments. Bahdanau has only concat score alignment model.

    \n
  6. \n
\n

\"Alignment

\n", + "system": "" + }, + { + "instruction": "What's the difference between Tensor and Variable in Tensorflow", + "input": "", + "output": "\n

Variable is basically a wrapper on Tensor that maintains state across multiple calls to run, and I think makes some things easier with saving and restoring graphs. A Variable needs to be initialized before you can run it. You provide an initial value when you define the Variable, but you have to call its initializer function in order to actually assign this value in your session and then use the Variable. A common way to do this is with tf.global_variables_initalizer().

\n

For example:

\n
import tensorflow as tf\ntest_var = tf.Variable([111, 11, 1])\nsess = tf.Session()\nsess.run(test_var)\n\n# Error!\n\nsess.run(tf.global_variables_initializer())  # initialize variables\nsess.run(test_var)\n# array([111, 11, 1], dtype=int32)\n
\n

As for why you use Variables instead of Tensors, basically a Variable is a Tensor with additional capability and utility. You can specify a Variable as trainable (the default, actually), meaning that your optimizer will adjust it in an effort to minimize your cost function; you can specify where the Variable resides on a distributed system; you can easily save and restore Variables and graphs. Some more information on how to use Variables can be found here.

\n", + "system": "" + }, + { + "instruction": "What is the difference between Keras and tf.keras in TensorFlow 1.1+?", + "input": "", + "output": "

tf.keras (formerly tf.contrib.keras) is an implementation of keras 2 implemented exclusively with/for tensorflow. It is hosted on the tensorflow repo and has a distinct code base than the official repo (the last commit there in the tf-keras branch dates back from May 2017).

\n\n

As a rule of thumb, if your code use any tensorflow-specific code, say anything in tf.data.* for providing inputs or tf.summary.* for visualization in tensorboard, it is simpler to just use tf.keras. (Some may even recommend not using the reference Keras implementation with TF because of occasional problems it has with this toolkit).

\n\n

On the other hand, if you plan to actively maintain a framework-agnostic code, using keras' own package is your only choice.

\n\n

If you don't care much about being framework-agnostic but don't use tensorflow-specific code, I would probably advise to go with tf.keras and start using tensorflow-specific code, esp. tf.data which is a game-changer in my opinion.

\n\n

EDIT

\n\n

I attended a talk by Chollet on TF2 (couldn't find a recording online) in which he basically said that support for frameworks other than TF would eventually drop and future developments of Keras would happen exclusively in tf.keras.

\n\n

From what I can see, this is already happening, as Keras' commit stream is getting thin these days.

\n\n

It makes a lot of sense since, as of now, the only other popular DL framework is pytorch, which is not supported by Keras. Keeping Keras code \"agnostic\" to tensorflow -- the only major framework it is supporting -- makes less and less sense.

\n\n

So today, my answer would be to use tf.keras by default, and keep Keras for legacy projects that would be hard to migrate -- that is the future-proof choice for Keras.

\n", + "system": "" + }, + { + "instruction": "TensorFlow wasn't compiled to use SSE (etc.) instructions, but these are available", + "input": "", + "output": "

Those are warnings (as indicated by the W after the colon. Errors have an E there).

\n

The warnings refer to the fact that your CPU supports SSE Instructions, which allow some fast in-hardware-parallel operations. Enabling these operations is a compile-time operation (i.e. to use SSE you need to build the library from the source enabling the specific SSE version you're targeting), in which case you might take a look at this question.

\n

Note, however, that SSE support influences only the computation speed. Tensorflow will work with or without SSE, but it might take longer for your code to run.\nNote, also, that this influences only the CPU. If you're using the GPU build of Tensorflow, all the operations run on the GPU will not benefit of SSE instructions.

\n", + "system": "" + }, + { + "instruction": "Why is my GPU slower than CPU when training LSTM/RNN models?", + "input": "", + "output": "

If you use Keras, use CuDNNLSTM in place of LSTM or CuDNNGRU in place of GRU. In my case (2 Tesla M60), I am seeing 10x boost of performance. By the way I am using batch size 128 as suggested by @Alexey Golyshev.

\n", + "system": "" + }, + { + "instruction": "ValueError: No gradients provided for any variable", + "input": "", + "output": "

This problem is caused by the following line: tf.nn.softmax_cross_entropy_with_logits(labels=activation, logits=Y)

\n

Based on documentation you should have

\n
\n

labels: Each row labels[i] must be a valid probability distribution.

\n

logits: Unscaled log probabilities.

\n
\n

So logits suppose to be your hypothesis and thus equal to activation and valid probability distribution is Y. So just change it with tf.nn.softmax_cross_entropy_with_logits(labels=Y, logits=activation)

\n", + "system": "" + }, + { + "instruction": "How to use tf.while_loop() in tensorflow", + "input": "", + "output": "

What is stopping you from adding more functionality to the body? You can build whatever complex computational graph you like in the body and take whatever inputs you like from the enclosing graph. Also, outside of the loop, you can then do whatever you want with whatever outputs you return. As you can see from the amount of 'whatevers', TensorFlow's control flow primitives were built with much generality in mind. Below is another 'simple' example, in case it helps.

\n\n
import tensorflow as tf\nimport numpy as np\n\ndef body(x):\n    a = tf.random_uniform(shape=[2, 2], dtype=tf.int32, maxval=100)\n    b = tf.constant(np.array([[1, 2], [3, 4]]), dtype=tf.int32)\n    c = a + b\n    return tf.nn.relu(x + c)\n\ndef condition(x):\n    return tf.reduce_sum(x) < 100\n\nx = tf.Variable(tf.constant(0, shape=[2, 2]))\n\nwith tf.Session():\n    tf.global_variables_initializer().run()\n    result = tf.while_loop(condition, body, [x])\n    print(result.eval())\n
\n", + "system": "" + }, + { + "instruction": "Installing tensorflow with anaconda in windows", + "input": "", + "output": "

Google has recently launched a newer version of TensorFlow r0.12 which include support of Windows both CPU and GPU version can now be installed using Python >=3.5.2 (only 64-bit) version.

\n

For CPU only version open command prompt and enter follow command

\n
pip install --upgrade https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow-0.12.0rc0-cp35-cp35m-win_amd64.whl\n
\n

Follow this TensorFlow on Windows for step-by-step instructions.

\n

UPDATE

\n

To install current latest version please run following command:

\n
pip install tensorflow #CPU only\npip install tensorflow-gpu #For GPU support\n
\n

UPDATE 2020

\n

TensorFlow 2.0 now has a single package for both CPU and GPU version, simply run

\n
pip install tensorflow\n
\n

If you're using Anaconda you can install TensorFlow GPU version and all of its dependencies (CUDA, cuDNN) by running:

\n
conda install -c tensorflow-gpu\n
\n", + "system": "" + }, + { + "instruction": "How to convert tf.int64 to tf.float32?", + "input": "", + "output": "

You can cast generally using:

\n\n
tf.cast(my_tensor, tf.float32)\n
\n\n

Replace tf.float32 with your desired type.

\n\n
\n\n

Edit: It seems at the moment at least, that tf.cast won't cast to an unsigned dtype (e.g. tf.uint8). To work around this, you can cast to the signed equivalent and used tf.bitcast to get all the way. e.g.

\n\n
tf.bitcast(tf.cast(my_tensor, tf.int8), tf.uint8)\n
\n", + "system": "" + }, + { + "instruction": "Tensorflow Dictionary lookup with String tensor", + "input": "", + "output": "

If you want to run this with new TF 2.x code with eager execution enabled by default. Below is the quick code snippet.

\n\n
import tensorflow as tf\n\n# build a lookup table\ntable = tf.lookup.StaticHashTable(\n    initializer=tf.lookup.KeyValueTensorInitializer(\n        keys=tf.constant([0, 1, 2, 3]),\n        values=tf.constant([10, 11, 12, 13]),\n    ),\n    default_value=tf.constant(-1),\n    name=\"class_weight\"\n)\n\n# now let us do a lookup\ninput_tensor = tf.constant([0, 0, 1, 1, 2, 2, 3, 3])\nout = table.lookup(input_tensor)\nprint(out)\n
\n\n

Output:

\n\n
tf.Tensor([10 10 11 11 12 12 13 13], shape=(8,), dtype=int32)\n
\n", + "system": "" + }, + { + "instruction": "InvalidArgumentError: cannot compute MatMul as input #0(zero-based) was expected to be a float tensor but is a double tensor [Op:MatMul]", + "input": "", + "output": "

Part 1: The problem is indeed the datatype of your input. By default your keras model expects float32 but you are passing a float64. You can either change the dtype of the model or change the input to float32.

\n\n

To change your model:

\n\n
def make_model():\n    net = tf.keras.Sequential()\n    net.add(tf.keras.layers.Dense(4, activation='relu', dtype='float32'))\n    net.add(tf.keras.layers.Dense(4, activation='relu'))\n    net.add(tf.keras.layers.Dense(1))\n    return net\n
\n\n

To change your input:\ny = y.astype('float32')

\n\n

Part 2: You need to call the function that computes your model (i.e. model(data)) under tf.GradientTape(). For example, you can replace your compute_loss method with the following:

\n\n
def compute_loss(model, x, y):\n    pred = model(x)\n    return tf.reduce_mean(tf.square(tf.subtract(pred, y)))\n
\n", + "system": "" + }, + { + "instruction": "How can I clear a model created with Keras and Tensorflow(as backend)?", + "input": "", + "output": "

keras.backend.clear_session() should clear the previous model. From https://keras.io/backend/:

\n\n
\n

Destroys the current TF graph and creates a new one.\n Useful to avoid clutter from old models / layers.

\n
\n", + "system": "" + }, + { + "instruction": "keras vs. tensorflow.python.keras - which one to use?", + "input": "", + "output": "

tensorflow.python.keras is just a bundle of keras with a single backend inside tensorflow package. This allows you to start using keras by installing just pip install tensorflow.

\n\n

keras package contains full keras library with three supported backends: tensorflow, theano and CNTK. If you even wish to switch between backends, you should choose keras package. This approach is also more flexible because it allows to install keras updates independently from tensorflow (which may not be easy to update, for example, because the next version may require a different version of CUDA driver) or vice versa. For this reason, I prefer to install keras as another package.

\n\n

In terms of API, there is no difference right now, but keras will probably be integrated more tightly into tensorflow in the future. So there is a chance there will be tensorflow-only features in keras, but even in this case it's not a blocker to use keras package.

\n\n

UPDATE

\n\n

As of Keras 2.3.0 release, Francois Chollet announced that users should switch towards tf.keras instead of plain Keras. Therefore, the change to tf.keras instead of keras should be made by all users.

\n", + "system": "" + }, + { + "instruction": "How to pip install old version of library(tensorflow)?", + "input": "", + "output": "

This works for me on Mac OS 10.13.1.

\n\n
pip install --user install tensorflow==1.3.0. \n
\n", + "system": "" + }, + { + "instruction": "Efficient element-wise multiplication of a matrix and a vector in TensorFlow", + "input": "", + "output": "

The simplest code to do this relies on the broadcasting behavior of tf.multiply()*, which is based on numpy's broadcasting behavior:

\n\n
x = tf.constant(5.0, shape=[5, 6])\nw = tf.constant([0.0, 1.0, 2.0, 3.0, 4.0, 5.0])\nxw = tf.multiply(x, w)\nmax_in_rows = tf.reduce_max(xw, 1)\n\nsess = tf.Session()\nprint sess.run(xw)\n# ==> [[0.0, 5.0, 10.0, 15.0, 20.0, 25.0],\n#      [0.0, 5.0, 10.0, 15.0, 20.0, 25.0],\n#      [0.0, 5.0, 10.0, 15.0, 20.0, 25.0],\n#      [0.0, 5.0, 10.0, 15.0, 20.0, 25.0],\n#      [0.0, 5.0, 10.0, 15.0, 20.0, 25.0]]\n\nprint sess.run(max_in_rows)\n# ==> [25.0, 25.0, 25.0, 25.0, 25.0]\n
\n\n

* In older versions of TensorFlow, tf.multiply() was called tf.mul(). You can also use the * operator (i.e. xw = x * w) to perform the same operation.

\n", + "system": "" + }, + { + "instruction": "What is the best way to implement weight constraints in TensorFlow?", + "input": "", + "output": "

You can take the Lagrangian approach and simply add a penalty for features of the variable you don't want.

\n\n

e.g. To encourage theta to be non-negative, you could add the following to the optimizer's objective function.

\n\n
    added_loss = -tf.minimum( tf.reduce_min(theta),0)\n
\n\n

If any theta are negative, then add2loss will be positive, otherwise zero. Scaling that to a meaningful value is left as an exercise to the reader. Scaling too little will not exert enough pressure. Too much may make things unstable.

\n", + "system": "" + }, + { + "instruction": "How can I clear a model created with Keras and Tensorflow(as backend)?", + "input": "", + "output": "

keras.backend.clear_session() should clear the previous model. From https://keras.io/backend/:

\n\n
\n

Destroys the current TF graph and creates a new one.\n Useful to avoid clutter from old models / layers.

\n
\n", + "system": "" + }, + { + "instruction": "Custom TensorFlow Keras optimizer", + "input": "", + "output": "

Update: TF2.2 forced me to clean up all implementations - so now they can be used as a reference for TF best practices. Also added a section below on _get_hyper vs. _set_hyper.

\n\n
\n\n

I've implemented Keras AdamW in all major TF & Keras versions - I invite you to examine optimizers_v2.py. Several points:

\n\n\n\n
\n\n\n\n

Latter deals with sparse layers - e.g. Embedding - and former with everything else; example.

\n\n\n\n

When defining trainable tf.Variables; example: weights' first and second order moments (e.g. Adam). It uses add_slot().

\n\n
\n\n

_get_hyper vs. _set_hyper: they enable setting and getting Python literals (int, str, etc), callables, and tensors. They exist largely for convenience: anything set via _set_hyper can be retrieved via _get_hyper, avoiding repeating boilerplate code. I dedicated a Q&A to it here.

\n", + "system": "" + }, + { + "instruction": "How does the Flatten layer work in Keras?", + "input": "", + "output": "

The Flatten() operator unrolls the values beginning at the last dimension (at least for Theano, which is \"channels first\", not \"channels last\" like TF. I can't run TensorFlow in my environment). This is equivalent to numpy.reshape with 'C' ordering:

\n\n
\n

\u2018C\u2019 means to read / write the elements using C-like index order, with\n the last axis index changing fastest, back to the first axis index\n changing slowest.

\n
\n\n

Here is a standalone example illustrating Flatten operator with the Keras Functional API. You should be able to easily adapt for your environment.

\n\n
import numpy as np\nfrom keras.layers import Input, Flatten\nfrom keras.models import Model\ninputs = Input(shape=(3,2,4))\n\n# Define a model consisting only of the Flatten operation\nprediction = Flatten()(inputs)\nmodel = Model(inputs=inputs, outputs=prediction)\n\nX = np.arange(0,24).reshape(1,3,2,4)\nprint(X)\n#[[[[ 0  1  2  3]\n#   [ 4  5  6  7]]\n#\n#  [[ 8  9 10 11]\n#   [12 13 14 15]]\n#\n#  [[16 17 18 19]\n#   [20 21 22 23]]]]\nmodel.predict(X)\n#array([[  0.,   1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.,\n#         11.,  12.,  13.,  14.,  15.,  16.,  17.,  18.,  19.,  20.,  21.,\n#         22.,  23.]], dtype=float32)\n
\n", + "system": "" + }, + { + "instruction": "Can I export a tensorflow summary to CSV?", + "input": "", + "output": "

While the answer here is as requested within tensorboard it only allows to download a csv for a single run of a single tag.\nIf you have for example 10 tags and 20 runs (what is not at all much) you would need to do the above step 200 times (that alone will probably take you more than a hour).\nIf now you for some reason would like to actually do something with the data for all runs for a single tag you would need to write some weird CSV accumulation script or copy everything by hand (what will probably cost you more than a day).

\n\n

Therefore I would like to add a solution that extracts a CSV file for every tag with all runs contained. Column headers are the run path names and row indices are the run step numbers.

\n\n
import os\nimport numpy as np\nimport pandas as pd\n\nfrom collections import defaultdict\nfrom tensorboard.backend.event_processing.event_accumulator import EventAccumulator\n\n\ndef tabulate_events(dpath):\n    summary_iterators = [EventAccumulator(os.path.join(dpath, dname)).Reload() for dname in os.listdir(dpath)]\n\n    tags = summary_iterators[0].Tags()['scalars']\n\n    for it in summary_iterators:\n        assert it.Tags()['scalars'] == tags\n\n    out = defaultdict(list)\n    steps = []\n\n    for tag in tags:\n        steps = [e.step for e in summary_iterators[0].Scalars(tag)]\n\n        for events in zip(*[acc.Scalars(tag) for acc in summary_iterators]):\n            assert len(set(e.step for e in events)) == 1\n\n            out[tag].append([e.value for e in events])\n\n    return out, steps\n\n\ndef to_csv(dpath):\n    dirs = os.listdir(dpath)\n\n    d, steps = tabulate_events(dpath)\n    tags, values = zip(*d.items())\n    np_values = np.array(values)\n\n    for index, tag in enumerate(tags):\n        df = pd.DataFrame(np_values[index], index=steps, columns=dirs)\n        df.to_csv(get_file_path(dpath, tag))\n\n\ndef get_file_path(dpath, tag):\n    file_name = tag.replace(\"/\", \"_\") + '.csv'\n    folder_path = os.path.join(dpath, 'csv')\n    if not os.path.exists(folder_path):\n        os.makedirs(folder_path)\n    return os.path.join(folder_path, file_name)\n\n\nif __name__ == '__main__':\n    path = \"path_to_your_summaries\"\n    to_csv(path)\n
\n\n

My solution builds upon: https://stackoverflow.com/a/48774926/2230045

\n\n
\n\n

EDIT:

\n\n

I created a more sophisticated version and released it on GitHub: https://github.com/Spenhouet/tensorboard-aggregator

\n\n

This version aggregates multiple tensorboard runs and is able to save the aggregates to a new tensorboard summary or as a .csv file.

\n", + "system": "" + }, + { + "instruction": "How to do slice assignment in Tensorflow", + "input": "", + "output": "

Currently, you can do slice assignment for variables in TensorFlow. There is no specific named function for it, but you can select a slice and call assign on it:

\n\n
my_var = my_var[4:8].assign(tf.zeros(4))\n
\n\n

First, note that (after having looked at the documentation) it seems that the return value of assign, even when applied to a slice, is always a reference to the whole variable after applying the update.

\n\n

EDIT: The information below is either deprecated, imprecise or was always wrong. The fact is that the returned value of assign is a tensor that can be readily used and already incorporates the dependency to the assignment, so simply evaluating that or using it in further operations will ensure it gets executed without need for an explicit tf.control_dependencies block.

\n\n
\n\n

Note, also, that this will only add the assignment op to the graph, but will not run it unless it is explicitly executed or set as a dependency of some other operation. A good practice is to use it in a tf.control_dependencies context:

\n\n
with tf.control_dependencies([my_var[4:8].assign(tf.zeros(4))]):\n    my_var = tf.identity(my_var)\n
\n\n

You can read more about it in TensorFlow issue #4638.

\n", + "system": "" + }, + { + "instruction": "Tensorflow: When to use tf.expand_dims?", + "input": "", + "output": "

expand_dims will not add or reduce elements in a tensor, it just changes the shape by adding 1 to dimensions. For example, a vector with 10 elements could be treated as a 10x1 matrix.

\n\n

The situation I have met to use expand_dims is when I tried to build a ConvNet to classify grayscale images. The grayscale images will be loaded as matrix of size [320, 320]. However, tf.nn.conv2d require input to be [batch, in_height, in_width, in_channels], where the in_channels dimension is missing in my data which in this case should be 1. So I used expand_dims to add one more dimension.

\n\n

In your case, I do not think you need expand_dims.

\n", + "system": "" + }, + { + "instruction": "Trouble with TensorFlow in Jupyter Notebook", + "input": "", + "output": "

Update

\n\n

TensorFlow website supports five installations.

\n\n

To my understanding, using Pip installation directly would be fine to import TensorFlow in Jupyter Notebook (as long as Jupyter Notebook was installed and there were no other issues) b/z it didn't create any virtual environments.

\n\n

Using virtualenv install and conda install would need to install jupyter into the newly created TensorFlow environment to allow TensorFlow to work in Jupyter Notebook (see the following original post section for more details).

\n\n

I believe docker install may require some port setup in the VirtualBox to make TensorFlow work in Jupyter Notebook (see this post).

\n\n

For installing from sources, it also depends on which environment the source code is built and installed into. If it's installed into a freshly created virtual environment or an virtual environment which didn't have Jupyter Notebook installed, it would also need to install Jupyter Notebook into the virtual environment to use Tensorflow in Jupyter Notebook.

\n\n

Original Post

\n\n

To use tensorflow in Ipython and/or Jupyter(Ipython) Notebook, you'll need to install Ipython and Jupyter (after installing tensorflow) under the tensorflow activated environment.

\n\n

Before install Ipython and Jupyter under tensorflow environment, if you do the following commands in terminal:

\n\n
username$ source activate tensorflow\n\n(tensorflow)username$ which ipython\n(tensorflow)username$ /Users/username/anaconda/bin/ipython\n\n(tensorflow)username$ which jupyter\n(tensorflow)username$ /Users/username/anaconda/bin/jupyter\n\n(tensorflow)username$ which python\n(tensorflow)username$ /User/username//anaconda/envs/tensorflow/bin/python\n
\n\n

This is telling you that when you open python from terminal, it is using the one installed in the \"environments\" where tensorflow is installed. Therefore you can actually import tensorflow successfully. However, if you are trying to run ipython and/or jupyter notebook, these are not installed under the \"environments\" equipped with tensorflow, hence it has to go back to use the regular environment which has no tensorflow module, hence you get an import error.

\n\n

You can verify this by listing out the items under envs/tensorflow/bin directory:

\n\n
(tensorflow) username$ ls /User/username/anaconda/envs/tensorflow/bin/\n
\n\n

You will see that there are no \"ipython\" and/or \"jupyer\" listing out.

\n\n

To use tensorflow with Ipython and/or Jupyter notebook, simply install them into the tensorflow environment:

\n\n
(tensorflow) username$ conda install ipython\n(tensorflow) username$ pip install jupyter #(use pip3 for python3)\n
\n\n

After installing them, there should be a \"jupyer\" and a \"ipython\" show up in the envs/tensorflow/bin/ directory.

\n\n

Notes:\nBefore trying to import tensorflow module in jupyter notebook, try close the notebook. And \"source deactivate tensorflow\" first, and then reactivate it (\"source activate tensorflow\") to make sure things are \"on the same page\". Then reopen the notebook and try import tensorflow. It should be import successfully (worked on mine at least).

\n", + "system": "" + }, + { + "instruction": "ImportError: cannot import name 'set_random_seed' from 'tensorflow' (C:\\Users\\polon\\Anaconda3\\lib\\site-packages\\tensorflow\\__init__.py)", + "input": "", + "output": "

In Tensoflow2 there is no need to perform

\n\n
from tensorflow import set_random_seed\n
\n\n

in order to run

\n\n
set_random_seed(x)\n
\n\n

(as it was in older version)

\n\n

Only have to run

\n\n
import tensorflow\ntensorflow.random.set_seed(x)\n
\n\n

Thanks to @David Buck

\n", + "system": "" + }, + { + "instruction": "how to get string value out of tf.tensor which dtype is string", + "input": "", + "output": "

You can use tf.py_func to wrap load_audio_file().

\n\n
import tensorflow as tf\n\ntf.enable_eager_execution()\n\ndef load_audio_file(file_path):\n    # you should decode bytes type to string type\n    print(\"file_path: \",bytes.decode(file_path),type(bytes.decode(file_path)))\n    return file_path\n\ntrain_dataset = tf.data.Dataset.list_files('clean_4s_val/*.wav')\ntrain_dataset = train_dataset.map(lambda x: tf.py_func(load_audio_file, [x], [tf.string]))\n\nfor one_element in train_dataset:\n    print(one_element)\n\nfile_path:  clean_4s_val/1.wav <class 'str'>\n(<tf.Tensor: id=32, shape=(), dtype=string, numpy=b'clean_4s_val/1.wav'>,)\nfile_path:  clean_4s_val/3.wav <class 'str'>\n(<tf.Tensor: id=34, shape=(), dtype=string, numpy=b'clean_4s_val/3.wav'>,)\nfile_path:  clean_4s_val/2.wav <class 'str'>\n(<tf.Tensor: id=36, shape=(), dtype=string, numpy=b'clean_4s_val/2.wav'>,)\n
\n\n

UPDATE for TF 2

\n\n

The above solution will not work with TF 2 (tested with 2.2.0), even when replacing tf.py_func with tf.py_function, giving

\n\n
InvalidArgumentError: TypeError: descriptor 'decode' requires a 'bytes' object but received a 'tensorflow.python.framework.ops.EagerTensor'\n
\n\n

To make it work in TF 2, make the following changes:

\n\n\n", + "system": "" + }, + { + "instruction": "tensorflow Mac OS gpu support", + "input": "", + "output": "

I wrote a little tutorial on compiling TensorFlow 1.2 with GPU support on macOS. I think it's customary to copy relevant parts to SO, so here it goes:

\n\n
    \n
  1. If you haven\u2019t used a TensorFlow-GPU set-up before, I suggest first setting everything up with TensorFlow 1.0 or 1.1, where you can still do pip install tensorflow-gpu. Once you get that working, the CUDA set-up would also work if you\u2019re compiling TensorFlow. If you have an external GPU, YellowPillow's answer (or mine) might help you get things set up.
  2. \n
  3. Follow the official tutorial \u201cInstalling TensorFlow from Sources\u201d, but obviously substitute git checkout r1.0 with git checkout r1.2.\nWhen doing ./configure, pay attention to the Python library path: it sometimes suggests an incorrect one. I chose the default options in most cases, except for: Python library path, CUDA support and compute capacity. Don\u2019t use Clang as the CUDA compiler: this will lead you to an error \u201cInconsistent crosstool configuration; no toolchain corresponding to 'local_darwin' found for cpu 'darwin'.\u201d. Using /usr/bin/gcc as your compiler will actually use Clang that comes with macOS / XCode. Below is my full configuration.
  4. \n
  5. TensorFlow 1.2 expects a C library called OpenMP, which is not available in the current Apple Clang. It should speed up multithreaded TensorFlow on multi-CPU machines, but it will also compile without it. We could try to build TensorFlow with gcc 4 (which I didn\u2019t manage), or simply remove the line that includes OpenMP from the build file. In my case I commented out line 98 of tensorflow/third_party/gpus/cuda/BUILD.tpl, which contained linkopts = [\u201c-lgomp\u201d] (but the location of the line might obviously change). Some people had issues with zmuldefs, but I assume that was with earlier versions; thanks to udnaan for pointing out that it\u2019s OK to comment out these lines.
  6. \n
  7. I had some problems building with the latest bazel 0.5.3, so I reverted to using 0.4.5 that I already had installed. But some discussion in a github issue mentioned bazel 0.5.2 also didn\u2019t have the problem.
  8. \n
  9. Now build with bazel and finish the installation as instructed by the official install guide. On my 3.2 GHz iMac this took about 37 minutes.
  10. \n
\n\n
\n

Using python library path: /Users/m/code/3rd/conda/envs/p3gpu/lib/python3.6/site-packages

\n \n

Do you wish to build TensorFlow with MKL support? [y/N] N

\n \n

No MKL support will be enabled for TensorFlow

\n \n

Please specify optimization flags to use during compilation when bazel option \"--config=opt\" is specified [Default is -march=native]:

\n \n

Do you wish to build TensorFlow with Google Cloud Platform support? [y/N]

\n \n

No Google Cloud Platform support will be enabled for TensorFlow

\n \n

Do you wish to build TensorFlow with Hadoop File System support? [y/N]

\n \n

No Hadoop File System support will be enabled for TensorFlow

\n \n

Do you wish to build TensorFlow with the XLA just-in-time compiler (experimental)? [y/N]

\n \n

No XLA support will be enabled for TensorFlow

\n \n

Do you wish to build TensorFlow with VERBS support? [y/N]

\n \n

No VERBS support will be enabled for TensorFlow

\n \n

Do you wish to build TensorFlow with OpenCL support? [y/N]

\n \n

No OpenCL support will be enabled for TensorFlow

\n \n

Do you wish to build TensorFlow with CUDA support? [y/N] y

\n \n

CUDA support will be enabled for TensorFlow

\n \n

Do you want to use clang as CUDA compiler? [y/N]

\n \n

nvcc will be used as CUDA compiler

\n \n

Please specify the CUDA SDK version you want to use, e.g. 7.0. [Leave empty to use system default]:

\n \n

Please specify the location where CUDA toolkit is installed. Refer to README.md for more details. [Default is /usr/local/cuda]:

\n \n

Please specify which gcc should be used by nvcc as the host compiler. [Default is /usr/bin/gcc]:

\n \n

Please specify the cuDNN version you want to use. [Leave empty to use system default]:

\n \n

Please specify the location where cuDNN library is installed. Refer to README.md for more details. [Default is /usr/local/cuda]:

\n \n

Please specify a list of comma-separated Cuda compute capabilities you want to build with.

\n \n

You can find the compute capability of your device at: https://developer.nvidia.com/cuda-gpus.

\n \n

Please note that each additional compute capability significantly increases your build time and binary size.

\n \n

[Default is: \"3.5,5.2\"]: 6.1

\n \n

INFO: Starting clean (this may take a while). Consider using --async if the clean takes more than several minutes.

\n \n

Configuration finished

\n
\n", + "system": "" + }, + { + "instruction": "How to load only specific weights on Keras", + "input": "", + "output": "

If your first 9 layers are consistently named between your original trained model and the new model, then you can use model.load_weights() with by_name=True. This will update weights only in the layers of your new model that have an identically named layer found in the original trained model.

\n\n

The name of the layer can be specified with the name keyword, for example:

\n\n
model.add(Dense(8, activation='relu',name='dens_1'))\n
\n", + "system": "" + }, + { + "instruction": "How do Monitored Training Sessions work?", + "input": "", + "output": "

I can't give some insights on how these classes were created, but here are a few things which I think are relevants on how you could use them.

\n\n

The tf.Session is a low level object in the python TensorFlow API while,\nas you said, the tf.train.MonitoredTrainingSession comes with a lot of handy features, especially useful in most of the common cases.

\n\n

Before describing some of the benefits of tf.train.MonitoredTrainingSession, let me answer the question about the graph used by the session. You can specify the tf.Graph used by the MonitoredTrainingSession by using a context manager with your_graph.as_default():

\n\n
from __future__ import print_function\nimport tensorflow as tf\n\ndef example():\n    g1 = tf.Graph()\n    with g1.as_default():\n        # Define operations and tensors in `g`.\n        c1 = tf.constant(42)\n        assert c1.graph is g1\n\n    g2 = tf.Graph()\n    with g2.as_default():\n        # Define operations and tensors in `g`.\n        c2 = tf.constant(3.14)\n        assert c2.graph is g2\n\n    # MonitoredTrainingSession example\n    with g1.as_default():\n        with tf.train.MonitoredTrainingSession() as sess:\n            print(c1.eval(session=sess))\n            # Next line raises\n            # ValueError: Cannot use the given session to evaluate tensor:\n            # the tensor's graph is different from the session's graph.\n            try:\n                print(c2.eval(session=sess))\n            except ValueError as e:\n                print(e)\n\n    # Session example\n    with tf.Session(graph=g2) as sess:\n        print(c2.eval(session=sess))\n        # Next line raises\n        # ValueError: Cannot use the given session to evaluate tensor:\n        # the tensor's graph is different from the session's graph.\n        try:\n            print(c1.eval(session=sess))\n        except ValueError as e:\n            print(e)\n\nif __name__ == '__main__':\n    example()\n
\n\n

So, as you said, the benefits of using MonitoredTrainingSession are that, this object takes care of

\n\n\n\n

but it has also the benefit of making your code easy to distribute as it also works differently depending if you specified the running process as a master or not.

\n\n

For example you could run something like:

\n\n
def run_my_model(train_op, session_args):\n    with tf.train.MonitoredTrainingSession(**session_args) as sess:\n        sess.run(train_op)\n
\n\n

that you would call in a non-distributed way:

\n\n
run_my_model(train_op, {})`\n
\n\n

or in a distributed way (see the distributed doc for more information on the inputs):

\n\n
run_my_model(train_op, {\"master\": server.target,\n                        \"is_chief\": (FLAGS.task_index == 0)})\n
\n\n

On the other hand, the benefit of using the raw tf.Session object is that, you don't have the extra benefits of tf.train.MonitoredTrainingSession, which can be useful if you don't plan to use them or if you want to get more control (for example on how the queues are started).

\n\n

EDIT (as per comment):\nFor the op initialisation, you would have to do something like (cf. official doc:

\n\n
# Define your graph and your ops\ninit_op = tf.global_variables_initializer()\nwith tf.Session() as sess:\n    sess.run(init_p)\n    sess.run(your_graph_ops,...)\n
\n\n

For the QueueRunner, I would refer you to the official doc where you will find more complete examples.

\n\n

EDIT2:

\n\n

The main concept to understand to get a sense on how tf.train.MonitoredTrainingSession works is the _WrappedSession class:

\n\n
\n

This wrapper is used as a base class for various session wrappers\n that provide additional functionality such as monitoring, coordination,\n and recovery.

\n
\n\n

The tf.train.MonitoredTrainingSession works (as of version 1.1) this way:

\n\n\n\n

In conclusion, the tf.train.MonitoredTrainingSession avoids a lot of boiler plate code while being easily extendable with the hooks mechanism.

\n", + "system": "" + }, + { + "instruction": "Should TensorFlow users prefer SavedModel over Checkpoint or GraphDef?", + "input": "", + "output": "

A checkpoint contains the value of (some of the) variables in a TensorFlow model. It is created by a Saver, which is either given specific Variables to save, or by default saves all (non-local) Variables.

\n\n

To use a checkpoint, you need to have a compatible TensorFlow Graph, whose Variables have the same names as the Variables in the checkpoint. (If you don't have a compatible Graph, you can still load the values stored in a checkpoint into selected Variables using the init_from_checkpoint utilities in contrib.)

\n\n

SavedModel is much more comprehensive: It contains a set of Graphs (MetaGraphs, in fact, saving collections and such), as well as a checkpoint which is supposed to be compatible with these Graphs, and any asset files that are needed to run the model (e.g. Vocabulary files). For each MetaGraph it contains, it also stores a set of signatures. Signatures define (named) input and output tensors.

\n\n

This means that given only a SavedModel, you can write tools (such as tensorflow/serving, or the new saved_model command line utility that will appear in tools/ shortly) that interpret or execute the graphs inside. All you have to provide is the data.

\n\n

If in doubt, I would always err on the side of writing a SavedModel, not just a checkpoint. Not only does this allow you to use tensorflow/serving (and other neat utilities that will grow in number), it makes sure that you have all the information necessary to run the model. Nothing is more frustrating than a checkpoint you cannot use any more because you modified your model and now it is incompatible with checkpoint files and all you want to do is run some predictions through it for comparison.

\n", + "system": "" + }, + { + "instruction": "Convert TensorFlow string to python string", + "input": "", + "output": "

In tensorflow 2.0.0, it can be done in the following way:

\n\n
import tensorflow as tf\n\nmy_str = tf.constant('Hello World')\nmy_str_npy = my_str.numpy()\n\nprint(my_str_npy)\ntype(my_str_npy)\n
\n\n

This converts a string tensor into a string of 'bytes' class

\n", + "system": "" + }, + { + "instruction": "'module' object has no attribute 'SummaryWriter'", + "input": "", + "output": "

tf.train.SummaryWriter is deprecated, instead use tf.summary.FileWriter.

\n\n

\u21b3 Adding Summaries to Event Files

\n\n
\n

It will be removed after 2016-11-30.\n Instructions for updating: Please switch to tf.summary.FileWriter. \n The interface and behavior is the same; this is just a rename.

\n
\n\n

<TF Official Migration Page> \u2733\ufe0e includes all current deprecated/renamed functions \u2733\ufe0e

\n", + "system": "" + }, + { + "instruction": "Understanding tf.extract_image_patches for extracting patches from an image", + "input": "", + "output": "

Here is how the method works:

\n\n

Here is some sample code with output to help demonstrate how it works:

\n
import tensorflow as tf\n\nn = 10\n# images is a 1 x 10 x 10 x 1 array that contains the numbers 1 through 100 in order\nimages = [[[[x * n + y + 1] for y in range(n)] for x in range(n)]]\n\n# We generate four outputs as follows:\n# 1. 3x3 patches with stride length 5\n# 2. Same as above, but the rate is increased to 2\n# 3. 4x4 patches with stride length 7; only one patch should be generated\n# 4. Same as above, but with padding set to 'SAME'\nwith tf.Session() as sess:\n  print tf.extract_image_patches(images=images, ksizes=[1, 3, 3, 1], strides=[1, 5, 5, 1], rates=[1, 1, 1, 1], padding='VALID').eval(), '\\n\\n'\n  print tf.extract_image_patches(images=images, ksizes=[1, 3, 3, 1], strides=[1, 5, 5, 1], rates=[1, 2, 2, 1], padding='VALID').eval(), '\\n\\n'\n  print tf.extract_image_patches(images=images, ksizes=[1, 4, 4, 1], strides=[1, 7, 7, 1], rates=[1, 1, 1, 1], padding='VALID').eval(), '\\n\\n'\n  print tf.extract_image_patches(images=images, ksizes=[1, 4, 4, 1], strides=[1, 7, 7, 1], rates=[1, 1, 1, 1], padding='SAME').eval()\n
\n

Output:

\n
[[[[ 1  2  3 11 12 13 21 22 23]\n   [ 6  7  8 16 17 18 26 27 28]]\n\n  [[51 52 53 61 62 63 71 72 73]\n   [56 57 58 66 67 68 76 77 78]]]]\n\n\n[[[[  1   3   5  21  23  25  41  43  45]\n   [  6   8  10  26  28  30  46  48  50]]\n\n  [[ 51  53  55  71  73  75  91  93  95]\n   [ 56  58  60  76  78  80  96  98 100]]]]\n\n\n[[[[ 1  2  3  4 11 12 13 14 21 22 23 24 31 32 33 34]]]]\n\n\n[[[[  1   2   3   4  11  12  13  14  21  22  23  24  31  32  33  34]\n   [  8   9  10   0  18  19  20   0  28  29  30   0  38  39  40   0]]\n\n  [[ 71  72  73  74  81  82  83  84  91  92  93  94   0   0   0   0]\n   [ 78  79  80   0  88  89  90   0  98  99 100   0   0   0   0   0]]]]\n
\n

So, for example, our first result looks like the following:

\n
 *  *  *  4  5  *  *  *  9 10 \n *  *  * 14 15  *  *  * 19 20 \n *  *  * 24 25  *  *  * 29 30 \n31 32 33 34 35 36 37 38 39 40 \n41 42 43 44 45 46 47 48 49 50 \n *  *  * 54 55  *  *  * 59 60 \n *  *  * 64 65  *  *  * 69 70 \n *  *  * 74 75  *  *  * 79 80 \n81 82 83 84 85 86 87 88 89 90 \n91 92 93 94 95 96 97 98 99 100 \n
\n

As you can see, we have 2 rows and 2 columns worth of patches, which are what out_rows and out_cols are.

\n", + "system": "" + }, + { + "instruction": "How do you get the name of the tensorflow output nodes in a Keras Model?", + "input": "", + "output": "

You can use Keras model.summary() to get the name of the last layer.

\n\n

If model.outputs is not empty you can get the node names via:

\n\n
[node.op.name for node in model.outputs]\n
\n\n

you get the session via

\n\n
session = keras.backend.get_session()\n
\n\n

and you convert all training variables to consts via

\n\n
min_graph = convert_variables_to_constants(session, session.graph_def, [node.op.name for node in model.outputs])\n
\n\n

after that you can write a protobuf-file via

\n\n
tensorflow.train.write_graph(min_graph, \"/logdir/\", \"file.pb\", as_text=True)\n
\n", + "system": "" + }, + { + "instruction": "In TensorFlow, how can I get nonzero values and their indices from a tensor with python?", + "input": "", + "output": "

You can achieve same result in Tensorflow using not_equal and where methods.

\n\n
zero = tf.constant(0, dtype=tf.float32)\nwhere = tf.not_equal(A, zero)\n
\n\n

where is a tensor of the same shape as A holding True or False, in the following case

\n\n
[[True, False],\n [False, True]]\n
\n\n

This would be sufficient to select zero or non-zero elements from A. If you want to obtain indices you can use wheremethod as follows:

\n\n
indices = tf.where(where)\n
\n\n

where tensor has two True values so indices tensor will have two entries. where tensor has rank of two, so entries will have two indices:

\n\n
[[0, 0],\n [1, 1]]\n
\n", + "system": "" + }, + { + "instruction": "TensorFlow - Read all examples from a TFRecords at once?", + "input": "", + "output": "

Just for clarity, I have a few thousand images in a single .tfrecords file, they're 720 by 720 rgb png files. The labels are one of 0,1,2,3.

\n\n

I also tried using the parse_example and couldn't make it work but this solution works with the parse_single_example.

\n\n

The downside is that right now I have to know how many items are in each .tf record, which is kind of a bummer. If I find a better way, I'll update the answer. Also, be careful going out of bounds of the number of records in the .tfrecords file, it will start over at the first record if you loop past the last record

\n\n

The trick was to have the queue runner use a coordinator.

\n\n

I left some code in here to save the images as they're being read in so that you can verify the image is correct.

\n\n
from PIL import Image\nimport numpy as np\nimport tensorflow as tf\n\ndef read_and_decode(filename_queue):\n reader = tf.TFRecordReader()\n _, serialized_example = reader.read(filename_queue)\n features = tf.parse_single_example(\n  serialized_example,\n  # Defaults are not specified since both keys are required.\n  features={\n      'image_raw': tf.FixedLenFeature([], tf.string),\n      'label': tf.FixedLenFeature([], tf.int64),\n      'height': tf.FixedLenFeature([], tf.int64),\n      'width': tf.FixedLenFeature([], tf.int64),\n      'depth': tf.FixedLenFeature([], tf.int64)\n  })\n image = tf.decode_raw(features['image_raw'], tf.uint8)\n label = tf.cast(features['label'], tf.int32)\n height = tf.cast(features['height'], tf.int32)\n width = tf.cast(features['width'], tf.int32)\n depth = tf.cast(features['depth'], tf.int32)\n return image, label, height, width, depth\n\n\ndef get_all_records(FILE):\n with tf.Session() as sess:\n   filename_queue = tf.train.string_input_producer([ FILE ])\n   image, label, height, width, depth = read_and_decode(filename_queue)\n   image = tf.reshape(image, tf.pack([height, width, 3]))\n   image.set_shape([720,720,3])\n   init_op = tf.initialize_all_variables()\n   sess.run(init_op)\n   coord = tf.train.Coordinator()\n   threads = tf.train.start_queue_runners(coord=coord)\n   for i in range(2053):\n     example, l = sess.run([image, label])\n     img = Image.fromarray(example, 'RGB')\n     img.save( \"output/\" + str(i) + '-train.png')\n\n     print (example,l)\n   coord.request_stop()\n   coord.join(threads)\n\nget_all_records('/path/to/train-0.tfrecords')\n
\n", + "system": "" + }, + { + "instruction": "Working with multiple graphs in TensorFlow", + "input": "", + "output": "

Your product is a global variable, and you've set it to point to \"g2/MatMul\".

\n\n

In particular

\n\n

Try

\n\n
print product\n
\n\n

and you'll see

\n\n
Tensor(\"g2/MatMul:0\", shape=(1, 1), dtype=float32)\n
\n\n

So the system takes \"g2/MatMul:0\" since that's the Tensor's name, and tries to find it in the graph g1 since that's the graph you set for the session. Incidentally you can see all nodes in the graph print [n.name for n in g1.as_graph_def().node]

\n\n

Generally, using more than one graph is rarely useful. You can't merge them and can't pass tensors between them. I'd recommend just doing

\n\n
tf.reset_default_graph()\na = tf.Constant(2)\nsess = tf.InteractiveSession()\n....\n
\n\n

This way you'll have one default graph and one default session and you can omit specifying graph or session in most cases. If you ever need to refer to them explicitly, you can get them from tf.get_default_graph() or tf.get_default_session()

\n", + "system": "" + }, + { + "instruction": "Clarification on tf.Tensor.set_shape()", + "input": "", + "output": "

As far as I know (and I wrote that code), there isn't a bug in Tensor.set_shape(). I think the misunderstanding stems from the confusing name of that method.

\n\n

To elaborate on the FAQ entry you quoted, Tensor.set_shape() is a pure-Python function that improves the shape information for a given tf.Tensor object. By \"improves\", I mean \"makes more specific\".

\n\n

Therefore, when you have a Tensor object t with shape (?,), that is a one-dimensional tensor of unknown length. You can call t.set_shape((1028178,)), and then t will have shape (1028178,) when you call t.get_shape(). This doesn't affect the underlying storage, or indeed anything on the backend: it merely means that subsequent shape inference using t can rely on the assertion that it is a vector of length 1028178.

\n\n

If t has shape (?,), a call to t.set_shape((478, 717, 3)) will fail, because TensorFlow already knows that t is a vector, so it cannot have shape (478, 717, 3). If you want to make a new Tensor with that shape from the contents of t, you can use reshaped_t = tf.reshape(t, (478, 717, 3)). This creates a new tf.Tensor object in Python; the actual implementation of tf.reshape() does this using a shallow copy of the tensor buffer, so it is inexpensive in practice.

\n\n

One analogy is that Tensor.set_shape() is like a run-time cast in an object-oriented language like Java. For example, if you have a pointer to an Object but know that, in fact, it is a String, you might do the cast (String) obj in order to pass obj to a method that expects a String argument. However, if you have a String s and try to cast it to a java.util.Vector, the compiler will give you an error, because these two types are unrelated.

\n", + "system": "" + }, + { + "instruction": "Multilabel Text Classification using TensorFlow", + "input": "", + "output": "

Change relu to sigmoid of output layer.\nModify cross entropy loss to explicit mathematical formula of sigmoid cross entropy loss (explicit loss was working in my case/version of tensorflow )

\n\n
import tensorflow as tf\n\n# hidden Layer\nclass HiddenLayer(object):\n    def __init__(self, input, n_in, n_out):\n        self.input = input\n\n        w_h = tf.Variable(tf.random_normal([n_in, n_out],mean = 0.0,stddev = 0.05))\n        b_h = tf.Variable(tf.zeros([n_out]))\n\n        self.w = w_h\n        self.b = b_h\n        self.params = [self.w, self.b]\n\n    def output(self):\n        linarg = tf.matmul(self.input, self.w) + self.b\n        self.output = tf.nn.relu(linarg)\n\n        return self.output\n\n# output Layer\nclass OutputLayer(object):\n    def __init__(self, input, n_in, n_out):\n        self.input = input\n\n        w_o = tf.Variable(tf.random_normal([n_in, n_out], mean = 0.0, stddev = 0.05))\n        b_o = tf.Variable(tf.zeros([n_out]))\n\n        self.w = w_o\n        self.b = b_o\n        self.params = [self.w, self.b]\n\n    def output(self):\n        linarg = tf.matmul(self.input, self.w) + self.b\n        #changed relu to sigmoid\n        self.output = tf.nn.sigmoid(linarg)\n\n        return self.output\n\n# model\ndef model():\n    h_layer = HiddenLayer(input = x, n_in = 20000, n_out = 1000)\n    o_layer = OutputLayer(input = h_layer.output(), n_in = 1000, n_out = 4000)\n\n    # loss function\n    out = o_layer.output()\n    # modified cross entropy to explicit mathematical formula of sigmoid cross entropy loss\n    cross_entropy = -tf.reduce_sum( (  (y_*tf.log(out + 1e-9)) + ((1-y_) * tf.log(1 - out + 1e-9)) )  , name='xentropy' )    \n\n    # regularization\n    l2 = (tf.nn.l2_loss(h_layer.w) + tf.nn.l2_loss(o_layer.w))\n    lambda_2 = 0.01\n\n    # compute loss\n    loss = cross_entropy + lambda_2 * l2\n\n    # compute accuracy for single label classification task\n    correct_pred = tf.equal(tf.argmax(out, 1), tf.argmax(y, 1))\n    accuracy = tf.reduce_mean(tf.cast(correct_pred, \"float\"))\n\n    return loss, accuracy\n
\n", + "system": "" + }, + { + "instruction": "ImportError: cannot import name 'to_categorical' from 'keras.utils' (/usr/local/lib/python3.7/dist-packages/keras/utils/__init__.py)", + "input": "", + "output": "

use this

\n
from tensorflow.keras.utils import to_categorical\n
\n

instead of

\n

from keras.utils import to_categorical

\n", + "system": "" + }, + { + "instruction": "Extract target from Tensorflow PrefetchDataset", + "input": "", + "output": "

You can convert it to a list with list(ds) and then recompile it as a normal Dataset with tf.data.Dataset.from_tensor_slices(list(ds)). From there your nightmare begins again but at least it's a nightmare that other people have had before.

\n

Note that for more complex datasets (e.g. nested dictionaries) you will need more preprocessing after calling list(ds), but this should work for the example you asked about.

\n

This is far from a satisfying answer but unfortunately the class is entirely undocumented and none of the standard Dataset tricks work.

\n", + "system": "" + }, + { + "instruction": "Should I use @tf.function for all functions?", + "input": "", + "output": "

TLDR: It depends on your function and whether you are in production or development. Don't use tf.function if you want to be able to debug your function easily, or if it falls under the limitations of AutoGraph or tf.v1 code compatibility.\nI would highly recommend watching the Inside TensorFlow talks about AutoGraph and Functions, not Sessions.

\n\n

In the following I'll break down the reasons, which are all taken from information made available online by Google.

\n\n

In general, the tf.function decorator causes a function to be compiled as a callable that executes a TensorFlow graph. This entails:

\n\n\n\n

There is detailed information available on the design ideas behind this.

\n\n

Benefits of decorating a function with tf.function

\n\n

General benefits

\n\n\n\n

For functions with Python code / Using AutoGraph via tf.function decoration

\n\n

If you want to use AutoGraph, using tf.function is highly recommended over calling AutoGraph directly.\nReasons for this include: Automatic control dependencies, it is required for some APIs, more caching, and exception helpers (Source).

\n\n

Drawbacks of decorating a function with tf.function

\n\n

General drawbacks

\n\n\n\n

For functions with Python code / Using AutoGraph via tf.function decoration

\n\n\n\n

Detailed information on AutoGraph limitations is available.

\n\n

For functions with tf.v1 code

\n\n\n\n

For functions with tf.v2 code

\n\n\n\n

Examples of limitations

\n\n

Creating variables more than once

\n\n

It is not allowed to create variables more than once, such as v in the following example:

\n\n
@tf.function\ndef f(x):\n    v = tf.Variable(1)\n    return tf.add(x, v)\n\nf(tf.constant(2))\n\n# => ValueError: tf.function-decorated function tried to create variables on non-first call.\n
\n\n

In the following code, this is mitigated by making sure that self.v is only created once:

\n\n
class C(object):\n    def __init__(self):\n        self.v = None\n    @tf.function\n    def f(self, x):\n        if self.v is None:\n            self.v = tf.Variable(1)\n        return tf.add(x, self.v)\n\nc = C()\nprint(c.f(tf.constant(2)))\n\n# => tf.Tensor(3, shape=(), dtype=int32)\n
\n\n

Hidden side effects not captured by AutoGraph

\n\n

Changes such as to self.a in this example can't be hidden, which leads to an error since cross-function analysis is not done (yet) (Source):

\n\n
class C(object):\n    def change_state(self):\n        self.a += 1\n\n    @tf.function\n    def f(self):\n        self.a = tf.constant(0)\n        if tf.constant(True):\n            self.change_state() # Mutation of self.a is hidden\n        tf.print(self.a)\n\nx = C()\nx.f()\n\n# => InaccessibleTensorError: The tensor 'Tensor(\"add:0\", shape=(), dtype=int32)' cannot be accessed here: it is defined in another function or code block. Use return values, explicit Python locals or TensorFlow collections to access it. Defined in: FuncGraph(name=cond_true_5, id=5477800528); accessed from: FuncGraph(name=f, id=5476093776).\n
\n\n

Changes in plain sight are no problem:

\n\n
class C(object):\n    @tf.function\n    def f(self):\n        self.a = tf.constant(0)\n        if tf.constant(True):\n            self.a += 1 # Mutation of self.a is in plain sight\n        tf.print(self.a)\n\nx = C()\nx.f()\n\n# => 1\n
\n\n

Example of limitation due to TF control flow

\n\n

This if statement leads to an error because the value for else needs to be defined for TF control flow:

\n\n
@tf.function\ndef f(a, b):\n    if tf.greater(a, b):\n        return tf.constant(1)\n\n# If a <= b would return None\nx = f(tf.constant(3), tf.constant(2))   \n\n# => ValueError: A value must also be returned from the else branch. If a value is returned from one branch of a conditional a value must be returned from all branches.\n
\n", + "system": "" + }, + { + "instruction": "How to use Model.fit which supports generators (after fit_generator deprecation)", + "input": "", + "output": "

Model.fit_generator is deprecated starting from tensorflow 2.1.0 which is currently is in rc1.\nYou can find the documentation for tf-2.1.0-rc1 here: https://www.tensorflow.org/versions/r2.1/api_docs/python/tf/keras/Model#fit

\n\n

As you can see the first argument of the Model.fit can take a generator so just pass it your generator.

\n", + "system": "" + }, + { + "instruction": "How to train a model in nodejs (tensorflow.js)?", + "input": "", + "output": "

First of all, the images needs to be converted to tensors. The first approach would be to create a tensor containing all the features (respectively a tensor containing all the labels). This should the way to go only if the dataset contains few images.

\n
  const imageBuffer = await fs.readFile(feature_file);\n  tensorFeature = tfnode.node.decodeImage(imageBuffer) // create a tensor for the image\n\n  // create an array of all the features\n  // by iterating over all the images\n  tensorFeatures = tf.stack([tensorFeature, tensorFeature2, tensorFeature3])\n
\n

The labels would be an array indicating the type of each image

\n
 labelArray = [0, 1, 2] // maybe 0 for dog, 1 for cat and 2 for birds\n
\n

One needs now to create a hot encoding of the labels

\n
 tensorLabels = tf.oneHot(tf.tensor1d(labelArray, 'int32'), 3);\n
\n

Once there is the tensors, one would need to create the model for training. Here is a simple model.

\n
const model = tf.sequential();\nmodel.add(tf.layers.conv2d({\n  inputShape: [height, width, numberOfChannels], // numberOfChannels = 3 for colorful images and one otherwise\n  filters: 32,\n  kernelSize: 3,\n  activation: 'relu',\n}));\nmodel.add(tf.layers.flatten());\nmodel.add(tf.layers.dense({units: 3, activation: 'softmax'}));\n
\n

Then the model can be trained

\n
model.fit(tensorFeatures, tensorLabels)\n
\n

If the dataset contains a lot of images, one would need to create a tfDataset instead. This answer discusses why.

\n
const genFeatureTensor = image => {\n      const imageBuffer = await fs.readFile(feature_file);\n      return tfnode.node.decodeImage(imageBuffer)\n}\n\nconst labelArray = indice => Array.from({length: numberOfClasses}, (_, k) => k === indice ? 1 : 0)\n\nfunction* dataGenerator() {\n  const numElements = numberOfImages;\n  let index = 0;\n  while (index < numFeatures) {\n    const feature = genFeatureTensor(imagePath);\n    const label = tf.tensor1d(labelArray(classImageIndex))\n    index++;\n    yield {xs: feature, ys: label};\n  }\n}\n\nconst ds = tf.data.generator(dataGenerator).batch(1) // specify an appropriate batchsize;\n
\n

And use model.fitDataset(ds) to train the model

\n
\n

The above is for training in nodejs. To do such a processing in the browser, genFeatureTensor can be written as follow:

\n
function loadImage(url){\n  return new Promise((resolve, reject) => {\n    const im = new Image()\n        im.crossOrigin = 'anonymous'\n        im.src = 'url'\n        im.onload = () => {\n          resolve(im)\n        }\n   })\n}\n\ngenFeatureTensor = image => {\n  const img = await loadImage(image);\n  return tf.browser.fromPixels(image);\n}\n
\n

One word of caution is that doing heavy processing might block the main thread in the browser. This is where web workers come into play.

\n", + "system": "" + }, + { + "instruction": "ImportError: Could not find 'cudart64_100.dll", + "input": "", + "output": "

The simplest way to fix is to install the latest \u2018NVIDIA GPU Computing Toolkit\u2019, because if it's not there, you'll be missing the 'cudart64_100.dll' library.\nThe only issue is that the latest copy of CUDA has this particular library upgraded to 'cudart64_101.dll', while the latest TensorFlow still requires the older 'cudart64_100.dll'.\nAnyways, one way to deal with this issue is to install the latest CUDA + CUDA from September 2018 and then copy 'cudart64_100.dll' library from old install to the new one.

\n\n

Or just visit my site where I linked the 'cudart64_100.dll' library downloaded from the CUDA Toolkit 10.0 (Sept 2018), to make it easier to copy it into the latest CUDA directory.

\n\n

Here are some screenshots to illustrate the process: https://www.joe0.com/2019/10/19/how-resolve-tensorflow-2-0-error-could-not-load-dynamic-library-cudart64_100-dll-dlerror-cudart64_100-dll-not-found/

\n", + "system": "" + }, + { + "instruction": "ValueError: Duplicate plugins for name projector", + "input": "", + "output": "

If you have two versions of tensorboard installed in your system,you need to uninstall one of them.

\n

I was stuck this for hours but I finally fixed it using:

\n

Worked like a charm:\nhttps://github.com/pytorch/pytorch/issues/22676

\n
pip uninstall tb-nightly tensorboardX tensorboard\npip install tensorboard\n
\n", + "system": "" + }, + { + "instruction": "How to quantize all nodes except a particular one?", + "input": "", + "output": "

EDIT: the previous answer refered to Tensorflow Lite code. I updated it to refer to Tensorflow.

\n

Looking at the implementation of Tensorflow's quantize_weights, these are the instances where weights don't get quantized:

\n
    \n
  1. tensor that is not type float
  2. \n
  3. tensor that has fewer than 1024 weights (or another number specified by the parameter minimum_size)
  4. \n
\n

If you are able to modify nodes in the graph so that they are excluded by one of the above rules, then quantize, then revert the nodes to the pre-quantized state, you might be able to do this.

\n", + "system": "" + }, + { + "instruction": "how to store numpy arrays as tfrecord?", + "input": "", + "output": "

The function _floats_feature described in the Tensorflow-Guide expects a scalar (either float32 or float64) as input.

\n\n
def _float_feature(value):\n  \"\"\"Returns a float_list from a float / double.\"\"\"\n  return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))\n
\n\n

As you can see the inputted scalar is written into a list (value=[value]) which is subsequently given to tf.train.FloatList as input. tf.train.FloatList expects an iterator that outputs a float in each iteration (as the list does).

\n\n

If your feature is not a scalar but a vectur, _float_feature can be rewritten to pass the iterator directly to tf.train.FloatList (instead of putting it into a list first).

\n\n
def _float_array_feature(value):\n  return tf.train.Feature(float_list=tf.train.FloatList(value=value))\n
\n\n

However if your feature has two or more dimensions this solution does not work anymore. Like @mmry described in his answer in this case flattening your feature or splitting it into several one-dimensional features would be a solution. The disadvantage of these two approaches is that the information about the actual shape of the feature is lost if no further effort is invested.

\n\n

Another possibility to write an example message for a higher dimensional array is to convert the array into a byte string and then use the _bytes_feature function described in the Tensorflow-Guide to write the example message for it. The example message is then serialized and written into a TFRecord file.

\n\n
import tensorflow as tf\nimport numpy as np\n\ndef _bytes_feature(value):\n    \"\"\"Returns a bytes_list from a string / byte.\"\"\"\n    if isinstance(value, type(tf.constant(0))): # if value ist tensor\n        value = value.numpy() # get value of tensor\n    return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\n\ndef serialize_array(array):\n  array = tf.io.serialize_tensor(array)\n  return array\n\n\n#----------------------------------------------------------------------------------\n# Create example data\narray_blueprint = np.arange(4, dtype='float64').reshape(2,2)\narrays = [array_blueprint+1, array_blueprint+2, array_blueprint+3]\n\n#----------------------------------------------------------------------------------\n# Write TFrecord file\nfile_path = 'data.tfrecords'\nwith tf.io.TFRecordWriter(file_path) as writer:\n  for array in arrays:\n    serialized_array = serialize_array(array)\n    feature = {'b_feature': _bytes_feature(serialized_array)}\n    example_message = tf.train.Example(features=tf.train.Features(feature=feature))\n    writer.write(example_message.SerializeToString())\n
\n\n

The serialized example messages stored in the TFRecord file can be accessed via tf.data.TFRecordDataset. After the example messages have been parsed, the original array needs to be restored from the byte string it was converted to. This is possible via tf.io.parse_tensor.

\n\n
# Read TFRecord file\ndef _parse_tfr_element(element):\n  parse_dic = {\n    'b_feature': tf.io.FixedLenFeature([], tf.string), # Note that it is tf.string, not tf.float32\n    }\n  example_message = tf.io.parse_single_example(element, parse_dic)\n\n  b_feature = example_message['b_feature'] # get byte string\n  feature = tf.io.parse_tensor(b_feature, out_type=tf.float64) # restore 2D array from byte string\n  return feature\n\n\ntfr_dataset = tf.data.TFRecordDataset('data.tfrecords') \nfor serialized_instance in tfr_dataset:\n  print(serialized_instance) # print serialized example messages\n\ndataset = tfr_dataset.map(_parse_tfr_element)\nfor instance in dataset:\n  print()\n  print(instance) # print parsed example messages with restored arrays\n
\n", + "system": "" + }, + { + "instruction": "Create keras callback to save model predictions and targets for each batch during training", + "input": "", + "output": "\n\n

NOTE: this answer is outdated and only works with TF1. Check @bers's answer for a solution tested on TF2.

\n\n
\n\n

After model compilation, the placeholder tensor for y_true is in model.targets and y_pred is in model.outputs.

\n\n

To save the values of these placeholders at each batch, you can:

\n\n
    \n
  1. First copy the values of these tensors into variables.
  2. \n
  3. Evaluate these variables in on_batch_end, and store the resulting arrays.
  4. \n
\n\n

Now step 1 is a bit involved because you'll have to add an tf.assign op to the training function model.train_function. Using current Keras API, this can be done by providing a fetches argument to K.function() when the training function is constructed.

\n\n

In model._make_train_function(), there's a line:

\n\n
self.train_function = K.function(inputs,\n                                 [self.total_loss] + self.metrics_tensors,\n                                 updates=updates,\n                                 name='train_function',\n                                 **self._function_kwargs)\n
\n\n

The fetches argument containing the tf.assign ops can be provided via model._function_kwargs (only works after Keras 2.1.0).

\n\n

As an example:

\n\n
from keras.layers import Dense\nfrom keras.models import Sequential\nfrom keras.callbacks import Callback\nfrom keras import backend as K\nimport tensorflow as tf\nimport numpy as np\n\nclass CollectOutputAndTarget(Callback):\n    def __init__(self):\n        super(CollectOutputAndTarget, self).__init__()\n        self.targets = []  # collect y_true batches\n        self.outputs = []  # collect y_pred batches\n\n        # the shape of these 2 variables will change according to batch shape\n        # to handle the \"last batch\", specify `validate_shape=False`\n        self.var_y_true = tf.Variable(0., validate_shape=False)\n        self.var_y_pred = tf.Variable(0., validate_shape=False)\n\n    def on_batch_end(self, batch, logs=None):\n        # evaluate the variables and save them into lists\n        self.targets.append(K.eval(self.var_y_true))\n        self.outputs.append(K.eval(self.var_y_pred))\n\n# build a simple model\n# have to compile first for model.targets and model.outputs to be prepared\nmodel = Sequential([Dense(5, input_shape=(10,))])\nmodel.compile(loss='mse', optimizer='adam')\n\n# initialize the variables and the `tf.assign` ops\ncbk = CollectOutputAndTarget()\nfetches = [tf.assign(cbk.var_y_true, model.targets[0], validate_shape=False),\n           tf.assign(cbk.var_y_pred, model.outputs[0], validate_shape=False)]\nmodel._function_kwargs = {'fetches': fetches}  # use `model._function_kwargs` if using `Model` instead of `Sequential`\n\n# fit the model and check results\nX = np.random.rand(10, 10)\nY = np.random.rand(10, 5)\nmodel.fit(X, Y, batch_size=8, callbacks=[cbk])\n
\n\n

Unless the number of samples can be divided by the batch size, the final batch will have a different size than other batches. So K.variable() and K.update() can't be used in this case. You'll have to use tf.Variable(..., validate_shape=False) and tf.assign(..., validate_shape=False) instead.

\n\n
\n\n

To verify the correctness of the saved arrays, you can add one line in training.py to print out the shuffled index array:

\n\n
if shuffle == 'batch':\n    index_array = _batch_shuffle(index_array, batch_size)\nelif shuffle:\n    np.random.shuffle(index_array)\n\nprint('Index array:', repr(index_array))  # Add this line\n\nbatches = _make_batches(num_train_samples, batch_size)\n
\n\n

The shuffled index array should be printed out during fitting:

\n\n
\nEpoch 1/1\nIndex array: array([8, 9, 3, 5, 4, 7, 1, 0, 6, 2])\n10/10 [==============================] - 0s 23ms/step - loss: 0.5670\n
\n\n

And you can check if cbk.targets is the same as Y[index_array]:

\n\n
index_array = np.array([8, 9, 3, 5, 4, 7, 1, 0, 6, 2])\nprint(Y[index_array])\n[[ 0.75325592  0.64857277  0.1926653   0.7642865   0.38901153]\n [ 0.77567689  0.13573623  0.4902501   0.42897559  0.55825652]\n [ 0.33760938  0.68195038  0.12303088  0.83509441  0.20991668]\n [ 0.98367778  0.61325065  0.28973401  0.28734073  0.93399794]\n [ 0.26097574  0.88219054  0.87951941  0.64887846  0.41996446]\n [ 0.97794604  0.91307569  0.93816428  0.2125808   0.94381495]\n [ 0.74813435  0.08036688  0.38094272  0.83178364  0.16713736]\n [ 0.52609421  0.39218962  0.21022047  0.58569125  0.08012982]\n [ 0.61276627  0.20679494  0.24124858  0.01262245  0.0994412 ]\n [ 0.6026137   0.25620512  0.7398164   0.52558182  0.09955769]]\n\nprint(cbk.targets)\n[array([[ 0.7532559 ,  0.64857274,  0.19266529,  0.76428652,  0.38901153],\n        [ 0.77567691,  0.13573623,  0.49025011,  0.42897558,  0.55825651],\n        [ 0.33760938,  0.68195039,  0.12303089,  0.83509439,  0.20991668],\n        [ 0.9836778 ,  0.61325067,  0.28973401,  0.28734073,  0.93399793],\n        [ 0.26097575,  0.88219053,  0.8795194 ,  0.64887846,  0.41996446],\n        [ 0.97794604,  0.91307569,  0.93816429,  0.2125808 ,  0.94381493],\n        [ 0.74813437,  0.08036689,  0.38094273,  0.83178365,  0.16713737],\n        [ 0.5260942 ,  0.39218962,  0.21022047,  0.58569127,  0.08012982]], dtype=float32),\n array([[ 0.61276627,  0.20679495,  0.24124858,  0.01262245,  0.0994412 ],\n        [ 0.60261369,  0.25620511,  0.73981643,  0.52558184,  0.09955769]], dtype=float32)]\n
\n\n

As you can see, there are two batches in cbk.targets (one \"full batch\" of size 8 and the final batch of size 2), and the row order is the same as Y[index_array].

\n", + "system": "" + }, + { + "instruction": "What is the difference of static Computational Graphs in tensorflow and dynamic Computational Graphs in Pytorch?", + "input": "", + "output": "

Both frameworks operate on tensors and view any model as a directed acyclic graph (DAG), but they differ drastically on how you can define them.

\n\n

TensorFlow follows \u2018data as code and code is data\u2019 idiom. In TensorFlow you define graph statically before a model can run. All communication with outer world is performed via tf.Session object and tf.Placeholder which are tensors that will be substituted by external data at runtime.

\n\n

In PyTorch things are way more imperative and dynamic: you can define, change and execute nodes as you go, no special session interfaces or placeholders. Overall, the framework is more tightly integrated with Python language and feels more native most of the times. When you write in TensorFlow sometimes you feel that your model is behind a brick wall with several tiny holes to communicate over. Anyways, this still sounds like a matter of taste more or less.

\n\n

However, those approaches differ not only in a software engineering perspective: there are several dynamic neural network architectures that can benefit from the dynamic approach. Recall RNNs: with static graphs, the input sequence length will stay constant. This means that if you develop a sentiment analysis model for English sentences you must fix the sentence length to some maximum value and pad all smaller sequences with zeros. Not too convenient, huh. And you will get more problems in the domain of recursive RNNs and tree-RNNs. Currently Tensorflow has limited support for dynamic inputs via Tensorflow Fold. PyTorch has it by-default.

\n\n

Reference:

\n\n

https://medium.com/towards-data-science/pytorch-vs-tensorflow-spotting-the-difference-25c75777377b

\n\n

https://www.reddit.com/r/MachineLearning/comments/5w3q74/d_so_pytorch_vs_tensorflow_whats_the_verdict_on/

\n", + "system": "" + }, + { + "instruction": "Difference between `apply_gradients` and `minimize` of optimizer in tensorflow", + "input": "", + "output": "

You can easily know from the link : https://www.tensorflow.org/get_started/get_started\n(tf.train API part) that they actually do the same job.\nThe difference it that: if you use the separated functions( tf.gradients, tf.apply_gradients), you can apply other mechanism between them, such as gradient clipping.

\n", + "system": "" + }, + { + "instruction": "How to turn off dropout for testing in Tensorflow?", + "input": "", + "output": "

The easiest way is to change the keep_prob parameter using a placeholder_with_default:

\n\n
prob = tf.placeholder_with_default(1.0, shape=())\nlayer = tf.nn.dropout(layer, prob)\n
\n\n

in this way when you train you can set the parameter like this:

\n\n
sess.run(train_step, feed_dict={prob: 0.5})\n
\n\n

and when you evaluate the default value of 1.0 is used.

\n", + "system": "" + }, + { + "instruction": "Are tf.layers.dense() and tf.contrib.layers.fully_connected() interchangeable?", + "input": "", + "output": "

They are essentially the same, the later calling the former.

\n\n

However tf.contrib.fully_connected adds a few functionalities on top of dense, in particular the possibility to pass a normalization and an activation in the parameters, \u00e0 la Keras. As noted by @wordforthewise, mind that the later defaults to tf.nn.relu.

\n\n

More generally, the TF API proposes (and mixes somewhat confusingly) low- and hi-level APIs; more on that here.

\n", + "system": "" + }, + { + "instruction": "What do the options in ConfigProto like allow_soft_placement and log_device_placement mean?", + "input": "", + "output": "

If you look at the API of ConfigProto, on line 278, you will see this:

\n\n
  // Whether soft placement is allowed. If allow_soft_placement is true,\n  // an op will be placed on CPU if\n  //   1. there's no GPU implementation for the OP\n  // or\n  //   2. no GPU devices are known or registered\n  // or\n  //   3. need to co-locate with reftype input(s) which are from CPU.\n  bool allow_soft_placement = 7;\n
\n\n

What this really means is that if you do something like this without allow_soft_placement=True, TensorFlow will throw an error.

\n\n
with tf.device('/gpu:0'):\n    # some op that doesn't have a GPU implementation\n
\n\n

Right below it, you will see on line 281:

\n\n
  // Whether device placements should be logged.\n  bool log_device_placement = 8;\n
\n\n

When log_device_placement=True, you will get a verbose output of something like this:

\n\n
2017-07-03 01:13:59.466748: I tensorflow/core/common_runtime/simple_placer.cc:841] Placeholder_1: (Placeholder)/job:localhost/replica:0/task:0/cpu:0\nPlaceholder: (Placeholder): /job:localhost/replica:0/task:0/cpu:0\n2017-07-03 01:13:59.466765: I tensorflow/core/common_runtime/simple_placer.cc:841] Placeholder: (Placeholder)/job:localhost/replica:0/task:0/cpu:0\nVariable/initial_value: (Const): /job:localhost/replica:0/task:0/cpu:0\n2017-07-03 01:13:59.466783: I tensorflow/core/common_runtime/simple_placer.cc:841] Variable/initial_value: (Const)/job:localhost/replica:0/task:0/cpu:0\n
\n\n

You can see where each operation is mapped to. For this case, they are all mapped to /cpu:0, but if you're in a distributed setting, there would be many more devices.

\n", + "system": "" + }, + { + "instruction": "Error: Failed to load the native TensorFlow runtime", + "input": "", + "output": "

My code worked perfectly after executing this line:

\n
pip install tensorflow --upgrade --force-reinstall\n
\n", + "system": "" + }, + { + "instruction": "Output from TensorFlow `py_func` has unknown rank/shape", + "input": "", + "output": "

Since py_func can execute arbitrary Python code and output anything, TensorFlow can't figure out the shape (it would require analyzing Python code of function body) You can instead give the shape manually

\n\n
y.set_shape(inp.get_shape())\n
\n", + "system": "" + }, + { + "instruction": "What is an epoch in TensorFlow?", + "input": "", + "output": "

An epoch, in Machine Learning, is the entire processing by the learning algorithm of the entire train-set.

\n\n

The MNIST train set is composed by 55000 samples.\nOnce the algorithm processed all those 55000 samples an epoch is passed.

\n", + "system": "" + }, + { + "instruction": "Tensorflow: How to convert scalar tensor to scalar variable in python?", + "input": "", + "output": "

In Tensorflow 2.0+, it's as simple as:

\n\n
my_tensor.numpy()\n
\n", + "system": "" + }, + { + "instruction": "How to fix MatMul Op has type float64 that does not match type float32 TypeError?", + "input": "", + "output": "

The tf.matmul() op does not perform automatic type conversions, so both of its inputs must have the same element type. The error message you are seeing indicates that you have a call to tf.matmul() where the first argument has type tf.float32, and the second argument has type tf.float64. You must convert one of the inputs to match the other, for example using tf.cast(x, tf.float32).

\n\n

Looking at your code, I don't see anywhere that a tf.float64 tensor is explicitly created (the default dtype for floating-point values in the TensorFlow Python API—e.g. for tf.constant(37.0)—is tf.float32). I would guess that the errors are caused by the np.loadtxt(filename) calls, which might be loading an np.float64 array. You can explicitly change them to load np.float32 arrays (which are converted to tf.float32 tensors) as follows:

\n\n
initial = np.loadtxt(filename).astype(np.float32)\n
\n", + "system": "" + }, + { + "instruction": "Tensorflow Different ways to Export and Run graph in C++", + "input": "", + "output": "

Here's my solution utilizing the V2 checkpoints introduced in TF 0.12.

\n\n

There's no need to convert all variables to constants or freeze the graph.

\n\n

Just for clarity, a V2 checkpoint looks like this in my directory models:

\n\n
checkpoint  # some information on the name of the files in the checkpoint\nmy-model.data-00000-of-00001  # the saved weights\nmy-model.index  # probably definition of data layout in the previous file\nmy-model.meta  # protobuf of the graph (nodes and topology info)\n
\n\n

Python part (saving)

\n\n
with tf.Session() as sess:\n    tf.train.Saver(tf.trainable_variables()).save(sess, 'models/my-model')\n
\n\n

If you create the Saver with tf.trainable_variables(), you can save yourself some headache and storage space. But maybe some more complicated models need all data to be saved, then remove this argument to Saver, just make sure you're creating the Saver after your graph is created. It is also very wise to give all variables/layers unique names, otherwise you can run in different problems.

\n\n

Python part (inference)

\n\n
with tf.Session() as sess:\n    saver = tf.train.import_meta_graph('models/my-model.meta')\n    saver.restore(sess, tf.train.latest_checkpoint('models/'))\n    outputTensors = sess.run(outputOps, feed_dict=feedDict)\n
\n\n

C++ part (inference)

\n\n

Note that checkpointPath isn't a path to any of the existing files, just their common prefix. If you mistakenly put there path to the .index file, TF won't tell you that was wrong, but it will die during inference due to uninitialized variables.

\n\n
#include <tensorflow/core/public/session.h>\n#include <tensorflow/core/protobuf/meta_graph.pb.h>\n\nusing namespace std;\nusing namespace tensorflow;\n\n...\n// set up your input paths\nconst string pathToGraph = \"models/my-model.meta\"\nconst string checkpointPath = \"models/my-model\";\n...\n\nauto session = NewSession(SessionOptions());\nif (session == nullptr) {\n    throw runtime_error(\"Could not create Tensorflow session.\");\n}\n\nStatus status;\n\n// Read in the protobuf graph we exported\nMetaGraphDef graph_def;\nstatus = ReadBinaryProto(Env::Default(), pathToGraph, &graph_def);\nif (!status.ok()) {\n    throw runtime_error(\"Error reading graph definition from \" + pathToGraph + \": \" + status.ToString());\n}\n\n// Add the graph to the session\nstatus = session->Create(graph_def.graph_def());\nif (!status.ok()) {\n    throw runtime_error(\"Error creating graph: \" + status.ToString());\n}\n\n// Read weights from the saved checkpoint\nTensor checkpointPathTensor(DT_STRING, TensorShape());\ncheckpointPathTensor.scalar<std::string>()() = checkpointPath;\nstatus = session->Run(\n        {{ graph_def.saver_def().filename_tensor_name(), checkpointPathTensor },},\n        {},\n        {graph_def.saver_def().restore_op_name()},\n        nullptr);\nif (!status.ok()) {\n    throw runtime_error(\"Error loading checkpoint from \" + checkpointPath + \": \" + status.ToString());\n}\n\n// and run the inference to your liking\nauto feedDict = ...\nauto outputOps = ...\nstd::vector<tensorflow::Tensor> outputTensors;\nstatus = session->Run(feedDict, outputOps, {}, &outputTensors);\n
\n", + "system": "" + }, + { + "instruction": "Tensor with unspecified dimension in tensorflow", + "input": "", + "output": "

As Ishamael says, all tensors have a static shape, which is known at graph construction time and accessible using Tensor.get_shape(); and a dynamic shape, which is only known at runtime and is accessible by fetching the value of the tensor, or passing it to an operator like tf.shape. In many cases, the static and dynamic shapes are the same, but they can be different - the static shape can be partially defined - in order allow the dynamic shape to vary from one step to the next.

\n\n

In your code normal_dist has a partially-defined static shape, because w_shape is a computed value. (TensorFlow sometimes attempts to evaluate\nthese computed values at graph construction time, but it gets stuck at tf.pack.) It infers the shape TensorShape([Dimension(None), Dimension(None)]), which means \"a matrix with an unknown number of rows and columns,\" because it knowns that w_shape is a vector of length 2, so the resulting normal_dist must be 2-dimensional.

\n\n

You have two options to deal with this. You can set the static shape as Ishamael suggests, but this requires you to know the shape at graph construction time. For example, the following may work:

\n\n
normal_dist.set_shape([input_data.get_shape()[1], labels.get_shape()[1]])\n
\n\n

Alternatively, you can pass validate_shape=False to the tf.Variable constructor. This allows you to create a variable with a partially-defined shape, but it limits the amount of static shape information that can be inferred later on in the graph.

\n", + "system": "" + }, + { + "instruction": "Printing the loss during TensorFlow training", + "input": "", + "output": "

You can fetch the value of cross_entropy by adding it to the list of arguments to sess.run(...). For example, your for-loop could be rewritten as follows:

\n\n
for i in range(100):\n    batch_xs, batch_ys = mnist.train.next_batch(100)\n    cross_entropy = -tf.reduce_sum(y_ * tf.log(y))\n    _, loss_val = sess.run([train_step, cross_entropy],\n                           feed_dict={x: batch_xs, y_: batch_ys})\n    print 'loss = ' + loss_val\n
\n\n

The same approach can be used to print the current value of a variable. Let's say, in addition to the value of cross_entropy, you wanted to print the value of a tf.Variable called W, you could do the following:

\n\n
for i in range(100):\n    batch_xs, batch_ys = mnist.train.next_batch(100)\n    cross_entropy = -tf.reduce_sum(y_ * tf.log(y))\n    _, loss_val, W_val = sess.run([train_step, cross_entropy, W],\n                                  feed_dict={x: batch_xs, y_: batch_ys})\n    print 'loss = %s' % loss_val\n    print 'W = %s' % W_val\n
\n", + "system": "" + }, + { + "instruction": "TensorFlow libdevice not found. Why is it not found in the searched path?", + "input": "", + "output": "

The following worked for me. With error message:

\n
error: Can't find libdevice directory ${CUDA_DIR}/nvvm/libdevice\n
\n

Firstly I searched for nvvm directory and then verified that libdevice directory existed:

\n
$ find / -type d -name nvvm 2>/dev/null\n/usr/lib/cuda/nvvm\n$ cd /usr/lib/cuda/nvvm\n/usr/lib/cuda/nvvm$ ls\nlibdevice\n/usr/lib/cuda/nvvm$ cd libdevice\n/usr/lib/cuda/nvvm/libdevice$ ls\nlibdevice.10.bc\n
\n

Then I exported the environment variable:

\n
export XLA_FLAGS=--xla_gpu_cuda_data_dir=/usr/lib/cuda\n
\n

as shown by @Insectatorious above. This solved the error and I was able to run the code.

\n", + "system": "" + }, + { + "instruction": "ModuleNotFoundError: No module named 'tensorflow_core.estimator' for tensorflow 2.1.0", + "input": "", + "output": "

TL;DR: Just solved this issue by making sure that both tensorflow and tensorflow-estimator were in the same version. (in my case, I needed to downgrade tensorflow-estimator, so conda install tensorflow-estimator=2.1.0 solved it for me)

\n

As you may have noticed, some tensorflow versions do not play well with certain GPUs, so I would first check some of the available builds with conda search tensorflow; then I would make sure that the chosen tensorflow build can actually recognize my GPU (with tf.config.list_physical_devices('GPU')); finally, I would search for a matching tensorflow-estimator build with conda search tensorflow-estimator and only then install it with conda install tensorflow-estimator=<chosen version> -n <my_venv>.

\n

It should be noted, however, that all these steps are mostly useful if you have interest in using your GPU. If that is not the case, than upgrading both packages (or downgrading/upgrading them so their versions match) may be the way.

\n", + "system": "" + }, + { + "instruction": "tensorflow warning - Found untraced functions such as lstm_cell_6_layer_call_and_return_conditional_losses", + "input": "", + "output": "

I think this warning can be safely ignored as you can find the same warning even in a tutorial given by tensorflow. I often see this warning when saving custom models such as graph NNs. You should be good to go as long as you don't want to access those non-callable functions.

\n

However, if you're annoyed by this big chunk of text, you can suppress this warning by adding the following at the top of the code.

\n
import absl.logging\nabsl.logging.set_verbosity(absl.logging.ERROR)\n
\n", + "system": "" + }, + { + "instruction": "ValueError: Shapes (None, 1) and (None, 3) are incompatible", + "input": "", + "output": "

The first problem is with the LSTM input_shape. input_shape = (20,85,1).

\n\n

From the doc: https://keras.io/layers/recurrent/

\n\n

LSTM layer expects 3D tensor with shape (batch_size, timesteps, input_dim).

\n\n

model.add(tf.keras.layers.Dense(nb_classes, activation='softmax')) - this suggets you're doing a multi-class classification.

\n\n

So, you need your y_train and y_test have to be one-hot-encoded. That means they must have dimension (number_of_samples, 3), where 3 denotes number of classes.

\n\n

You need to apply tensorflow.keras.utils.to_categorical to them.

\n\n
y_train = to_categorical(y_train, 3)\ny_test = to_categorical(y_test, 3)\n
\n\n

ref: https://www.tensorflow.org/api_docs/python/tf/keras/utils/to_categorical

\n\n

tf.keras.callbacks.History() - this callback is automatically applied to every Keras model. The History object gets returned by the fit method of models.

\n\n

ref: https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/History

\n", + "system": "" + }, + { + "instruction": "how to programmatically determine available GPU memory with tensorflow?", + "input": "", + "output": "

This code will return free GPU memory in MegaBytes for each GPU:

\n
import subprocess as sp\nimport os\n\ndef get_gpu_memory():\n    command = "nvidia-smi --query-gpu=memory.free --format=csv"\n    memory_free_info = sp.check_output(command.split()).decode('ascii').split('\\n')[:-1][1:]\n    memory_free_values = [int(x.split()[0]) for i, x in enumerate(memory_free_info)]\n    return memory_free_values\n\nget_gpu_memory()\n
\n

This answer relies on nvidia-smi being installed (which is pretty much always the case for Nvidia GPUs) and therefore is limited to NVidia GPUs.

\n", + "system": "" + }, + { + "instruction": "Non-deterministic behavior of TensorFlow while_loop()", + "input": "", + "output": "

Most likely, your problem is stemming from seeding issues, make sure that you set a seed for both random.seed(), and for numpy.random.seed(). You'll need to seed both, as numpy's random seed is independent from the random random state.

\n", + "system": "" + }, + { + "instruction": "Tensorflow: Multiple loss functions vs Multiple training ops", + "input": "", + "output": "

I want to make a subtle point that I don't think was made in previous answers.

\n\n

If you were using something like GradientDescentOptimizer, these would be very similar operations. That's because taking gradients is a linear operation, and the gradient of a sum is the same as the sum of the gradients.

\n\n

But, ADAM does something special: regardless of the scale of your loss, it scales the gradients so that they're always on the order of your learning rate. If you multiplied your loss by 1000, it wouldn't affect ADAM, because the change it would be normalized away.

\n\n

So, if your two losses are roughly the same magnitude, then it shouldn't make a difference. If one is much larger than the other, then keep in mind that summing before the minimization will essentially ignore the small one, while making two ops will spend equal effort minimizing both.

\n\n

I personally like dividing them up, which gives you more control over how much to focus on one loss or the other. For example, if it was multi-task learning, and one task was more important to get right than the other, two ops with different learning rates roughly accomplishes this.

\n", + "system": "" + }, + { + "instruction": "Keras replacing input layer", + "input": "", + "output": "

When you saved your model using:

\n\n
old_model.save('my_model.h5')\n
\n\n

it will save following:

\n\n
    \n
  1. The architecture of the model, allowing to create the model.
  2. \n
  3. The weights of the model.
  4. \n
  5. The training configuration of the model (loss, optimizer).
  6. \n
  7. The state of the optimizer, allowing training to resume from where you left before.
  8. \n
\n\n

So then, when you load the model:

\n\n
res50_model = load_model('my_model.h5')\n
\n\n

you should get the same model back, you can verify the same using:

\n\n
res50_model.summary()\nres50_model.get_weights()\n
\n\n

Now you can, pop the input layer and add your own using:

\n\n
res50_model.layers.pop(0)\nres50_model.summary()\n
\n\n

add new input layer:

\n\n
newInput = Input(batch_shape=(0,299,299,3))    # let us say this new InputLayer\nnewOutputs = res50_model(newInput)\nnewModel = Model(newInput, newOutputs)\n\nnewModel.summary()\nres50_model.summary()\n
\n", + "system": "" + }, + { + "instruction": "How to fix ipykernel_launcher.py: error: unrecognized arguments in jupyter?", + "input": "", + "output": "

A more elegant solution would be:

\n\n
args, unknown = parser.parse_known_args()\n
\n\n

instead of

\n\n
args = parser.parse_args()\n
\n", + "system": "" + }, + { + "instruction": "Difference between tf.data.Dataset.map() and tf.data.Dataset.apply()", + "input": "", + "output": "

The difference is that map will execute one function on every element of the Dataset separately, whereas apply will execute one function on the whole Dataset at once (such as group_by_window given as example in the documentation).

\n\n

The argument of apply is a function that takes a Dataset and returns a Dataset when the argument of map is a function that takes one element and returns one transformed element.

\n", + "system": "" + }, + { + "instruction": "Keras confusion about number of layers", + "input": "", + "output": "

Your first one consists of a 100 neurons input layer connected to one single output neuron

\n\n

Your second one consists of a 100 neurons input layer, one hidden layer of 32 neurons and one output layer of one single neuron.

\n\n

You have to think of your first layer as your input layer (with the same number of neurons as the dimenson, so 100 for you) connected to another layer with as many neuron as you specify (1 in your first case, 32 in the second one)

\n\n

In Keras what is useful is the command

\n\n
model.summary()\n
\n", + "system": "" + }, + { + "instruction": "How to install Tensorflow on Python 2.7 on Windows?", + "input": "", + "output": "

If you only need TensorFlow because of Keras and your are on Python 2.7.x, you can avoid installing Tensorflow(Google) and replace it by CNTK(Microsoft). According to Jeong-Yoon Lee CNTK is a lot (about 2 to 4 times) faster than TensorFlow for LSTM (Bidirectional LSTM on IMDb Data and Text Generation via LSTM), while speeds for other type of neural networks are close to each other.\nYour Keras code does not need to be modified (I checked it with 2 examples of Keras using TensorFlow and succesfully replaced TensorFlow with CNTK, without changing anything the Keras code.

\n\n

So how do you install it?

\n\n

-CPU-only version of CNTK:

\n\n
\n

pip install\n https://cntk.ai/PythonWheel/CPU-Only/cntk-2.4-cp27-cp27m-win_amd64.whl

\n
\n\n

-GPU version of CNTK:

\n\n
\n

pip install\n https://cntk.ai/PythonWheel/GPU/cntk-2.4-cp27-cp27m-win_amd64.whl

\n
\n\n

-Test CNTK install:

\n\n
\n

python -c \"import cntk; print(cntk.version)\"

\n
\n\n

-Install Keras: The Python Deep Learning library

\n\n
\n

pip install keras

\n
\n\n

-Enable CNTK as Keras back end iso TensorFlow

\n\n

modify the \"keras.json\" file under %USERPROFILE%/.keras

\n\n
{\n    \"epsilon\": 1e-07, \n    \"image_data_format\": \"channels_last\", \n    \"backend\": \"cntk\", \n    \"floatx\": \"float32\" \n}\n
\n", + "system": "" + }, + { + "instruction": "You must feed a value for placeholder tensor 'Placeholder' with dtype float", + "input": "", + "output": "

Some questions

\n\n

first
\nwhy you use sess = tf.InteractiveSession() and with tf.Session() as sess: at same time, just curious

\n\n

second\nwhat is your placeholder name x or images?
\nif name is x, {images: x_data...} won't feed x_data to x, it override(?) images
\nI think feed_dict should be {x: x_data...}

\n\n

if name is images,do you have two images in your program, placeholder and shuffle data, try to modify name of variable

\n", + "system": "" + }, + { + "instruction": "Keras verbose training progress bar writing a new line on each batch issue", + "input": "", + "output": "

I've added built-in support for keras in tqdm so you could use it instead (pip install "tqdm>=4.41.0"):

\n
from tqdm.keras import TqdmCallback\n...\nmodel.fit(..., verbose=0, callbacks=[TqdmCallback(verbose=2)])\n
\n

This turns off keras' progress (verbose=0), and uses tqdm instead. For the callback, verbose=2 means separate progressbars for epochs and batches. 1 means clear batch bars when done. 0 means only show epochs (never show batch bars).

\n

If there are problems with it please open an issue at https://github.com/tqdm/tqdm/issues

\n", + "system": "" + }, + { + "instruction": "what does the question mark in tensorflow shape mean?", + "input": "", + "output": "

It means that first dimension is not fixed in the graph and it can vary between run calls

\n", + "system": "" + }, + { + "instruction": "The print of string constant is always attached with 'b' inTensorFlow", + "input": "", + "output": "

Use sess.run(hello).decode() because it is a bytestring. decode method will return the string.

\n\n

Your print statement must look like

\n\n
print(sess.run(hello).decode())\n
\n", + "system": "" + }, + { + "instruction": "Obtaining total number of records from .tfrecords file in Tensorflow", + "input": "", + "output": "

To count the number of records, you should be able to use tf.python_io.tf_record_iterator.

\n\n
c = 0\nfor fn in tf_records_filenames:\n  for record in tf.python_io.tf_record_iterator(fn):\n     c += 1\n
\n\n

To just keep track of the model training, tensorboard comes in handy.

\n", + "system": "" + }, + { + "instruction": "Keras Maxpooling2d layer gives ValueError", + "input": "", + "output": "

Quoting an answer mentioned in github, you need to specify the dimension ordering:

\n\n

Keras is a wrapper over Theano or Tensorflow libraries. Keras uses the setting variable image_dim_ordering to decide if the input layer is Theano or Tensorflow format. This setting can be specified in 2 ways -

\n\n
    \n
  1. specify 'tf' or 'th' in ~/.keras/keras.json like so - image_dim_ordering: 'th'. Note: this is a json file.
  2. \n
  3. or specify the image_dim_ordering in your model like so: model.add(MaxPooling2D(pool_size=(2, 2), dim_ordering=\"th\"))
  4. \n
\n\n

Update: Apr 2020 Keras 2.2.5 link seems to have an updated API where dim_ordering is changed to data_format so:

\n\n

keras.layers.MaxPooling2D(pool_size=(2, 2), strides=None, padding='valid', data_format='channels_first') to get NCHW or use channels_last to get NHWC

\n\n

Appendix: image_dim_ordering in 'th' mode the channels dimension (the depth) is at index 1 (e.g. 3, 256, 256). In 'tf' mode is it at index 3 (e.g. 256, 256, 3). Quoting @naoko from comments.

\n", + "system": "" + }, + { + "instruction": "Tensorflow Documentation", + "input": "", + "output": "

Do not Google about Tensorflow documentation, use the TensorFlow Python reference documentation and ctrl + f

\n", + "system": "" + }, + { + "instruction": "How to suppress verbose Tensorflow logging?", + "input": "", + "output": "

2.0 Update (10/8/19)\nSetting TF_CPP_MIN_LOG_LEVEL should still work (see below in v0.12+ update), but there is currently an issue open (see issue #31870). If setting TF_CPP_MIN_LOG_LEVEL does not work for you (again, see below), try doing the following to set the log level:

\n\n
import tensorflow as tf\ntf.get_logger().setLevel('INFO')\n
\n\n

In addition, please see the documentation on tf.autograph.set_verbosity which sets the verbosity of autograph log messages - for example:

\n\n
# Can also be set using the AUTOGRAPH_VERBOSITY environment variable\ntf.autograph.set_verbosity(1)\n
\n\n

v0.12+ Update (5/20/17), Working through TF 2.0+:

\n\n

In TensorFlow 0.12+, per this issue, you can now control logging via the environmental variable called TF_CPP_MIN_LOG_LEVEL; it defaults to 0 (all logs shown) but can be set to one of the following values under the Level column.

\n\n
  Level | Level for Humans | Level Description                  \n -------|------------------|------------------------------------ \n  0     | DEBUG            | [Default] Print all messages       \n  1     | INFO             | Filter out INFO messages           \n  2     | WARNING          | Filter out INFO & WARNING messages \n  3     | ERROR            | Filter out all messages      \n
\n\n

See the following generic OS example using Python:

\n\n
import os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'  # or any {'0', '1', '2'}\nimport tensorflow as tf\n
\n\n

To be thorough, you call also set the level for the Python tf_logging module, which is used in e.g. summary ops, tensorboard, various estimators, etc.

\n\n
# append to lines above\ntf.logging.set_verbosity(tf.logging.ERROR)  # or any {DEBUG, INFO, WARN, ERROR, FATAL}\n
\n\n

For 1.14 you will receive warnings if you do not change to use the v1 API as follows:

\n\n
# append to lines above\ntf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)  # or any {DEBUG, INFO, WARN, ERROR, FATAL}\n
\n\n


\nFor Prior Versions of TensorFlow or TF-Learn Logging (v0.11.x or lower):

\n\n

View the page below for information on TensorFlow logging; with the new update, you're able to set the logging verbosity to either DEBUG, INFO, WARN, ERROR, or FATAL. For example:

\n\n
tf.logging.set_verbosity(tf.logging.ERROR)\n
\n\n

The page additionally goes over monitors which can be used with TF-Learn models. Here is the page.

\n\n

This doesn't block all logging, though (only TF-Learn). I have two solutions; one is a 'technically correct' solution (Linux) and the other involves rebuilding TensorFlow.

\n\n
script -c 'python [FILENAME].py' | grep -v 'I tensorflow/'\n
\n\n

For the other, please see this answer which involves modifying source and rebuilding TensorFlow.

\n", + "system": "" + }, + { + "instruction": "Confused by the behavior of `tf.cond`", + "input": "", + "output": "

TL;DR: If you want tf.cond() to perform a side effect (like an assignment) in one of the branches, you must create the op that performs the side effect inside the function that you pass to tf.cond().

\n

The behavior of tf.cond() is a little unintuitive. Because execution in a TensorFlow graph flows forward through the graph, all operations that you refer to in either branch must execute before the conditional is evaluated. This means that both the true and the false branches receive a control dependency on the tf.assign() op, and so y always gets set to 2, even if pred is False.

\n

The solution is to create the tf.assign() op inside the function that defines the true branch. For example, you could structure your code as follows:

\n
pred = tf.placeholder(tf.bool, shape=[])\nx = tf.Variable([1])\ndef update_x_2():\n  with tf.control_dependencies([tf.assign(x, [2])]):\n    return tf.identity(x)\ny = tf.cond(pred, update_x_2, lambda: tf.identity(x))\nwith tf.Session() as session:\n  session.run(tf.initialize_all_variables())\n  print(y.eval(feed_dict={pred: False}))  # ==> [1]\n  print(y.eval(feed_dict={pred: True}))   # ==> [2]\n
\n", + "system": "" + }, + { + "instruction": "Could not load dynamic library 'libcudart.so.11.0';", + "input": "", + "output": "

Firstly:\nCan you find out where the "libcudart.so.11.0" is\nIf you lost it at error stack, you can replace the "libcudart.so.11.0" by your word in below:

\n
sudo find / -name 'libcudart.so.11.0'\n
\n

Outputs in my system. This result shows where the "libcudart.so.11.0" is in the system:

\n
/usr/local/cuda-11.1/targets/x86_64-linux/lib/libcudart.so.11.0\n
\n

If the result shows nothing, please make sure you have install cuda or other staff that must install in your system.

\n

Second, add the path to environment file.

\n
# edit /etc/profile\nsudo vim /etc/profile\n# append path to "LD_LIBRARY_PATH" in profile file\nexport LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda-11.1/targets/x86_64-linux/lib\n# make environment file work\nsource /etc/profile\n
\n

You may also refer to this link

\n

Third thing you may try is:

\n
conda install cudatoolkit\n
\n", + "system": "" + }, + { + "instruction": "Could not load dynamic library 'libcublas.so.10'; dlerror: libcublas.so.10: cannot open shared object file: No such file or directory;", + "input": "", + "output": "

On Ubuntu 20.04, you can simply install NVIDIAs cuda toolkit cuda:

\n
sudo apt-get update\nsudo apt install nvidia-cuda-toolkit\n
\n

There are also install advices for Windows.

\n

The packge is around 1GB and it took a while to install... Some minutes later you need to export PATH variables so that it can be found:

\n
    \n
  1. Find Shared Object
  2. \n
\n
sudo find / -name 'libcudart.so*'\n\n/usr/lib/x86_64-linux-gnu/libcudart.so.10.1\n/usr/lib/x86_64-linux-gnu/libcudart.so\n
\n
    \n
  1. Add the folder to path, so that python finds it
  2. \n
\n
export PATH=/usr/lib/x86_64-linux-gnu${PATH:+:${PATH}}\nexport LD_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu:${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}\n
\n
    \n
  1. Permissions
  2. \n
\n
sudo chmod a+r /usr/lib/x86_64-linux-gnu/libcuda*\n
\n

Helped me

\n", + "system": "" + }, + { + "instruction": "How does TensorFlow SparseCategoricalCrossentropy work?", + "input": "", + "output": "

SparseCategoricalCrossentropy and CategoricalCrossentropy both compute categorical cross-entropy. The only difference is in how the targets/labels should be encoded.

\n\n

When using SparseCategoricalCrossentropy the targets are represented by the index of the category (starting from 0). Your outputs have shape 4x2, which means you have two categories. Therefore, the targets should be a 4 dimensional vector with entries that are either 0 or 1. For example:

\n\n
scce = tf.keras.losses.SparseCategoricalCrossentropy();\nLoss = scce(\n  tf.constant([ 0,    0,    0,    1   ], tf.float32),\n  tf.constant([[1,2],[3,4],[5,6],[7,8]], tf.float32))\n
\n\n

This in contrast to CategoricalCrossentropy where the labels should be one-hot encoded:

\n\n
cce = tf.keras.losses.CategoricalCrossentropy();\nLoss = cce(\n  tf.constant([ [1,0]    [1,0],    [1, 0],   [0, 1]   ], tf.float32),\n  tf.constant([[1,2],[3,4],[5,6],[7,8]], tf.float32))\n
\n\n

SparseCategoricalCrossentropy is more efficient when you have a lot of categories.

\n", + "system": "" + }, + { + "instruction": "Why does keras model predict slower after compile?", + "input": "", + "output": "

UPDATE - 1/15/2020: the current best practice for small batch sizes should be to feed inputs to the model directly - i.e. preds = model(x), and if layers behave differently at train / inference, model(x, training=False). Per latest commit, this is now documented.

\n\n

I haven't benchmarked these, but per the Git discussion, it's also worth trying predict_on_batch() - especially with improvements in TF 2.1.

\n\n
\n\n

ULTIMATE CULPRIT: self._experimental_run_tf_function = True. It's experimental. But it's not actually bad.

\n\n

To any TensorFlow devs reading: clean up your code. It's a mess. And it violates important coding practices, such as one function does one thing; _process_inputs does a lot more than \"process inputs\", same for _standardize_user_data. \"I'm not paid enough\" - but you do pay, in extra time spent understanding your own stuff, and in users filling your Issues page with bugs easier resolved with a clearer code.

\n\n
\n\n

SUMMARY: it's only a little slower with compile().

\n\n

compile() sets an internal flag which assigns a different prediction function to predict. This function constructs a new graph upon each call, slowing it down relative to uncompiled. However, the difference is only pronounced when train time is much shorter than data processing time. If we increase the model size to at least mid-sized, the two become equal. See code at the bottom.

\n\n

This slight increase in data processing time is more than compensated by amplified graph capability. Since it's more efficient to keep only one model graph around, the one pre-compile is discarded. Nonetheless: if your model is small relative to data, you are better off without compile() for model inference. See my other answer for a workaround.

\n\n
\n\n

WHAT SHOULD I DO?

\n\n

Compare model performance compiled vs uncompiled as I have in code at the bottom.

\n\n\n\n

Yes, both are possible, and it will depend on (1) data size; (2) model size; (3) hardware. Code at the bottom actually shows compiled model being faster, but 10 iterations is a small sample. See \"workarounds\" in my other answer for the \"how-to\".

\n\n
\n\n

DETAILS:

\n\n

This took a while to debug, but was fun. Below I describe the key culprits I discovered, cite some relevant documentation, and show profiler results that led to the ultimate bottleneck.

\n\n

(FLAG == self.experimental_run_tf_function, for brevity)

\n\n
    \n
  1. Model by default instantiates with FLAG=False. compile() sets it to True.
  2. \n
  3. predict() involves acquiring the prediction function, func = self._select_training_loop(x)
  4. \n
  5. Without any special kwargs passed to predict and compile, all other flags are such that:\n\n
  6. \n
  7. From source code docstring, (A) is heavily graph-reliant, uses more distribution strategy, and ops are prone to creating & destroying graph elements, which \"may\" (do) impact performance.
  8. \n
\n\n

True culprit: _process_inputs(), accounting for 81% of runtime. Its major component? _create_graph_function(), 72% of runtime. This method does not even exist for (B). Using a mid-sized model, however, _process_inputs comprises less than 1% of runtime. Code at bottom, and profiling results follow.

\n\n
\n\n

DATA PROCESSORS:

\n\n

(A): <class 'tensorflow.python.keras.engine.data_adapter.TensorLikeDataAdapter'>, used in _process_inputs() . Relevant source code

\n\n

(B): numpy.ndarray, returned by convert_eager_tensors_to_numpy. Relevant source code, and here

\n\n
\n\n

MODEL EXECUTION FUNCTION (e.g. predict)

\n\n

(A): distribution function, and here

\n\n

(B): distribution function (different), and here

\n\n
\n\n

PROFILER: results for code in my other answer, \"tiny model\", and in this answer, \"medium model\":

\n\n

Tiny model: 1000 iterations, compile()

\n\n

\n\n

Tiny model: 1000 iterations, no compile()

\n\n

\n\n

Medium model: 10 iterations

\n\n

\n\n
\n\n

DOCUMENTATION (indirectly) on effects of compile(): source

\n\n
\n

Unlike other TensorFlow operations, we don't convert python\n numerical inputs to tensors. Moreover, a new graph is generated for each\n distinct python numerical value, for example calling g(2) and g(3) will\n generate two new graphs

\n \n

function instantiates a separate graph for every unique set of input\n shapes and datatypes. For example, the following code snippet will result\n in three distinct graphs being traced, as each input has a different\n shape

\n \n

A single tf.function object might need to map to multiple computation graphs\n under the hood. This should be visible only as performance (tracing graphs has\n a nonzero computational and memory cost) but should not affect the correctness\n of the program

\n
\n\n
\n\n

COUNTEREXAMPLE:

\n\n
from tensorflow.keras.layers import Input, Dense, LSTM, Bidirectional, Conv1D\nfrom tensorflow.keras.layers import Flatten, Dropout\nfrom tensorflow.keras.models import Model\nimport numpy as np\nfrom time import time\n\ndef timeit(func, arg, iterations):\n    t0 = time()\n    for _ in range(iterations):\n        func(arg)\n    print(\"%.4f sec\" % (time() - t0))\n\nbatch_size = 32\nbatch_shape = (batch_size, 400, 16)\nipt   = Input(batch_shape=batch_shape)\nx     = Bidirectional(LSTM(512, activation='relu', return_sequences=True))(ipt)\nx     = LSTM(512, activation='relu', return_sequences=True)(ipt)\nx     = Conv1D(128, 400, 1, padding='same')(x)\nx     = Flatten()(x)\nx     = Dense(256, activation='relu')(x)\nx     = Dropout(0.5)(x)\nx     = Dense(128, activation='relu')(x)\nx     = Dense(64,  activation='relu')(x)\nout   = Dense(1,  activation='sigmoid')(x)\nmodel = Model(ipt, out)\n\nX = np.random.randn(*batch_shape)\ntimeit(model.predict, X, 10)\nmodel.compile('adam', loss='binary_crossentropy')\ntimeit(model.predict, X, 10)\n
\n\n

Outputs:

\n\n
34.8542 sec\n34.7435 sec\n
\n", + "system": "" + }, + { + "instruction": "How to understand masked multi-head attention in transformer", + "input": "", + "output": "

I had the very same question after reading the Transformer paper. I found no complete and detailed answer to the question in the Internet so I'll try to explain my understanding of Masked Multi-Head Attention.

\n

The short answer is - we need masking to make the training parallel. And the parallelization is good as it allows the model to train faster. I've also made a video with explanation of this mechanism.

\n

Here's an example explaining the idea. Let's say we train to translate "I love you" to German. The encoder works in parallel mode - it can produce vector representation of the input sequence ("I love you") within a constant number of steps (i.e. the number of steps doesn't depend on the length of the input sequence).

\n

Let's say the encoder produces the numbers 11, 12, 13 as the vector representations of the input sequence. In reality these vectors will be much longer but for simplicity we use the short ones. Also for simplicity we ignore the service tokens, like - beginning of the sequence, - end of the sequence and others.

\n

During the training we know that the translation should be "Ich liebe dich" (we always know the expected output during the training). Let's say the expected vector representations of the "Ich liebe dich" words are 21, 22, 23.

\n

If we make the decoder training in sequential mode, it'll look like the training of the Recurrent Neural Network. The following sequential steps will be performed:

\n\n

This means we'll need to make 3 sequential operations (in general case - a sequential operation per each input). Also we'll have an accumulating error on each next iteration. Also we don't use attention as we only look to a single previous output.

\n

As we actually know the expected outputs we can adjust the process and make it parallel. There's no need to wait for the previous step output.

\n\n

This algorithm can be executed in parallel and also it doesn't accumulate the error. And this algorithm uses attention (i.e. looks to all previous inputs) thus has more information about the context to consider while making the prediction.

\n

And here is where we need the masking. The training algorithm knows the entire expected output (21, 22, 23). It hides (masks) a part of this known output sequence for each of the parallel operations.

\n\n

Masking itself is implemented as the following (from the original paper):

\n
\n

We implement this inside of scaled dot-product attention by masking\nout (setting to \u2212\u221e) all values in the input of the softmax which\ncorrespond to illegal connections

\n
\n

Note: during the inference (not training) the decoder works in the sequential (not parallel) mode as it doesn't know the output sequence initially. But it's different from RNN approach as Transformer inference still uses self-attention and looks at all previous outputs (but not only the very previous one).

\n

Note 2: I've seen in some materials that masking can be used differently for non-translation applications. For example, for language modeling the masking can be used to hide some words from the input sentence and the model will try to predict them during the training using other, non-masked words (i.e. learn to understand the context).

\n", + "system": "" + }, + { + "instruction": "How to clear GPU memory WITHOUT restarting runtime in Google Colaboratory (Tensorflow)", + "input": "", + "output": "

in tensorflow you van use numba library:

\n
!pip install numba\n\nfrom numba import cuda \ndevice = cuda.get_current_device()\ndevice.reset()\n
\n", + "system": "" + }, + { + "instruction": "ValueError: Can't convert non-rectangular Python sequence to Tensor", + "input": "", + "output": "

I'm not sure whether they exist in TensorFlow 1 but TensorFlow 2.0 supports RaggedTensors, which the documentation describes as "... the TensorFlow equivalent of nested variable-length lists."

\n

I think it would be trivial to convert your data to RaggedTensors. It might even be as easy as:

\n
data_tensor = tf.ragged.constant(data)\n
\n

Example:

\n
>>> a = tf.ragged.constant([[1],[2,3]])\n>>> a\n<tf.RaggedTensor [[1], [2, 3]]>\n
\n", + "system": "" + }, + { + "instruction": "model.summary() can't print output shape while using subclass model", + "input": "", + "output": "

I have used this method to solve this problem, I don't know if there is an easier way.

\n\n
class subclass(Model):\n    def __init__(self):\n        ...\n    def call(self, x):\n        ...\n\n    def model(self):\n        x = Input(shape=(24, 24, 3))\n        return Model(inputs=[x], outputs=self.call(x))\n\n\n\nif __name__ == '__main__':\n    sub = subclass()\n    sub.model().summary()\n
\n", + "system": "" + }, + { + "instruction": "Is there a version of TensorFlow not compiled for AVX instructions?", + "input": "", + "output": "

A best practices approach suggested by peter-cordes is to see what gcc is going to make of your 'what capabilities your cpu has' by issuing the following:

\n\n
gcc -O3 -fverbose-asm -march=native -xc /dev/null -S -o- | less\n
\n\n

This command will provide information (all) about your cpu capabilities from the view of gcc, whom is going to do the build, so gcc's view matters.

\n\n

When does this come up? When a program offers to tailor itself to your cpu. Dang. What do I know about my cpu. Well, the above line will tell you all you need to know.

\n\n

That said, generally, people/developers that are promoting cpu based capabilities will state or suggest a list of things that go faster/better/stronger if your cpu has *. And the above will give you *. Read carefully what you see. If you don't have it, you don't want it, i.e.

\n\n
-mno-avx(whatever you don't want;in my case it was avx)\n
\n\n

A good overview of install of CPU capable on older cpu(s) is provided by\nMikael Fernandez Simalango for Ubuntu 16.04 LTS. It assumes a python2.7 environ but easily translates to python3. The heart of the matter is extracting which cpu instruction extensions are available on your particular cpu that will be used in addition to -march=native via /proc/cpuinfo, (but note, it appears limited to what flags it accepts, so may be better to actually read through the instruction above and reflect)

\n\n
grep flags -m1 /proc/cpuinfo | cut -d \":\" -f 2 | tr '[:upper:]' \n'[:lower:]' | { read FLAGS; OPT=\"-march=native\"; for flag in $FLAGS; \ndo case \"$flag\" in \"sse4_1\" | \"sse4_2\" | \"ssse3\" | \"fma\" | \"cx16\" | \n\"popcnt\" | \"avx\" | \"avx2\") OPT+=\" -m$flag\";; esac; done; \nMODOPT=${OPT//_/\\.}; echo \"$MODOPT\"; }\n
\n\n

Running this on my old box output:

\n\n
-march=native -mssse3 -mcx16 -msse4.1 -msse4.2 -mpopcnt\n
\n\n

It gets part way there. What is not clear is how to say, 'not this' and 'not that', which for old CPUs would be, most likely, -mno-avx.

\n\n

For an old cpu, which -march matters and Nephanth very usefully addresses this:

\n\n
gcc -march=native -Q --help=target|grep march\n
\n\n

produces

\n\n
-march=                             westmere\n
\n\n

which means my response to the ./compile question should be or might be, and note the quotes 'westmere' which is also in the gcc docs so the ' ' must be there for a reason

\n\n
-march='westmere' -mssse3 -mcx16 -msse4.1 -msse4.2 -mpopcnt -mno-avx\n
\n\n

but this is probably much better (see discussion below):

\n\n
-march=native -mssse3 -mcx16 -msse4.1 -msse4.2 -mpopcnt -mno-avx\n
\n\n

The -mno-avx is an option for gcc, and results, after many hours, in

\n\n
Python 3.5.2 (default, Nov 23 2017, 16:37:01) \n[GCC 5.4.0 20160609] on linux\nType \"help\", \"copyright\", \"credits\" or \"license\" for more \ninformation.\n>>> import tensorflow as tf\n>>> \n>>> tf.__version__\n'2.0.0-alpha0'\n
\n\n

which looks like success.

\n\n

Restated:\nIn either order, find out what instructions are (or not) supported by your cpu, and state those explicitly.

\n", + "system": "" + }, + { + "instruction": "How to import keras.engine.topology in Tensorflow?", + "input": "", + "output": "

You can import Layer and InputSpec from TensorFlow as follows:

\n\n
from tensorflow.python.keras.layers import Layer, InputSpec\n
\n\n

UPDATE: 30/10/2019

\n\n
from tensorflow.keras.layers import Layer, InputSpec\n
\n", + "system": "" + }, + { + "instruction": "How can I test a .tflite model to prove that it behaves as the original model using the same Test Data?", + "input": "", + "output": "

You may use TensorFlow Lite Python interpreter to test your tflite model.

\n\n

It allows you to feed input data in python shell and read the output directly like you are just using a normal tensorflow model.

\n\n

I have answered this question here.

\n\n

And you can read this TensorFlow lite official guide for detailed information.

\n\n

You can also use Netron to visualize your model. It allows you to load your .tflite file directly and inspect your model architecture and model weights.

\n", + "system": "" + }, + { + "instruction": "shuffle in the model.fit of keras", + "input": "", + "output": "

It will shuffle your entire dataset (x, y and sample_weight together) first and then make batches according to the batch_size argument you passed to fit.

\n

Edit

\n

As @yuk pointed out in the comment, the code has been changed significantly since 2018. The documentation for the shuffle parameter now seems more clear on its own. You can choose to shuffle the entire training data or just shuffle the batch:

\n
        shuffle: Boolean (whether to shuffle the training data\n            before each epoch) or str (for 'batch'). This argument is ignored\n            when `x` is a generator. 'batch' is a special option for dealing\n            with the limitations of HDF5 data; it shuffles in batch-sized\n            chunks. Has no effect when `steps_per_epoch` is not `None`.\n
\n", + "system": "" + }, + { + "instruction": "Tensorflow object detection config files documentation", + "input": "", + "output": "

As mentioned in the configuration documentation, configuration files are just Protocol Buffers objects described in the .proto files under research/object_detection/protos. The top level object is a TrainEvalPipelineConfig defined in pipeline.proto, and different files describe each of the elements. For example, data_augmentation_options are PreprocessingStep objects, defined in preprocessor.proto (which in turn can include a range of other possible objects for different preprocessing tasks). The meaning of each object and field may or may not be obvious or well-documented, but you can always refer to the source code to see exactly how each value is being used (for example, check preprocessor.py to understand how data augmentation is done).

\n", + "system": "" + }, + { + "instruction": "Why do we use tf.name_scope()", + "input": "", + "output": "

They are not the same thing.

\n\n
import tensorflow as tf\nc1 = tf.constant(42)\nwith tf.name_scope('s1'):\n    c2 = tf.constant(42)\nprint(c1.name)\nprint(c2.name)\n
\n\n

prints

\n\n
Const:0\ns1/Const:0\n
\n\n

So as the name suggests, the scope functions create a scope for the names of the ops you create inside. This has an effect on how you refer to tensors, on reuse, on how the graph shows in TensorBoard and so on.

\n", + "system": "" + }, + { + "instruction": "Tensorflow VarLenFeature vs FixedLenFeature", + "input": "", + "output": "

You can load images probably beacause you saved them using feature type tf.train.BytesList() and whole image data is one big byte value inside a list.

\n

If I'm right you're using tf.decode_raw to get the data out of the image you load from TFRecord.

\n

Regarding example use cases:\nI use VarLenFeature for saving datasets for object detection task:\nThere's variable amount of bounding boxes per image (equal to object in image) therefore I need another feature objects_number to track amount of objects (and bboxes).\nEach bounding box itself is a list of 4 float coordinates

\n

I'm using following code to load it:

\n
features = tf.parse_single_example(\n    serialized_example,\n    features={\n        # We know the length of both fields. If not the\n        # tf.VarLenFeature could be used\n        'height': tf.FixedLenFeature([], tf.int64),\n        'width': tf.FixedLenFeature([], tf.int64),\n        'depth': tf.FixedLenFeature([], tf.int64),\n        # Label part\n        'objects_number': tf.FixedLenFeature([], tf.int64),\n        'bboxes': tf.VarLenFeature(tf.float32),\n        'labels': tf.VarLenFeature(tf.int64),\n        # Dense data\n        'image_raw': tf.FixedLenFeature([],tf.string)\n\n    })\n\n# Get metadata\nobjects_number = tf.cast(features['objects_number'], tf.int32)\nheight = tf.cast(features['height'], tf.int32)\nwidth = tf.cast(features['width'], tf.int32)\ndepth = tf.cast(features['depth'], tf.int32)\n\n# Actual data\nimage_shape = tf.parallel_stack([height, width, depth])\nbboxes_shape = tf.parallel_stack([objects_number, 4])\n\n# BBOX data is actually dense convert it to dense tensor\nbboxes = tf.sparse_tensor_to_dense(features['bboxes'], default_value=0)\n\n# Since information about shape is lost reshape it\nbboxes = tf.reshape(bboxes, bboxes_shape)\nimage = tf.decode_raw(features['image_raw'], tf.uint8)\nimage = tf.reshape(image, image_shape)\n
\n

Notice that "image_raw" is fixed length Feature (has one element) and holds values of type "bytes", however a value of "bytes" type can itself have variable size (its a string of bytes, and can have many symbols within it).\nSo "image_raw" is a list with ONE element of type "bytes", which can be super big.

\n

To further elaborate on how it works:\nFeatures are lists of values, those values have specific "type".

\n

Datatypes for features are subset of data types for tensors, you have:

\n\n

You can check here tensors data types.

\n

So you can store variable length data without VarLenFeatures at all (actually well you do it), but first you would need to convert it into bytes/string feature, and then decode it.\nAnd this is most common method.

\n", + "system": "" + }, + { + "instruction": "Tensorflow Slim: TypeError: Expected int32, got list containing Tensors of type '_Message' instead", + "input": "", + "output": "

I got the same problem when using the 1.0 released and I could make it work without having to roll back on a previous version.

\n\n

The problem is caused by change in the api. That discussion helped me to find the solution: Google group > \nRecent API Changes in TensorFlow

\n\n

You just have to update all the line with tf.concat

\n\n

for example

\n\n
net = tf.concat(3, [branch_0, branch_1, branch_2, branch_3])\n
\n\n

should be changed to

\n\n
net = tf.concat([branch_0, branch_1, branch_2, branch_3], 3)\n
\n\n

Note:

\n\n

I was able to use the models without problem. But I still got error afterward when wanting to load the pretrained weight.\nSeems that the slim module got several changed since they made the checkpoint file. The graph created by the code and the one present in the checkpoint file were different.

\n\n

Note2:

\n\n

I was able to use the pretrain weights for inception_resnet_v2 by adding to all conv2d layer biases_initializer=None

\n", + "system": "" + }, + { + "instruction": "how to implement tensorflow's next_batch for own data", + "input": "", + "output": "

The link you posted says: \"we get a \"batch\" of one hundred random data points from our training set\". In my example I use a global function (not a method like in your example) so there will be a difference in syntax.

\n\n

In my function you'll need to pass the number of samples wanted and the data array.

\n\n

Here is the correct code, which ensures samples have correct labels:

\n\n
import numpy as np\n\ndef next_batch(num, data, labels):\n    '''\n    Return a total of `num` random samples and labels. \n    '''\n    idx = np.arange(0 , len(data))\n    np.random.shuffle(idx)\n    idx = idx[:num]\n    data_shuffle = [data[ i] for i in idx]\n    labels_shuffle = [labels[ i] for i in idx]\n\n    return np.asarray(data_shuffle), np.asarray(labels_shuffle)\n\nXtr, Ytr = np.arange(0, 10), np.arange(0, 100).reshape(10, 10)\nprint(Xtr)\nprint(Ytr)\n\nXtr, Ytr = next_batch(5, Xtr, Ytr)\nprint('\\n5 random samples')\nprint(Xtr)\nprint(Ytr)\n
\n\n

And a demo run:

\n\n
[0 1 2 3 4 5 6 7 8 9]\n[[ 0  1  2  3  4  5  6  7  8  9]\n [10 11 12 13 14 15 16 17 18 19]\n [20 21 22 23 24 25 26 27 28 29]\n [30 31 32 33 34 35 36 37 38 39]\n [40 41 42 43 44 45 46 47 48 49]\n [50 51 52 53 54 55 56 57 58 59]\n [60 61 62 63 64 65 66 67 68 69]\n [70 71 72 73 74 75 76 77 78 79]\n [80 81 82 83 84 85 86 87 88 89]\n [90 91 92 93 94 95 96 97 98 99]]\n\n5 random samples\n[9 1 5 6 7]\n[[90 91 92 93 94 95 96 97 98 99]\n [10 11 12 13 14 15 16 17 18 19]\n [50 51 52 53 54 55 56 57 58 59]\n [60 61 62 63 64 65 66 67 68 69]\n [70 71 72 73 74 75 76 77 78 79]]\n
\n", + "system": "" + }, + { + "instruction": "How to redirect TensorFlow logging to a file?", + "input": "", + "output": "
import logging\n\n# get TF logger\nlog = logging.getLogger('tensorflow')\nlog.setLevel(logging.DEBUG)\n\n# create formatter and add it to the handlers\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n\n# create file handler which logs even debug messages\nfh = logging.FileHandler('tensorflow.log')\nfh.setLevel(logging.DEBUG)\nfh.setFormatter(formatter)\nlog.addHandler(fh)\n
\n\n

My solution is inspired by this thread.

\n", + "system": "" + }, + { + "instruction": "What's the difference between tensorflow dynamic_rnn and rnn?", + "input": "", + "output": "

From RNNs in Tensorflow, a Practical Guide and Undocumented Features by Denny Britz, published in August 21, 2016.

\n\n
\n

tf.nn.rnn creates an unrolled graph for a fixed RNN length. That\n means, if you call tf.nn.rnn with inputs having 200 time steps you are\n creating a static graph with 200 RNN steps. First, graph creation is\n slow. Second, you\u2019re unable to pass in longer sequences (> 200) than\n you\u2019ve originally specified.

\n \n

tf.nn.dynamic_rnn solves this. It uses a tf.While loop to dynamically\n construct the graph when it is executed. That means graph creation is\n faster and you can feed batches of variable size.

\n
\n", + "system": "" + }, + { + "instruction": "tensorflow deep neural network for regression always predict same results in one batch", + "input": "", + "output": "

Short answer:

\n\n

Transpose your pred vector using tf.transpose(pred).

\n\n

Longer answer:

\n\n

The problem is that pred (the predictions) and y (the labels) are not of the same shape: one is a row vector and the other a column vector. Apparently when you apply an element-wise operation on them, you'll get a matrix, which is not what you want.

\n\n

The solution is to transpose the prediction vector using tf.transpose() to get a proper vector and thus a proper loss function. Actually, if you set the batch size to 1 in your example you'll see that it works even without the fix, because transposing a 1x1 vector is a no-op.

\n\n

I applied this fix to your example code and observed the following behaviour. Before the fix:

\n\n
Epoch: 0245 cost= 84.743440580\n[*]----------------------------\nlabel value: 23 estimated value: [ 27.47437096]\nlabel value: 50 estimated value: [ 24.71126747]\nlabel value: 22 estimated value: [ 23.87785912]\n
\n\n

And after the fix at the same point in time:

\n\n
Epoch: 0245 cost= 4.181439120\n[*]----------------------------\nlabel value: 23 estimated value: [ 21.64333534]\nlabel value: 50 estimated value: [ 48.76105118]\nlabel value: 22 estimated value: [ 24.27996063]\n
\n\n

You'll see that the cost is much lower and that it actually learned the value 50 properly. You'll have to do some fine-tuning on the learning rate and such to improve your results of course.

\n", + "system": "" + }, + { + "instruction": "Does TensorFlow have cross validation implemented?", + "input": "", + "output": "

As already discussed, tensorflow doesn't provide its own way to cross-validate the model. The recommended way is to use KFold. It's a bit tedious, but doable. Here's a complete example of cross-validating MNIST model with tensorflow and KFold:

\n\n
from sklearn.model_selection import KFold\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n# Parameters\nlearning_rate = 0.01\nbatch_size = 500\n\n# TF graph\nx = tf.placeholder(tf.float32, [None, 784])\ny = tf.placeholder(tf.float32, [None, 10])\nW = tf.Variable(tf.zeros([784, 10]))\nb = tf.Variable(tf.zeros([10]))\npred = tf.nn.softmax(tf.matmul(x, W) + b)\ncost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred), reduction_indices=1))\noptimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)\ncorrect_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\ninit = tf.global_variables_initializer()\n\nmnist = input_data.read_data_sets(\"data/mnist-tf\", one_hot=True)\ntrain_x_all = mnist.train.images\ntrain_y_all = mnist.train.labels\ntest_x = mnist.test.images\ntest_y = mnist.test.labels\n\ndef run_train(session, train_x, train_y):\n  print \"\\nStart training\"\n  session.run(init)\n  for epoch in range(10):\n    total_batch = int(train_x.shape[0] / batch_size)\n    for i in range(total_batch):\n      batch_x = train_x[i*batch_size:(i+1)*batch_size]\n      batch_y = train_y[i*batch_size:(i+1)*batch_size]\n      _, c = session.run([optimizer, cost], feed_dict={x: batch_x, y: batch_y})\n      if i % 50 == 0:\n        print \"Epoch #%d step=%d cost=%f\" % (epoch, i, c)\n\ndef cross_validate(session, split_size=5):\n  results = []\n  kf = KFold(n_splits=split_size)\n  for train_idx, val_idx in kf.split(train_x_all, train_y_all):\n    train_x = train_x_all[train_idx]\n    train_y = train_y_all[train_idx]\n    val_x = train_x_all[val_idx]\n    val_y = train_y_all[val_idx]\n    run_train(session, train_x, train_y)\n    results.append(session.run(accuracy, feed_dict={x: val_x, y: val_y}))\n  return results\n\nwith tf.Session() as session:\n  result = cross_validate(session)\n  print \"Cross-validation result: %s\" % result\n  print \"Test accuracy: %f\" % session.run(accuracy, feed_dict={x: test_x, y: test_y})\n
\n", + "system": "" + }, + { + "instruction": "What does opt.apply_gradients() do in TensorFlow?", + "input": "", + "output": "

The update rule that the apply_gradients method actually applies depends on the specific optimizer. Take a look at the implementation of apply_gradients in the tf.train.Optimizer class here. It relies on the derived classes implementing the update rule in the methods _apply_dense and _apply_spares. The update rule you are referring to is implemented by the GradientDescentOptimizer.

\n\n

Regarding your desired positive additive update: If what you are calling opt is an instantiation of GradientDescentOptimizer, then you could indeed achieve what you want to do by

\n\n
grads_and_vars = opt.compute_gradients(E, [v])\neta = opt._learning_rate\nmy_grads_and_vars = [(g-(1/eta)*p, v) for g, v in grads_and_vars]\nopt.apply_gradients(my_grads_and_vars)\n
\n\n

The more elegant way to do this is probably to write a new optimizer (inheriting from tf.train.Optimizer) that implements your desired update rule directly.

\n", + "system": "" + }, + { + "instruction": "ImportError: cannot import name 'BatchNormalization' from 'keras.layers.normalization'", + "input": "", + "output": "

You should import BatchNormalization in following way:

\n
from tensorflow.keras.layers import BatchNormalization\n
\n", + "system": "" + }, + { + "instruction": "AttributeError: module 'tensorflow.python.keras.utils.generic_utils' has no attribute 'populate_dict_with_module_objects'", + "input": "", + "output": "

change from keras import models to from tensorflow.keras import models
\nthis solved the problem for me with tensorflow 2.5.0

\n", + "system": "" + }, + { + "instruction": "Unexpected keyword argument 'ragged' in Keras", + "input": "", + "output": "

So I tried link above which you have mentioned teachable machine
\nAs it turns out model you have exported is from tensorflow.keras and not directly from keras API. These two are different. So while loading it might be using tf.ragged tensors that might not be compatible with keras API.
\n
Soulution to your issue:

\nDon't import keras directly as your model is saved with Tensorflow's keras high level api. Change all your imports to tensorflow.keras\n

Change:

\n\n
from keras.preprocessing.image import img_to_array\nfrom keras.models import load_model\n
\n\n

to this:

\n\n
from tensorflow.keras.preprocessing.image import img_to_array\nfrom tensorflow.keras.models import load_model\n
\n\n

It will solve your issue.

\n\n

EDIT :
\nAll of your imports, either should be from Keras or tensorflow.keras. Although being same API few things are different which creates these kind of issues. Also for tensorflow backend tf.keras is preferred, because Keras 2.3.0 is last major release which will support backends other than tensorflow.

\n\n
\n

This release brings the API in sync with the tf.keras API as of TensorFlow 2.0. However note that it does not support most TensorFlow 2.0 features, in particular eager execution. If you need these features, use tf.keras.\n This is also the last major release of multi-backend Keras. Going forward, we recommend that users consider switching their Keras code to tf.keras in TensorFlow 2.0.

\n
\n", + "system": "" + }, + { + "instruction": "How to input a list of lists with different sizes in tf.data.Dataset", + "input": "", + "output": "

You can use tf.data.Dataset.from_generator() to convert any iterable Python object (like a list of lists) into a Dataset:

\n\n
t = [[4, 2], [3, 4, 5]]\n\ndataset = tf.data.Dataset.from_generator(lambda: t, tf.int32, output_shapes=[None])\n\niterator = dataset.make_one_shot_iterator()\nnext_element = iterator.get_next()\n\nwith tf.Session() as sess:\n  print(sess.run(next_element))  # ==> '[4, 2]'\n  print(sess.run(next_element))  # ==> '[3, 4, 5]'\n
\n", + "system": "" + }, + { + "instruction": "ImportError: No module named 'keras'", + "input": "", + "output": "

Hi I have an solution try this if you are using Anaconda-Navigator

\n\n

go to Anaconda Environment and search keras package and then install.

\n\n

\"install

\n\n

\"enter

\n\n

after install just type import keras in shell its working.

\n\n

\"enter

\n", + "system": "" + }, + { + "instruction": "Loading SavedModel is a lot slower than loading a tf.train.Saver checkpoint", + "input": "", + "output": "

I am by no ways an expert in Tensorflow, but if I had to take a guess as to why this is happening, I would say that:

\n\n\n\n

Depending on the size of your graph, recreating everything that it contained might take some time.

\n\n

Concerning the second question, as @J H said, if there are no reasons for you to use one strategy over the other, and time is of the essence, then just go with the fastest one.

\n", + "system": "" + }, + { + "instruction": "Tensorflow: Cannot interpret feed_dict key as Tensor", + "input": "", + "output": "

This worked for me

\n\n
from keras import backend as K\n
\n\n

and after predicting my data i inserted this part of code\nthen i had again loaded the model.

\n\n
K.clear_session()\n
\n\n

i faced this problem in production server,\nbut in my pc it was running fine

\n\n

...........

\n\n
from keras import backend as K\n\n#Before prediction\nK.clear_session()\n\n#After prediction\nK.clear_session()\n
\n", + "system": "" + }, + { + "instruction": "What is the equivalent of np.std() in TensorFlow?", + "input": "", + "output": "

To get the mean and variance just use tf.nn.moments.

\n\n
mean, var = tf.nn.moments(x, axes=[1])\n
\n\n

For more on tf.nn.moments params see docs

\n", + "system": "" + }, + { + "instruction": "Cannot convert a partially converted tensor in TensorFlow", + "input": "", + "output": "

You just need to feed it in as a single example but in the batched shape. So that means adding an extra dimension to the shape e.g.

\n\n
batch_size = 32 # set this to the actual size of your batch\ntf.truncated_normal((batch_size, 784), mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)\n
\n\n

This way it will \"fit\" into the placeholder.

\n\n

If you expect batch_size to change you can also use:

\n\n
tf.truncated_normal(tf.shape(input_tensor), mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)\n
\n\n

Where input_tensor could be a placeholder or just whatever tensor is going to have this noise added to it.

\n", + "system": "" + }, + { + "instruction": "How to profile TensorFlow networks?", + "input": "", + "output": "

If you want to find how much time was spent on each operation at TF, you can do this in tensorboard using runtime statistics. You will need to do something like this (check the full example in the above-mentioned link):

\n\n
run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)\nrun_metadata = tf.RunMetadata()\nsess.run(<values_you_want_to_execute>, options=run_options, run_metadata=run_metadata)\nyour_writer.add_run_metadata(run_metadata, 'step%d' % i)\n
\n\n
\n\n

Better than just printing it you can see it in tensorboard:

\n\n
\n

Additionally, clicking on a node will display the exact total memory,\n compute time, and tensor output sizes.

\n
\n\n

Also now tensorflow has a debugger. Here is a tutorial of how to use it.

\n\n

\"[Example

\n", + "system": "" + }, + { + "instruction": "Run Tensorflow unit tests", + "input": "", + "output": "

The easiest way to run the TensorFlow unit tests is using Bazel, assuming you have downloaded the source from Git:

\n\n
# All tests (for C++ changes).\n$ bazel test //tensorflow/...\n\n# All Python tests (for Python front-end changes).\n$ bazel test //tensorflow/python/...\n\n# All tests (with GPU support).\n$ bazel test -c opt --config=cuda //tensorflow/...\n$ bazel test -c opt --config=cuda //tensorflow/python/...\n
\n", + "system": "" + }, + { + "instruction": "ImportError: No module named 'keras'", + "input": "", + "output": "

Hi I have an solution try this if you are using Anaconda-Navigator

\n\n

go to Anaconda Environment and search keras package and then install.

\n\n

\"install

\n\n

\"enter

\n\n

after install just type import keras in shell its working.

\n\n

\"enter

\n", + "system": "" + }, + { + "instruction": "Tensorflow GradientTape "Gradients does not exist for variables" intermittently", + "input": "", + "output": "

The solution given by Nguy\u1ec5n and gkennos will suppress the error because it would replace all None by zeros.\nHowever, it is a big issue that your gradient is null at any point in time.\nThe problem described above is certainly caused by unconnected variables (by default PyTorch will throw runtime error).

\n

The most common case of unconnected layers can be exemplify as follow:

\n
 def some_func(x):\n       x1 = x * some variables\n       x2 = x1 + some variables #x2 discontinued after here\n       x3 = x1 / some variables\n       return x3\n
\n

Now observe that x2 is unconnected, so gradient will not be propagated throw it. Carefully debug your code for unconnected variables.

\n", + "system": "" + }, + { + "instruction": "Description of TF Lite's Toco converter args for quantization aware training", + "input": "", + "output": "

You should never need to manually set the quantization stats.

\n\n

Have you tried the post-training-quantization tutorials?

\n\n

https://www.tensorflow.org/lite/performance/post_training_integer_quant

\n\n

Basically they set the quantization options:

\n\n
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\nconverter.inference_input_type = tf.uint8\nconverter.inference_output_type = tf.uint8\n
\n\n

Then they pass a \"representative dataset\" to the converter, so that the converter can run the model a few batches to gather the necessary statistics:

\n\n
def representative_data_gen():\n  for input_value in mnist_ds.take(100):\n    yield [input_value]\n\nconverter.representative_dataset = representative_data_gen\n
\n\n

While there are options for quantized training, it's always easier to to do post-training quantization.

\n", + "system": "" + }, + { + "instruction": "Graph optimizations on a tensorflow serveable created using tf.Estimator", + "input": "", + "output": "

The way to go from a SavedModel to a servable after running tensorflow graph transforms is to use the SavedModel Builder API.

\n

First, you need to create a SavedModel Builder object and then rebuild the graph you have just transformed, using the SavedModel Builder API.

\n

Next, you need to add the assets, signatures, and other meta-data back into the model. Finally, you need to call the SavedModel Builder API's save() method, which will save the model as a servable.

\n

This servable can then be used with tensorflow serving.

\n", + "system": "" + }, + { + "instruction": "Tensorboard Error: No dashboards are active for current data set", + "input": "", + "output": "

Your issue may be related to the drive you are attempting to start tensorboard from and the drive your logdir is on. Tensorboard uses a colon to separate the optional run name and the path in the logdir flag, so your path is being interpreted as \\path\\to\\output\\folder with name C.

\n\n

This can be worked around by either starting tensorboard from the same drive as your log directory or by providing an explicit run name, e.g. logdir=mylogs:C:\\path\\to\\output\\folder

\n\n

See here for reference to the issue.

\n", + "system": "" + }, + { + "instruction": "Is there any way to get variable importance with Keras?", + "input": "", + "output": "

*Edited to include relevant code to implement permutation importance.

\n\n

I answered a similar question at Feature Importance Chart in neural network using Keras in Python. It does implement what Teque5 mentioned above, namely shuffling the variable among your sample or permutation importance using the ELI5 package.

\n\n
from keras.wrappers.scikit_learn import KerasClassifier, KerasRegressor\nimport eli5\nfrom eli5.sklearn import PermutationImportance\n\ndef base_model():\n    model = Sequential()        \n    ...\n    return model\n\nX = ...\ny = ...\n\nmy_model = KerasRegressor(build_fn=basemodel, **sk_params)    \nmy_model.fit(X,y)\n\nperm = PermutationImportance(my_model, random_state=1).fit(X,y)\neli5.show_weights(perm, feature_names = X.columns.tolist())\n
\n", + "system": "" + }, + { + "instruction": "ValueError: Tensor must be from the same graph as Tensor with Bidirectinal RNN in Tensorflow", + "input": "", + "output": "

TensorFlow stores all operations on an operational graph. This graph defines what functions output to where, and it links it all together so that it can follow the steps you have set up in the graph to produce your final output. If you try to input a Tensor or operation on one graph into a Tensor or operation on another graph it will fail. Everything must be on the same execution graph.

\n\n

Try removing with tf.Graph().as_default():

\n\n

TensorFlow provides you a default graph which is referred to if you do not specify a graph. You are probably using the default graph in one spot and a different graph in your training block.

\n\n

There does not seem to be a reason you are specifying a graph as default here and most likely you are using separate graphs on accident. If you really want to specify a graph then you probably want to pass it as a variable, not set it like this.

\n", + "system": "" + }, + { + "instruction": "ImportError: No module named 'tensorflow.python'", + "input": "", + "output": "

Uninstall tensorflow:

\n\n
pip uninstall tensorflow\n
\n\n

Then reinstall it:

\n\n
pip install tensorflow\n
\n", + "system": "" + }, + { + "instruction": "Unable to open Tensorboard in browser", + "input": "", + "output": "

Had the same problem this morning. Solved it with

\n\n
tensorboard --logdir=data/ --host localhost --port 8088\n
\n\n

Navigated the browser to http://localhost:8088

\n", + "system": "" + }, + { + "instruction": "Flatten batch in tensorflow", + "input": "", + "output": "

You can do it easily with tf.reshape() without knowing the batch size.

\n\n
x = tf.placeholder(tf.float32, shape=[None, 9,2])\nshape = x.get_shape().as_list()        # a list: [None, 9, 2]\ndim = numpy.prod(shape[1:])            # dim = prod(9,2) = 18\nx2 = tf.reshape(x, [-1, dim])           # -1 means \"all\"\n
\n\n

The -1 in the last line means the whole column no matter what the batchsize is in the runtime. You can see it in tf.reshape().

\n\n
\n\n

Update: shape = [None, 3, None]

\n\n

Thanks @kbrose. For the cases where more than 1 dimension are undefined, we can use tf.shape() with tf.reduce_prod() alternatively.

\n\n
x = tf.placeholder(tf.float32, shape=[None, 3, None])\ndim = tf.reduce_prod(tf.shape(x)[1:])\nx2 = tf.reshape(x, [-1, dim])\n
\n\n

tf.shape() returns a shape Tensor which can be evaluated in runtime. The difference between tf.get_shape() and tf.shape() can be seen in the doc.

\n\n

I also tried tf.contrib.layers.flatten() in another . It is simplest for the first case, but it can't handle the second.

\n", + "system": "" + }, + { + "instruction": "TensorFlow - numpy-like tensor indexing", + "input": "", + "output": "

You can actually do that now with tf.gather_nd. Let's say you have a matrix m like the following:

\n\n
| 1 2 3 4 |\n| 5 6 7 8 |\n
\n\n

And you want to build a matrix r of size, let's say, 3x2, built from elements of m, like this:

\n\n
| 3 6 |\n| 2 7 |\n| 5 3 |\n| 1 1 |\n
\n\n

Each element of r corresponds to a row and column of m, and you can have matrices rows and cols with these indices (zero-based, since we are programming, not doing math!):

\n\n
       | 0 1 |         | 2 1 |\nrows = | 0 1 |  cols = | 1 2 |\n       | 1 0 |         | 0 2 |\n       | 0 0 |         | 0 0 |\n
\n\n

Which you can stack into a 3-dimensional tensor like this:

\n\n
| | 0 2 | | 1 1 | |\n| | 0 1 | | 1 2 | |\n| | 1 0 | | 2 0 | |\n| | 0 0 | | 0 0 | |\n
\n\n

This way, you can get from m to r through rows and cols as follows:

\n\n
import numpy as np\nimport tensorflow as tf\n\nm = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])\nrows = np.array([[0, 1], [0, 1], [1, 0], [0, 0]])\ncols = np.array([[2, 1], [1, 2], [0, 2], [0, 0]])\n\nx = tf.placeholder('float32', (None, None))\nidx1 = tf.placeholder('int32', (None, None))\nidx2 = tf.placeholder('int32', (None, None))\nresult = tf.gather_nd(x, tf.stack((idx1, idx2), -1))\n\nwith tf.Session() as sess:\n    r = sess.run(result, feed_dict={\n        x: m,\n        idx1: rows,\n        idx2: cols,\n    })\nprint(r)\n
\n\n

Output:

\n\n
[[ 3.  6.]\n [ 2.  7.]\n [ 5.  3.]\n [ 1.  1.]]\n
\n", + "system": "" + }, + { + "instruction": "How to fix AttributeError: partially initialized module 'charset_normalizer' has no attribute 'md__mypyc' (most likely due to a circular import)", + "input": "", + "output": "

Your traceback doesn't show which version of the charset-normalizer package is installed.

\n

I got a similar error when training an xgboost model using Ray. I had charset-normalizer v3.0.1 installed. Upgrading it to v3.1.0 fixed the error.

\n

Try running

\n
pip install --force-reinstall charset-normalizer==3.1.0\n
\n

or simply

\n
pip install -U --force-reinstall charset-normalizer  \n
\n

Then rerun your code and see if that does the trick!

\n", + "system": "" + }, + { + "instruction": "Tensorflow GPU Could not load dynamic library 'cusolver64_10.dll'; dlerror: cusolver64_10.dll not found", + "input": "", + "output": "Step 1\n
 Move to C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v11.2\\bin\n
\nStep 2\n
Rename file cusolver64_11.dll  To  cusolver64_10.dll \n
\n

\"enter

\n
 cusolver64_10.dll \n
\n

\"enter

\n", + "system": "" + }, + { + "instruction": "Why is Tensorflow not recognizing my GPU after conda install?", + "input": "", + "output": "

August 2021 Conda install may be working now, as according to @ComputerScientist in the comments below, conda install tensorflow-gpu==2.4.1 will give cudatoolkit-10.1.243 and cudnn-7.6.5

\n

The following was written in Jan 2021 and is out of date

\n

Currently conda install tensorflow-gpu installs tensorflow v2.3.0 and does NOT install the conda cudnn or cudatoolkit packages. Installing them manually (e.g. with conda install cudatoolkit=10.1) does not seem to fix the problem either.

\n

A solution is to install an earlier version of tensorflow, which does install cudnn and cudatoolkit, then upgrade with pip

\n
conda install tensorflow-gpu=2.1\npip install tensorflow-gpu==2.3.1\n
\n

(2.4.0 uses cuda 11.0 and cudnn 8.0, however cudnn 8.0 is not in anaconda as of 16/12/2020)

\n

Edit: please also see @GZ0's answer, which links to a github discussion with a one-line solution

\n", + "system": "" + }, + { + "instruction": "How to install libcusolver.so.11", + "input": "", + "output": "

If you want a concrete solution, just find libcusolver.so.10 on your machine and create a link to libcusolver.so.11:

\n

Following command solved issue for me:

\n
sudo ln -s /usr/local/cuda-11.0/targets/x86_64-linux/lib/libcusolver.so.10 /usr/local/cuda-11.0/targets/x86_64-linux/lib/libcusolver.so.11\n
\n

Credit to: https://github.com/tensorflow/tensorflow/issues/43947

\n", + "system": "" + }, + { + "instruction": "Replacing placeholder for tensorflow v2", + "input": "", + "output": "

Make your code work with TF 2.0

\n

Below is a sample code which you can use with TF 2.0.\nIt relies on the compatibility API\nthat is accessible as tensorflow.compat.v1, and requires to disable v2 behaviors.\nI don't know if it behaves as you expected.\nIf not, then provide us more explanation of what you try to achieve.

\n
import tensorflow.compat.v1 as tf\ntf.disable_v2_behavior()\n\n@tf.function\ndef construct_graph(graph_dict, inputs, outputs):\n    queue = inputs[:]\n    make_dict = {}\n    for key, val in graph_dict.items():\n        if key in inputs:\n            make_dict[key] = tf.placeholder(tf.float32, name=key)\n        else:\n            make_dict[key] = None\n    # Breadth-First search of graph starting from inputs\n    while len(queue) != 0:\n        cur = graph_dict[queue[0]]\n        for outg in cur["outgoing"]:\n            if make_dict[outg[0]]: # If discovered node, do add/multiply operation\n                make_dict[outg[0]] = tf.add(make_dict[outg[0]], tf.multiply(outg[1], make_dict[queue[0]]))\n            else: # If undiscovered node, input is just coming in multiplied and add outgoing to queue\n                make_dict[outg[0]] = tf.multiply(make_dict[queue[0]], outg[1])\n                for outgo in graph_dict[outg[0]]["outgoing"]:\n                    queue.append(outgo[0])\n        queue.pop(0)\n    # Returns one data graph for each output\n    return [make_dict[x] for x in outputs]\n\ndef main():\n    graph_def = {\n        "B": {\n            "incoming": [],\n            "outgoing": [("A", 1.0)]\n        },\n        "C": {\n            "incoming": [],\n            "outgoing": [("A", 1.0)]\n        },\n        "A": {\n            "incoming": [("B", 2.0), ("C", -1.0)],\n            "outgoing": [("D", 3.0)]\n        },\n        "D": {\n            "incoming": [("A", 2.0)],\n            "outgoing": []\n        }\n    }\n    outputs = construct_graph(graph_def, ["B", "C"], ["A"])\n    print(outputs)\n\nif __name__ == "__main__":\n    main()\n
\n
[<tf.Tensor 'PartitionedCall:0' shape=<unknown> dtype=float32>]\n
\n

\u00a0Migrate your code to TF 2.0

\n

While the above snippet is valid, it is still tied to TF 1.0.\nTo migrate it to TF 2.0 you have to refactor a little bit your code.

\n

Instead of returning a list of tensors, which were callables with TF 1.0, I advise you to return a list of\nkeras.layers.Model.

\n

Below is a working example:

\n
import tensorflow as tf\n\ndef construct_graph(graph_dict, inputs, outputs):\n    queue = inputs[:]\n    make_dict = {}\n    for key, val in graph_dict.items():\n        if key in inputs:\n            # Use keras.Input instead of placeholders\n            make_dict[key] = tf.keras.Input(name=key, shape=(), dtype=tf.dtypes.float32)\n        else:\n            make_dict[key] = None\n    # Breadth-First search of graph starting from inputs\n    while len(queue) != 0:\n        cur = graph_dict[queue[0]]\n        for outg in cur["outgoing"]:\n            if make_dict[outg[0]] is not None: # If discovered node, do add/multiply operation\n                make_dict[outg[0]] = tf.keras.layers.add([\n                    make_dict[outg[0]],\n                    tf.keras.layers.multiply(\n                        [[outg[1]], make_dict[queue[0]]],\n                    )],\n                )\n            else: # If undiscovered node, input is just coming in multiplied and add outgoing to queue\n                make_dict[outg[0]] = tf.keras.layers.multiply(\n                    [make_dict[queue[0]], [outg[1]]]\n                )\n                for outgo in graph_dict[outg[0]]["outgoing"]:\n                    queue.append(outgo[0])\n        queue.pop(0)\n    # Returns one data graph for each output\n    model_inputs = [make_dict[key] for key in inputs]\n    model_outputs = [make_dict[key] for key in outputs]\n    return [tf.keras.Model(inputs=model_inputs, outputs=o) for o in model_outputs]\n\ndef main():\n    graph_def = {\n        "B": {\n            "incoming": [],\n            "outgoing": [("A", 1.0)]\n        },\n        "C": {\n            "incoming": [],\n            "outgoing": [("A", 1.0)]\n        },\n        "A": {\n            "incoming": [("B", 2.0), ("C", -1.0)],\n            "outgoing": [("D", 3.0)]\n        },\n        "D": {\n            "incoming": [("A", 2.0)],\n            "outgoing": []\n        }\n    }\n    outputs = construct_graph(graph_def, ["B", "C"], ["A"])\n    print("Builded models:", outputs)\n    for o in outputs:\n        o.summary(120)\n        print("Output:", o((1.0, 1.0)))\n\nif __name__ == "__main__":\n    main()\n
\n

What to notice here?

\n\n

Here is the output of the code.

\n
Builded models: [<tensorflow.python.keras.engine.training.Model object at 0x7fa0b49f0f50>]\nModel: "model"\n________________________________________________________________________________________________________________________\nLayer (type)                           Output Shape               Param #       Connected to                            \n========================================================================================================================\nB (InputLayer)                         [(None,)]                  0                                                     \n________________________________________________________________________________________________________________________\nC (InputLayer)                         [(None,)]                  0                                                     \n________________________________________________________________________________________________________________________\ntf_op_layer_mul (TensorFlowOpLayer)    [(None,)]                  0             B[0][0]                                 \n________________________________________________________________________________________________________________________\ntf_op_layer_mul_1 (TensorFlowOpLayer)  [(None,)]                  0             C[0][0]                                 \n________________________________________________________________________________________________________________________\nadd (Add)                              (None,)                    0             tf_op_layer_mul[0][0]                   \n                                                                                tf_op_layer_mul_1[0][0]                 \n========================================================================================================================\nTotal params: 0\nTrainable params: 0\nNon-trainable params: 0\n________________________________________________________________________________________________________________________\nOutput: tf.Tensor([2.], shape=(1,), dtype=float32)\n
\n", + "system": "" + }, + { + "instruction": "Force Anaconda to install tensorflow 1.14", + "input": "", + "output": "

You can force installing a certain version of any package found on Anaconda using simply an = operator with the package version attached to it.

\n\n

So, if you want to install tensorflow 1.14, you can run the following command:

\n\n
conda install -c conda-forge tensorflow=1.14\n
\n\n

You can replace 1.14 with any other versions. To see the available versions of tensorflow on Anaconda, you can run:

\n\n
conda search tensorflow\n
\n", + "system": "" + }, + { + "instruction": "ValueError: Shape mismatch: The shape of labels (received (15,)) should equal the shape of logits except for the last dimension (received (5, 3))", + "input": "", + "output": "

The difference between sparse_categorical_crossentropy and categorical_crossentropy is whether your targets are one-hot encoded.

\n\n

The shape of label batch is (5,3), which means it has been one-hot encoded. So you should use categorical_crossentropy loss function.

\n\n
model.compile(optimizer='adam',\n              loss='categorical_crossentropy',\n              metrics=['accuracy'])\n
\n", + "system": "" + }, + { + "instruction": "Why do some object detection neural networks return all zeros in OpenCV 4.1.0?", + "input": "", + "output": "

Some models expect normalized values for channel intensity. Normally, an image is represented in uint8 pixels (values ranging from 0 ~ 255). You would need to convert it to float32 (from -1 ~ 1). Basically, for such a model, your image would be interpreted as a blank picture (mostly all white pixels).

\n

Here's a python function that could be used to normalize the image:

\n
def processFrame(image):\n    img = cv2.resize(image, (input_width, input_height)) # input sizes of detector \n    img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    # Normalize pixel values if using a floating model\n    img_rgb = (np.float32(img_rgb) - 127.5) / 127.5\n
\n", + "system": "" + }, + { + "instruction": "ValueError: Output tensors to a Model must be the output of a TensorFlow `Layer`", + "input": "", + "output": "

I have found a way to work around to solve the problem.\nFor anyone who encounters the same issue, you can use the Lambda layer to wrap your tensorflow operations, this is what I did:

\n\n
from tensorflow.python.keras.layers import Lambda;\n\ndef norm(fc2):\n\n    fc2_norm = K.l2_normalize(fc2, axis = 3);\n    illum_est = tf.reduce_sum(fc2_norm, axis = (1, 2));\n    illum_est = K.l2_normalize(illum_est);\n\n    return illum_est;\n\nillum_est = Lambda(norm)(fc2);\n
\n", + "system": "" + }, + { + "instruction": "How to add report_tensor_allocations_upon_oom to RunOptions in Keras", + "input": "", + "output": "

TF1 solution:

\n

Its not as hard as it seems, what you need to know is that according to the documentation, the **kwargs parameter passed to model.compile will be passed to session.run

\n

So you can do something like:

\n
import tensorflow as tf\nrun_opts = tf.RunOptions(report_tensor_allocations_upon_oom = True)\n\nmodel.compile(loss = "...", optimizer = "...", metrics = "..", options = run_opts)\n
\n

And it should be passed directly each time session.run is called.

\n

TF2:

\n

The solution above works only for tf1. For tf2, unfortunately, it appears there is no easy solution yet.

\n", + "system": "" + }, + { + "instruction": "Darknet YOLO image size", + "input": "", + "output": "

You don't have to resize it, because Darknet will do it instead of you!

\n\n

It means you really don't need to do that and you can use different image sizes during your training. What you posted above is just network configuration. There should be full network definition as well. And the height and the width tell you what's the network resolution. And it also keeps aspect ratio, check e.g this.

\n", + "system": "" + }, + { + "instruction": "Keras early stopping callback error, val_loss metric not available", + "input": "", + "output": "

If the error only occurs when you use smaller datasets, you're very likely using datasets small enough to not have a single sample in the validation set.

\n\n

Thus it cannot calculate a validation loss.

\n", + "system": "" + }, + { + "instruction": "Feeding .npy (numpy files) into tensorflow data pipeline", + "input": "", + "output": "

It is actually possible to read directly NPY files with TensorFlow instead of TFRecords. The key pieces are tf.data.FixedLengthRecordDataset and tf.io.decode_raw, along with a look at the documentation of the NPY format. For simplicity, let's suppose that a float32 NPY file containing an array with shape (N, K) is given, and you know the number of features K beforehand, as well as the fact that it is a float32 array. An NPY file is just a binary file with a small header and followed by the raw array data (object arrays are different, but we're considering numbers now). In short, you can find the size of this header with a function like this:

\n
def npy_header_offset(npy_path):\n    with open(str(npy_path), 'rb') as f:\n        if f.read(6) != b'\\x93NUMPY':\n            raise ValueError('Invalid NPY file.')\n        version_major, version_minor = f.read(2)\n        if version_major == 1:\n            header_len_size = 2\n        elif version_major == 2:\n            header_len_size = 4\n        else:\n            raise ValueError('Unknown NPY file version {}.{}.'.format(version_major, version_minor))\n        header_len = sum(b << (8 * i) for i, b in enumerate(f.read(header_len_size)))\n        header = f.read(header_len)\n        if not header.endswith(b'\\n'):\n            raise ValueError('Invalid NPY file.')\n        return f.tell()\n
\n

With this you can create a dataset like this:

\n
import tensorflow as tf\n\nnpy_file = 'my_file.npy'\nnum_features = ...\ndtype = tf.float32\nheader_offset = npy_header_offset(npy_file)\ndataset = tf.data.FixedLengthRecordDataset([npy_file], num_features * dtype.size, header_bytes=header_offset)\n
\n

Each element of this dataset contains a long string of bytes representing a single example. You can now decode it to obtain an actual array:

\n
dataset = dataset.map(lambda s: tf.io.decode_raw(s, dtype))\n
\n

The elements will have indeterminate shape, though, because TensorFlow does not keep track of the length of the strings. You can just enforce the shape since you know the number of features:

\n
dataset = dataset.map(lambda s: tf.reshape(tf.io.decode_raw(s, dtype), (num_features,)))\n
\n

Similarly, you can choose to perform this step after batching, or combine it in whatever way you feel like.

\n

The limitation is that you had to know the number of features in advance. It is possible to extract it from the NumPy header, though, just a bit of a pain, and in any case very hardly from within TensorFlow, so the file names would need to be known in advance. Another limitation is that, as it is, the solution requires you to either use only one file per dataset or files that have the same header size, although if you know that all the arrays have the same size that should actually be the case.

\n

Admittedly, if one considers this kind of approach it may just be better to have a pure binary file without headers, and either hard code the number of features or read them from a different source...

\n", + "system": "" + }, + { + "instruction": "Tensor is not an element of this graph", + "input": "", + "output": "

Try first:

\n\n
import tensorflow as tf\ngraph = tf.get_default_graph()\n
\n\n

Then, when you need to use predict:

\n\n
with graph.as_default():\n     y = model.predict(X)\n
\n", + "system": "" + }, + { + "instruction": "difference between Tensorflow's Graph and GraphDef", + "input": "", + "output": "

Graph or Computional Graph is the core concept of tensorflow to present computation. When you use tensorflow, you firstly create you own Computation Graph and pass the Graph to tensorflow. How to do that? As you may know, tensorflow support many front-end programming languages, like Python, C++, Java and Go and the core language is C++; how do the other languages transform the Graph to C++? They use a tool called protobuf which can generate specific language stubs, that's where the GraphDef come from. It's a serialized version of Graph.

\n\n
\n

which one should I have to run a graph loaded from protobuf file (.pb)

\n
\n\n

You should read your *pb file using GraphDef and bind the GraphDef to a (default) Graph, then use a session to run the Graph for computation, like the following code:

\n\n
import tensorflow as tf\nfrom tensorflow.python.platform import gfile\nwith tf.Session() as sess:\n    model_filename ='PATH_TO_PB.pb'\n    with gfile.FastGFile(model_filename, 'rb') as f:\n        graph_def = tf.GraphDef()\n        graph_def.ParseFromString(f.read())\n        g_in = tf.import_graph_def(graph_def)\nLOGDIR='/logs/tests/1/'\ntrain_writer = tf.summary.FileWriter(LOGDIR)\ntrain_writer.add_graph(sess.graph)\n
\n", + "system": "" + }, + { + "instruction": "how to implement early stopping in tensorflow", + "input": "", + "output": "

Here is my implementation of the early stopping u can adapt it:

\n\n

The early stopping can be applied at certain stages of the training process, such as at the end of each epoch. Specifically; in my case; I monitor the test (validation) loss at each epoch and after the test loss has not improved after 20 epochs (self.require_improvement= 20) , the training is interrupted.

\n\n

You can set the max epochs to 10000 or 20000 or whatever you want (self.max_epochs = 10000).

\n\n
  self.require_improvement= 20\n  self.max_epochs = 10000\n
\n\n

Here is my training function where I use the early stopping:

\n\n

def train(self):

\n\n
# training data\n    train_input = self.Normalize(self.x_train)\n    train_output = self.y_train.copy()            \n#===============\n    save_sess=self.sess # this used to compare the result of previous sess with actual one\n# ===============\n  #costs history :\n    costs = []\n    costs_inter=[]\n# =================\n  #for early stopping :\n    best_cost=1000000 \n    stop = False\n    last_improvement=0\n# ================\n    n_samples = train_input.shape[0] # size of the training set\n# ===============\n   #train the mini_batches model using the early stopping criteria\n    epoch = 0\n    while epoch < self.max_epochs and stop == False:\n        #train the model on the traning set by mini batches\n        #suffle then split the training set to mini-batches of size self.batch_size\n        seq =list(range(n_samples))\n        random.shuffle(seq)\n        mini_batches = [\n            seq[k:k+self.batch_size]\n            for k in range(0,n_samples, self.batch_size)\n        ]\n\n        avg_cost = 0. # The average cost of mini_batches\n        step= 0\n\n        for sample in mini_batches:\n\n            batch_x = x_train.iloc[sample, :]\n            batch_y =train_output.iloc[sample, :]\n            batch_y = np.array(batch_y).flatten()\n\n            feed_dict={self.X: batch_x,self.Y:batch_y, self.is_train:True}\n\n            _, cost,acc=self.sess.run([self.train_step, self.loss_, self.accuracy_],feed_dict=feed_dict)\n            avg_cost += cost *len(sample)/n_samples \n            print('epoch[{}] step [{}] train -- loss : {}, accuracy : {}'.format(epoch,step, avg_cost, acc))\n            step += 100\n\n        #cost history since the last best cost\n        costs_inter.append(avg_cost)\n\n        #early stopping based on the validation set/ max_steps_without_decrease of the loss value : require_improvement\n        if avg_cost < best_cost:\n            save_sess= self.sess # save session\n            best_cost = avg_cost\n            costs +=costs_inter # costs history of the validatio set\n            last_improvement = 0\n            costs_inter= []\n        else:\n            last_improvement +=1\n        if last_improvement > self.require_improvement:\n            print(\"No improvement found during the ( self.require_improvement) last iterations, stopping optimization.\")\n            # Break out from the loop.\n            stop = True\n            self.sess=save_sess # restore session with the best cost\n\n        ## Run validation after every epoch : \n        print('---------------------------------------------------------')\n        self.y_validation = np.array(self.y_validation).flatten()\n        loss_valid, acc_valid = self.sess.run([self.loss_,self.accuracy_], \n                                              feed_dict={self.X: self.x_validation, self.Y: self.y_validation,self.is_train: True})\n        print(\"Epoch: {0}, validation loss: {1:.2f}, validation accuracy: {2:.01%}\".format(epoch + 1, loss_valid, acc_valid))\n        print('---------------------------------------------------------')\n\n        epoch +=1\n
\n\n

We can resume the important code here :

\n\n
def train(self):\n  ...\n      #costs history :\n        costs = []\n        costs_inter=[]\n      #for early stopping :\n        best_cost=1000000 \n        stop = False\n        last_improvement=0\n       #train the mini_batches model using the early stopping criteria\n        epoch = 0\n        while epoch < self.max_epochs and stop == False:\n            ...\n            for sample in mini_batches:\n            ...                   \n            #cost history since the last best cost\n            costs_inter.append(avg_cost)\n\n            #early stopping based on the validation set/ max_steps_without_decrease of the loss value : require_improvement\n            if avg_cost < best_cost:\n                save_sess= self.sess # save session\n                best_cost = avg_cost\n                costs +=costs_inter # costs history of the validatio set\n                last_improvement = 0\n                costs_inter= []\n            else:\n                last_improvement +=1\n            if last_improvement > self.require_improvement:\n                print(\"No improvement found during the ( self.require_improvement) last iterations, stopping optimization.\")\n                # Break out from the loop.\n                stop = True\n                self.sess=save_sess # restore session with the best cost\n            ...\n            epoch +=1\n
\n\n

Hope it will help someone :).

\n", + "system": "" + }, + { + "instruction": "How to properly use tf.metrics.accuracy?", + "input": "", + "output": "

TL;DR

\n\n

The accuracy function tf.metrics.accuracy calculates how often predictions matches labels based on two local variables it creates: total and count, that are used to compute the frequency with which logits matches labels.

\n\n
acc, acc_op = tf.metrics.accuracy(labels=tf.argmax(labels, 1), \n                                  predictions=tf.argmax(logits,1))\n\nprint(sess.run([acc, acc_op]))\nprint(sess.run([acc]))\n# Output\n#[0.0, 0.66666669]\n#[0.66666669]\n
\n\n\n\n

To understand why the acc returns 0.0, go through the details below.

\n\n
\n\n

Details using a simple example:

\n\n
logits = tf.placeholder(tf.int64, [2,3])\nlabels = tf.Variable([[0, 1, 0], [1, 0, 1]])\n\nacc, acc_op = tf.metrics.accuracy(labels=tf.argmax(labels, 1),   \n                                  predictions=tf.argmax(logits,1))\n
\n\n

Initialize the variables:

\n\n

Since metrics.accuracy creates two local variables total and count, we need to call local_variables_initializer() to initialize them.

\n\n
sess = tf.Session()\n\nsess.run(tf.local_variables_initializer())\nsess.run(tf.global_variables_initializer())\n\nstream_vars = [i for i in tf.local_variables()]\nprint(stream_vars)\n\n#[<tf.Variable 'accuracy/total:0' shape=() dtype=float32_ref>,\n# <tf.Variable 'accuracy/count:0' shape=() dtype=float32_ref>]\n
\n\n

Understanding update ops and accuracy calculation:

\n\n
print('acc:',sess.run(acc, {logits:[[0,1,0],[1,0,1]]}))\n#acc: 0.0\n\nprint('[total, count]:',sess.run(stream_vars)) \n#[total, count]: [0.0, 0.0]\n
\n\n

The above returns 0.0 for accuracy as total and count are zeros, inspite of giving matching inputs.

\n\n
print('ops:', sess.run(acc_op, {logits:[[0,1,0],[1,0,1]]})) \n#ops: 1.0\n\nprint('[total, count]:',sess.run(stream_vars)) \n#[total, count]: [2.0, 2.0]\n
\n\n

With the new inputs, the accuracy is calculated when the update op is called. Note: since all the logits and labels match, we get accuracy of 1.0 and the local variables total and count actually give total correctly predicted and the total comparisons made.

\n\n

Now we call accuracy with the new inputs (not the update ops):

\n\n
print('acc:', sess.run(acc,{logits:[[1,0,0],[0,1,0]]}))\n#acc: 1.0\n
\n\n

Accuracy call doesnt update the metrics with the new inputs, it just returns the value using the two local variables. Note: the logits and labels dont match in this case. Now calling update ops again:

\n\n
print('op:',sess.run(acc_op,{logits:[[0,1,0],[0,1,0]]}))\n#op: 0.75 \nprint('[total, count]:',sess.run(stream_vars)) \n#[total, count]: [3.0, 4.0]\n
\n\n

The metrics are updated to new inputs

\n\n
\n\n

For more information on how to use the metrics during training and how to reset them during validation, can be found here.

\n", + "system": "" + }, + { + "instruction": "What is the advantage of using an InputLayer (or an Input) in a Keras model with Tensorflow tensors?", + "input": "", + "output": "

It would seem that InputLayer has some uses:

\n\n", + "system": "" + }, + { + "instruction": "tensorboard: command not found", + "input": "", + "output": "

You could call tensorboard as a python module like this:

\n\n
python3 -m tensorboard.main --logdir=~/my/training/dir\n
\n\n

or add this to your .profile

\n\n

alias tensorboard='python3 -m tensorboard.main'

\n", + "system": "" + }, + { + "instruction": "Tensorflow: How does tf.get_variable work?", + "input": "", + "output": "

tf.get_variable(name) creates a new variable called name (or add _ if name already exists in the current scope) in the tensorflow graph.

\n

In your example, you're creating a python variable called var1.

\n

The name of that variable in the tensorflow graph is not ** var1, but is Variable:0.

\n

Every node you define has its own name that you can specify or let tensorflow give a default (and always different) one. You can see the name value accessing the name property of the python variable. (ie print(var1.name)).

\n

On your second line, you're defining a Python variable var2 whose name in the tensorflow graph is var1.

\n

The script

\n
import tensorflow as tf\n\nvar1 = tf.Variable(3.,dtype=tf.float64)\nprint(var1.name)\nvar2 = tf.get_variable("var1",[],dtype=tf.float64)\nprint(var2.name)\n
\n

In fact prints:

\n
Variable:0\nvar1:0\n
\n

If you, instead, want to define a variable (node) called var1 in the tensorflow graph and then getting a reference to that node, you cannot simply use tf.get_variable("var1"), because it will create a new different variable valled var1_1.

\n

This script

\n
var1 = tf.Variable(3.,dtype=tf.float64, name="var1")\nprint(var1.name)\nvar2 = tf.get_variable("var1",[],dtype=tf.float64)\nprint(var2.name)\n
\n

prints:

\n
var1:0\nvar1_1:0\n
\n

If you want to create a reference to the node var1, you first:

\n
    \n
  1. Have to replace tf.Variable with tf.get_variable. The variables created with tf.Variable can't be shared, while the latter can.

    \n
  2. \n
  3. Know what the scope of the var1 is and allow the reuse of that scope when declaring the reference.

    \n
  4. \n
\n

Looking at the code is the better way for understanding

\n
import tensorflow as tf\n\n#var1 = tf.Variable(3.,dtype=tf.float64, name="var1")\nvar1 = tf.get_variable(initializer=tf.constant_initializer(3.), dtype=tf.float64, name="var1", shape=())\ncurrent_scope = tf.contrib.framework.get_name_scope()\nprint(var1.name)\nwith tf.variable_scope(current_scope, reuse=True):\n    var2 = tf.get_variable("var1",[],dtype=tf.float64)\n    print(var2.name)\n
\n

outputs:

\n
var1:0\nvar1:0\n
\n", + "system": "" + }, + { + "instruction": "How does one train multiple models in a single script in TensorFlow when there are GPUs present?", + "input": "", + "output": "

I think that running all models in one single script can be bad practice in the long term (see my suggestion below for a better alternative). However, if you would like to do it, here is a solution: You can encapsulate your TF session into a process with the multiprocessing module, this will make sure TF releases the session memory once the process is done. Here is a code snippet:

\n\n
from multiprocessing import Pool\nimport contextlib\ndef my_model((param1, param2, param3)): # Note the extra (), required by the pool syntax\n    < your code >\n\nnum_pool_worker=1 # can be bigger than 1, to enable parallel execution \nwith contextlib.closing(Pool(num_pool_workers)) as po: # This ensures that the processes get closed once they are done\n     pool_results = po.map_async(my_model,\n                                    ((param1, param2, param3)\n                                     for param1, param2, param3 in params_list))\n     results_list = pool_results.get()\n
\n\n

Note from OP: The random number generator seed does not reset automatically with the multi-processing library if you choose to use it. Details here: Using python multiprocessing with different random seed for each process

\n\n

About TF resource allocation: Usually TF allocates much more resources than it needs. Many times you can restrict each process to use a fraction of the total GPU memory, and discover through trial and error the fraction your script requires.

\n\n

You can do it with the following snippet

\n\n
gpu_memory_fraction = 0.3 # Choose this number through trial and error\ngpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_memory_fraction,)\nsession_config = tf.ConfigProto(gpu_options=gpu_options)\nsess = tf.Session(config=session_config, graph=graph)\n
\n\n

Note that sometimes TF increases the memory usage in order to accelerate the execution. Therefore, reducing the memory usage might make your model run slower.

\n\n

Answers to the new questions in your edit/comments:

\n\n
    \n
  1. Yes, Tensorflow will be re-allocated every time a new process is created, and cleared once a process ends.

  2. \n
  3. The for-loop in your edit should also do the job. I suggest to use Pool instead, because it will enable you to run several models concurrently on a single GPU. See my notes about setting gpu_memory_fraction and \"choosing the maximal number of processes\". Also note that: (1) The Pool map runs the loop for you, so you don't need an outer for-loop once you use it. (2) In your example, you should have something like mdl=get_model(args) before calling train()

  4. \n
  5. Weird tuple parenthesis: Pool only accepts a single argument, therefore we use a tuple to pass multiple arguments. See multiprocessing.pool.map and function with two arguments for more details. As suggested in one answer, you can make it more readable with

    \n\n
    def train_mdl(params):\n    (x,y)=params\n    < your code >\n
  6. \n
  7. As @Seven suggested, you can use CUDA_VISIBLE_DEVICES environment variable to choose which GPU to use for your process. You can do it from within your python script using the following on the beginning of the process function (train_mdl).

    \n\n
    import os # the import can be on the top of the python script\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"{}\".format(gpu_id)\n
  8. \n
\n\n

A better practice for executing your experiments would be to isolate your training/evaluation code from the hyper parameters/ model search code.\nE.g. have a script named train.py, which accepts a specific combination of hyper parameters and references to your data as arguments, and executes training for a single model.

\n\n

Then, to iterate through the all the possible combinations of parameters you can use a simple task (jobs) queue, and submit all the possible combinations of hyper-parametrs as separate jobs. The task queue will feed your jobs one at a time to your machine. Usually, you can also set the queue to execute number of processes concurrently (see details below).

\n\n

Specifically, I use task spooler, which is super easy to install and handful (doesn't requires admin privileges, details below).

\n\n

Basic usage is (see notes below about task spooler usage):

\n\n
ts <your-command>\n
\n\n

In practice, I have a separate python script that manages my experiments, set all the arguments per specific experiment and send the jobs to the ts queue.

\n\n

Here are some relevant snippets of python code from my experiments manager:

\n\n

run_bash executes a bash command

\n\n
def run_bash(cmd):\n    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, executable='/bin/bash')\n    out = p.stdout.read().strip()\n    return out  # This is the stdout from the shell command\n
\n\n

The next snippet sets the number of concurrent processes to be run (see note below about choosing the maximal number of processes):

\n\n
max_job_num_per_gpu = 2\nrun_bash('ts -S %d'%max_job_num_per_gpu)\n
\n\n

The next snippet iterates through a list of all combinations of hyper params / model params. Each element of the list is a dictionary, where the keys are the command line arguments for the train.py script

\n\n
for combination_dict in combinations_list:\n\n    job_cmd = 'python train.py ' + '  '.join(\n            ['--{}={}'.format(flag, value) for flag, value in combination_dict.iteritems()])\n\n    submit_cmd = \"ts bash -c '%s'\" % job_cmd\n    run_bash(submit_cmd)\n
\n\n

A note about about choosing the maximal number of processes:

\n\n

If you are short on GPUs, you can use gpu_memory_fraction you found, to set the number of processes as max_job_num_per_gpu=int(1/gpu_memory_fraction)

\n\n

Notes about task spooler (ts):

\n\n
    \n
  1. You could set the number of concurrent processes to run (\"slots\") with:

    \n\n

    ts -S <number-of-slots>

  2. \n
  3. Installing ts doesn't requires admin privileges. You can download and compile it from source with a simple make, add it to your path and you're done.

  4. \n
  5. You can set up multiple queues (I use it for multiple GPUs), with

    \n\n

    TS_SOCKET=<path_to_queue_name> ts <your-command>

    \n\n

    e.g.

    \n\n

    TS_SOCKET=/tmp/socket-ts.gpu_queue_1 ts <your-command>

    \n\n

    TS_SOCKET=/tmp/socket-ts.gpu_queue_2 ts <your-command>

  6. \n
  7. See here for further usage example

  8. \n
\n\n

A note about automatically setting the path names and file names:\nOnce you separate your main code from the experiment manager, you will need an efficient way to generate file names and directory names, given the hyper-params. I usually keep my important hyper params in a dictionary and use the following function to generate a single chained string from the dictionary key-value pairs.\nHere are the functions I use for doing it:

\n\n
def build_string_from_dict(d, sep='%'):\n    \"\"\"\n     Builds a string from a dictionary.\n     Mainly used for formatting hyper-params to file names.\n     Key-value pairs are sorted by the key name.\n\n    Args:\n        d: dictionary\n\n    Returns: string\n    :param d: input dictionary\n    :param sep: key-value separator\n\n    \"\"\"\n\n    return sep.join(['{}={}'.format(k, _value2str(d[k])) for k in sorted(d.keys())])\n\n\ndef _value2str(val):\n    if isinstance(val, float): \n        # %g means: \"Floating point format.\n        # Uses lowercase exponential format if exponent is less than -4 or not less than precision,\n        # decimal format otherwise.\"\n        val = '%g' % val\n    else:\n        val = '{}'.format(val)\n    val = re.sub('\\.', '_', val)\n    return val\n
\n", + "system": "" + }, + { + "instruction": "Converting from Pandas dataframe to TensorFlow tensor object", + "input": "", + "output": "

Here is one solution I found that works on Google Colab:

\n
import pandas as pd\nimport tensorflow as tf\n#Read the file to a pandas object\ndata=pd.read_csv('filedir')\n#convert the pandas object to a tensor\ndata=tf.convert_to_tensor(data)\ntype(data)\n
\n

This will print something like:

\n
tensorflow.python.framework.ops.Tensor\n
\n", + "system": "" + }, + { + "instruction": "Hyperparameter optimization for Deep Learning Structures using Bayesian Optimization", + "input": "", + "output": "
\n

Although I am still not fully understanding the optimization\n algorithm, I feed like it will help me greatly.

\n
\n\n

First up, let me briefly explain this part.\nBayesian Optimization methods aim to deal with exploration-exploitation trade off in the multi-armed bandit problem. In this problem, there is an unknown function, which we can evaluate in any point, but each evaluation costs (direct penalty or opportunity cost), and the goal is to find its maximum using as few trials as possible. Basically, the trade off is this: you know the function in a finite set of points (of which some are good and some are bad), so you can try an area around the current local maximum, hoping to improve it (exploitation), or you can try a completely new area of space, that can potentially be much better or much worse (exploration), or somewhere in between.

\n\n

Bayesian Optimization methods (e.g. PI, EI, UCB), build a model of the target function using a Gaussian Process (GP) and at each step choose the most \"promising\" point based on their GP model (note that \"promising\" can be defined differently by different particular methods).

\n\n

Here's an example:

\n\n

\"sin(x)*x\"

\n\n

The true function is f(x) = x * sin(x) (black curve) on [-10, 10] interval. Red dots represent each trial, red curve is the GP mean, blue curve is the mean plus or minus one standard deviation. \nAs you can see, the GP model doesn't match the true function everywhere, but the optimizer fairly quickly identified the \"hot\" area around -8 and started to exploit it.

\n\n
\n

How do I set up the Bayesian Optimization with regards to a deep\n network?

\n
\n\n

In this case, the space is defined by (possibly transformed) hyperparameters, usually a multidimensional unit hypercube.

\n\n

For example, suppose you have three hyperparameters: a learning rate \u03b1 in [0.001, 0.01], the regularizer \u03bb in [0.1, 1] (both continuous) and the hidden layer size N in [50..100] (integer). The space for optimization is a 3-dimensional cube [0, 1]*[0, 1]*[0, 1]. Each point (p0, p1, p2) in this cube corresponds to a trinity (\u03b1, \u03bb, N) by the following transformation:

\n\n
p0 -> \u03b1 = 10**(p0-3)\np1 -> \u03bb = 10**(p1-1)\np2 -> N = int(p2*50 + 50)\n
\n\n
\n

What is the function I am trying to optimize? Is it the cost of the\n validation set after N epochs?

\n
\n\n

Correct, the target function is neural network validation accuracy. Clearly, each evaluation is expensive, because it requires at least several epochs for training.

\n\n

Also note that the target function is stochastic, i.e. two evaluations on the same point may slightly differ, but it's not a blocker for Bayesian Optimization, though it obviously increases the uncertainty.

\n\n
\n

Is spearmint a good starting point for this task? Any other\n suggestions for this task?

\n
\n\n

spearmint is a good library, you can definitely work with that. I can also recommend hyperopt.

\n\n

In my own research, I ended up writing my own tiny library, basically for two reasons: I wanted to code exact Bayesian method to use (in particular, I found a portfolio strategy of UCB and PI converged faster than anything else, in my case); plus there is another technique that can save up to 50% of training time called learning curve prediction (the idea is to skip full learning cycle when the optimizer is confident the model doesn't learn as fast as in other areas). I'm not aware of any library that implements this, so I coded it myself, and in the end it paid off. If you're interested, the code is on GitHub.

\n", + "system": "" + }, + { + "instruction": "Tensorflow Confusion Matrix in TensorBoard", + "input": "", + "output": "

Here is something I have put together That works reasonably well. Still need to adjust a few things like the tick placements etc.

\n\n

\"Confusion

\n\n

Here is the function that will pretty much do everything for you.

\n\n
from textwrap import wrap\nimport re\nimport itertools\nimport tfplot\nimport matplotlib\nimport numpy as np\nfrom sklearn.metrics import confusion_matrix\n\n\n\ndef plot_confusion_matrix(correct_labels, predict_labels, labels, title='Confusion matrix', tensor_name = 'MyFigure/image', normalize=False):\n''' \nParameters:\n    correct_labels                  : These are your true classification categories.\n    predict_labels                  : These are you predicted classification categories\n    labels                          : This is a lit of labels which will be used to display the axix labels\n    title='Confusion matrix'        : Title for your matrix\n    tensor_name = 'MyFigure/image'  : Name for the output summay tensor\n\nReturns:\n    summary: TensorFlow summary \n\nOther itema to note:\n    - Depending on the number of category and the data , you may have to modify the figzie, font sizes etc. \n    - Currently, some of the ticks dont line up due to rotations.\n'''\ncm = confusion_matrix(correct_labels, predict_labels, labels=labels)\nif normalize:\n    cm = cm.astype('float')*10 / cm.sum(axis=1)[:, np.newaxis]\n    cm = np.nan_to_num(cm, copy=True)\n    cm = cm.astype('int')\n\nnp.set_printoptions(precision=2)\n###fig, ax = matplotlib.figure.Figure()\n\nfig = matplotlib.figure.Figure(figsize=(7, 7), dpi=320, facecolor='w', edgecolor='k')\nax = fig.add_subplot(1, 1, 1)\nim = ax.imshow(cm, cmap='Oranges')\n\nclasses = [re.sub(r'([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))', r'\\1 ', x) for x in labels]\nclasses = ['\\n'.join(wrap(l, 40)) for l in classes]\n\ntick_marks = np.arange(len(classes))\n\nax.set_xlabel('Predicted', fontsize=7)\nax.set_xticks(tick_marks)\nc = ax.set_xticklabels(classes, fontsize=4, rotation=-90,  ha='center')\nax.xaxis.set_label_position('bottom')\nax.xaxis.tick_bottom()\n\nax.set_ylabel('True Label', fontsize=7)\nax.set_yticks(tick_marks)\nax.set_yticklabels(classes, fontsize=4, va ='center')\nax.yaxis.set_label_position('left')\nax.yaxis.tick_left()\n\nfor i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n    ax.text(j, i, format(cm[i, j], 'd') if cm[i,j]!=0 else '.', horizontalalignment=\"center\", fontsize=6, verticalalignment='center', color= \"black\")\nfig.set_tight_layout(True)\nsummary = tfplot.figure.to_summary(fig, tag=tensor_name)\nreturn summary\n
\n\n#\n\n

And here is the rest of the code that you will need to call this functions.

\n\n
''' confusion matrix summaries '''\nimg_d_summary_dir = os.path.join(checkpoint_dir, \"summaries\", \"img\")\nimg_d_summary_writer = tf.summary.FileWriter(img_d_summary_dir, sess.graph)\nimg_d_summary = plot_confusion_matrix(correct_labels, predict_labels, labels, tensor_name='dev/cm')\nimg_d_summary_writer.add_summary(img_d_summary, current_step)\n
\n\n

Confuse away!!!

\n", + "system": "" + }, + { + "instruction": "Tensorflow mean squared error loss function", + "input": "", + "output": "

I would say that the third equation is different, while the 1st and 2nd are formally the same but behave differently due to numerical concerns.

\n\n

I think that the 3rd equation (using l2_loss) is just returning 1/2 of the squared Euclidean norm, that is, the sum of the element-wise square of the input, which is x=prediction-Y. You are not dividing by the number of samples anywhere. Thus, if you have a very large number of samples, the computation may overflow (returning Inf).

\n\n

The other two are formally the same, computing the mean of the element-wise squared x tensor. However, while the documentation does not specify it explicitly, it is very likely that reduce_mean uses an algorithm adapted to avoid overflowing with very large number of samples. In other words, it likely does not try to sum everything first and then divide by N, but use some kind of rolling mean that can adapt to an arbitrary number of samples without necessarily causing an overflow.

\n", + "system": "" + }, + { + "instruction": "Dot product of two vectors in tensorflow", + "input": "", + "output": "

One of the easiest way to calculate dot product between two tensors (vector is 1D tensor) is using tf.tensordot

\n\n
a = tf.placeholder(tf.float32, shape=(5))\nb = tf.placeholder(tf.float32, shape=(5))\n\ndot_a_b = tf.tensordot(a, b, 1)\n\nwith tf.Session() as sess:\n    print(dot_a_b.eval(feed_dict={a: [1, 2, 3, 4, 5], b: [6, 7, 8, 9, 10]}))\n# results: 130.0\n
\n", + "system": "" + }, + { + "instruction": "Show training and validation accuracy in TensorFlow using same graph", + "input": "", + "output": "

You can reuse the the accuracy node but you need to use two different SummaryWriters, one for the training runs and one for the test data. Also you have to assign the scalar summary for accuracy to a variable.

\n\n
accuracy_summary = tf.scalar_summary(\"Training Accuracy\", accuracy)\ntf.scalar_summary(\"SomethingElse\", foo)\nsummary_op = tf.merge_all_summaries()\nsummaries_dir = '/me/mydir/'\ntrain_writer = tf.train.SummaryWriter(summaries_dir + '/train', sess.graph)\ntest_writer = tf.train.SummaryWriter(summaries_dir + '/test')\n
\n\n

Then in your training loop you have the normal training and record your summaries with the train_writer. In addition you run the graph on the test set each 100th iteration and record only the accuracy summary with the test_writer.

\n\n
# Record train set summaries, and train\nsummary, _ = sess.run([summary_op, train_step], feed_dict=...)\ntrain_writer.add_summary(summary, n)\nif n % 100 == 0:  # Record summaries and test-set accuracy\n  summary, acc = sess.run([accuracy_summary, accuracy], feed_dict=...)\n  test_writer.add_summary(summary, n)\n  print('Accuracy at step %s: %s' % (n, acc))\n
\n\n

You can then point TensorBoard to the parent directory (summaries_dir) and it will load both data sets.

\n\n

This can be also found in the TensorFlow HowTo's https://www.tensorflow.org/versions/r0.11/how_tos/summaries_and_tensorboard/index.html

\n", + "system": "" + }, + { + "instruction": "Cannot import keras after installation", + "input": "", + "output": "

Diagnose

\n\n

If you have pip installed (you should have it until you use Python 3.5), list the installed Python packages, like this:

\n\n
$ pip list | grep -i keras\nKeras (1.1.0)\n
\n\n

If you don\u2019t see Keras, it means that the previous installation failed or is incomplete (this lib has this dependancies: numpy (1.11.2), PyYAML (3.12), scipy (0.18.1), six (1.10.0), and Theano (0.8.2).)

\n\n

Consult the pip.log to see what\u2019s wrong.

\n\n

You can also display your Python path like this:

\n\n
$ python3 -c 'import sys, pprint; pprint.pprint(sys.path)'\n['',\n '/Library/Frameworks/Python.framework/Versions/3.5/lib/python35.zip',\n '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5',\n '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/plat-darwin',\n '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/lib-dynload',\n '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages']\n
\n\n

Make sure the Keras library appears in the /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages path (the path is different on Ubuntu).

\n\n

If not, try do uninstall it, and retry installation:

\n\n
$ pip uninstall Keras\n
\n\n

Use a virtualenv

\n\n

It\u2019s a bad idea to use and pollute your system-wide Python. I recommend using a virtualenv (see this guide).

\n\n

The best usage is to create a virtualenv directory (in your home, for instance), and store your virtualenvs in:

\n\n
cd virtualenv/\nvirtualenv -p python3.5 py-keras\nsource py-keras/bin/activate\npip install -q -U pip setuptools wheel\n
\n\n

Then install Keras:

\n\n
pip install keras\n
\n\n

You get:

\n\n
$ pip list\nKeras (1.1.0)\nnumpy (1.11.2)\npip (8.1.2)\nPyYAML (3.12)\nscipy (0.18.1)\nsetuptools (28.3.0)\nsix (1.10.0)\nTheano (0.8.2)\nwheel (0.30.0a0)\n
\n\n

But, you also need to install extra libraries, like Tensorflow:

\n\n
$ python -c \"import keras\"\nUsing TensorFlow backend.\nTraceback (most recent call last):\n  ...\nImportError: No module named 'tensorflow'\n
\n\n

The installation guide of TesnsorFlow is here: https://www.tensorflow.org/versions/r0.11/get_started/os_setup.html#pip-installation

\n", + "system": "" + }, + { + "instruction": "How to perform k-fold cross validation with tensorflow?", + "input": "", + "output": "

I know this question is old but in case someone is looking to do something similar, expanding on ahmedhosny's answer:

\n\n

The new tensorflow datasets API has the ability to create dataset objects using python generators, so along with scikit-learn's KFold one option can be to create a dataset from the KFold.split() generator:

\n\n
import numpy as np\n\nfrom sklearn.model_selection import LeaveOneOut,KFold\n\nimport tensorflow as tf\nimport tensorflow.contrib.eager as tfe\ntf.enable_eager_execution()\n\nfrom sklearn.datasets import load_iris\ndata = load_iris()\nX=data['data']\ny=data['target']\n\ndef make_dataset(X_data,y_data,n_splits):\n\n    def gen():\n        for train_index, test_index in KFold(n_splits).split(X_data):\n            X_train, X_test = X_data[train_index], X_data[test_index]\n            y_train, y_test = y_data[train_index], y_data[test_index]\n            yield X_train,y_train,X_test,y_test\n\n    return tf.data.Dataset.from_generator(gen, (tf.float64,tf.float64,tf.float64,tf.float64))\n\ndataset=make_dataset(X,y,10)\n
\n\n

Then one can iterate through the dataset either in the graph based tensorflow or using eager execution. Using eager execution:

\n\n
for X_train,y_train,X_test,y_test in tfe.Iterator(dataset):\n    ....\n
\n", + "system": "" + }, + { + "instruction": "Tensorflow and Multiprocessing: Passing Sessions", + "input": "", + "output": "

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

\n\n

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

\n\n

Ray is a good framework for doing this. You can define a Python class which manages the TensorFlow Session and exposes a method for running your simulation.

\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
\n\n

Here are a few more examples of parallelizing TensorFlow with Ray.

\n\n

See the Ray documentation. Note that I'm one of the Ray developers.

\n", + "system": "" + }, + { + "instruction": "Is there a way of determining how much GPU memory is in use by TensorFlow?", + "input": "", + "output": "

(1) There is some limited support with Timeline for logging memory allocations. Here is an example for its usage:

\n\n
    run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)\n    run_metadata = tf.RunMetadata()\n    summary, _ = sess.run([merged, train_step],\n                          feed_dict=feed_dict(True),\n                          options=run_options,\n                          run_metadata=run_metadata)\n    train_writer.add_run_metadata(run_metadata, 'step%03d' % i)\n    train_writer.add_summary(summary, i)\n    print('Adding run metadata for', i)\n    tl = timeline.Timeline(run_metadata.step_stats)\n    print(tl.generate_chrome_trace_format(show_memory=True))\n    trace_file = tf.gfile.Open(name='timeline', mode='w')\n    trace_file.write(tl.generate_chrome_trace_format(show_memory=True))\n
\n\n

You can give this code a try with the MNIST example (mnist with summaries)

\n\n

This will generate a tracing file named timeline, which you can open with chrome://tracing. Note that this only gives an approximated GPU memory usage statistics. It basically simulated a GPU execution, but doesn't have access to the full graph metadata. It also can't know how many variables have been assigned to the GPU.

\n\n

(2) For a very coarse measure of GPU memory usage, nvidia-smi will show the total device memory usage at the time you run the command.

\n\n

nvprof can show the on-chip shared memory usage and register usage at the CUDA kernel level, but doesn't show the global/device memory usage.

\n\n

Here is an example command: nvprof --print-gpu-trace matrixMul

\n\n

And more details here:\nhttp://docs.nvidia.com/cuda/profiler-users-guide/#abstract

\n", + "system": "" + }, + { + "instruction": "Google Colab error: Import "tensorflow.keras.models" could not be resolved(reportMissingImports)", + "input": "", + "output": "

this worked for me.

\n
from tensorflow import keras\nfrom keras.layers import Dense\nfrom keras.models import Sequential, load_model\n
\n", + "system": "" + }, + { + "instruction": "What is the difference between MaxPool and MaxPooling layers in Keras?", + "input": "", + "output": "

They are basically the same thing (i.e. aliases of each other). For future readers who might want to know how this could be determined: go to the documentation page of the layer (you can use the list here) and click on "View aliases". This is then accompanied by a blue plus sign (+).

\n

For example, if you go to MaxPool2D documentation and do this, you will find MaxPooling2D in the list of aliases of this layer as follow:

\n

\"MaxPool

\n", + "system": "" + }, + { + "instruction": "what does class_mode parameter in Keras image_gen.flow_from_directory() signify?", + "input": "", + "output": "

class_mode: One of "categorical", "binary", "sparse", "input", or None. Default: "categorical". Determines the type of label arrays that are returned: - "categorical" will be 2D one-hot encoded labels, - "binary" will be 1D binary labels, "sparse" will be 1D integer labels, - "input" will be images identical to input images (mainly used to work with autoencoders). - If None, no labels are returned (the generator will only yield batches of image data, which is useful to use with model.predict_generator()). Please note that in case of class_mode None, the data still needs to reside in a subdirectory of directory for it to work correctly.

\n", + "system": "" + }, + { + "instruction": "Issue with add method in tensorflow : AttributeError: module 'tensorflow.python.framework.ops' has no attribute '_TensorLike'", + "input": "", + "output": "

For me, the fix was importing

\n\n
from tensorflow.keras import Sequential\nfrom tensorflow.keras.layers import Conv2D, Flatten, Dense\n
\n\n

instead of

\n\n
from keras import Sequential\nfrom keras.layers import Conv2D, Flatten, Dense\n
\n\n

There seems to be some weird compatibility issues between keras and tensorflow.keras

\n", + "system": "" + }, + { + "instruction": "How to downgrade tensorflow version in colab?", + "input": "", + "output": "

You can downgrade Tensorflow to a previous version without GPU support on Google Colab. I ran:

\n
!pip install tensorflow==1.14.0\nimport tensorflow as tf\nprint(tf.__version__)\n
\n

which initially returned

\n
2.0.0-dev20190130\n
\n

but when I returned to it after a few hours, I got the version I requested:

\n
1.14.0\n
\n

Trying to downgrade to a version with GPU support:

\n
!pip install tensorflow-gpu==1.14.0\n
\n

requires restarting the runtime and fails, as importing import tensorflow as tf returns:

\n
\nImportError: libcublas.so.9.0: cannot open shared object file: No such file or directory\n
\n

Update

\n

When the import fails you can always downgrade CUDA to version 9.0 using following commands

\n
!wget https://developer.nvidia.com/compute/cuda/9.0/Prod/local_installers/cuda-repo-ubuntu1604-9-0-local_9.0.176-1_amd64-deb\n!dpkg -i cuda-repo-ubuntu1604-9-0-local_9.0.176-1_amd64-deb\n!apt-key add /var/cuda-repo-9-0-local/7fa2af80.pub\n!apt-get update\n!apt-get install cuda=9.0.176-1\n
\n

You can check the version of CUDA by running:

\n
!nvcc --version\n
\n

Second update

\n

This code now seems to fail, see the follow-up question at How to downgrade to tensorflow-gpu version 1.12 in google colab

\n", + "system": "" + }, + { + "instruction": "Python: Neural Network - TypeError: 'History' object is not subscriptable", + "input": "", + "output": "

Call to model.fit() returns a History object that has a member history, which is of type dict.

\n\n

So you can replace :

\n\n
model2.fit(X, y, validation_split=0.33, epochs=30, callbacks= \n[early_stopping_monitor], verbose=False)\n
\n\n

with

\n\n
history2 = model2.fit(X, y, validation_split=0.33, epochs=30, callbacks= \n[early_stopping_monitor], verbose=False)\n
\n\n

Similarly for other models.

\n\n

and then you can use :

\n\n
plt.plot(history1.history['val_loss'], 'r', history2.history['val_loss'], 'b', \nhistory3.history['val_loss'], 'g')\n
\n", + "system": "" + }, + { + "instruction": "ModuleNotFoundError: No module named 'tensorflow.examples'", + "input": "", + "output": "

I think you should use like bellow on tensorflow 2

\n\n
import tensorflow_datasets\nmnist = tensorflow_datasets.load('mnist')\n
\n", + "system": "" + }, + { + "instruction": "Is there a better way to guess possible unknown variables without brute force than I am doing? Machine learning?", + "input": "", + "output": "

I hate to let you down but I really don't think a neural net will help at all for this problem, and IMO the best answer to your question is the advice \"don't waste your time trying neural nets\".

\n\n

An easy rule of thumb for deciding whether or not neural networks are applicable is to think, \"can an average adult human solve this problem reasonably well in a few seconds?\" For problems like \"what's in this image\", \"respond to this question\", or \"transcribe this audio clip\", the answer is yes. But for your problem, the answer is a most definite no.

\n\n

Neural networks have limitations, and one is that they don't deal well with highly logical problems. This is because the answers are generally not \"smooth\". If you take an image and slightly change a handful of pixels, the content of the image is still the same. If you take an audio clip and insert a few milliseconds of noise, a neural net will probably still be able to figure out what's said. But in your problem, change a single day's \"total basket value\" by only 1 unit, and your answer(s) will drastically change.

\n\n

It seems that the only way to solve your problem is with a \"classical\" algorithmic approach. As currently stated, there might not be any algorithm better than brute force, and it might not be possible to rule out much. For example, what if every day has the property that all fruits are priced the same? The count of each fruit can vary, as long as the total number of fruits is fixed, so the number of possibilities is still exponential in the number of fruits. If your goal is to \"produce a list of possibilities\", then no algorithm can be better than exponential time since this list can be exponentially large in some cases.

\n\n

It's interesting that part of your problem can be reduced to an integer linear program (ILP). Consider a single day, where you are given the basket total B and each fruit's cost c_i, for i=1 through i=n (if n is the total number of distinct fruits). Let's say the prices are large, so it's not obvious that you can \"fill up\" the basket with unit cost fruits. It can be hard in this situation to even find a single solution. Formulated as an ILP, this is equivalent to finding integer values of x_i such that:

\n\n
sum_i (x_i*c_i) = x_1*c_1 + x_2*c_2 + ... + x_n*c_n = B\n
\n\n

and x_i >= 0 for all 1 <= i <= n (can't have negative fruits), and sum_i x_i <= 100 (can have at most 100 fruits).

\n\n

The good news is that decent ILP solvers exist -- you can just hand over the above formulas and the solver will do its best to find a single solution. You can even add an \"objective function\" that the solver will maximize or minimize -- minimizing sum_i x_i has the effect of minimizing the total number of fruits in the basket. The bad news is that ILP is NP-complete, so there is almost no hope of finding an efficient solution for a large number of fruits (which equals the number of variables x_i).

\n\n

I think the best approach forward is to try the ILP approach, but also introduce some more constraints on the scenario. For example, what if all fruits had a different prime number cost? This has the nice property that if you find one solution, you can enumerate a bunch of other related solutions. If an apple costs m and an orange costs n, where m and n are relatively prime, then you can \"trade\" n*x apples for m*x oranges without changing the basket total, for any integer x>0 (so long as you have enough apples and oranges to begin with). If you choose all fruits to have different prime number costs, then all of the costs will be pairwise relatively prime. I think this approach will result in relatively few solutions for a given day.

\n\n

You might also consider other constraints, such as \"there can't be more than 5 fruits of a single kind in the basket\" (add the constraint x_i <= 5), or \"there can be at most 5 distinct kinds of fruits in the basket\" (but this is harder to encode as an ILP constraint). Adding these kinds of constraints will make it easier for the ILP solver to find a solution.

\n\n

Of course the above discussion is focused on a single day, and you have multiple days' worth of data. If the hardest part of the problem is finding any solution for any day at all (which happens if your prices are large), then using an ILP solver will give you a large boost. If solutions are easy to find (which happens if you have a very-low-cost fruit that can \"fill up\" your basket), and the hardest part of the problem is finding solutions that are \"consistent\" across multiple days, then the ILP approach might not be the best fit, and in general this problem seems much more difficult to reason about.

\n\n

Edit: and as mentioned in the comments, for some interpretations of the \"10% change\" constraint, you can even encode the entire multi-day problem as an ILP.

\n", + "system": "" + }, + { + "instruction": "Get the bounding box coordinates in the TensorFlow object detection API tutorial", + "input": "", + "output": "
\n

I tried printing output_dict['detection_boxes'] but I am not sure what\n the numbers mean

\n
\n\n

You can check out the code for yourself. visualize_boxes_and_labels_on_image_array is defined here.

\n\n

Note that you are passing use_normalized_coordinates=True. If you trace the function calls, you will see your numbers [ 0.56213236, 0.2780568 , 0.91445708, 0.69120586] etc. are the values [ymin, xmin, ymax, xmax] where the image coordinates:

\n\n
(left, right, top, bottom) = (xmin * im_width, xmax * im_width, \n                              ymin * im_height, ymax * im_height)\n
\n\n

are computed by the function:

\n\n
def draw_bounding_box_on_image(image,\n                           ymin,\n                           xmin,\n                           ymax,\n                           xmax,\n                           color='red',\n                           thickness=4,\n                           display_str_list=(),\n                           use_normalized_coordinates=True):\n  \"\"\"Adds a bounding box to an image.\n  Bounding box coordinates can be specified in either absolute (pixel) or\n  normalized coordinates by setting the use_normalized_coordinates argument.\n  Each string in display_str_list is displayed on a separate line above the\n  bounding box in black text on a rectangle filled with the input 'color'.\n  If the top of the bounding box extends to the edge of the image, the strings\n  are displayed below the bounding box.\n  Args:\n    image: a PIL.Image object.\n    ymin: ymin of bounding box.\n    xmin: xmin of bounding box.\n    ymax: ymax of bounding box.\n    xmax: xmax of bounding box.\n    color: color to draw bounding box. Default is red.\n    thickness: line thickness. Default value is 4.\n    display_str_list: list of strings to display in box\n                      (each to be shown on its own line).\n    use_normalized_coordinates: If True (default), treat coordinates\n      ymin, xmin, ymax, xmax as relative to the image.  Otherwise treat\n      coordinates as absolute.\n  \"\"\"\n  draw = ImageDraw.Draw(image)\n  im_width, im_height = image.size\n  if use_normalized_coordinates:\n    (left, right, top, bottom) = (xmin * im_width, xmax * im_width,\n                                  ymin * im_height, ymax * im_height)\n
\n", + "system": "" + }, + { + "instruction": "ValueError: Variable rnn/basic_rnn_cell/kernel already exists, disallowed. Did you mean to set reuse=True or reuse=tf.AUTO_REUSE in VarScope?", + "input": "", + "output": "

Does this happen when you run the model for the first time (upon opening a new python console)?

\n\n

If not, you need to clear you computational graph. You can do that by putting this line at the beginning of your script.

\n\n
tf.reset_default_graph()\n
\n", + "system": "" + }, + { + "instruction": "Building a mutlivariate, multi-task LSTM with Keras", + "input": "", + "output": "

So:

\n\n
\n

Firstly, how would I slice up my data for the batches? Since I have\n three full years, does it make sense to simply push through three\n batches, each time of size one year? Or does it make more sense to\n make smaller batches (say 30 days) and also to using sliding windows?\n I.e. instead of 36 batches of 30 days each, I use 36 * 6 batches of 30\n days each, each time sliding with 5 days? Or is this not really the\n way LSTMs should be used? (Note that there is quite a bit of\n seasonality in the data, to I need to catch that kind of long-term\n trend as well).

\n
\n\n

Honestly - modeling such data is something really hard. First of all - I wouldn't advise you to use LSTMs as they are rather designed to capture a little bit different kind of data (e.g. NLP or speech where it's really important to model long-term dependencies - not seasonality) and they need a lot of data in order to be learned. I would rather advise you to use either GRU or SimpleRNN which are way easier to learn and should be better for your task.

\n\n

When it comes to batching - I would definitely advise you to use a fixed window technique as it will end up in producing way more data points than feeding a whole year or a whole month. Try to set a number of days as meta parameter which will be also optimized by using different values in training and choosing the most suitable one.

\n\n

When it comes to seasonality - of course, this is a case but:

\n\n\n\n

What I advise you to do instead is:

\n\n\n\n
\n

Secondly, does it make sense to use return_sequences=True here? In\n other words, I keep my Y data as is (50, 1096, 3) so that (as far as\n I've understood it) there is a prediction at every time step for which\n a loss can be calculated against the target data? Or would I be better\n off with return_sequences=False, so that only the final value of each\n batch is used to evaluate the loss (i.e. if using yearly batches, then\n in 2016 for product 1, we evaluate against the Dec 2016 value of\n (1,1,1)).

\n
\n\n

Using return_sequences=True might be useful but only in following cases:

\n\n
    \n
  1. When a given LSTM (or another recurrent layer) will be followed by yet another recurrent layer.
  2. \n
  3. In a scenario - when you feed a shifted original series as an output by what you are simultaneously learning a model in different time windows, etc.
  4. \n
\n\n

The way described in a second point might be an interesting approach but keep the mind in mind that it might be a little bit hard to implement as you will need to rewrite your model in order to obtain a production result. What also might be harder is that you'll need to test your model against many types of time instabilities - and such approach might make this totally unfeasible.

\n\n
\n

Thirdly how should I deal with the 50 different products? They are\n different, but still strongly correlated and we've seen with other\n approaches (for example an MLP with simple time-windows) that the\n results are better when all products are considered in the same model.\n Some ideas that are currently on the table are:

\n \n \n
\n\n

I would definitely go for a first choice but before providing a detailed explanation I will discuss disadvantages of 2nd and 3rd ones:

\n\n\n\n

Before getting to my choice - let's discuss yet another issue - redundancies in your dataset. I guess that you have 3 kinds of features:

\n\n\n\n

Now you have table of size (timesteps, m * n, products). I would transform it into table of shape (timesteps, products * m + n) as general features are the same for all products. This will save you a lot of memory and also make it feasible to feed to recurrent network (keep in mind that recurrent layers in keras have only one feature dimension - whereas you had two - product and feature ones).

\n\n

So why the first approach is the best in my opinion? Becasue it takes advantage of many interesting dependencies from data. Of course - this might harm the training process - but there is an easy trick to overcome this: dimensionality reduction. You could e.g. train PCA on your 150 dimensional vector and reduce it size to a much smaller one - thanks to what you have your dependencies modeled by PCA and your output has a much more feasible size.

\n\n
\n

Fourthly, how do I deal with validation data? Normally I would just\n keep out a randomly selected sample to validate against, but here we\n need to keep the time ordering in place. So I guess the best is to\n just keep a few months aside?

\n
\n\n

This is a really important question. From my experience - you need to test your solution against many types of instabilities in order to be sure that it works fine. So a few rules which you should keep in mind:

\n\n\n\n

The last point might be a little bit vague - so to provide you some examples:

\n\n\n\n

Of course - you could try yet another hold outs.

\n\n
\n

Fifthly, and this is the part that is probably the most unclear to me\n - how can I use the actual results to perform predictions? Let's say I used return_sequences=False and I trained on all three years in three\n batches (each time up to Nov) with the goal of training the model to\n predict the next value (Dec 2014, Dec 2015, Dec 2016). If I want to\n use these results in 2017, how does this actually work? If I\n understood it correctly, the only thing I can do in this instance is\n to then feed the model all the data points for Jan to Nov 2017 and it\n will give me back a prediction for Dec 2017. Is that correct? However,\n if I were to use return_sequences=True, then trained on all data up to\n Dec 2016, would I then be able to get a prediction for Jan 2017 just\n by giving the model the features observed at Jan 2017? Or do I need to\n also give it the 12 months before Jan 2017? What about Feb 2017, do I\n in addition need to give the value for 2017, plus a further 11 months\n before that? (If it sounds like I'm confused, it's because I am!)

\n
\n\n

This depends on how you've built your model:

\n\n\n\n

Here - more info on what kind of model you've choosed is needed.

\n", + "system": "" + }, + { + "instruction": "What is the difference between [], [None], None and () for the shape of a placeholder?", + "input": "", + "output": "

TensorFlow uses arrays rather than tuples. It converts tuples to arrays. Therefore [] and () are equivalent.

\n\n

Now, consider this code example:

\n\n
x = tf.placeholder(dtype=tf.int32, shape=[], name=\"foo1\")\ny = tf.placeholder(dtype=tf.int32, shape=[None], name=\"foo2\")\nz = tf.placeholder(dtype=tf.int32, shape=None, name=\"foo3\")\n\nval1 = np.array((1, 2, 3))\nval2 = 45\n\nwith tf.Session() as sess:\n    sess.run(tf.global_variables_initializer())\n\n    #print(sess.run(x, feed_dict = {x: val1}))  # Fails\n    print(sess.run(y, feed_dict = {y: val1}))\n    print(sess.run(z, feed_dict = {z: val1}))\n\n    print(sess.run(x, feed_dict = {x: val2}))\n    #print(sess.run(y, feed_dict = {y: val2}))  # Fails\n    print(sess.run(z, feed_dict = {z: val2}))\n
\n\n

As can be seen, placeholder with [] shape takes a single scalar value directly. Placeholder with [None] shape takes a 1-dimensional array and placeholder with None shape can take in any value while computation takes place.

\n", + "system": "" } ] \ No newline at end of file