MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Tensorsflow Lab1 – Tensorsflow And Variables

This lab covers the two core data structures in TensorFlow 2: immutable tensors created with tf.constant, and mutable tf.Variable objects that hold state such as model weights. The notebook embedded above creates tensors, converts them to and from NumPy, reshapes them, and updates variables in place. The sections below explain what each step does, give a runnable script version with expected output, and cover the dtype and shape errors beginners run into most often.


Tensors vs variables at a glance

A tensor (tf.Tensor) is a typed, multi-dimensional array. Once created it cannot be changed. Every operation, such as x0 + 5 or tf.reshape, returns a new tensor. A variable (tf.Variable) wraps a tensor whose value can be updated in place with assign, assign_add and assign_sub. Keras layers store their weights and biases as variables, and optimizers update them in place on every training step.

Propertytf.Tensor (tf.constant)tf.Variable
MutableNo, operations return new tensorsYes, through assign, assign_add and assign_sub
Typical useInputs, intermediate results, constantsModel parameters, counters, persistent state
Tracked by GradientTape automaticallyNo, needs tape.watch()Yes, if trainable=True (the default)
Saved in checkpointsNoYes, when attached to a tracked object such as a Keras model or tf.train.Checkpoint
Result of math on ittf.Tensortf.Tensor, not a variable

The last row explains the notebook heading "Operations on Variables result in a Tensor": tf.add(v1, v2) reads both variables and returns an ordinary tensor. v1 itself is unchanged.

Prerequisites and environment setup

The notebook metadata shows Python 3.7, which current TensorFlow releases no longer support. Use a recent Python 3 version that your chosen TensorFlow release supports, and work inside a virtual environment.

python3 -m venv tf-lab
source tf-lab/bin/activate        # Windows: tf-lab\Scripts\activate
pip install --upgrade pip
pip install tensorflow numpy jupyter

# Verify the install and see which devices TensorFlow can use
python -c "import tensorflow as tf; print(tf.__version__); print(tf.config.list_physical_devices())"

jupyter notebookCode language: PHP (php)

Note: On Linux machines with an NVIDIA GPU, recent TensorFlow releases can install the CUDA libraries for you with pip install "tensorflow[and-cuda]". The lab itself runs fine on CPU, and the device placement log above shows every op running on CPU:0.

Runnable script version of the lab

The notebook cells were run out of order (the execution counts jump from 2 to 26 to 51). The script below runs the same steps top to bottom, so you can save it as tensors_lab.py and run it with python tensors_lab.py. Device placement logging is left out to keep the output readable.

import numpy as np
import tensorflow as tf

print("Eager:", tf.executing_eagerly())

# Constant tensors
x0 = tf.constant(3)                       # scalar, int32
x1 = tf.constant([1.1, 2.2, 3.3, 4.4])    # shape (4,), float32
x2 = tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]])
x2 = tf.cast(x2, tf.float32)              # int32 -> float32

print(x0.shape, x0.dtype, x0.numpy())
print((x0 + 5).numpy())
print(tf.add(x1, 5.0).numpy())
print(tf.multiply(x1, x2).numpy())        # (4,) broadcast against (2, 4)

# NumPy interop
arr = np.array([[10, 20], [30, 40], [50, 60]])
x4 = tf.convert_to_tensor(arr)
print(tf.is_tensor(arr), tf.is_tensor(x4), x4.dtype)
print(np.sqrt(x2))                        # returns a NumPy array

# Creation and reshape
t0 = tf.zeros([3, 5], tf.int32)
print(tf.reshape(t0, (5, 3)).shape)

# Variables
v1 = tf.Variable([[1.5, 2, 5], [2, 6, 8]])
v1.assign([[10, 20, 30], [40, 50, 60]])
v1[0, 0].assign(100)
v1.assign_add(tf.ones_like(v1))
v1.assign_sub(2 * tf.ones_like(v1))
print(v1.numpy())

# Copying a variable copies its value
var_a = tf.Variable([2.0, 3.0])
var_b = tf.Variable(var_a)
var_b.assign([200, 300])
print(var_a.numpy(), var_b.numpy())Code language: PHP (php)

