Open In App

Tensorflow – linspace() in Python

Last Updated : 20 Apr, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

TensorFlow is an open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks. While working with TensorFlow many times we need to generate evenly-spaced values in an interval.

  • tensorflow.linspace(): This method takes starting tensor, ending tensor, number of values and axis and returns a Tensor with specified number of evenly spaced values.

Example 1: 

python3




# importing the library
import tensorflow as tf
 
# Initializing Input
start = tf.constant(1, dtype = tf.float64)
end = tf.constant(5, dtype = tf.float64)
num = 5
 
# Printing the Input
print("start: ", start)
print("end: ", end)
print("num: ", num)
 
# Getting evenly spaced values
res = tf.linspace(start, end, num)
 
# Printing the resulting tensor
print("Result: ", res)


Output:

start:  tf.Tensor(1.0, shape=(), dtype=float64)
end:  tf.Tensor(5.0, shape=(), dtype=float64)
num:  5
Result:  tf.Tensor([1. 2. 3. 4. 5.], shape=(5, ), dtype=float64)

Example 2: This example uses 2-D tensors and on providing different axis value different Tensors will be generated. This type of evenly-spaced value generation is currently allowed in nightly version. 

python3




# importing the library
import tensorflow as tf
 
# Initializing Input
start = tf.constant((1, 15), dtype = tf.float64)
end = tf.constant((10, 35), dtype = tf.float64)
num = 5
 
# Printing the Input
print("start: ", start)
print("end: ", end)
print("num: ", num)
 
# Getting evenly spaced values
res = tf.linspace(start, end, num, axis = 0)
 
# Printing the resulting tensor
print("Result 1: ", res)
 
# Getting evenly spaced values
res = tf.linspace(start, end, num, axis = 1)
 
# Printing the resulting tensor
print("Result 2: ", res)


Output:

start:  tf.Tensor([ 1. 15.], shape=(2, ), dtype=float64)
end:  tf.Tensor([10. 35.], shape=(2, ), dtype=float64)
num:  5
Result 1:  tf.Tensor(
[[ 1.   15.  ]
 [ 3.25 20.  ]
 [ 5.5  25.  ]
 [ 7.75 30.  ]
 [10.   35.  ]], shape=(5, 2), dtype=float64)

Result 2:  tf.Tensor(
[[ 1.    3.25  5.5   7.75 10.  ]
 [15.   20.   25.   30.   35.  ]], shape=(2, 5), dtype=float64)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads