The use of the NumPy library for getting started with Python machine learning--free sharing tutorial Python from getting started to mastering 30 days to quickly learn Python video tutorial

Series Article Directory

Chapter 1 Use of the Pandas library for getting started with Python machine learning

Chapter 2 Use of the NumPy Library for Getting Started with Python Machine Learning

Chapter 2 Creation, Indexing, Slicing, Data Cleaning, Data Analysis, etc. of Series and DataFrame for Introduction to
Python Machine Learning Chapter 2 Data Visualization for Introduction to Python Machine Learning
Chapter 2 Machine Learning Algorithms for Introduction to Python Machine Learning
Chapter 2 Python Machine Practical projects for getting started



insert image description here

foreword

NumPy is an important scientific computing library in Python. It provides efficient multi-dimensional array objects and various mathematical functions, which can facilitate vectorized calculations and array operations. In machine learning, NumPy is often used for data processing and preprocessing to prepare for subsequent model training and evaluation. This article will introduce the basic operations and methods of the NumPy library, including the creation and operation of arrays, common functions, broadcast mechanism, random number generation, file operations, linear algebra operations, etc. I hope it can help readers better grasp the use of NumPy and provide help for machine learning and data analysis.

1. Introduction to NumPy library

NumPy is an important scientific computing library in Python. It provides efficient multi-dimensional array objects and various mathematical functions, which can facilitate vectorized calculations and array operations. The main functions of NumPy include the creation and operation of arrays, statistics and calculations of arrays, sorting and searching of arrays, random number generation, file operations, linear algebra operations, etc.

The role of the NumPy library

The main role of the NumPy library is to provide efficient multi-dimensional array objects and various mathematical functions, which can facilitate vectorized calculations and array operations. NumPy's array object can store any type of data, including integers, floating-point numbers, complex numbers, Boolean values, etc., and can perform basic mathematical operations, logical operations, comparison operations, etc.

Installation of the NumPy library

Before installing the NumPy library, you need to install the Python environment first. The NumPy library can be installed with the following command:

Copy pip install numpy

2. Creation and manipulation of NumPy arrays

The NumPy array is the most important data structure in the NumPy library. It is a multidimensional array object that can store any type of data. The creation and manipulation of NumPy arrays includes the following aspects:

Create NumPy arrays

You can use the array() function of the NumPy library to create a NumPy array, or you can use other functions to create a specific type of array, such as the zeros() function to create an array of all zeros, the ones() function to create an array of all ones, and the empty() function to create an empty array wait.

Properties of NumPy arrays

The attributes of a NumPy array include the shape, data type, dimension, number of elements, etc. of the array. You can use the shape attribute to obtain the shape of the array, the dtype attribute to obtain the data type of the array, the ndim attribute to obtain the dimension of the array, and the size attribute to obtain the number of elements in the array, etc.

Indexing and slicing of NumPy arrays

The indexing and slicing of NumPy arrays are similar to Python lists, and the elements of the array can be obtained using integer indexing, slicing, Boolean indexing, etc. A colon (:) can be used to indicate a slice range, and a boolean array can be used to indicate a conditional index.

Operations on NumPy arrays

NumPy arrays support basic mathematical operations, logical operations, comparison operations, etc., and you can use various functions in the NumPy library to perform array operations. Operations on NumPy arrays include element-level operations, matrix operations, and broadcast operations.

import numpy as np

# 创建一维数组
a = np.array([1, 2, 3])
print(a)

# 创建二维数组
b = np.array([[1, 2, 3], [4, 5, 6]])
print(b)

# 创建全零数组
c = np.zeros((2, 3))
print(c)

# 创建全一数组
d = np.ones((2, 3))
print(d)