Expected output (TensorFlow may print some startup log lines first):

Eager: True
() <dtype: 'int32'> 3
8
[6.1 7.2 8.3 9.4]
[[ 1.1       4.4       9.9      17.6     ]
 [ 5.5      13.200001 23.1      35.2     ]]
False True <dtype: 'int64'>
[[1.        1.4142135 1.7320508 2.       ]
 [2.236068  2.4494898 2.6457512 2.828427 ]]
(5, 3)
[[99. 19. 29.]
 [39. 49. 59.]]
[2. 3.] [200. 300.]Code language: PHP (php)

Note: The 13.200001 value is normal float32 rounding, not a bug. Compare floating-point results with np.allclose instead of ==.

How dtypes, casting and broadcasting behave

  • Default dtypes: Python ints become int32 and Python floats become float32 in tf.constant. NumPy arrays keep their own dtype, which is why x4 is int64. NumPy 1.x on Windows defaults to int32, so older Windows setups may show int32 there.
  • No implicit promotion between tensors: TensorFlow does not silently mix int32 and float32 tensors. That is why the lab calls tf.cast(x2, tf.float32) before tf.multiply(x1, x2).
  • Python scalars adapt: in x0 + 5 the literal 5 is converted to the dtype of x0. x0 + 5.5 fails because 5.5 cannot be represented as int32.
  • Broadcasting: x1 has shape (4,) and x2 has shape (2, 4). The trailing dimensions match, so x1 is applied to each row. This follows the same rules as NumPy.
  • Reshape keeps the element count: (3, 5) to (5, 3) works because both hold 15 elements. Pass -1 for one dimension to let TensorFlow infer it, for example tf.reshape(t0, (-1, 3)).
  • NumPy functions on tensors: np.square(x2) and np.sqrt(x2) convert the tensor to a NumPy array and return a NumPy array, not a tensor. Use tf.square and tf.sqrt to stay inside TensorFlow, which matters for GPU execution, tf.function and gradients.

Why variables matter: a gradient step

The lab shows how to mutate variables but not why you would. The main reason is training. tf.GradientTape automatically watches trainable variables, computes gradients with respect to them, and the update is then applied in place. This is a hand-written version of what a Keras optimizer does.

import tensorflow as tf

w = tf.Variable(3.0)                      # trainable by default
step = tf.Variable(0, trainable=False)    # state that should not get gradients

with tf.GradientTape() as tape:
    loss = w * w                          # d(loss)/dw = 2w = 6

grad = tape.gradient(loss, w)
w.assign_sub(0.1 * grad)                  # gradient descent: 3.0 - 0.6
step.assign_add(1)

print(grad.numpy(), w.numpy(), step.numpy())
# 6.0 2.4 1

# A constant is not watched automatically
c = tf.constant(3.0)
with tf.GradientTape() as tape:
    y = c * c
print(tape.gradient(y, c))                # NoneCode language: PHP (php)

To get gradients for a constant, call tape.watch(c) inside the with block. In real code, pass name= when creating variables, for example tf.Variable(0.0, name="bias"). Every variable in the lab shows up as Variable:0, and named variables are much easier to find in checkpoints and debugging output.

Common errors and how to fix them

ErrorCauseFix
InvalidArgumentError: cannot compute AddV2 as input #1(zero-based) was expected to be a int32 tensor but is a float tensorMixing int32 and float32 tensors in one opCast one side with tf.cast(t, tf.float32) or create both with the same dtype=
TypeError: Cannot convert 5.5 to EagerTensor of dtype int32Adding a Python float to an integer tensorCreate the tensor as float, e.g. tf.constant(3.0)
TypeError: 'EagerTensor' object does not support item assignmentTrying x0[0] = 1 on a tf.TensorUse a tf.Variable and v[0].assign(1), or build a new tensor with tf.tensor_scatter_nd_update
InvalidArgumentError: Input to reshape is a tensor with 15 values, but the requested shape has 16Target shape has a different element countMake the product of the dimensions match, or use -1 for one dimension
ValueError about incompatible shapes on assignv.assign() with a value of a different shapeAssign a value of the same shape, or create the variable with shape=tf.TensorShape(None) if its shape must change
Device placement log lines missing in JupyterThe log goes to the process log stream, not always to the cell outputCheck the terminal running Jupyter, and call set_log_device_placement(True) before any ops run

