TensorFlow Unleashed: Your Ultimate Handbook for Embarking on the Machine Learning Journey | by Henoshan Athimoolanathan | Sep, 2023


Source: https://www.tensorflow.org

Welcome to the fascinating realm of artificial intelligence powered by TensorFlow. The future of machine learning is built upon this cutting-edge technological marvel. Let’s dive into the core concept. TensorFlow was crafted by the tech giant, Google, to elevate machine learning applications to the next level with simplicity and effectiveness.

Usually, TensorFlow goes by the abbreviation ‘tf.’ TensorFlow operates based on the concept of tensors, which are 3-dimensional arrays. Visualizing tensors as cuboids with length, width, and depth helps us handle them effectively for our analytical needs. Tensors also make analytical tasks easier compared to older methods.

In this article, I’m going to be your guide from the very basics. We’ll start by unraveling the mystery behind tensors and gradually lead you toward harnessing TensorFlow’s incredible potential effectively. Whether you’re a complete beginner or looking to expand your machine learning skills, this comprehensive guide will equip you with the knowledge and tools you need to excel in the world of TensorFlow. So, let’s embark on this exciting journey together and unlock the mystery behind the word “tf”.

import tensorflow as tf

Creating tensors using tf.constant(), tf.Variable(), or by converting NumPy arrays to tensors using tf.convert_to_tensor().

# Create a tensor with a constant value
tensor1 = tf.constant(3.0) # A scalar tensor
tensor2 = tf.constant([1, 2, 3, 4, 5]) # A 1D tensor
tensor3 = tf.constant([[1, 2], [3, 4]]) # A 2D tensor

# Creating a new variable tensor
variable_tensor = tf.Variable([1.0, 2.0, 3.0])

# Changing the value of a already defined variable tensor
variable_tensor.assign([4.0, 5.0, 6.0])

# Here I need to import NumPy library to create an array. 
# Then I will convert NumPy arrays as tensor.

import numpy as np

numpy_array = np.array([1, 2, 3, 4, 5])

# Convert a NumPy array to a tensor
tensor_from_numpy = tf.convert_to_tensor(numpy_array)

Here, we also can create tensor (2D arrays) with zeros or ones.

# Create tensors filled with ones and zeros
ones_tensor = tf.ones([3, 3]) # A 3x3 tensor filled with ones
zeros_tensor = tf.zeros([2, 4]) # A 2x4 tensor filled with zeros

TensorFlow provides various functions to create tensors filled with random values. Some common ones include tf.random.normal (generates values from a normal distribution), tf.random.uniform (generates values from a uniform distribution), and tf.random.shuffle (shuffles the elements of a tensor randomly). These functions allow you to control the distribution and shape of the random tensor you want to create.

# Random values between 0 and 1 >> Here dimension is 2x3
random_uniform_tensor = tf.random.uniform([2, 3], minval=0, maxval=1)

# Random values from a normal distribution >> Here dimension is 3x2
random_normal_tensor = tf.random.normal([3, 2], mean=0.0, stddev=1.0)

TensorFlow supports a wide range of operations that you can perform on tensors. Here’s a list of common operations along with code examples:

General Operations

Assume that following operations are done over predefined tensors; ‘tensor1’, ‘tensor2’, ‘tensor’, ‘matrix1’, ‘matrix2’ and ‘matrix’.

# Addition
result = tf.add(tensor1, tensor2)

# Substraction
result = tf.subtract(tensor1, tensor2)

# Multiplication
result = tf.multiply(tensor1, tensor2)

# Division
result = tf.divide(tensor1, tensor2)

# Element-wise sqaure
result = tf.square(tensor)

# Matrix multiplication
result = tf.matmul(matrix1, matrix2)

# Matrix transposition
transposed_matrix = tf.transpose(matrix)

Reduction Operations

# Sum across axes

# Sum of elements across rows
sum_across_rows = tf.reduce_sum(matrix, axis=0)

# Sum of elements across columns
sum_across_columns = tf.reduce_sum(matrix, axis=1)

# Mean Calculation
mean = tf.reduce_mean(matrix)
# Maximum calculation
max_value = tf.reduce_max(matrix)

# Minimum calculation
min_value = tf.reduce_min(matrix)

Reshaping and Slicing

# Reshape Tensor
reshaped_tensor = tf.reshape(tensor, shape)

# Slice Tensor
sliced_tensor = tensor[start:end]

>>> Example:
import tensorflow as tf

# Create a 1D tensor
original_tensor = tf.constant([1, 2, 3, 4, 5, 6])

# Reshape the tensor into a 2D tensor (3 rows and 2 columns)
reshaped_tensor = tf.reshape(original_tensor, (3, 2))

print("Original Tensor:")
print(original_tensor)

print("\nReshaped Tensor:")
print(reshaped_tensor)

>>> Expected output

Original Tensor:
[1 2 3 4 5 6]
Reshaped Tensor:
[[1 2]
[3 4]
[5 6]]

import tensorflow as tf

# Create a 2D tensor
matrix = tf.constant([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])

# Slice a portion of the tensor (rows 1 to 2, columns 0 to 2)
sliced_tensor = matrix[1:3, 0:3]

