Skip to main content
What is numpy.ones() and uses

What is numpy.ones() and uses

The np.ones() function returns a one-dimensional matrix. It can be used to initialize the weights in TensorFlow and other statistical tasks during the first iteration.

Numpy is a popular Python library for numerical computing, and the numpy.ones() function is useful for creating arrays filled with ones.

The basic syntax for numpy.ones() is as follows::

numpy.ones(shape, dtype=float, order='C')

Parameters:

  • Shape: is the shape of the array
  • Dtype: is the datatype. It is optional. The default value is float64
  • Order: The default is C, which is an essential row style.

Return Value :

The np.ones() function returns an array with element values as ones.

You can also checkout other python tutorials:

How To use numpy.ones() Method

Here’s an example usage of numpy.ones():

import numpy as np
b = np.ones(2, dtype = int)
print("Matrix b : \n", b)

a = np.ones([2, 2], dtype = int)
print("\nMatrix a : \n", a)

c = np.ones([3, 3])
print("\nMatrix c : \n", c)

d = np.ones((1,2,3), dtype=np.int16)
print("\nMatrix d : \n", c)

In the above example, the numpy.ones() function is used to create arrays of different shapes and data types.

Output:

Matrix b : 
 [1 1]

Matrix a : 
 [[1 1]
 [1 1]]

Matrix c : 
 [[ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]]

Matrix d :
[[[1 1 1]
  [1 1 1]]]

Int filled Array

Create an array of type int filled with ones

d = np.ones(4, dtype=int)
print(d)

Output:

[1 1 1 1]

Reference :

https://numpy.org/devdocs/reference/generated/numpy.ones.html

Leave a Reply

Your email address will not be published. Required fields are marked *