本文通过对以下题目进行分析与解答,从而了解Numpy的用法。

其中第一节为基本知识介绍,第二节为题目解答。

题目如下:

Numpy学习与应用(一)

基础知识:

1.numpy中的axis

axis常常出现在numpy对矩阵的操作中,指定不同的axis可以从不同方向(如二维矩阵中,axis=0沿纵向,axis=1沿横向)进行操作。


以下是解题过程中所需用到的函数:

1. numpy.random.normal(分别以loc和scale为均值与标准差,随机生成size个数)

numpy.random.normal(loc=0.0scale=1.0size=None)

Draw random samples from a normal (Gaussian) distribution.

The probability density function of the normal distribution, first derived by De Moivre and 200 years later by both Gauss and Laplace independently [R500500], is often called the bell curve because of its characteristic shape (see the example below).

The normal distributions occurs often in nature. For example, it describes the commonly occurring distribution of samples influenced by a large number of tiny, random disturbances, each with its own unique distribution [R500500].

Parameters:

loc : float or array_like of floats

Mean (“centre”) of the distribution.

scale : float or array_like of floats

Standard deviation (spread or “width”) of the distribution.

size : int or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if loc and scale are both scalars. Otherwise, np.broadcast(loc, scale).size samples are drawn.

Returns:

out : ndarray or scalar

Drawn samples from the parameterized normal distribution.

2. scipy.linalg.toeplitz(生成一个第一行向量为c,第一列向量为r的托普利兹矩阵)

scipy.linalg.toeplitz(cr=None)

Construct a Toeplitz matrix.

The Toeplitz matrix has constant diagonals, with c as its first column and r as its first row. If r is not given, r ==conjugate(c) is assumed.

Parameters:

c : array_like

First column of the matrix. Whatever the actual shape of c, it will be converted to a 1-D array.

r : array_like

First row of the matrix. If None, r = conjugate(c) is assumed; in this case, if c[0] is real, the result is a Hermitian matrix. r[0] is ignored; the first row of the returned matrix is [c[0], r[1:]]. Whatever the actual shape of r, it will be converted to a 1-D array.

Returns:

A : (len(c), len(r)) ndarray

The Toeplitz matrix. Dtype is the same as (c[0] + r[0]).dtype.

3. numpy.dot(如果a,b为一维矩阵,则计算二者的内积;若a,b为二维数组,则进行二者的矩阵乘法运算)

numpy.dot(about=None)

Dot product of two arrays. Specifically,

  • If both a and b are 1-D arrays, it is inner product of vectors (without complex conjugation).

  • If both a and b are 2-D arrays, it is matrix multiplication, but using matmul or a @ b is preferred.

  • If either a or b is 0-D (scalar), it is equivalent to multiply and using numpy.multiply(a, b) or a * b is preferred.

  • If a is an N-D array and b is a 1-D array, it is a sum product over the last axis of a and b.

  • If a is an N-D array and b is an M-D array (where M>=2), it is a sum product over the last axis of a and the second-to-last axis of b:

    dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
    
Parameters:

a : array_like

First argument.

b : array_like

Second argument.

out : ndarray, optional

Output argument. This must have the exact kind that would be returned if it was not used. In particular, it must have the right type, must be C-contiguous, and its dtype must be the dtype that would be returned for dot(a,b). This is a performance feature. Therefore, if these conditions are not met, an exception is raised, instead of attempting to be flexible.

Returns:

output : ndarray

Returns the dot product of a and b. If a and b are both scalars or both 1-D arrays then a scalar is returned; otherwise an array is returned. If out is given, then it is returned.

Raises:

ValueError

If the last dimension of a is not the same size as the second-to-last dimension of b.

4. numpy.eye(生成N*M的矩阵,其中左上角的元素到该元素正右下方的元素都为1,其余元素为0,若M缺省,则生成N*N的单位矩阵)

numpy.eye(NM=Nonek=0dtype=<class 'float'>order='C')[source]

Return a 2-D array with ones on the diagonal and zeros elsewhere.

Parameters:

N : int

Number of rows in the output.

M : int, optional

Number of columns in the output. If None, defaults to N.

k : int, optional

Index of the diagonal: 0 (the default) refers to the main diagonal, a positive value refers to an upper diagonal, and a negative value to a lower diagonal.

dtype : data-type, optional

Data-type of the returned array.

order : {‘C’, ‘F’}, optional

Whether the output should be stored in row-major (C-style) or column-major (Fortran-style) order in memory.

New in version 1.14.0.

Returns:

I : ndarray of shape (N,M)

An array where all elements are equal to zero, except for the k-th diagonal, whose values are equal to one.

5. numpy.ones(返回一个给定shape和type的矩阵,其中所有元素为1)

numpy.ones(shapedtype=Noneorder='C')[source]

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

Parameters:

