Personal tools

Examples in Python

Nuts_022023A
[Nuts - Dionisvera/Shutterstock]

- Overview

In TensorFlow, scalars, vectors, and matrices are all represented as tensors, which are n-dimensional arrays. Scalars are 0-dimensional tensors, vectors are 1-dimensional tensors, and matrices are 2-dimensional tensors. TensorFlow provides various methods for creating and manipulating these tensors. 

Here's how to create and use them:


- Scalars

1. Creation: 

Python 

    import tensorflow as tf
    scalar = tf.constant(42)
    print(scalar)

 

2. Usage: 

Scalars can be used in calculations like any other numerical value.

 

- Vectors

1. Creation: 

Python


    vector = tf.constant([1, 2, 3, 4, 5])
    print(vector)

 
Usage: Vectors can be used in operations like addition, subtraction, dot products, etc.

Python

 

    vector_2 = tf.constant([6, 7, 8, 9, 10])
    sum_vector = tf.add(vector, vector_2)
    print(sum_vector)

 

- Matrices 

1. Creation: 

Python


    matrix = tf.constant([[1, 2], [3, 4]])
    print(matrix)

Usage: Matrices can be used in operations like matrix multiplication, transpose, etc.

Python

    matrix_2 = tf.constant([[5, 6], [7, 8]])
    product_matrix = tf.matmul(matrix, matrix_2)
    print(product_matrix)


- Tensor Operations


TensorFlow provides a wide range of operations for manipulating tensors, including:

Element-wise operations: tf.add, tf.subtract, tf.multiply, tf.divide
Reductions: tf.reduce_sum, tf.reduce_mean, tf.reduce_max
Reshaping: tf.reshape
Slicing: matrix[1:3, 0:2]
Other operations: tf.matmul, tf.transpose, tf.linalg.diag, etc.


- Example 1

Example of using a vector in a neural network (a very simplified example): 

Python

# Assume input is a vector
input_vector = tf.constant([0.1, 0.2, 0.3])


# Define weights as a matrix
weights = tf.constant([[0.2, 0.4], [0.6, 0.8], [1.0, 1.2]])

# Calculate the output using matrix multiplication
output = tf.matmul(tf.expand_dims(input_vector, 0), weights)

print(output)


 

- Example 2

This example shows how a vector can be used as input to a neural network layer represented by a matrix of weights. The tf.expand_dims function is used to add a dimension to the input vector, making it compatible with matrix multiplication. 

 
 

[More to come ...]

 

Document Actions