print("Original Tensor:")
print(matrix)

print("\nSliced Tensor:")
print(sliced_tensor)

>>> Expected output

Original Tensor:
[[1 2 3]
[4 5 6]
[7 8 9]]
Sliced Tensor:
[[4 5 6]
[7 8 9]]

Math Functions

# Exponential Function
exp_result = tf.exp(tensor)

# Square root
sqrt_result = tf.sqrt(tensor)

# Logarithm
log_result = tf.math.log(tensor)

>>> Example (Exponential Function):>>> 
import tensorflow as tf

# Create a tensor
tensor = tf.constant([1.0, 2.0, 3.0, 4.0])

# Compute the element-wise exponential
exp_result = tf.exp(tensor)

print("Original Tensor:")
print(tensor)

print("\nExponential Result:")
print(exp_result)

>>> Expected output
Original Tensor:
[1. 2. 3. 4.]
Exponential Result:
[ 2.7182817 7.389056 20.085537 54.59815 ]
>>> Example (Square root):
import tensorflow as tf

# Create a tensor
tensor = tf.constant([1.0, 4.0, 9.0, 16.0])

# Compute the element-wise square root
sqrt_result = tf.sqrt(tensor)

print("Original Tensor:")
print(tensor)

print("\nSquare Root Result:")
print(sqrt_result)

>>> Expected output

Original Tensor:
[ 1. 4. 9. 16.]
Square Root Result:
[1. 2. 3. 4.]

>>> Example (Logarithm):
import tensorflow as tf

# Create a tensor
tensor = tf.constant([1.0, 2.0, 4.0, 8.0])

# Compute the element-wise natural logarithm
log_result = tf.math.log(tensor)

print("Original Tensor:")
print(tensor)

print("\nLogarithm Result:")
print(log_result)

>>> Expected output

Original Tensor:
[1. 2. 4. 8.]
Logarithm Result:
[0. 0.6931472 1.3862944 2.0794415]

Comparison Operations

# Element-wise Comparison
comparison_result = tf.equal(tensor1, tensor2)

# Finding Maximum and Minimum Values
max_value = tf.argmax(tensor)
min_value = tf.argmin(tensor)

>>> Example (Element-wise Comparison):
import tensorflow as tf

# Create two tensors
tensor1 = tf.constant([1, 2, 3, 4])
tensor2 = tf.constant([2, 2, 3, 3])

# Perform element-wise comparison
comparison_result = tf.equal(tensor1, tensor2)

print("Tensor 1:")
print(tensor1)

print("\nTensor 2:")
print(tensor2)

print("\nComparison Result:")
print(comparison_result)

>>> Expected output

Tensor 1:
[1 2 3 4]
Tensor 2:
[2 2 3 3]
Comparison Result:
[False True True False]

>>> Example (Finding Maximum and Minimum Values):
import tensorflow as tf

# Creating a tensor
tensor = tf.constant([3, 1, 4, 1, 5, 9, 2, 6, 5, 3])

# Finding the maximum value's index
max_index = tf.argmax(tensor)

# Finding the minimum value's index
min_index = tf.argmin(tensor)

print("Tensor:")
print(tensor)

print("\nIndex of Maximum Value:", max_index.numpy())

print("Index of Minimum Value:", min_index.numpy())

>>> Expected output

Tensor:
[3 1 4 1 5 9 2 6 5 3]
Index of Maximum Value: 5
Index of Minimum Value: 1

Advanced Math Operations

# Trigonometric Functions
sine = tf.sin(angles)
cosine = tf.cos(angles)

# Hyperbolic Functions
sinh = tf.sinh(values)
cosh = tf.cosh(values)

>>> Example (Trigonometric Functions):
import tensorflow as tf

# Create a tensor of angles in radians
angles = tf.constant([0.0, tf.math.pi / 4, tf.math.pi / 2])

# Compute sine and cosine of the angles
sine = tf.sin(angles)
cosine = tf.cos(angles)

print("Angles (radians):", angles.numpy())
print("Sine:", sine.numpy())
print("Cosine:", cosine.numpy())

>>> Expected Output:

Angles (radians): [0. 0.7853982 1.5707964]
Sine: [0. 0.70710677 1. ]
Cosine: [1.000000e+00 7.071067e-01 6.123234e-17]

>>> Example (Hyperbolic Functions):
import tensorflow as tf

# Create a tensor
values = tf.constant([0.0, 1.0, 2.0])

# Compute hyperbolic sine and cosine
sinh = tf.sinh(values)
cosh = tf.cosh(values)

print("Values:", values.numpy())
print("Hyperbolic Sine:", sinh.numpy())
print("Hyperbolic Cosine:", cosh.numpy())

>>> Expected Output:

Values: [0. 1. 2.]
Hyperbolic Sine: [ 0. 1.1752012 3.6268604 ]
Hyperbolic Cosine: [1. 1.5430806 3.7621956 ]

In this example, tf.argmax() and tf.argmin() are used to find the indices of the maximum and minimum values in the input tensor, respectively.



Source link

Be the first to comment

Leave a Reply

Your email address will not be published.


*