随机数的使用是很多算法的关键步骤,例如蒙特卡洛法、遗传算法中的轮盘赌法的过程,因此对于任意一种语言,掌握其各类型随机数生成的方法至关重要,Python与R在随机数底层生成上都依靠梅森旋转(twister)来生成高质量的随机数,但在语法上存在着很多异同点。

Python

numpy中的random模块

from numpy import random
?random
Type: module
String form: <module 'numpy.random' from 'D:\\anaconda\\lib\\site-packages\\numpy\\random\\__init__.py'>
File: d:\anaconda\lib\site-packages\numpy\random\__init__.py
Docstring:
========================
Random Number Generation
========================
==================== =========================================================
Utility functions
==============================================================================
random_sample Uniformly distributed floats over ``[0, 1)``.
random Alias for `random_sample`.
bytes Uniformly distributed random bytes.
random_integers Uniformly distributed integers in a given range.
permutation Randomly permute a sequence / generate a random sequence.
shuffle Randomly permute a sequence in place.
seed Seed the random number generator.
choice Random sample from 1-D array.
==================== =========================================================
==================== =========================================================
Compatibility functions
==============================================================================
rand Uniformly distributed values.
randn Normally distributed values.
ranf Uniformly distributed floating point numbers.
randint Uniformly distributed integers in a given range.
==================== =========================================================
==================== =========================================================
Univariate distributions
==============================================================================
beta Beta distribution over ``[0, 1]``.
binomial Binomial distribution.
chisquare :math:`\chi^2` distribution.
exponential Exponential distribution.
f F (Fisher-Snedecor) distribution.
gamma Gamma distribution.
geometric Geometric distribution.
gumbel Gumbel distribution.
hypergeometric Hypergeometric distribution.
laplace Laplace distribution.
logistic Logistic distribution.
lognormal Log-normal distribution.
logseries Logarithmic series distribution.
negative_binomial Negative binomial distribution.
noncentral_chisquare Non-central chi-square distribution.
noncentral_f Non-central F distribution.
normal Normal / Gaussian distribution.
pareto Pareto distribution.
poisson Poisson distribution.
power Power distribution.
rayleigh Rayleigh distribution.
triangular Triangular distribution.
uniform Uniform distribution.
vonmises Von Mises circular distribution.
wald Wald (inverse Gaussian) distribution.
weibull Weibull distribution.
zipf Zipf's distribution over ranked data.
==================== =========================================================
==================== =========================================================
Multivariate distributions
==============================================================================
dirichlet Multivariate generalization of Beta distribution.
multinomial Multivariate generalization of the binomial distribution.
multivariate_normal Multivariate generalization of the normal distribution.
==================== =========================================================
==================== =========================================================
Standard distributions
==============================================================================
standard_cauchy Standard Cauchy-Lorentz distribution.
standard_exponential Standard exponential distribution.
standard_gamma Standard Gamma distribution.
standard_normal Standard normal distribution.
standard_t Standard Student's t-distribution.
==================== =========================================================
==================== =========================================================
Internal functions
==============================================================================
get_state Get tuple representing internal state of generator.
set_state Set state of generator.
==================== =========================================================

上述random的模块说明文档详细说明了random中内置的各种随机数生成方法,下面针对其中一些常见的举例说明:

1.random.random_sample()与random.random()

生成[0,1]之间的服从均匀分布的浮点随机数

from numpy import random
for i in range(10):
print(random.random_sample())
0.5131167122678871
0.3182844248720986
0.5391999374256481
0.2212549424277599
0.80648135792427
0.34225462561468434
0.5388888490671446
0.00587378555105833
0.6731524781805254
0.21002426217873815

2.random.random_integers()

生成指定范围内的可重复整数

random.random_integers(1,10,10)
Out[44]: array([ 9, 10, 6, 4, 10, 10, 5, 3, 1, 6])

3.random.permutation()

生成指定范围内所有整数的一次随机排列

for i in range(5):
token = random.permutation(5)
print(token)
print(set(token))
[0 2 1 3 4]
{0, 1, 2, 3, 4}
[0 3 4 2 1]
{0, 1, 2, 3, 4}
[2 3 1 4 0]
{0, 1, 2, 3, 4}
[4 3 0 1 2]
{0, 1, 2, 3, 4}
[1 2 4 0 3]
{0, 1, 2, 3, 4}