# 创建空数组
e = np.empty((2, 

insert image description here

3. Common functions of NumPy

The NumPy library provides a wealth of functions and methods, which can easily perform array shape operations, array element operations, array statistical calculations, array sorting and searching, etc. Commonly used functions include the following aspects:

Array shape manipulation functions

Array shape manipulation functions include reshape(), flatten(), transpose(), swapaxes(), etc., which can easily change the shape and dimension of an array.

Array Element Manipulation Functions

Array element operation functions include sum() function, mean() function, std() function, var() function, etc., which can conveniently perform statistical calculation of array elements.

Array Statistics Functions

Array statistical functions include min() function, max() function, argmin() function, argmax() function, etc., which can conveniently perform statistical calculation and search of array elements.

Array sort function

Array sorting functions include sort() function, argsort() function, lexsort() function, searchsorted() function, etc., which can conveniently sort and search array elements.
Array shape manipulation functions

Array shape manipulation functions include reshape(), flatten(), transpose(), swapaxes(), etc., which can easily change the shape and dimension of an array.

复制import numpy as np

# reshape函数改变数组形状
a = np.array([[1, 2], [3, 4], [5, 6]])
b = a.reshape((2, 3))
print(b)

# flatten函数将多维数组转换为一维数组
c = np.array([[1, 2], [3, 4], [5, 6]])
d = c.flatten()
print(d)

# transpose函数将数组进行转置
e = np.array([[1, 2], [3, 4], [5, 6]])
f = e.transpose()
print(f)

# swapaxes函数交换数组的两个轴
g = np.array([[1, 2], [3, 4], [5, 6]])
h = np.swapaxes(g, 0, 1)
print(h)

数组元素操作函数

数组元素操作函数包括sum()函数、mean()函数、std()函数、var()函数等,可以方便地进行数组元素的统计计算。

# sum函数计算数组元素的和
a = np.array([1, 2, 3])
b = np.sum(a)
print(b)

# mean函数计算数组元素的平均值
c = np.array([1, 2, 3])
d = np.mean(c)
print(d)

# std函数计算数组元素的标准差
e = np.array([1, 2, 3])
f = np.std(e)
print(f)

# var函数计算数组元素的方差
g = np.array([1, 2, 3])
h = np.var(g)
print(h)

Array Statistics Functions

Array statistical functions include min() function, max() function, argmin() function, argmax() function, etc., which can conveniently perform statistical calculation and search of array elements.

复制import numpy as np

# min函数计算数组元素的最小值
a = np.array([1, 2, 3])
b = np.min(a)
print(b)

# max函数计算数组元素的最大值
c = np.array([1, 2, 3])
d = np.max(c)
print(d)

# argmin函数查找数组元素的最小值的索引
e = np.array([1, 2, 3])
f = np.argmin(e)
print(f)

# argmax函数查找数组元素的最大值的索引
g = np.array([1, 2, 3])
h = np.argmax(g)
print(h)

Array sort function

Array sorting functions include sort() function, argsort() function, lexsort() function, searchsorted() function, etc., which can conveniently sort and search array elements.

复制import numpy as np

# sort函数对数组元素进行排序
a = np.array([3, 1, 2])
b = np.sort(a)
print(b)

# argsort函数返回数组元素排序后的索引
c = np.array([3, 1, 2])
d = np.argsort(c)
print(d)

# lexsort函数对多个数组进行排序
e = np.array([3, 1, 2])
f = np.array([1, 2, 3])
g = np.lexsort((e, f))
print(g)

# searchsorted函数在有序数组中查找元素的插入位置
h = np.array([1, 2, 3])
i = np.searchsorted(h, 2)
print

4. NumPy broadcast mechanism

The broadcasting mechanism is a very important feature in NumPy, which enables operations on arrays of different shapes without explicit shape conversions. The application of the broadcast mechanism can greatly simplify the code of array operations and improve the efficiency of the code.

The concept of the broadcast mechanism

The broadcast mechanism means that when NumPy performs array operations, it automatically expands arrays of different shapes so that they have the same shape, and then performs operations. The rules of the broadcasting mechanism include two aspects: First, NumPy will compare the shapes of the two arrays one by one from the end. If the shapes of the two arrays are the same or the shape of one of the arrays is 1, they are considered to be capable of broadcasting; secondly , NumPy will automatically expand an array of shape 1 to have the same shape as another array.

Application of broadcast mechanism

The application of the broadcast mechanism includes addition, subtraction, multiplication and division of arrays, comparison operations of arrays, logical operations of arrays, etc. When performing array operations, you can use the broadcast mechanism to simplify the code and improve the efficiency of the code.

Five, NumPy random number generation

The NumPy library provides a wealth of random number generation functions, which can easily generate various types of random numbers. The random number generation function includes the following aspects:

random number generator

Random number generation functions include rand() function, randn() function, randint() function, uniform() function, normal() function, etc., which can easily generate various types of random numbers.
The NumPy library provides a variety of random number generation functions, including generating random integers, generating random floating point numbers, generating random arrays, and more. These functions can easily generate random numbers conforming to a specific distribution, which can be helpful for simulation and experimentation.

import numpy as np

# randint函数生成指定范围内的随机整数
a = np.random.randint(0, 10, size=(3, 3))
print(a)

generate random integer

Random integers within a specified range can be generated using the random.randint() function of the NumPy library.
Generate random floating point numbers

You can use the random.rand() function of the NumPy library to generate random floating-point numbers of a specified shape, or you can use the random.randn() function to generate random floating-point numbers that conform to the standard normal distribution.

random number seed

The random number seed refers to the initial state of the random number generator, and the generation of random numbers can be controlled by setting the random number seed. The random number seed can be set using the random.seed() function of the NumPy library.

import numpy as np

# rand函数生成指定形状的随机浮点数
a = np.random.rand(3, 3)
print(a)

# randn函数生成符合标准正态分布的随机浮点数
b = np.random.randn(3, 3)
print(b)

generate random seed

Random seeds can be generated using the random.seed() function of the NumPy library to control the generation of random numbers.

import numpy as np

# seed函数生成随机种子
np.random.seed(0)
a = np.random.rand(3, 3)
print(a)

Six, NumPy file operation

insert image description here

The NumPy library provides a wealth of file manipulation functions that can easily read and write various types of files. File operation functions include the following aspects:

read text file

You can use the loadtxt() function, genfromtxt() function, fromfile() function, etc. of the NumPy library to read data in text files.

import numpy as np

# 从CSV文件中读取数组数据
a = np.genfromtxt('data.csv', delimiter=',')
print(a)

# 将数组数据保存到CSV文件中
b = np.array([[1, 2], [3, 4]])
np.savetxt('data.csv', b, delimiter=',')

read binary file

You can use the load() function, loadtxt() function, fromfile() function, etc. of the NumPy library to read the data in the binary file.

import numpy as np

# 保存数组数据到文件中
a = np.array([[1, 2], [3, 4]])
np.save('data.npy', a)

# 从文件中读取数组数据
b = np.load('data.npy')
print(b)

write to text file

Data can be written to text files using the savetxt() function, tofile() function, etc. of the NumPy library.

import numpy as np

# 保存数组数据到文本文件中
a = np.array([[1, 2], [3, 4]])
np.savetxt('data.txt', a)

# 从文本文件中读取数组数据
b = np.loadtxt('data.txt')
print(b)

write binary file

Data can be written to binary files using the save() function, savez() function, etc. of the NumPy library.

Seven, NumPy's linear algebra operations

The NumPy library provides a wealth of linear algebra operation functions, which can facilitate matrix creation, matrix operation, and matrix decomposition. Linear algebra operation functions include the following aspects:
NumPy library provides a variety of linear algebra operation functions, including matrix multiplication, matrix inversion, matrix determinant, eigenvalue and eigenvector, etc. These functions can conveniently perform linear algebra operations and provide assistance for data analysis and model training.

matrix multiplication

Matrix multiplication can be performed using the dot() function of the NumPy library.

import numpy as np

# 矩阵乘法运算
def matrix_multiply(a, b):
    c = np.dot(a, b)
    return c

a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
c = matrix_multiply(a, b)
print(c)

Matrix creation and manipulation

You can use the mat() function and array() function of the NumPy library to create matrix objects, and you can use the T attribute, H attribute, etc. to perform operations such as matrix transposition and conjugation.
matrix inversion

The inverse of a matrix can be found using the inv() function of the NumPy library.

import numpy as np

# 求解矩阵的逆矩阵
def matrix_inverse(a):
    b = np.linalg.inv(a)
    return b

a = np.array([[1, 2], [3, 4]])
b = matrix_inverse(a)
print(b)

Matrix operations

You can use the dot() function, multiply() function, inv() function, solve() function, etc. of the NumPy library to perform operations such as matrix multiplication, element-level multiplication, matrix inversion, and matrix solving.

Matrix decomposition

You can use the eig() function, svd() function, qr() function, etc. of the NumPy library to perform eigenvalue decomposition, singular value decomposition, QR decomposition, etc. of the matrix. matrix determinant

The determinant of a matrix can be calculated using the det() function of the NumPy library.

import numpy as np

# 计算矩阵的行列式
def matrix_determinant(a):
    b = np.linalg.det(a)
    return b

a = np.array([[1, 2], [3, 4]])
b = matrix_determinant(a)
print(b)

Follow me and share learning materials on the whole network

8. Summary and Outlook

The NumPy library is a very important scientific computing library in Python. It provides efficient multi-dimensional array objects and various mathematical functions, which can facilitate vectorized calculations and array operations. This article introduces the basic operations and methods of the NumPy library, including the creation and operation of arrays, common functions, broadcast mechanism, random number generation, file operations, linear algebra operations, etc. The advantage of the NumPy library is that it provides efficient array operations and mathematical functions that facilitate scientific computing and data analysis. In the future, with the development of data science and artificial intelligence, the application prospect of NumPy library will be broader.
Network disk sharing
Python from entry to proficiency in 30 days to quickly learn Python video tutorial
Link: https://pan.baidu.com/s/19FeaVPN_F0scxYR24e1MCg?pwd=c8qz
Extraction code: c8qz

Guess you like

Origin blog.csdn.net/CDB3399/article/details/130650487