Notes and corrections for the notebook

  • The post title spells the library as "Tensorsflow". The correct name is TensorFlow.
  • The notebook kernel is Python 3.7.4, which current TensorFlow releases do not support. Recreate the environment with a supported Python 3 version as shown above.
  • The cells were executed out of order. Use Kernel > Restart & Run All to confirm the notebook works top to bottom before relying on its outputs.
  • The markdown typo "perfomed" should read "performed".
  • v1.assign_add([[1, 1, 1], [1, 1, 1]]) works, but tf.ones_like(v1) keeps the shape and dtype tied to the variable and avoids hard-coding the shape.
  • np.square(x2) and np.sqrt(x2) return NumPy arrays, not tensors. Prefer tf.square and tf.sqrt inside models.

Best practices

  • Set dtypes explicitly (dtype=tf.float32) for anything that feeds a model. Most layers and optimizers expect float32.
  • Use variables only for state that must persist or be trained. Everything else should be a plain tensor.
  • Mark counters and other non-learned state with trainable=False so optimizers and tapes skip them.
  • Avoid calling .numpy() inside training loops or tf.function code. It forces a copy back to host memory and breaks graph tracing.
  • Turn off tf.debugging.set_log_device_placement outside of debugging. It logs every single op.

Frequently asked questions

What is the difference between tf.constant and tf.Variable?

tf.constant creates an immutable tensor, and every operation on it returns a new tensor. tf.Variable holds a value you can change in place with assign, assign_add and assign_sub. It is also tracked automatically for gradients and checkpoints, which is why it is used for model weights.

How do I convert a TensorFlow tensor to a NumPy array?

In eager mode, call .numpy() on the tensor or variable. To go the other way, use tf.convert_to_tensor(array) or tf.constant(array). Both keep the NumPy dtype unless you pass dtype=.

Why does adding an int tensor and a float tensor fail in TensorFlow?

Unlike NumPy, TensorFlow does not automatically promote dtypes between tensors, so an int32 + float32 op raises InvalidArgumentError. Cast one operand with tf.cast so both have the same dtype.

Does tf.Variable(other_variable) share memory with the original?

No. It creates a new variable initialized with a copy of the current value, so later assignments to one do not affect the other. The final cells of the lab demonstrate this.

Is the result of an operation on a variable also a variable?

No. Operations such as tf.add(v1, v2) read the variables and return a regular tf.Tensor. Only the assign family of methods changes a variable.

Related tutorials

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
I'm Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms. I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.

Related Posts

Tensorsflow Lab8 – Tensorsflow FunctionalModel

This lab uses the UCI heart disease dataset (303 patients, 13 features, a binary target) to build a binary classifier with the Keras Functional API in TensorFlow….

Read More

Tensorsflow Lab7 – Tensorsflow SequentialModel

This lab uses the WHO life expectancy dataset to build a regression model with the TensorFlow Keras Sequential API. The notebook above covers loading the data, inspecting…

Read More

Tensorsflow Lab6 – Tensorsflow SimpleLinearRegression

This lab builds simple linear regression (y = Wx + b) from scratch in TensorFlow 2. It creates the weight and bias with tf.Variable, computes gradients of…

Read More

Tensorsflow Lab5 – Tensorsflow GradientTape

tf.GradientTape is TensorFlow's automatic differentiation API. It records the operations you run inside a with block, then plays them back in reverse to compute gradients for training….

Read More

Tensorsflow Lab4 – Tensorsflow function

This lab shows how tf.function turns ordinary Python functions into TensorFlow graphs. It covers how AutoGraph converts if, for and while into graph ops, why Python side…

Read More

Tensorsflow Lab3 – Tensorsflow EagerExecution

In eager execution, TensorFlow runs each operation as soon as Python calls it and gives you a concrete value back, with no graph to build first. It…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x