shape : int or sequence 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 : {‘C’, ‘F’}, optional

Whether to store multidimensional data in C- or Fortran-contiguous (row- or column-wise) order in memory.

Returns:

out : ndarray

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

6. numpy.linalg.solve(解一个线性矩阵方程或线性标量方程组)

numpy.linalg.solve(ab)[source]

Solve a linear matrix equation, or system of linear scalar equations.

Computes the “exact” solution, x, of the well-determined, i.e., full rank, linear matrix equation ax = b.

Parameters:

a : (…, M, M) array_like

Coefficient matrix.

b : {(…, M,), (…, M, K)}, array_like

Ordinate or “dependent variable” values.

Returns:

x : {(…, M,), (…, M, K)} ndarray

Solution to the system a x = b. Returned shape is identical to b.

Raises:

LinAlgError

If a is singular or not square.

7. numpy.linalg.norm(根据ord的值计算矩阵x的范数)

numpy.linalg.norm(xord=Noneaxis=Nonekeepdims=False)[source]

Matrix or vector norm.

This function is able to return one of eight different matrix norms, or one of an infinite number of vector norms (described below), depending on the value of the ord parameter.

Parameters:

x : array_like

Input array. If axis is None, x must be 1-D or 2-D.

ord : {non-zero int, inf, -inf, ‘fro’, ‘nuc’}, optional

Order of the norm (see table under Notes). inf means numpy’s inf object.

axis : {int, 2-tuple of ints, None}, optional

If axis is an integer, it specifies the axis of x along which to compute the vector norms. If axis is a 2-tuple, it specifies the axes that hold 2-D matrices, and the matrix norms of these matrices are computed. If axis is None then either a vector norm (when x is 1-D) or a matrix norm (when x is 2-D) is returned.

keepdims : bool, optional

If this is set to True, the axes which are normed over are left in the result as dimensions with size one. With this option the result will broadcast correctly against the original x.

New in version 1.10.0.

Returns:

n : float or ndarray

Norm of the matrix or vector(s).

8. numpy.random.standard_normal(生成符合标准正态分布的数据)

numpy.random.standard_normal(size=None)

Draw samples from a standard Normal distribution (mean=0, stdev=1).

Parameters:

size : int or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned.

Returns:

out : float or ndarray

Drawn samples.

9. numpy.zeros(生成大小为shape的,类型为dtype的矩阵,矩阵中元素全为0)

numpy.zeros(shapedtype=floatorder='C')

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

Parameters:

shape : int or sequence 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 : {‘C’, ‘F’}, optional

Whether to store multidimensional data in C- or Fortran-contiguous (row- or column-wise) order in memory.

Returns:

out : ndarray

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

10. numpy.random.binomial(生成符合二项分布b(n,p)的数据)

numpy.random.binomial(npsize=None)

Draw samples from a binomial distribution.

Samples are drawn from a binomial distribution with specified parameters, n trials and p probability of success where n an integer >= 0 and p is in the interval [0,1]. (n may be input as a float, but it is truncated to an integer in use)

Parameters:

n : int or array_like of ints

Parameter of the distribution, >= 0. Floats are also accepted, but they will be truncated to integers.

p : float or array_like of floats

Parameter of the distribution, >= 0 and <=1.

size : int or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if n and p are both scalars. Otherwise, np.broadcast(n, p).size samples are drawn.

Returns:

out : ndarray or scalar

Drawn samples from the parameterized binomial distribution, where each sample is equal to the number of successes over the n trials.

11. numpy.argmax(在指定轴的方向返回最大元素的索引)

numpy.argmax(aaxis=Noneout=None)[source]

Returns the indices of the maximum values along an axis.

Parameters:

a : array_like

Input array.

axis : int, optional

By default, the index is into the flattened array, otherwise along the specified axis.

out : array, optional

If provided, the result will be inserted into this array. It should be of the appropriate shape and dtype.

Returns:

index_array : ndarray of ints

Array of indices into the array. It has the same shape as a.shape with the dimension along axisremoved.

12. numpy.argmin(在指定轴的方向返回最小元素的索引)

numpy.argmin(aaxis=Noneout=None)[source]

Returns the indices of the minimum values along an axis.

Parameters:

a : array_like

Input array.

axis : int, optional

By default, the index is into the flattened array, otherwise along the specified axis.

out : array, optional

If provided, the result will be inserted into this array. It should be of the appropriate shape and dtype.

Returns:

index_array : ndarray of ints

Array of indices into the array. It has the same shape as a.shape with the dimension along axisremoved.


相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-10-12
  • 2021-11-19
  • 2021-10-01
  • 2021-10-14
  • 2021-12-01
猜你喜欢
  • 2021-07-30
  • 2022-12-23
  • 2021-06-19
  • 2022-12-23
  • 2021-11-13
  • 2021-12-15
相关资源
相似解决方案