4.random.shuffle()

将指定的列表随机打乱顺序

list = [i for i in range(10)]
random.shuffle(list)
print(list)
[6, 8, 2, 4, 5, 3, 0, 7, 1, 9]

5.random.seed()

以括号中的整数为起点设置伪随机数种子,同样的随机数种子设置后生成的随机数相同

random.seed(42)
print(random.permutation(5))
random.seed(42)
print(random.permutation(5))
[1 4 2 0 3]
[1 4 2 0 3]

6.random.choice()

从制定的序列中随机抽取多个元素(有放回或无放回,通过replace参数控制)

list = [i for i in range(10)]
random.choice(list,6,replace=False)#有放回
Out[8]: array([9, 6, 4, 2, 7, 8])
random.choice(list,6,replace=False)#无放回
Out[9]: array([1, 3, 9, 4, 0, 8])

7.random.rand()

生成0-1中服从均匀分布的多个随机数

random.rand(5)
Out[19]: array([0.86317047, 0.43070734, 0.85228662, 0.74797087, 0.76224563])

8.random.randn()

生成多个服从标准正态分布的随机数

random.randn(10)
Out[21]:
array([-0.25617082, -0.85531159, -0.18286371, 1.25656827, -0.72270841,
0.13949334, 0.92318096, -1.12549131, -0.46908035, -0.28388281])

9.random.randint()

等可能的生成指定范围内的多个随机整数

random.randint(1,10,5)
Out[29]: array([2, 9, 8, 8, 9])

R

作为专为统计而生的一种语言,R在随机数生成上自然是异常的丰富,这里仅举常用的一些随机数生成函数

1.rnorm()

生成服从正态分布的随机数,其中参数mean控制均值,sd控制标准差

> rnorm(5,mean=0,sd=1)
[1] -0.36167951 -0.50435239 -0.20245800 0.07877604 0.23662553

2.runif()

生成指定范围内的均匀分布随机数

> runif(5, min=0,max=10)
[1] 3.2774081 1.7341489 8.4128022 3.1511841 0.3385417

3.sample()

以不放回的方式生成指定范围内的随机整数序列

> sample(1:10,5,replace=T)#有放回
[1] 4 9 3 4 4
> sample(1:10,5,replace=F)#无放回
[1] 3 2 6 8 1

4.set.seed()

以括号内的整数值作为随机数发生算法的起点,因此通过控制伪随机数种子的参数,可以实现随机抽样的重现

而真正的随机算法里是默认以系统时间等我们认为充分随机的数字作为起点

> set.seed(42)
> sample(1:10,5,replace=F)
[1] 10 9 3 6 4
> set.seed(42)
> sample(1:10,5,replace=F)
[1] 10 9 3 6 4

