Python create zeros matrix

Что такое функция numpy.zeros() в Python — примеры

В данном руководстве рассмотрим, что такое функция numpy.zeros() в Python. Она создает новый массив нулей указанной формы и типа данных.

Синтаксис

Параметры

Метод numpy.zeros() принимает три параметра, один из которых является необязательным.

  • Первый параметр — это shape, целое число или последовательность целых чисел.
  • Второй параметр — datatype, является необязательным и представляет собой тип данных возвращаемого массива. Если вы не определите тип данных, np.zeros() по умолчанию будет использовать тип данных с плавающей запятой.
  • Третий параметр — это order, представляющий порядок в памяти, такой как C_contiguous или F_contiguous.

Возвращаемое значение

Функция np zeros() возвращает массив со значениями элементов в виде нулей.

Примеры программ с методом numpy.zeros() в Python

Пример 1

Проблема с np.array() заключается в том, что он не всегда эффективен и довольно громоздок в случае, если вам нужно создать обширный массив или массив с большими размерами.

Метод NumPy zeros() позволяет создавать массивы, содержащие только нули. Он используется для получения нового массива заданных форм и типов, заполненных нулями.

Читайте также:  Using svg images in html

Пример 2

В этом примере мы видим, что после передачи формы матрицы мы получаем нули в качестве ее элемента, используя numpy zeros(). Таким образом, 1-й пример имеет размер 1 × 4, и все значения, заполненные нулями, такие же, как и в двух других матрицах.

В третьей матрице, arr3, все они являются числами с плавающей запятой. Помните, что элементы массива Numpy должны иметь один и тот же тип данных, и если мы не определим тип данных, то функция по умолчанию будет создавать числа с плавающей запятой.

Пример 3

Мы можем создавать массивы определенной формы, указав параметр shape.

Источник

numpy.zeros#

Return a new array of given shape and type, filled with zeros.

Parameters : shape int or tuple of ints

Shape of the new array, e.g., (2, 3) or 2 .

dtype data-type, optional

The desired data-type for the array, e.g., numpy.int8 . Default is numpy.float64 .

order , optional, default: ‘C’

Whether to store multi-dimensional data in row-major (C-style) or column-major (Fortran-style) order in memory.

like array_like, optional

Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.

Array of zeros with the given shape, dtype, and order.

Return an array of zeros with shape and type of input.

Return a new uninitialized array.

Return a new array setting values to one.

Return a new array of given shape filled with value.

>>> np.zeros((5,), dtype=int) array([0, 0, 0, 0, 0]) 
>>> s = (2,2) >>> np.zeros(s) array([[ 0., 0.], [ 0., 0.]]) 
>>> np.zeros((2,), dtype=[('x', 'i4'), ('y', 'i4')]) # custom dtype array([(0, 0), (0, 0)], dtype=[('x', ' 

Источник

NumPy Zeros: Create Zero Arrays and Matrix in NumPy

Numpy zeros matrix cover image

In this tutorial, you’ll learn how to generate a zero matrix using the NumPy zeros function. Zero arrays and matrices have special purposes in machine learning. Being able to create them efficiently will allow you to become more capable in linear algebra and machine learning.

By the end of this tutorial, you’ll have learned:

  • Why to create zero matrices
  • How to use the NumPy .zeros() function
  • How to create 1D, 2D, and 3D zero arrays and matricies
  • How to change the data types of the zeros in the matrix

What is a Zero Matrix?

A zeros matrix is a special type of matrix where every value is a zero. This allows you to create a matrix that has special properties and characteristics when interacting with other matrices. Typically, a zero matrix is defined as 0m,n, where m and n represent the dimensions of that matrix.

This means that a zero matrix of size (4,4) would look like this:

# A Zero Matrix of size 4x4 [[0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.]]

Let’s take a look at some of the characteristics of this type matrix. Let’s imagine we have a zero matrix 0 and another matrix A . Then, we have the following characteristics:

Knowing this can allow us to determine some more important characteristics in machine learning. In the following sections, you’ll learn how to generate zero matrices in Python using NumPy.

Understanding the NumPy Zeros Function

In order to create a zero matrix using Python and NumPy, we can use the Numpy .zeros() function. Let’s take a look the np.zeros() function function and its parameters:

# The NumPy zeros() function np.zeros( shape, # Int or tuple of ints dtype=float, # Data type for array order='C', # Memory optimization like=None # Reference object to help create )

In this tutorial, we’ll focus on the first two parameters. The shape= parameter allows you to define the size of the zeros array or matrix that is to be created. The dtype= parameter allows you to set the data type of the zero matrix being created.

Create a 1-Dimensional Zeros Array in Numpy

Let’s take a look at one of the simplest ways in which we can create a zeros matrix in Python: a one-dimension array of zeros. This can be done by passing in a single integer into the shape argument of the zeros function.

Let’s see how to create a zero array of size 5 using Python:

# Creating an array of zeros import numpy as np array_1d = np.zeros(5) print(array_1d) # Returns: [0. 0. 0. 0. 0.]

By default, NumPy will create a one-dimensional array with the data type of floats.

Create a 2-Dimensional Zeros Matrix in Numpy

NumPy makes it equally easy to create a 2-dimensional zero matrix. We can do this by passing in a tuple of integers that represent the dimensions of this matrix. By default, NumPy will use a data type of floats.

Let’s see how to create a 3×2 matrix of zeros using NumPy:

# Creating a Zeros Matrix in NumPy import numpy as np matrix_2d = np.zeros((3,2)) print(matrix_2d) # Returns: # [[0. 0.] # [0. 0.] # [0. 0.]]

