TensorFlow Basics
TensorFlow fundamentals and basic operations.
Installation & Import
Install TensorFlow
pip install tensorflow
Import
import tensorflow as tf
print(tf.__version__)
Check GPU availability
print(tf.config.list_physical_devices("GPU"))
Tensors
Create tensor
tensor = tf.constant([1, 2, 3, 4])
Create tensor with shape
matrix = tf.constant([[1, 2], [3, 4]])
Zeros and ones
zeros = tf.zeros([3, 3])
ones = tf.ones([2, 2])
Random values
random = tf.random.normal([3, 3])
Tensor properties
print(tensor.shape)
print(tensor.dtype)
Basic Operations
Arithmetic operations
a = tf.constant([1, 2, 3])
b = tf.constant([4, 5, 6])
add = a + b
sub = a - b
mul = a * b
div = a / b
Matrix multiplication
matmul = tf.matmul(matrix1, matrix2)
Reshape tensor
reshaped = tf.reshape(tensor, [2, 2])
Variables
Create variable
var = tf.Variable([1.0, 2.0, 3.0])
Assign new value
var.assign([4.0, 5.0, 6.0])
Add to variable
var.assign_add([1.0, 1.0, 1.0])
Multiply variable
var.assign_sub([0.5, 0.5, 0.5)