np.random总结
import numpy as np
(1)np.random.random_sample
help(np.random.random_sample)
Help on built-in function random_sample:
random_sample(...) method of mtrand.RandomState instance
random_sample(size=None)
Return random floats in the half-open interval [0.0, 1.0).
Results are from the "continuous uniform" distribution over the
stated interval. To sample :math:`Unif[a, b), b > a` multiply
the output of `random_sample` by `(b-a)` and add `a`::
(b - a) * random_sample() + a
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 of floats
Array of random floats of shape `size` (unless ``size=None``, in which
case a single float is returned).
Examples
--------
>>> np.random.random_sample()
0.47108547995356098
>>> type(np.random.random_sample())
<type 'float'>
>>> np.random.random_sample((5,))
array([ 0.30220482, 0.86820401, 0.1654503 , 0.11659149, 0.54323428])
Three-by-two array of random numbers from [-5, 0):
>>> 5 * np.random.random_sample((3, 2)) - 5
array([[-3.99149989, -0.52338984],
[-2.99091858, -0.79479508],
[-1.23204345, -1.75224494]])
np.random.random_sample((m,n))给出m*n的均匀分布的随机数组。
np.random.random_sample((3,3))
array([[0.29173378, 0.29419769, 0.47702224],
[0.67796941, 0.12930519, 0.06604015],
[0.41514769, 0.61113887, 0.2035459 ]])
如果要得到[a,b)的均匀分布的随机数组,只需要(b-a)*np.random.random_sample((m,n))+a:
(5-2)*np.random.random_sample((3,3))+2 #2 ~5均匀分布随机数
array([[4.19892161, 4.66196903, 2.90223592],
[4.70942939, 2.73620934, 2.22161209],
[3.46348355, 4.58905218, 2.33377181]])
(2)np.random.rand
help(np.random.rand)
Help on built-in function rand:
rand(...) method of mtrand.RandomState instance
rand(d0, d1, ..., dn)
Random values in a given shape.
Create an array of the given shape and populate it with
random samples from a uniform distribution
over ``[0, 1)``.
Parameters
----------
d0, d1, ..., dn : int, optional
The dimensions of the returned array, should all be positive.
If no argument is given a single Python float is returned.
Returns
-------
out : ndarray, shape ``(d0, d1, ..., dn)``
Random values.
See Also
--------
random
Notes
-----
This is a convenience function. If you want an interface that
takes a shape-tuple as the first argument, refer to
np.random.random_sample .
Examples
--------
>>> np.random.rand(3,2)
array([[ 0.14022471, 0.96360618], #random
[ 0.37601032, 0.25528411], #random
[ 0.49313049, 0.94909878]]) #random
np.random.rand(d0,d1..)是np.random.random_sample的简洁用法,也是形成d0*d1*...维度的[0,1)的随机数组
np.random.rand(3,3)
array([[0.30821699, 0.64856611, 0.17575119],
[0.99049116, 0.60985425, 0.01740196],
[0.49243809, 0.98859105, 0.71051433]])
(3)np.random.randn
help(np.random.randn)
Help on built-in function randn:
randn(...) method of mtrand.RandomState instance
randn(d0, d1, ..., dn)
Return a sample (or samples) from the "standard normal" distribution.
If positive, int_like or int-convertible arguments are provided,
`randn` generates an array of shape ``(d0, d1, ..., dn)``, filled
with random floats sampled from a univariate "normal" (Gaussian)
distribution of mean 0 and variance 1 (if any of the :math:`d_i` are
floats, they are first converted to integers by truncation). A single
float randomly sampled from the distribution is returned if no
argument is provided.
This is a convenience function. If you want an interface that takes a
tuple as the first argument, use `numpy.random.standard_normal` instead.
Parameters
----------
d0, d1, ..., dn : int, optional
The dimensions of the returned array, should be all positive.
If no argument is given a single Python float is returned.
Returns
-------
Z : ndarray or float
A ``(d0, d1, ..., dn)``-shaped array of floating-point samples from
the standard normal distribution, or a single such float if
no parameters were supplied.
See Also
--------
standard_normal : Similar, but takes a tuple as its argument.
Notes
-----
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.randn(d0,d1...dn)是形成(d0*d1...dn)维度的均值为0,均方差为1的标准正太分布随机数组.
(4) np.random.randint
help(np.random.randint)
Help on built-in function randint:
randint(...) method of mtrand.RandomState instance
randint(low, high=None, size=None, dtype='l')
Return random integers from `low` (inclusive) to `high` (exclusive).
Return random integers from the "discrete uniform" distribution of
the specified dtype in the "half-open" interval [`low`, `high`). If
`high` is None (the default), then results are from [0, `low`).
Parameters
----------
low : int
Lowest (signed) integer to be drawn from the distribution (unless
``high=None``, in which case this parameter is one above the
*highest* such integer).
high : int, optional
If provided, one above the largest (signed) integer to be drawn
from the distribution (see above for behavior if ``high=None``).
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.
dtype : dtype, optional
Desired dtype of the result. All dtypes are determined by their
name, i.e., 'int64', 'int', etc, so byteorder is not available
and a specific precision may have different C types depending
on the platform. The default value is 'np.int'.
.. versionadded:: 1.11.0
Returns
-------
out : int or ndarray of ints
`size`-shaped array of random integers from the appropriate
distribution, or a single such random int if `size` not provided.
See Also
--------
random.random_integers : similar to `randint`, only for the closed
interval [`low`, `high`], and 1 is the lowest value if `high` is
omitted. In particular, this other one is the one to use to generate
uniformly distributed discrete non-integers.
Examples
--------
>>> np.random.randint(2, size=10)
array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0])
>>> np.random.randint(1, size=10)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
Generate a 2 x 4 array of ints between 0 and 4, inclusive:
>>> np.random.randint(5, size=(2, 4))
array([[4, 0, 2, 1],
[3, 2, 2, 0]])
randint(low, high=None, size=None, dtype='l')是得到size规模的[low,high)的随机数组,如果high=None,那么,形成size规模的[0,low)的随机数组;
random_integers(low,high=None,size=None,dtype='1')与randint类似,唯一的区别是[low,high]。
(5)np.random.binomial
help(np.random.binomial)
Help on built-in function binomial:
binomial(...) method of mtrand.RandomState instance
binomial(n, p, size=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.
See Also
--------
scipy.stats.binom : probability density function, distribution or
cumulative density function, etc.
Notes
-----
The probability density for the binomial distribution is
.. math:: P(N) = \binom{n}{N}p^N(1-p)^{n-N},
where :math:`n` is the number of trials, :math:`p` is the probability
of success, and :math:`N` is the number of successes.
When estimating the standard error of a proportion in a population by
using a random sample, the normal distribution works well unless the
product p*n <=5, where p = population proportion estimate, and n =
number of samples, in which case the binomial distribution is used
instead. For example, a sample of 15 people shows 4 who are left
handed, and 11 who are right handed. Then p = 4/15 = 27%. 0.27*15 = 4,
so the binomial distribution should be used in this case.
References
----------
.. [1] Dalgaard, Peter, "Introductory Statistics with R",
Springer-Verlag, 2002.
.. [2] Glantz, Stanton A. "Primer of Biostatistics.", McGraw-Hill,
Fifth Edition, 2002.
.. [3] Lentner, Marvin, "Elementary Applied Statistics", Bogden
and Quigley, 1972.
.. [4] Weisstein, Eric W. "Binomial Distribution." From MathWorld--A
Wolfram Web Resource.
http://mathworld.wolfram.com/BinomialDistribution.html
.. [5] Wikipedia, "Binomial distribution",
http://en.wikipedia.org/wiki/Binomial_distribution
Examples
--------
Draw samples from the distribution:
>>> n, p = 10, .5 # number of trials, probability of each trial
>>> s = np.random.binomial(n, p, 1000)
# result of flipping a coin 10 times, tested 1000 times.
A real world example. A company drills 9 wild-cat oil exploration
wells, each with an estimated probability of success of 0.1. All nine
wells fail. What is the probability of that happening?
Let's do 20,000 trials of the model, and count the number that
generate zero positive results.
>>> sum(np.random.binomial(9, 0.1, 20000) == 0)/20000.
# answer = 0.38885, or 38%.
binomial(n, p, size=None) 形成符合二项分布概率的size的[0,n]的随机数组,其中二项分布的单次成功概率为p
np.random.binomial(5,0.1,4)
array([0, 2, 0, 0])
5 in np.random.binomial(5,0.1,10000)
False
5 in np.random.binomial(5,0.1,1000000)
True
np.random总结的更多相关文章
- 怎么理解np.random.seed()?
在使用numpy时,难免会用到随机数生成器.我一直对np.random.seed(),随机数种子搞不懂.很多博客也就粗略的说,利用随机数种子,每次生成的随机数相同. 我有两个疑惑:1, 利用随机数种子 ...
- 对抗生成网络-图像卷积-mnist数据生成(代码) 1.tf.layers.conv2d(卷积操作) 2.tf.layers.conv2d_transpose(反卷积操作) 3.tf.layers.batch_normalize(归一化操作) 4.tf.maximum(用于lrelu) 5.tf.train_variable(训练中所有参数) 6.np.random.uniform(生成正态数据
1. tf.layers.conv2d(input, filter, kernel_size, stride, padding) # 进行卷积操作 参数说明:input输入数据, filter特征图的 ...
- NP:建立可视化输入的二次函数数据点集np.linspace+np.random.shuffle+np.random.normal
import numpy as np import matplotlib.pyplot as plt def fix_seed(seed=1): #重复观看一样东西 # reproducible np ...
- np.random.rand均匀分布随机数和np.random.randn正态分布随机数函数使用方法
np.random.rand用法 觉得有用的话,欢迎一起讨论相互学习~Follow Me 生成特定形状下[0,1)下的均匀分布随机数 np.random.rand(a1,a2,a3...)生成形状为( ...
- np.random.choice方法
np.random.choice方法 觉得有用的话,欢迎一起讨论相互学习~Follow Me def choice(a, size=None, replace=True, p=None) 表示从a中随 ...
- numpy中的np.random.mtrand.RandomState
1 RandomState 的应用场景概述 在训练神经网络时,苦于没有数据,此时numpy为我们提供了 “生产” 数据集的一种方式. 例如在搭建神经网络(一)中的 4.3 准备数据集 章节中就是采用n ...
- np.random.normal()正态分布
高斯分布的概率密度函数 numpy中 numpy.random.normal(loc=0.0, scale=1.0, size=None) 参数的意义为: loc:float 概率分布的均值,对应着整 ...
- np.random.randn()、np.random.rand()、np.random.randint()
(1)np.random.randn()函数 语法: np.random.randn(d0,d1,d2……dn) 1)当函数括号内没有参数时,则返回一个浮点数: 2)当函数括号内有一个参数时,则返回秩 ...
- np.random.random()系列函数
1.np.random.random()函数参数 np.random.random((1000, 20)) 上面这个就代表生成1000行 20列的浮点数,浮点数都是从0-1中随机. 2.numpy.r ...
- np.random.seed()
124.np.random.seed()的作用 陈容喜 关注 2018.01.11 21:36 字数 3 阅读 4460评论 0喜欢 6 今天看到一段代码时遇到了np.random.seed(),搞不 ...
随机推荐
- 全程使用 AI 从 0 到 1 写了个小工具
背景 好长时间没写技术方面的文章了,主要的原因是AI的发展实在太快太快,尤其是从去年ChatGPT的普及到今年DeepSeek的爆火,AI的世界可谓是三天一个小变化五天一个大版本,AI的能力每天都在以 ...
- .NET Core 中如何实现缓存的预热?
在构建高性能的 .NET Core 应用时,缓存是提升系统响应速度.减轻数据库压力的利器.然而,缓存并非一蹴而就,它也需要"热身"才能发挥最佳性能.这就是缓存预热的意义所在. 一. ...
- Error: Address already in use
端口被某个进程占用 使用命令 lsof -i:端口号 然后看到进程号,直接杀掉进程就好 kill -9 进程号
- 解决 Docker 日志文件太大的问题
Docker 在不重建容器的情况下,日志文件默认会一直追加,时间一长会逐渐占满服务器的硬盘的空间,内存消耗也会一直增加,本篇来了解一些控制日志文件的方法. 清理单个文件 运行时控制 全局配置 Dock ...
- java学习-5-核心类:字符串StringBuilder
对字符串进行拼接,用java标准库提供的可变对象:StringBuilder. StringBuilder sb = StringBuilder(1024); for (int i = 0;i < ...
- RL · Exploration | 使用时序距离构造 intrinsic reward,鼓励 agent 探索
论文标题:Episodic Novelty Through Temporal Distance. ICLR 2025,8 8 6 5 poster. arxiv:https://arxiv.org/a ...
- Spring 的 resolveBeforeInstantiation 方法作用详解
一.定义 resolveBeforeInstantiation 是 Spring 框架中 AbstractAutowireCapableBeanFactory 类的核心方法之一,它在 Bean 的实例 ...
- Eclipse 配置maven默认源及本地仓库
1.window->Preferences 2.Maven-> User Setting 3.全局配置Global Settings/用户配置 User Settings 修改为自己的配 ...
- jmeter从csv文件中取数据设置变量的方法
从csv取数据是参数化方法之一 首先,CSV数据文件设置,选择数据文件,点击http请求,右键-添加-配置元件-csv data set config,添加CSV数据文件设置 添加后可对设置名称进行修 ...
- 使用CAMEL创建第一个Agent Society
CAMEL介绍 CAMEL 是一个开源社区,致力于探索代理的扩展规律.相信,在大规模研究这些代理可以提供对其行为.能力和潜在风险的宝贵见解.为了促进这一领域的研究,实现了并支持各种类型的代理.任务.提 ...