An in-depth analysis of NumPy functions: practical applications and examples

WBOY
Release: 2024-01-26 09:49:17
Original
919 people have browsed it

An in-depth analysis of NumPy functions: practical applications and examples

NumPy is an important scientific computing library in Python, providing powerful multi-dimensional array objects and broadcast functions, as well as many functions for array operations and calculations. In the fields of data science and machine learning, NumPy is widely used for array operations and numerical calculations. This article will comprehensively analyze the common functions of NumPy, give applications and examples, and provide specific code examples.

1. Overview of NumPy functions

NumPy functions are mainly divided into several categories such as array operation functions, mathematical functions, statistical functions and logical functions. These functions will be introduced in detail below:

  1. Array operation functions

(1) Create an array: Use NumPy’s function np.array() to create an array. Just pass in a list or tuple.

Sample code:

import numpy as np

a = np.array([1, 2, 3])
b = np.array((4, 5, 6))
print(a)
print(b)
Copy after login

Output result:

[1 2 3]
[4 5 6]
Copy after login

(2) Shape of the array: The shape information of the array can be obtained by using the function shape of the array.

Sample code:

import numpy as np

a = np.array([[1, 2, 3], [4, 5, 6]])
print(a.shape)
Copy after login

Output result:

(2, 3)
Copy after login

(3) Array indexing and slicing: Using array indexing and slicing operations, you can easily obtain the elements in the array elements and subarrays.

Sample code:

import numpy as np

a = np.array([[1, 2, 3], [4, 5, 6]])
print(a[0, 1])
print(a[:, 1:3])
Copy after login

Output result:

2
[[2 3]
 [5 6]]
Copy after login
  1. Mathematical function

NumPy provides many commonly used mathematical functions, such as Exponential functions, logarithmic functions, trigonometric functions, etc.

(1) Exponential function: Use the np.exp() function to calculate the exponent of each element in an array.

Sample code:

import numpy as np

a = np.array([1, 2, 3])
print(np.exp(a))
Copy after login

Output result:

[ 2.71828183  7.3890561  20.08553692]
Copy after login

(2) Logarithmic function: Use the np.log() function to calculate the natural logarithm of each element in an array logarithm.

Sample code:

import numpy as np

a = np.array([1, 2, 3])
print(np.log(a))
Copy after login

Output result:

[0.         0.69314718 1.09861229]
Copy after login

(3) Trigonometric functions: np.sin(), np.cos() and np.tan( can be used ) functions calculate the sine, cosine, and tangent of each element in an array.

Sample code:

import numpy as np

a = np.array([0, np.pi/2, np.pi])
print(np.sin(a))
Copy after login

Output results:

[0.00000000e+00 1.00000000e+00 1.22464680e-16]
Copy after login
  1. Statistical functions

NumPy provides many functions for statistical analysis , such as maximum value, mean value, variance, etc.

(1) Mean: Use the np.mean() function to calculate the average of an array.

Sample code:

import numpy as np

a = np.array([1, 2, 3, 4, 5])
print(np.mean(a))
Copy after login

Output result:

3.0
Copy after login

(2) Maximum value and minimum value: The np.max() and np.min() functions can be used respectively Calculate the maximum and minimum values ​​of an array.

Sample code:

import numpy as np

a = np.array([1, 2, 3, 4, 5])
print(np.max(a))
print(np.min(a))
Copy after login

Output result:

5
1
Copy after login

(3) Variance and standard deviation: can be calculated separately using the np.var() and np.std() functions The variance and standard deviation of an array.

Sample code:

import numpy as np

a = np.array([1, 2, 3, 4, 5])
print(np.var(a))
print(np.std(a))
Copy after login

Output result:

2.0
1.4142135623730951
Copy after login
  1. Logical function

Logical function is mainly used to perform Boolean operations on arrays and logical judgment.

(1) Logical operations: You can use functions such as np.logical_and(), np.logical_or() and np.logical_not() to perform logical AND, logical OR and logical NOT operations.

Sample code:

import numpy as np

a = np.array([True, False, True])
b = np.array([False, True, True])
print(np.logical_and(a, b))
print(np.logical_or(a, b))
print(np.logical_not(a))
Copy after login

Output result:

[False False  True]
[ True  True  True]
[False  True False]
Copy after login

(2) Logical judgment: You can use the np.all() and np.any() functions to judge the Whether the elements all meet a certain condition.

Sample code:

import numpy as np

a = np.array([1, 2, 3, 4, 5])
print(np.all(a > 0))
print(np.any(a > 3))
Copy after login

Output result:

True
True
Copy after login

2. Applications and examples

Two specific applications and examples will be given below. Demonstrates the use of NumPy functions.

  1. Calculate Euclidean distance

Euclidean distance is a common method used to calculate the distance between two vectors.

Sample code:

import numpy as np

def euclidean_distance(a, b):
    return np.sqrt(np.sum(np.square(a - b)))

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
dist = euclidean_distance(a, b)
print(dist)
Copy after login

Output result:

5.196152422706632
Copy after login
  1. One-hot encoding

One-hot encoding is a method of converting discrete features into The method of converting into digital features is often used in classification problems.

Sample code:

import numpy as np

def one_hot_encode(labels, num_classes):
    encoded = np.zeros((len(labels), num_classes))
    for i, label in enumerate(labels):
        encoded[i, label] = 1
    return encoded

labels = np.array([0, 1, 2, 1, 0])
num_classes = 3
encoded_labels = one_hot_encode(labels, num_classes)
print(encoded_labels)
Copy after login

Output result:

[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]
 [0. 1. 0.]
 [1. 0. 0.]]
Copy after login

The above is a comprehensive analysis of the NumPy function, as well as two specific applications and examples. By learning the use of NumPy functions, we can process and calculate array data more flexibly, playing an important role in the practice of data science and machine learning. I hope this article will be helpful to readers in their learning and application of NumPy functions.

The above is the detailed content of An in-depth analysis of NumPy functions: practical applications and examples. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!