All topics

TensorFlow interview questions

19 questions with answers. 343 open jobs in India ask for TensorFlow.

  1. What's the difference between tf.placeholder and tf.Variable?

    In short, you use tf.Variable for trainable variables such as weights (W) and biases (B) for your model.

    weights = tf.Variable(
        tf.truncated_normal([IMAGE_PIXELS, hidden1_units],
                        stddev=1.0 / math.sqrt(float(IMAGE_PIXELS))), name='weights')
    biases = tf.Variable(tf.zeros([hidden1_units]), name='biases')
    

    tf.placeholder is used to feed actual training examples.

    images_placeholder = tf.placeholder(tf.float32, shape=(batch_size, IMAGE_PIXELS))
    labels_placeholder = tf.placeholder(tf.int32, shape=(batch_size))
    

    This is how you feed the training examples during the training:

    for step in xrange(FLAGS.max_steps):
        feed_dict = {
           images_placeholder: images_feed,
           labels_placeholder: labels_feed,
         }
        _, loss_value = sess.run([train_op, loss], feed_dict=feed_dict)
    

    Your tf.variables will be trained (modified) as the result of this training.

    See more at https://www.tensorflow.org/versions/r0.7/tutorials/mnist/tf/index.html. (Examples are taken from the web page.)

    From Stack Overflow: asked by J.Doe, answered by Sung Kim (CC BY-SA 3.0)

  2. What's the difference of name scope and a variable scope in tensorflow?

    Let's begin by a short introduction to variable sharing. It is a mechanism in TensorFlow that allows for sharing variables accessed in different parts of the code without passing references to the variable around.

    The method tf.get_variable can be used with the name of the variable as the argument to either create a new variable with such name or retrieve the one that was created before. This is different from using the tf.Variable constructor which will create a new variable every time it is called (and potentially add a suffix to the variable name if a variable with such name already exists).

    It is for the purpose of the variable sharing mechanism that a separate type of scope (variable scope) was introduced.

    As a result, we end up having two different types of scopes:

    Both scopes have the same effect on all operations as well as variables created using tf.Variable, i.e., the scope will be added as a prefix to the operation or variable name.

    However, name scope is ignored by tf.get_variable. We can see that in the following example:

    with tf.name_scope("my_scope"):
        v1 = tf.get_variable("var1", [1], dtype=tf.float32)
        v2 = tf.Variable(1, name="var2", dtype=tf.float32)
        a = tf.add(v1, v2)
    print(v1.name)  # var1:0
    print(v2.name)  # my_scope/var2:0
    print(a.name)   # my_scope/Add:0
    

    The only way to place a variable accessed using tf.get_variable in a scope is to use a variable scope, as in the following example:

    with tf.variable_scope("my_scope"):
        v1 = tf.get_variable("var1", [1], dtype=tf.float32)
        v2 = tf.Variable(1, name="var2", dtype=tf.float32)
        a = tf.add(v1, v2)
    print(v1.name)  # my_scope/var1:0
    print(v2.name)  # my_scope/var2:0
    print(a.name)   # my_scope/Add:0
    

    This allows us to easily share variables across different parts of the program, even within different name scopes:

    with tf.name_scope("foo"):
        with tf.variable_scope("var_scope"):
            v = tf.get_variable("var", [1])
    with tf.name_scope("bar"):
        with tf.variable_scope("var_scope", reuse=True):
            v1 = tf.get_variable("var", [1])
    assert v1 == v
    print(v.name)   # var_scope/var:0
    print(v1.name)  # var_scope/var:0
    

    UPDATE

    As of version r0.11, op_scope and variable_op_scope are both deprecated and replaced by name_scope and variable_scope.

    From Stack Overflow: asked by Xiuyi Yang, answered by Andrzej Pronobis (CC BY-SA 4.0)

  3. In TensorFlow, what is the difference between Session.run() and Tensor.eval()?

    If you have a Tensor t, calling t.eval() is equivalent to calling tf.get_default_session().run(t).

    You can make a session the default as follows:

    t = tf.constant(42.0)
    sess = tf.Session()
    with sess.as_default():   # or `with sess:` to close on exit
        assert sess is tf.get_default_session()
        assert t.eval() == sess.run(t)
    

    The most important difference is that you can use sess.run() to fetch the values of many tensors in the same step:

    t = tf.constant(42.0)
    u = tf.constant(37.0)
    tu = tf.mul(t, u)
    ut = tf.mul(u, t)
    with sess.as_default():
       tu.eval()  # runs one step
       ut.eval()  # runs one step
       sess.run([tu, ut])  # evaluates both tensors in a single step
    

    Note that each call to eval and run will execute the whole graph from scratch. To cache the result of a computation, assign it to a tf.Variable.

    From Stack Overflow: asked by Geoffrey Irving, answered by mrry (CC BY-SA 3.0)

  4. Why is TensorFlow 2 much slower than TensorFlow 1?

    UPDATE 8/1730/2020: TF 2.3 has finally done it: all cases run as fast, or notably faster, than any previous version.

    Further, my previous update was unfair to TF; my GPU was to blame, has been overheating lately. If you see a rising stem plot of iteration times, it's a reliable symptom. Lastly, see a dev's note on Eager vs Graph.

    This might be my last update on this answer. The true stats on your model's speed can only be found by you, on your device.

    UPDATE 5/19/2020: TF 2.2, using same tests: only a minor improvement in Eager speed. Plots for Large-Large Numpy train_on_batch case below, x-axis is successive fit iterations; my GPU isn't near its full capacity, so doubt it's throttling, but iterations do get slower over time.

    Per above, Graph and Eager are 1.56x and 1.97x slower than their TF1 counterparts, respectively. Unsure I'll debug this further, as I'm considering switching to Pytorch per TensorFlow's poor support for custom / low-level functionality. I did, however, open an Issue to get devs' feedback.

    UPDATE 2/18/2020: I've benched 2.1 and 2.1-nightly; the results are mixed. All but one configs (model & data size) are as fast as or much faster than the best of TF2 & TF1. The one that's slower, and slower dramatically, is Large-Large - esp. in Graph execution (1.6x to 2.5x slower).

    Furthermore, there are extreme reproducibility differences between Graph and Eager for a large model I tested - one not explainable via randomness/compute-parallelism. I can't currently present reproducible code for these claims per time constraints, so instead I strongly recommend testing this for your own models.

    Haven't opened a Git issue on these yet, but I did comment on the original - no response yet. I'll update the answer(s) once progress is made.

    VERDICT: it isn't, IF you know what you're doing. But if you don't, it could cost you, lots - by a few GPU upgrades on average, and by multiple GPUs worst-case.

    THIS ANSWER: aims to provide a high-level description of the issue, as well as guidelines for how to decide on the training configuration specific to your needs. For a detailed, low-level description, which includes all benchmarking results + code used, see my other answer.

    I'll be updating my answer(s) w/ more info if I learn any - can bookmark / "star" this question for reference.

    ISSUE SUMMARY: as confirmed by a TensorFlow developer, Q. Scott Zhu, TF2 focused development on Eager execution & tight integration w/ Keras, which involved sweeping changes in TF source - including at graph-level. Benefits: greatly expanded processing, distribution, debug, and deployment capabilities. The cost of some of these, however, is speed.

    The matter, however, is fairly more complex. It isn't just TF1 vs. TF2 - factors yielding significant differences in train speed include:

    1. TF2 vs. TF1
    2. Eager vs. Graph mode
    3. keras vs. tf.keras
    4. numpy vs. tf.data.Dataset vs. ...
    5. train_on_batch() vs. fit()
    6. GPU vs. CPU
    7. model(x) vs. model.predict(x) vs. ...

    Unfortunately, almost none of the above are independent of the other, and each can at least double execution time relative to another. Fortunately, you can determine what'll work best systematically, and with a few shortcuts - as I'll be showing.

    WHAT SHOULD I DO? Currently, the only way is - experiment for your specific model, data, and hardware. No single configuration will always work best - but there are do's and don't's to simplify your search:

    Read the rest at the sourceFrom Stack Overflow: asked by OverLordGoldDragon, answered by OverLordGoldDragon (CC BY-SA 4.0)

  5. Understanding TensorBoard (weight) histograms

    It appears that the network hasn't learned anything in the layers one to three. The last layer does change, so that means that there either may be something wrong with the gradients (if you're tampering with them manually), you're constraining learning to the last layer by optimizing only its weights or the last layer really 'eats up' all error. It could also be that only biases are learned. The network appears to learn something though, but it might not be using its full potential. More context would be needed here, but playing around with the learning rate (e.g. using a smaller one) might be worth a shot.

    In general, histograms display the number of occurrences of a value relative to each other values. Simply speaking, if the possible values are in a range of 0..9 and you see a spike of amount 10 on the value 0, this means that 10 inputs assume the value 0; in contrast, if the histogram shows a plateau of 1 for all values of 0..9, it means that for 10 inputs, each possible value 0..9 occurs exactly once. You can also use histograms to visualize probability distributions when you normalize all histogram values by their total sum; if you do that, you'll intuitively obtain the likelihood with which a certain value (on the x axis) will appear (compared to other inputs).

    Now for layer1/weights, the plateau means that:

    • most of the weights are in the range of -0.15 to 0.15
    • it is (mostly) equally likely for a weight to have any of these values, i.e. they are (almost) uniformly distributed

    Said differently, almost the same number of weights have the values -0.15, 0.0, 0.15 and everything in between. There are some weights having slightly smaller or higher values. So in short, this simply looks like the weights have been initialized using a uniform distribution with zero mean and value range -0.15..0.15 ... give or take. If you do indeed use uniform initialization, then this is typical when the network has not been trained yet.

    In comparison, layer1/activations forms a bell curve (gaussian)-like shape: The values are centered around a specific value, in this case 0, but they may also be greater or smaller than that (equally likely so, since it's symmetric). Most values appear close around the mean of 0, but values do range from -0.8 to 0.8. I assume that the layer1/activations is taken as the distribution over all layer outputs in a batch. You can see that the values do change over time.

    The layer 4 histogram doesn't tell me anything specific. From the shape, it's just showing that some weight values around -0.1, 0.05 and 0.25 tend to be occur with a higher probability; a reason could be, that different parts of each neuron there actually pick up the same information and are basically redundant. This can mean that you could actually use a smaller network or that your network has the potential to learn more distinguishing features in order to prevent overfitting. These are just assumptions though.

    Also, as already stated in the comments below, do add bias units. By leaving them out, you are forcefully constraining your network to a possibly invalid solution.

    From Stack Overflow: asked by Sung Kim, answered by sunside (CC BY-SA 3.0)

  6. Can I run Keras model on gpu?

    Yes you can run keras models on GPU. Few things you will have to check first.

    1. your system has GPU (Nvidia. As AMD doesn't work yet)
    2. You have installed the GPU version of tensorflow
    3. You have installed CUDA installation instructions
    4. Verify that tensorflow is running with GPU check if GPU is working

    sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

    for TF > v2.0

    sess = tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(log_device_placement=True))

    (Thanks @nbro and @Ferro for pointing this out in the comments)

    OR

    from tensorflow.python.client import device_lib
    print(device_lib.list_local_devices())
    

    output will be something like this:

    [
      name: "/cpu:0"device_type: "CPU",
      name: "/gpu:0"device_type: "GPU"
    ]
    

    Once all this is done your model will run on GPU:

    To Check if keras(>=2.1.1) is using GPU:

    from keras import backend as K
    K.tensorflow_backend._get_available_gpus()
    

    All the best.

    From Stack Overflow: asked by Ryan , answered by Vikash Singh (CC BY-SA 4.0)

  7. How does tf.app.run() work?
    if __name__ == "__main__":
    

    means current file is executed under a shell instead of imported as a module.

    tf.app.run()
    

    As you can see through the file app.py

    def run(main=None, argv=None):
      """Runs the program with an optional 'main' function and 'argv' list."""
      f = flags.FLAGS
      # Extract the args from the optional `argv` list.
      args = argv[1:] if argv else None
      # Parse the known flags from that list, or from the command
      # line otherwise.
      # pylint: disable=protected-access
      flags_passthrough = f._parse_flags(args=args)
      # pylint: enable=protected-access
      main = main or sys.modules['__main__'].main
      # Call the main function, passing through any arguments
      # to the final program.
      sys.exit(main(sys.argv[:1] + flags_passthrough))
    

    Let's break line by line:

    flags_passthrough = f._parse_flags(args=args)
    

    This ensures that the argument you pass through command line is valid,e.g. python my_model.py --data_dir='...' --max_iteration=10000 Actually, this feature is implemented based on python standard argparse module.

    main = main or sys.modules['__main__'].main
    

    The first main in right side of = is the first argument of current function run(main=None, argv=None) . While sys.modules['__main__'] means current running file(e.g. my_model.py).

    So there are two cases:

    1. You don't have a main function in my_model.py Then you have to call tf.app.run(my_main_running_function)

    2. you have a main function in my_model.py. (This is mostly the case.)

    Last line:

    sys.exit(main(sys.argv[:1] + flags_passthrough))
    

    ensures your main(argv) or my_main_running_function(argv) function is called with parsed arguments properly.

    From Stack Overflow: asked by Anurag Ranjan, answered by lei du (CC BY-SA 3.0)

  8. What does tf.nn.conv2d do in tensorflow?

    Ok I think this is about the simplest way to explain it all.

    Your example is 1 image, size 2x2, with 1 channel. You have 1 filter, with size 1x1, and 1 channel (size is height x width x channels x number of filters).

    For this simple case the resulting 2x2, 1 channel image (size 1x2x2x1, number of images x height x width x x channels) is the result of multiplying the filter value by each pixel of the image.

    Now let's try more channels:

    input = tf.Variable(tf.random_normal([1,3,3,5]))
    filter = tf.Variable(tf.random_normal([1,1,5,1]))
    op = tf.nn.conv2d(input, filter, strides=[1, 1, 1, 1], padding='VALID')
    

    Here the 3x3 image and the 1x1 filter each have 5 channels. The resulting image will be 3x3 with 1 channel (size 1x3x3x1), where the value of each pixel is the dot product across channels of the filter with the corresponding pixel in the input image.

    Now with a 3x3 filter

    input = tf.Variable(tf.random_normal([1,3,3,5]))
    filter = tf.Variable(tf.random_normal([3,3,5,1]))
    op = tf.nn.conv2d(input, filter, strides=[1, 1, 1, 1], padding='VALID')
    

    Here we get a 1x1 image, with 1 channel (size 1x1x1x1). The value is the sum of the 9, 5-element dot products. But you could just call this a 45-element dot product.

    Now with a bigger image

    input = tf.Variable(tf.random_normal([1,5,5,5]))
    filter = tf.Variable(tf.random_normal([3,3,5,1]))
    op = tf.nn.conv2d(input, filter, strides=[1, 1, 1, 1], padding='VALID')
    

    The output is a 3x3 1-channel image (size 1x3x3x1). Each of these values is a sum of 9, 5-element dot products.

    Each output is made by centering the filter on one of the 9 center pixels of the input image, so that none of the filter sticks out. The xs below represent the filter centers for each output pixel.

    .....
    .xxx.
    .xxx.
    .xxx.
    .....
    

    Now with "SAME" padding:

    input = tf.Variable(tf.random_normal([1,5,5,5]))
    filter = tf.Variable(tf.random_normal([3,3,5,1]))
    op = tf.nn.conv2d(input, filter, strides=[1, 1, 1, 1], padding='SAME')
    

    This gives a 5x5 output image (size 1x5x5x1). This is done by centering the filter at each position on the image.

    Any of the 5-element dot products where the filter sticks out past the edge of the image get a value of zero.

    So the corners are only sums of 4, 5-element dot products.

    Now with multiple filters.

    input = tf.Variable(tf.random_normal([1,5,5,5]))
    filter = tf.Variable(tf.random_normal([3,3,5,7]))
    op = tf.nn.conv2d(input, filter, strides=[1, 1, 1, 1], padding='SAME')
    

    This still gives a 5x5 output image, but with 7 channels (size 1x5x5x7). Where each channel is produced by one of the filters in the set.

    Now with strides 2,2:

    input = tf.Variable(tf.random_normal([1,5,5,5]))
    filter = tf.Variable(tf.random_normal([3,3,5,7]))
    op = tf.nn.conv2d(input, filter, strides=[1, 2, 2, 1], padding='SAME')
    

    Now the result still has 7 channels, but is only 3x3 (size 1x3x3x7).

    This is because instead of centering the filters at every point on the image, the filters are centered at every other point on the image, taking steps (strides) of width 2. The x's below represent the filter center for each output pixel, on the input image.

    x.x.x
    .....
    x.x.x
    .....
    x.x.x
    

    And of course the first dimension of the input is the number of images so you can apply it over a batch of 10 images, for example:

    input = tf.Variable(tf.random_normal([10,5,5,5]))
    filter = tf.Variable(tf.random_normal([3,3,5,7]))
    op = tf.nn.conv2d(input, filter, strides=[1, 2, 2, 1], padding='SAME')
    

    This performs the same operation, for each image independently, giving a stack of 10 images as the result (size 10x3x3x7)

    From Stack Overflow: asked by Shubhashis, answered by mdaoust (CC BY-SA 3.0)

  9. Should we do learning rate decay for adam optimizer

    It depends. ADAM updates any parameter with an individual learning rate. This means that every parameter in the network has a specific learning rate associated.

    But the single learning rate for each parameter is computed using lambda (the initial learning rate) as an upper limit. This means that every single learning rate can vary from 0 (no update) to lambda (maximum update).

    It's true, that the learning rates adapt themselves during training steps, but if you want to be sure that every update step doesn't exceed lambda you can than lower lambda using exponential decay or whatever. It can help to reduce loss during the latest step of training, when the computed loss with the previously associated lambda parameter has stopped to decrease.

    From Stack Overflow: asked by meng lin, answered by nessuno (CC BY-SA 4.0)

  10. Difference between Variable and get_variable in TensorFlow

    I'd recommend to always use tf.get_variable(...) -- it will make it way easier to refactor your code if you need to share variables at any time, e.g. in a multi-gpu setting (see the multi-gpu CIFAR example). There is no downside to it.

    Pure tf.Variable is lower-level; at some point tf.get_variable() did not exist so some code still uses the low-level way.

    From Stack Overflow: asked by Lifu Huang, answered by Lukasz Kaiser (CC BY-SA 3.0)

  11. Meaning of buffer_size in Dataset.map , Dataset.prefetch and Dataset.shuffle

    TL;DR Despite their similar names, these arguments have quite difference meanings. The buffer_size in Dataset.shuffle() can affect the randomness of your dataset, and hence the order in which elements are produced. The buffer_size in Dataset.prefetch() only affects the time it takes to produce the next element.

    The buffer_size argument in tf.data.Dataset.prefetch() and the output_buffer_size argument in tf.contrib.data.Dataset.map() provide a way to tune the performance of your input pipeline: both arguments tell TensorFlow to create a buffer of at most buffer_size elements, and a background thread to fill that buffer in the background. (Note that we removed the output_buffer_size argument from Dataset.map() when it moved from tf.contrib.data to tf.data. New code should use Dataset.prefetch() after map() to get the same behavior.)

    Adding a prefetch buffer can improve performance by overlapping the preprocessing of data with downstream computation. Typically it is most useful to add a small prefetch buffer (with perhaps just a single element) at the very end of the pipeline, but more complex pipelines can benefit from additional prefetching, especially when the time to produce a single element can vary.

    By contrast, the buffer_size argument to tf.data.Dataset.shuffle() affects the randomness of the transformation. We designed the Dataset.shuffle() transformation (like the tf.train.shuffle_batch() function that it replaces) to handle datasets that are too large to fit in memory. Instead of shuffling the entire dataset, it maintains a buffer of buffer_size elements, and randomly selects the next element from that buffer (replacing it with the next input element, if one is available). Changing the value of buffer_size affects how uniform the shuffling is: if buffer_size is greater than the number of elements in the dataset, you get a uniform shuffle; if it is 1 then you get no shuffling at all. For very large datasets, a typical "good enough" approach is to randomly shard the data into multiple files once before training, then shuffle the filenames uniformly, and then use a smaller shuffle buffer. However, the appropriate choice will depend on the exact nature of your training job.

    From Stack Overflow: asked by Ujjwal, answered by mrry (CC BY-SA 3.0)

  12. What's the difference between sparse_softmax_cross_entropy_with_logits and softmax_cross_entropy_with_logits?

    Having two different functions is a convenience, as they produce the same result.

    The difference is simple:

    • For sparse_softmax_cross_entropy_with_logits, labels must have the shape [batch_size] and the dtype int32 or int64. Each label is an int in range [0, num_classes-1].
    • For softmax_cross_entropy_with_logits, labels must have the shape [batch_size, num_classes] and dtype float32 or float64.

    Labels used in softmax_cross_entropy_with_logits are the one hot version of labels used in sparse_softmax_cross_entropy_with_logits.

    Another tiny difference is that with sparse_softmax_cross_entropy_with_logits, you can give -1 as a label to have loss 0 on this label.

    From Stack Overflow: asked by daniel451, answered by Olivier Moindrot (CC BY-SA 3.0)

  13. What's the purpose of tf.app.flags in TensorFlow?

    The tf.app.flags module is presently a thin wrapper around python-gflags, so the documentation for that project is the best resource for how to use it argparse, which implements a subset of the functionality in python-gflags.

    Note that this module is currently packaged as a convenience for writing demo apps, and is not technically part of the public API, so it may change in future.

    We recommend that you implement your own flag parsing using argparse or whatever library you prefer.

    EDIT: The tf.app.flags module is not in fact implemented using python-gflags, but it uses a similar API.

    From Stack Overflow: asked by flyaway1217, answered by mrry (CC BY-SA 3.0)

  14. Can Keras with Tensorflow backend be forced to use CPU or GPU at will?

    If you want to force Keras to use CPU

    Way 1

    import os
    os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"   # see issue #152
    os.environ["CUDA_VISIBLE_DEVICES"] = ""
    

    before Keras / Tensorflow is imported.

    Way 2

    Run your script as

    $ CUDA_VISIBLE_DEVICES="" ./your_keras_code.py
    

    See also

    1. https://github.com/keras-team/keras/issues/152
    2. https://github.com/fchollet/keras/issues/4613

    From Stack Overflow: asked by mikal94305, answered by Martin Thoma (CC BY-SA 3.0)

  15. Does model.compile() initialize all the weights and biases in Keras (tensorflow backend)?

    When to use?

    If you're using compile, surely it must be after load_model(). After all, you need a model to compile. (PS: load_model automatically compiles the model with the optimizer that was saved along with the model)

    What does compile do?

    Compile defines the loss function, the optimizer and the metrics. That's all.

    It has nothing to do with the weights and you can compile a model as many times as you want without causing any problem to pretrained weights.

    You need a compiled model to train (because training uses the loss function and the optimizer). But it's not necessary to compile a model for predicting.

    Do you need to use compile more than once?

    Only if:

    • You want to change one of these:
      • Loss function
      • Optimizer / Learning rate
      • Metrics
      • The trainable property of some layer
    • You loaded (or created) a model that is not compiled yet. Or your load/save method didn't consider the previous compilation.

    Consequences of compiling again:

    If you compile a model again, you will lose the optimizer states.

    This means that your training will suffer a little at the beginning until it adjusts the learning rate, the momentums, etc. But there is absolutely no damage to the weights (unless, of course, your initial learning rate is so big that the first training step wildly changes the fine tuned weights).

    From Stack Overflow: asked by Preetom Saha Arko, answered by Daniel Möller (CC BY-SA 4.0)

  16. Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2

    What is this warning about?

    Modern CPUs provide a lot of low-level instructions, besides the usual arithmetic and logic, known as extensions, e.g. SSE2, SSE4, AVX, etc. From the Wikipedia:

    Advanced Vector Extensions (AVX) are extensions to the x86 instruction set architecture for microprocessors from Intel and AMD proposed by Intel in March 2008 and first supported by Intel with the Sandy Bridge processor shipping in Q1 2011 and later on by AMD with the Bulldozer processor shipping in Q3 2011. AVX provides new features, new instructions and a new coding scheme.

    In particular, AVX introduces fused multiply-accumulate (FMA) operations, which speed up linear algebra computation, namely dot-product, matrix multiply, convolution, etc. Almost every machine-learning training involves a great deal of these operations, hence will be faster on a CPU that supports AVX and FMA (up to 300%). The warning states that your CPU does support AVX (hooray!).

    I'd like to stress here: it's all about CPU only.

    Why isn't it used then?

    Because tensorflow default distribution is built without CPU extensions, such as SSE4.1, SSE4.2, AVX, AVX2, FMA, etc. The default builds (ones from pip install tensorflow) are intended to be compatible with as many CPUs as possible. Another argument is that even with these extensions CPU is a lot slower than a GPU, and it's expected for medium- and large-scale machine-learning training to be performed on a GPU.

    What should you do?

    If you have a GPU, you shouldn't care about AVX support, because most expensive ops will be dispatched on a GPU device (unless explicitly set not to). In this case, you can simply ignore this warning by

    # Just disables the warning, doesn't take advantage of AVX/FMA to run faster
    import os
    os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
    

    ... or by setting export TF_CPP_MIN_LOG_LEVEL=2 if you're on Unix. Tensorflow is working fine anyway, but you won't see these annoying warnings.

    If you don't have a GPU and want to utilize CPU as much as possible, you should build tensorflow from the source optimized for your CPU with AVX, AVX2, and FMA enabled if your CPU supports them. It's been discussed in this question and also this GitHub issue. Tensorflow uses an ad-hoc build system called bazel and building it is not that trivial, but is certainly doable. After this, not only will the warning disappear, tensorflow performance should also improve.

    From Stack Overflow: asked by csg, answered by Maxim (CC BY-SA 4.0)

  17. How to save/restore a model after training?

    Tensorflow 2 Docs

    Saving Checkpoints

    Adapted from the docs

    # -------------------------
    # -----  Toy Context  -----
    # -------------------------
    import tensorflow as tf
    class Net(tf.keras.Model):
        """A simple linear model."""
        def __init__(self):
            super(Net, self).__init__()
            self.l1 = tf.keras.layers.Dense(5)
        def call(self, x):
            return self.l1(x)
    def toy_dataset():
        inputs = tf.range(10.0)[:, None]
        labels = inputs * 5.0 + tf.range(5.0)[None, :]
        return (
            tf.data.Dataset.from_tensor_slices(dict(x=inputs, y=labels)).repeat().batch(2)
        )
    def train_step(net, example, optimizer):
        """Trains `net` on `example` using `optimizer`."""
        with tf.GradientTape() as tape:
            output = net(example["x"])
            loss = tf.reduce_mean(tf.abs(output - example["y"]))
        variables = net.trainable_variables
        gradients = tape.gradient(loss, variables)
        optimizer.apply_gradients(zip(gradients, variables))
        return loss
    # ----------------------------
    # -----  Create Objects  -----
    # ----------------------------
    net = Net()
    opt = tf.keras.optimizers.Adam(0.1)
    dataset = toy_dataset()
    iterator = iter(dataset)
    ckpt = tf.train.Checkpoint(
        step=tf.Variable(1), optimizer=opt, net=net, iterator=iterator
    )
    manager = tf.train.CheckpointManager(ckpt, "./tf_ckpts", max_to_keep=3)
    # ----------------------------
    # -----  Train and Save  -----
    # ----------------------------
    ckpt.restore(manager.latest_checkpoint)
    if manager.latest_checkpoint:
        print("Restored from {}".format(manager.latest_checkpoint))
    else:
        print("Initializing from scratch.")
    for _ in range(50):
        example = next(iterator)
        loss = train_step(net, example, opt)
        ckpt.step.assign_add(1)
        if int(ckpt.step) % 10 == 0:
            save_path = manager.save()
            print("Saved checkpoint for step {}: {}".format(int(ckpt.step), save_path))
            print("loss {:1.2f}".format(loss.numpy()))
    # ---------------------
    # -----  Restore  -----
    # ---------------------
    # In another script, re-initialize objects
    opt = tf.keras.optimizers.Adam(0.1)
    net = Net()
    dataset = toy_dataset()
    iterator = iter(dataset)
    ckpt = tf.train.Checkpoint(
        step=tf.Variable(1), optimizer=opt, net=net, iterator=iterator
    )
    manager = tf.train.CheckpointManager(ckpt, "./tf_ckpts", max_to_keep=3)
    # Re-use the manager code above ^
    ckpt.restore(manager.latest_checkpoint)
    if manager.latest_checkpoint:
        print("Restored from {}".format(manager.latest_checkpoint))
    else:
        print("Initializing from scratch.")
    for _ in range(50):
        example = next(iterator)
        # Continue training or evaluate etc.
    

    More links

    Checkpoints capture the exact value of all parameters (tf.Variable objects) used by a model. Checkpoints do not contain any description of the computation defined by the model and thus are typically only useful when source code that will use the saved parameter values is available.

    The SavedModel format on the other hand includes a serialized description of the computation defined by the model in addition to the parameter values (checkpoint). Models in this format are independent of the source code that created the model. They are thus suitable for deployment via TensorFlow Serving, TensorFlow Lite, TensorFlow.js, or programs in other programming languages (the C, C++, Java, Go, Rust, C# etc. TensorFlow APIs).

    (Highlights are my own)

    Tensorflow < 2

    From the docs:

    Save

    Read the rest at the sourceFrom Stack Overflow: asked by mathetes, answered by ted (CC BY-SA 4.0)

  18. How to tell if tensorflow is using gpu acceleration from inside python shell?

    No, I don't think "open CUDA library" is enough to tell, because different nodes of the graph may be on different devices.

    When using tensorflow2:

    print("Num GPUs Available: ", len(tf.config.list_physical_devices('GPU')))
    

    For tensorflow1, to find out which device is used, you can enable log device placement like this:

    sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
    

    Check your console for this type of output.

    From Stack Overflow: asked by Tamim Addari, answered by Yao Zhang (CC BY-SA 4.0)

  19. How can I prevent TensorFlow from allocating the totality of a GPU memory?

    You can set the fraction of GPU memory to be allocated when you construct a tf.Session by passing a tf.GPUOptions as part of the optional config argument:

    # Assume that you have 12GB of GPU memory and want to allocate ~4GB:
    gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.333)
    sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))
    

    The per_process_gpu_memory_fraction acts as a hard upper bound on the amount of GPU memory that will be used by the process on each GPU on the same machine. Currently, this fraction is applied uniformly to all of the GPUs on the same machine; there is no way to set this on a per-GPU basis.

    From Stack Overflow: asked by Fabien C., answered by mrry (CC BY-SA 3.0)

Related topics

Where these questions come from

Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.