Random Tensor Generation for TensorFlow Testing

  • Share this:

Code introduction


The function generates a random tensor with a specified number of dimensions, used to test the random number generation feature in TensorFlow.


Technology Stack : TensorFlow, NumPy

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
import tensorflow as tf
import numpy as np
import random

def random_tensor_shape(shape):
    """
    Generate a random tensor shape based on TensorFlow and NumPy.
    """
    # Randomly select the number of dimensions
    num_dimensions = random.randint(1, 5)
    
    # Randomly select the size for each dimension
    dimensions = [random.randint(1, 100) for _ in range(num_dimensions)]
    
    # Create a random tensor of the selected shape
    tensor = tf.random.uniform(shape=dimensions, minval=0, maxval=1, dtype=tf.float32)
    
    return tensor