zsh2270365028的个人博客分享 http://blog.sciencenet.cn/u/zsh2270365028

博文

Python-numpy

已有 2364 次阅读 2019-9-3 10:30 |个人分类:Python|系统分类:科研笔记

创建数组:
1.array()函数
a1 = np.array([1,2,3,4])
a2 = np.array([(1,2),(3,4)])
a3 = np.array([[1,2],[3,4]])
print(a1)
print(a2)
pritn(a3)

2.arange(开始值,终止值,步长,)函数
缺点:一些无法轻易预测获得的元素个数,需要提前计算步长
a4 = np.arange(0,1,0.125)
print('a4::::::',a4)

3 linspace(开始值,终止值,元素个数)函数
a5 = np.linspace(0.1,1,10)
print('a5::::::',a5)
a6 = np.linspace(1,10,9)
print('a6::::::',a6)

4 logspace()函数创建等比数列
例如:生成10^1 ~ 10^3之间的3个等比数列
a7 = np.logspace(1,3,4)
print(a7)


扩展:
通常,数据的元素开始都是未知的,但是它的大小是已知的,因此,numpy提供一些使用占位符创建的数组函数。
这最小化了扩展数组的需要和高昂的运算代价
1.zeros()函数
a8 = np.zeros((2,3))
print(a8)

2.ones()函数
a9 = np.ones((2,3))
print(a9)

3.empty()函数
创建一个内容随机并且依赖于内存状态的数组
a10 = np.empty((2,3))
print(a10)

4.eye(N)函数
生成N阶矩阵,并且对角线元素为1
a11 = np.eye(3)
print('a11:::::\n',a11)

5.diag()函数
a12 = np.diag([1,2,3,4])
print('a12:::::\n',a12)
;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# mu1 = [1, 1], mu2 = [-1, -1]
mu1 = np.ones(2)
mu2 = -np.ones(2)
# Signature: np.ones(shape, dtype=None, order='C')
# Docstring:
# Return a new array of given shape and type, filled with ones.
# Examples
# --------
# >>> np.ones(5)
# array([ 1.,  1.,  1.,  1.,  1.])

# >>> np.ones((5,), dtype=int)
# array([1, 1, 1, 1, 1])

# >>> np.ones((2, 1))
# array([[ 1.],
#        [ 1.]])

# >>> s = (2,2)
# >>> np.ones(s)
# array([[ 1.,  1.],
#        [ 1.,  1.]])

# Width of 0.1 in each dimension
;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# np.logaddexp?
# all signature:  np.logaddexp(*args, **kwargs)
# Type:            ufunc
# String form:     <ufunc 'logaddexp'>
# File:            ~/anaconda3/lib/python3.7/site-packages/numpy/__init__.py
# Docstring:      
# logaddexp(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])

# Logarithm of the sum of exponentiations of the inputs.

# Calculates ``log(exp(x1) + exp(x2))``. This function is useful in
# statistics where the calculated probabilities of events may be so small
# as to exceed the range of normal floating point numbers.  In such cases
# the logarithm of the calculated probability is stored. This function
# allows adding probabilities stored in such a fashion.
# prob1=np.log(1e-50)
# prob2=np.log(2.5e-50)
# prob12=np.logaddexp(prob1,prob2)
# prob12

# np.dot?
# >>> np.dot(3, 4)
# 12

# Neither argument is complex-conjugated:

# >>> np.dot([2j, 3j], [2j, 3j])
# (-13+0j)

# For 2-D arrays it is the matrix product:

# >>> a = [[1, 0], [0, 1]]
# >>> b = [[4, 1], [2, 2]]
# >>> np.dot(a, b)
# array([[4, 1],
#        [2, 2]])

# >>> a = np.arange(3*4*5*6).reshape((3,4,5,6))
# >>> b = np.arange(3*4*5*6)[::-1].reshape((5,4,6,3))
# >>> np.dot(a, b)[2,3,2,1,2,2]
# 499128
;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
np.random.randn()
For random samples from :math:`N(\mu, \sigma^2)`, use:

