(数据科学学习手札03)Python与R在随机数生成上的异同
随机数的使用是很多算法的关键步骤,例如蒙特卡洛法、遗传算法中的轮盘赌法的过程,因此对于任意一种语言,掌握其各类型随机数生成的方法至关重要,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在随机数生成上的异同的更多相关文章
- (数据科学学习手札58)在R中处理有缺失值数据的高级方法
一.简介 在实际工作中,遇到数据中带有缺失值是非常常见的现象,简单粗暴的做法如直接删除包含缺失值的记录.删除缺失值比例过大的变量.用0填充缺失值等,但这些做法会很大程度上影响原始数据的分布或者浪费来之 ...
- (数据科学学习手札47)基于Python的网络数据采集实战(2)
一.简介 马上大四了,最近在暑期实习,在数据挖掘的主业之外,也帮助同事做了很多网络数据采集的内容,接下来的数篇文章就将一一罗列出来,来续写几个月前开的这个网络数据采集实战的坑. 二.马蜂窝评论数据采集 ...
- (数据科学学习手札80)用Python编写小工具下载OSM路网数据
本文对应脚本已上传至我的Github仓库https://github.com/CNFeffery/DataScienceStudyNotes 1 简介 我们平时在数据可视化或空间数据分析的过程中经常会 ...
- (数据科学学习手札50)基于Python的网络数据采集-selenium篇(上)
一.简介 接着几个月之前的(数据科学学习手札31)基于Python的网络数据采集(初级篇),在那篇文章中,我们介绍了关于网络爬虫的基础知识(基本的请求库,基本的解析库,CSS,正则表达式等),在那篇文 ...
- (数据科学学习手札32)Python中re模块的详细介绍
一.简介 关于正则表达式,我在前一篇(数据科学学习手札31)中已经做了详细介绍,本篇将对Python中自带模块re的常用功能进行总结: re作为Python中专为正则表达式相关功能做出支持的模块,提供 ...
- (数据科学学习手札90)Python+Kepler.gl轻松制作时间轮播图
本文示例代码及数据已上传至我的Github仓库https://github.com/CNFeffery/DataScienceStudyNotes 1 简介 Kepler.gl作为一款强大的开源地理信 ...
- (数据科学学习手札55)利用ggthemr来美化ggplot2图像
一.简介 R中的ggplot2是一个非常强大灵活的数据可视化包,熟悉其绘图规则后便可以自由地生成各种可视化图像,但其默认的色彩和样式在很多时候难免有些过于朴素,本文将要介绍的ggthemr包专门针对原 ...
- (数据科学学习手札40)tensorflow实现LSTM时间序列预测
一.简介 上一篇中我们较为详细地铺垫了关于RNN及其变种LSTM的一些基本知识,也提到了LSTM在时间序列预测上优越的性能,本篇就将对如何利用tensorflow,在实际时间序列预测任务中搭建模型来完 ...
- (数据科学学习手札69)详解pandas中的map、apply、applymap、groupby、agg
*从本篇开始所有文章的数据和代码都已上传至我的github仓库:https://github.com/CNFeffery/DataScienceStudyNotes 一.简介 pandas提供了很多方 ...
随机推荐
- Django问卷调查项目思路流程
Django问卷调查项目思路流程: 1 后端思路 : 需求分析 ---- 找出各实体对应关系 ---- 设计model架构 ---- 统一资源封装 --- 提供资源API入口 ---- 设计项目实体功 ...
- Android 回调的理解,觉得写得好就转过来。。。收藏一下
转自:一个经典例子让你彻彻底底理解java回调机制 以前不理解什么叫回调,天天听人家说加一个回调方法啥的,心里想我草,什么叫回调方法啊?然后自己就在网上找啊找啊找,找了很多也不是很明白,现在知道了,所 ...
- IOS 公司标示使用反向域名
1. 公司标示使用反向域名========================================正向域名 www.baidu.com 用来标示一台网络主机反向域名 cn.itcast.Myd ...
- listview加载显示图片
public class ImageAndTextListAdapter extends ArrayAdapter<ImageAndText> { private ListView lis ...
- Uva 11396 爪分解
题目链接:https://vjudge.net/contest/166461#problem/A 题意: 给定一个图,特点是每个点的度都是3,求是不是原图可以分解为全部鸡爪:每条边只属于一个鸡爪: 分 ...
- hihocoder 后缀自动机四·重复旋律7
题目 在\(DAG\)上跑一个\(dp\)就好了 设\(ans_i\)表示到了\(SAM\)的\(i\)位置上所有的子串形成的数的和,之后我们顺便记录一个方案数\(d_i\) 之后我们直接转移就好了 ...
- 布局方式-inline-block布局
.像文本一样排block元素 .没有清除浮动等问题 .需要处理间隙 一种方式 <style> .container{ width: 800px; height: 200px; fo ...
- Velocity 模板
Velocity 模板引擎介绍 引:https://www.ibm.com/developerworks/cn/java/j-lo-velocity1/ 在 现今的软件开发过程中,软件开发人员将更多的 ...
- Hinge Loss
http://blog.csdn.net/luo123n/article/details/48878759 https://en.wikipedia.org/wiki/Hinge_loss ...
- SPFA 全面讲解
SPFA全面讲解 --最短路高效算法 标签: 最短路 简介:SPFA 是1994年在西安交通大学段凡丁同学所提出,是将Dijsktra以及Bellman-Ford两种最短路算法完美结合的一个算法,效率 ...