tf.keras.backend.cast

TensorFlow 1 version View source on GitHub

Casts a tensor to a different dtype and returns it.

tf.keras.backend.cast(
    x,
    dtype
)

You can cast a Keras variable but it still returns a Keras tensor.

Arguments:

  • x: Keras tensor (or variable).
  • dtype: String, either ('float16', 'float32', or 'float64').

Returns:

Keras tensor with dtype dtype.

Examples:

Cast a float32 variable to a float64 tensor

<pre class="devsite-click-to-copy prettyprint lang-py">
<code class="devsite-terminal" data-terminal-prefix="&gt;&gt;&gt;">import tensorflow as tf</code>
<code class="no-select nocode">    &gt;&gt;&gt; from tensorflow.keras import backend as K</code>
<code class="no-select nocode">    &gt;&gt;&gt; input = K.ones(shape=(1,3))</code>
<code class="no-select nocode">    &gt;&gt;&gt; print(input)</code>
<code class="no-select nocode">    &gt;&gt;&gt; cast_input = K.cast(input, dtype=&#39;float64&#39;)</code>
<code class="no-select nocode">    &gt;&gt;&gt; print(cast_input)</code>
<code class="no-select nocode"></code>
<code class="no-select nocode">    &lt;tf.Variable &#39;Variable:0&#39; shape=(1, 3) dtype=float32,</code>
<code class="no-select nocode">         numpy=array([[1., 1., 1.]], dtype=float32)&gt;</code>
<code class="no-select nocode">    tf.Tensor([[1. 1. 1.]], shape=(1, 3), dtype=float64)</code>
</pre>

Compat aliases