np.random里让你迷糊的随机数函数到底咋区分(结合tensorflow)

小测

  1. numpy以下哪个函数不能产生正态分布的随机数( )
    A. standard_normal B.randn C.random D.normal

  2. 从[0,1)范围的标准分布中产生1个随机数,以下哪个numpy函数是错误的( )
    A. rand B.random C.uniform D.randn

  3. 用numpy产生1个3行4列数值范围在[1,10)之间的整数二维数组的正确代码是( )
    A. np.random.randint((1,10),(3,4))
    B. np.random.randint(3,4,(1,10))
    C. np.random.ranint((3,4),(1,10))
    D. np.random.randint(1,10,(3,4))

参考答案:C D D

答对的同学可以略过本篇博文。

口诀:random、rand一回事,后者照顾matlab; 两者size有区别,前元(组)后整(数)别搞错; 正态分布都带n,tf只用一normal;均匀分布uniform, 0/1范围用random、rand;numpy参数low、high、size,tf先要设shape。

import tensorflow as tf
import numpy as np

numpy和tensorflow数据的几点不同:
(1) numpy产生的浮点数数组默认为float64,tf默认为float32; 但整数都一样都是int32
(2) numpy同一功能提供了多种函数实现。 比如考虑到从matlab语言过渡到python,在产生一个随机数时rand和random函数功能完全一致。
np.random.seed(4)
np.random.rand()
np.random.seed(4)
np.random.random()
结果均输出0.9670298390136767

(3) matlab描述数组的size时会用一组整数,numpy照顾了这样一个习惯,比如产生(4,5)的[0,1)均匀分配二维数组:
np.random.seed(10)
np.random.rand(4,5) #仿matlab,整数描述size
np.random.seed(10)
np.random.random((4,5)) #元组或列表描述

结果均为:
‘’’
array([[0.77132064, 0.02075195, 0.63364823, 0.74880388, 0.49850701],
[0.22479665, 0.19806286, 0.76053071, 0.16911084, 0.08833981],
[0.68535982, 0.95339335, 0.00394827, 0.51219226, 0.81262096],
[0.61252607, 0.72175532, 0.29187607, 0.91777412, 0.71457578]])
‘’’

(4) tf语法非常简洁,用shape参数描述产生的张量形状,而且要先设定shape,再设定其它参数。
#产生正态分布的随机数
tf.random.normal([4,5], mean=0.0, stddev=1.0)

#numpy以下3种方法均可:
np.random.randn(4,5) #仿matlab,整数描述size
np.random.standard_normal((4,5)) #元组描述size
np.random.normal(0.0, 1.0, [4,5]) #指定均值和标准差后再设定size

#产生均匀分布的随机数
tf.random.uniform([4,5], minval=0, maxval=1)
#类似于:
np.random.seed(5)
np.random.rand(4,5) #[0,1)
np.random.seed(5)
np.random.random([4,5]) #[0,1)
np.random.seed(5)
np.random.uniform(0,1,(4,5)) #先设定low和high,再设定size
#结果均为:
‘’’
array([[0.22199317, 0.87073231, 0.20671916, 0.91861091, 0.48841119],
[0.61174386, 0.76590786, 0.51841799, 0.2968005 , 0.18772123],
[0.08074127, 0.7384403 , 0.44130922, 0.15830987, 0.87993703],
[0.27408646, 0.41423502, 0.29607993, 0.62878791, 0.57983781]])
‘’’

(5) numpy数组可以用convert_to_tensor函数转为张量
a = np.random.randint(1,10,(3,4))
b = tf.convert_to_tensor(a)
print(b)
‘’’
tf.Tensor(
[[7 4 4 3]
[2 6 8 5]
[4 2 8 4]], shape=(3, 4), dtype=int32)
‘’’

(6) 创建全0、全1、全为指定值的张量
#tf语法:
tf.zeros([4,5], tf.int32) #dtype默认为tf.float32
tf.ones([3,4], tf.float64) #dtype默认为tf.float32
tf.fill([2,3], 9) #默认为dtype=int32

#numpy语法:
np.zeros([4,5], np.int32) #默认float64
np.ones([3,4], np.float64) #默认float64
np.full([3,4],9) #与填充的值有关,如9.0就是float64,如9就是int32

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值