(数据科学学习手札03)Python与R在随机数生成上的异同的更多相关文章

  1. (数据科学学习手札58)在R中处理有缺失值数据的高级方法

    一.简介 在实际工作中,遇到数据中带有缺失值是非常常见的现象,简单粗暴的做法如直接删除包含缺失值的记录.删除缺失值比例过大的变量.用0填充缺失值等,但这些做法会很大程度上影响原始数据的分布或者浪费来之 ...

  2. (数据科学学习手札47)基于Python的网络数据采集实战(2)

    一.简介 马上大四了,最近在暑期实习,在数据挖掘的主业之外,也帮助同事做了很多网络数据采集的内容,接下来的数篇文章就将一一罗列出来,来续写几个月前开的这个网络数据采集实战的坑. 二.马蜂窝评论数据采集 ...

  3. (数据科学学习手札80)用Python编写小工具下载OSM路网数据

    本文对应脚本已上传至我的Github仓库https://github.com/CNFeffery/DataScienceStudyNotes 1 简介 我们平时在数据可视化或空间数据分析的过程中经常会 ...

  4. (数据科学学习手札50)基于Python的网络数据采集-selenium篇(上)

    一.简介 接着几个月之前的(数据科学学习手札31)基于Python的网络数据采集(初级篇),在那篇文章中,我们介绍了关于网络爬虫的基础知识(基本的请求库,基本的解析库,CSS,正则表达式等),在那篇文 ...

  5. (数据科学学习手札32)Python中re模块的详细介绍

    一.简介 关于正则表达式,我在前一篇(数据科学学习手札31)中已经做了详细介绍,本篇将对Python中自带模块re的常用功能进行总结: re作为Python中专为正则表达式相关功能做出支持的模块,提供 ...

  6. (数据科学学习手札90)Python+Kepler.gl轻松制作时间轮播图

    本文示例代码及数据已上传至我的Github仓库https://github.com/CNFeffery/DataScienceStudyNotes 1 简介 Kepler.gl作为一款强大的开源地理信 ...

  7. (数据科学学习手札55)利用ggthemr来美化ggplot2图像

    一.简介 R中的ggplot2是一个非常强大灵活的数据可视化包,熟悉其绘图规则后便可以自由地生成各种可视化图像,但其默认的色彩和样式在很多时候难免有些过于朴素,本文将要介绍的ggthemr包专门针对原 ...

  8. (数据科学学习手札40)tensorflow实现LSTM时间序列预测

    一.简介 上一篇中我们较为详细地铺垫了关于RNN及其变种LSTM的一些基本知识,也提到了LSTM在时间序列预测上优越的性能,本篇就将对如何利用tensorflow,在实际时间序列预测任务中搭建模型来完 ...

  9. (数据科学学习手札69)详解pandas中的map、apply、applymap、groupby、agg

    *从本篇开始所有文章的数据和代码都已上传至我的github仓库:https://github.com/CNFeffery/DataScienceStudyNotes 一.简介 pandas提供了很多方 ...

随机推荐

  1. Laravel 开源电商体验与部署

    体验 开源项目已经部署了体验环境,开源通过扫描下方小程序码进行体验: 我们部署了 Laravel API demo 环境,访问地址:https://demo-open-admin.ibrand.cc/ ...

  2. babel 的一些记录

    babel 的作用是将高版本的代码转换成低版本的可支持的代码: 过程是 读取 source code 转换为语法树 -> 经过处理 -> 转换为 code: babel有preset和pl ...

  3. Inner Join, Left Outer Join和Association的区别

    测试用的CDS视图的源代码,第8行用Inner Join连接TJ02T, 后者存放了所有系统状态的ID和描述. Inner Join测试结果:对于那些在TJ02T里没有维护描述信息的状态,它们不会出现 ...

  4. W5100与MCU的连接方式

    W5100与MCU的连接方式 W5100与MCU的连接方式主要有直接总线连接.间接总线连接.SPI总线连接这三种连接方法,不同的连接方法适应于不同的场合,应该按需选择最恰当的连接方式. 1)直接总线连 ...

  5. Django:web框架本质

    一,web框架本质 我们可以这样理解:所有的Web应用本质上就是一个socket服务端,而用户的浏览器就是一个socket客户端. 这样我们就可以自己实现Web框架了. 1,自定义web框架 impo ...

  6. 【转】Android手机分辨率基础知识(DPI,DIP计算)

    1.术语和概念 术语 说明 备注 Screen size(屏幕尺寸) 指的是手机实际的物理尺寸,比如常用的2.8英寸,3.2英寸,3.5英寸,3.7英寸 摩托罗拉milestone手机是3.7英寸 A ...

  7. Sublime Text 3的安装,卸载,更新,激活

    安装: 下载安装包:建议到官方网站下载,网址:http://www.sublimetext.com/3 . 卸载 在Finder中进入“/Users/用户名/Library/Application S ...

  8. Going deeper with convolutions(GoogLeNet、Inception)

    从LeNet-5开始,cnn就有了标准的结构:stacked convolutional layers are followed by one or more fully-connected laye ...

  9. 【洛谷P1363】幻象迷宫

    P1363 幻想迷宫 显然,若从原图中起点走到相邻的图中对应的"起点"位置 ,就可以无限走下去, 若一个点从原图中可以到达,到了非原图中也可以到达,就可以无限走下去 我们不妨记录下 ...

  10. 【洛谷P3389】(模板)高斯消元

    对于高斯消元法求解线性方程组, 我的理解就类似于我们在做数学题时的加减消元法, 只是把它写成一个通用的程序运算过程 对于一个线性方程组,我们从左往右每次将一列对应的行以下的元通过加减消元消去, 每个元 ...