``sigma * np.random.randn(...) + mu``

Examples
--------
>>> np.random.randn()
2.1923875335537315 #random

Two-by-four array of samples from N(3, 6.25):

>>> 2.5 * np.random.randn(2, 4) + 3
array([[-4.49401501,  4.00950034, -1.81814867,  7.29718677],  #random
       [ 0.39924804,  4.68456316,  4.99394529,  4.84057254]]) #random
;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
np.random.normal?
normal(loc=0.0, scale=1.0, size=None)
Draw random samples from a normal (Gaussian) distribution.
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.
;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#stats.norm.pdf?
;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Methods
rvs(loc=0, scale=1, size=1, random_state=None)     Random variates.
pdf(x, loc=0, scale=1)     Probability density function.
logpdf(x, loc=0, scale=1)     Log of the probability density function.
cdf(x, loc=0, scale=1)     Cumulative distribution function.
logcdf(x, loc=0, scale=1)     Log of the cumulative distribution function.
sf(x, loc=0, scale=1)     Survival function (also defined as 1 - cdf, but sf is sometimes more accurate).
logsf(x, loc=0, scale=1)     Log of the survival function.
ppf(q, loc=0, scale=1)     Percent point function (inverse of cdf — percentiles).
isf(q, loc=0, scale=1)     Inverse survival function (inverse of sf).
moment(n, loc=0, scale=1)     Non-central moment of order n
stats(loc=0, scale=1, moments='mv')     Mean(‘m’), variance(‘v’), skew(‘s’), and/or kurtosis(‘k’).
entropy(loc=0, scale=1)     (Differential) entropy of the RV.
fit(data, loc=0, scale=1)     Parameter estimates for generic data.
expect(func, args=(), loc=0, scale=1, lb=None, ub=None, conditional=False, **kwds)     
Expected value of a function (of one argument) with respect to the distribution.
median(loc=0, scale=1)     Median of the distribution.
mean(loc=0, scale=1)     Mean of the distribution.
var(loc=0, scale=1)     Variance of the distribution.
std(loc=0, scale=1)     Standard deviation of the distribution.
interval(alpha, loc=0, scale=1)     Endpoints of the range that contains alpha percent of the distribution
;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
stats.norm.cdf(x=3, loc=0, scale=1) - stats.norm.cdf(x=-3, loc=0, scale=1)#
stats.norm.ppf(0.5,loc=1,scale=1)
;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Signature: random.gauss(mu, sigma)
Docstring:
Gaussian distribution.

mu is the mean, and sigma is the standard deviation.  This is
slightly faster than the normalvariate() function.

Not thread-safe without a lock around calls.
File:      ~/anaconda3/lib/python3.7/random.py
Type:      method
;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
np.random.standard_normal()#standard_normal(size=None)

# Draw samples from a standard Normal distribution (mean=0, stdev=1).
;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#module模块
import numpy as np
import emcee
import corner
import matplotlib as plt
import matplotlib
import scipy
import random#提供了生成随机数的工具
import math#为浮点运算提供对底层C函数库的访问
import scipy.stats as stats#或者from scipy import stats
from timeit import Timer#可以对解决同一问题的不同方法之间的性能差异给出解答

from datetime import date#为日期和时间处理同时提供了简单和复杂的方法
import os#提供与操作系统相关联的函数
import sys#调用命令行参数
import re#高级字符串处理提供了正则表达式的工具
import glob#提供了一个函数用于从目录通配符搜索中生成文件列表
import zlib#以下模块可以直接支持通用的数据打包和压缩格式:zlib/gzip/bz2/zipfile/tarfile
import smtplib#发送电子邮件
from urllib.request import urlopen#处理从urls接收的urllib.request



https://blog.sciencenet.cn/blog-587102-1196445.html

上一篇:ubuntu18.04 install anaconda
下一篇:[转载]matplotlib marker 设置
收藏 IP: 119.78.226.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-4-28 07:56

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部