Create a 3-Dimensional Zeros Matrix in Numpy

To create a three dimensional zeros matrix in NumPy, we can simply pass in a tuple of length three. Let’s see how we can create a tuple that is of size (3,3,2) :

# Creating a 3-Dimensional Zeros Matrix import numpy as np matrix_3d = np.zeros((3,3,2)) print(matrix_3d) # Returns: # [[[0. 0.] # [0. 0.] # [0. 0.]] # [[0. 0.] # [0. 0.] # [0. 0.]] # [[0. 0.] # [0. 0.] # [0. 0.]]]

How to Change the Data Type of a Zeros Matrix in Numpy

By default, NumPy will pass in floats into the zeros matrix it creates using the np.zeros() function. We can use the dtype= parameter to change the data type of values in the zeros matrix.

Let’s see how we can create a zeros matrix with integers instead of floats:

# Creating a Zero Matrix with Integers import numpy as np matrix_2d = np.zeros((3,2), dtype=int) print(matrix_2d) # Returns: # [[0 0] # [0 0] # [0 0]]

You can go even further than this and pass in a tuple of data types. This allows you to easily create tuples of zeros of different data types in NumPy:

# Changing data types in zero matrix import numpy as np matrix_2d = np.zeros((3,2), dtype=[('a', 'float'), ('b', 'int')]) print(matrix_2d) # Returns: # [[(0., 0) (0., 0)] # [(0., 0) (0., 0)] # [(0., 0) (0., 0)]]

In the above example, we create a zero matrix that contains tuples of zeros. In the tuple, the first data type is a float while the second is an integer.

Understanding the Order Parameter in Numpy Zeros

NumPy also lets you customize the style in which data are stored in row-major or column-major styles in memory. This gives you additional flexibility to change how memory is handled while creating zero matrices.

By using the order= parameter, you can pass in either ‘C’ or ‘F’ in order to modify how these values are stored. By using ‘C’ , data will be stored in a row-major format. Meanwhile, when you pass in ‘F’ , the data are stored as column-major (Fortran style).

NumPy will default to using the row-major format. We can change this by setting the order= parameter:

# Changing the matrix to column-major import numpy as np matrix_2d = np.zeros((3,2), order='F') print(matrix_2d) # Returns: # [[0. 0.] # [0. 0.] # [0. 0.]]

Conclusion

In this tutorial, you learned how to use NumPy to create zero matrices. You first learned what the characteristics of a zero matrix are. Then, you learned how to create arrays of zeros, as well as two-dimensional and three-dimensional arrays of zeros in NumPy. Finally, you learned how change the ordering of the matrix.

Additional Resources

To learn more about related topics, check out the tutorials below:

Источник

How to Create a Zero Matrix in Python

How to Create a Zero Matrix in Python | Previously we have developed programs to create matrix in Python now, we will discuss how to create a zero matrix in python. Matrix is a rectangular table arranged in the form of rows and columns, in the programming world we implement matrix by using arrays by classifying it as 1D and 2D arrays. In this section, there are some examples to create a zero matrix in python.

How to Create a Zero Matrix in Python

A zero matrix is a matrix that contains all 0 elements. The np.zeros() is a function in NumPy that creates a zero matrix, here dtype is used to specify the data type of the elements.

import numpy as np m = np.zeros([3, 3], dtype=int) print(m)

The above code creates a zero matrix with 3 rows and 3 columns.

Python Program to Create a Zero Matrix

This python program also performs the same task but in different ways. In this program, we will create a zero matrix in python without NumPy.

m, n = 2, 3 matrix = [[0] * n for i in range(m)]

Python Program Examples with Output

  • Perfect Square in Python
  • Absolute Value in Python
  • Simple Calculator in Python
  • Fibonacci Series in Python
  • Get the ASCII value of Char
  • Reverse a Number in Python
  • Reverse a Negative Number
  • Find Prime Factors in Python
  • Get the First Digit of a Number
  • Math.factorial() – Math Factorial
  • Even Number Python Program
  • Odd Number Python Program
  • Even Odd Program in Python
  • Multiplication Table in Python
  • Leap Year Program in Python
  • Fibonacci Series using Recursion
  • Find Factors of a Number in Python
  • Factorial of a Number using Loops
  • Factorial in Python using Recursion
  • Factorial using User-defined Function
  • Difference Between Two Numbers
  • Solve Quadratic Equation in Python
  • Sum of Digits of a Number in Python
  • Find Largest of 3 Numbers in Python
  • Sum of N Natural Numbers in Python
  • Average of N Numbers in Python
  • Find Sum of N Numbers in Python
  • Count Number of Digits in a Number
  • Find LCM of Two Numbers in Python
  • HCF or GCD of 2 Numbers in Python
  • Print ASCII Table in Python
  • Pandas Divide Two Columns
  • Check Vowel or Consonant in Python
  • Check Whether Character is Alphabet
  • Convert ASCII to Char
  • Convert ASCII to String
  • Convert String to ASCII
  • Hex String to ASCII String
  • Decimal to Binary in Python
  • Binary to Decimal in Python
  • Decimal to Octal in Python
  • Octal to Decimal in Python
  • Decimal to Hexadecimal in Python
  • Hexadecimal to Decimal in Python
  • Celsius to Fahrenheit in Python
  • Fahrenheit to Celsius in Python
  • Convert Celsius to Kelvin in Python
  • Celsius to Fahrenheit and Vice-Versa
  • Convert Celsius to Fahrenheit using Function
  • Celsius to Fahrenheit and Vice-Versa using Function

Источник

Оцените статью