首页 > 编程语言 >Python:常用Numpy介绍

Python:常用Numpy介绍

时间:2023-01-10 00:55:08浏览次数:51  
标签:返回 常用 Python where random np array Numpy size

numpy.random.RandomState()函数

1.函数用法

功能 :可以通过numpy工具包生成模拟数据集,使用RandomState获得随机数生成器。

一般拿来对初始化模型的权重。

1.np.random.normal()函数

Parameters

  • loc:float or array_like of floats 浮点数或浮点数数组。

    分布的均值

  • scal:float or array_like of floats 浮点数或浮点数数组。分布的方差,不能为负。

  • size:int or tuple of ints, optional 整数或整数构成的元组。

    输出形状。例如,如果给定的形状是 (m, n, k) ,则绘制 m * n * k 样本。如果 size 为 None(默认),如果 locscale 都是标量,则返回单个值。否则,将抽取np.broadcast(loc, scale).size 样本。

例子

mu, sigma = 0, 0.1 #均值(loc)和方差(scal)
s = np.random.normal(mu, sigma, 1000)
abs(mu - np.mean(s))
##输出结果:
	0.0 #可能会有点小偏差
abs(sigma - np.std(s, ddof=1))
##输出结果
	0.1#可能会有点小偏差

Two-by-four 来自 N(3, 6.25) 的样本数组:

>>> np.random.normal(3, 2.5, size=(2, 4))
array([[-4.49401501,  4.00950034, -1.81814867,  7.29718677],   # random
       [ 0.39924804,  4.68456316,  4.99394529,  4.84057254]])  # random

数组模式

下面生成size = (200,3)的数组

#安列进行设定均值,方差
D = np.random.normal((3, 5, 4),(0.75, 1.00, 0.75),(200, 3))
print(np.mean(D[:,0]),  # 应该为3,会有点小偏差 
      np.mean(D[:,1]),  # 应该为5,会有点小偏差
      np.mean(D[:,2])   # 应该为4,会有点小偏差
     )
print(np.std(D[:,0]), # 0.75左右
      np.std(D[:,1]), # 1 左右
      np.std(D[:,2])  # 0.75左右
     )

np.where()的使用方法

函数用法

np.where有两种用法

  • np.where(condition,x,y) 当where内有三个参数时,第一个参数表示条件,当条件成立时where方法返回x,当条件不成立时where返回y。
  • np.where(condition) 当where内只有一个参数时,那个参数表示条件,当条件成立时,where返回的是每个符合condition条件元素的坐标,返回的是以元组的形式。

例子

#用法一
#当self.net_input(X)返回的值大于等于0.0时,where返回1,否则返回0
np.where(self.net_input(X) >= 0.0, 1, 0)
#用法二
a = np.array([2,4,6,8,10])
#只有一个参数表示条件的时候
np.where(a > 5)

输出:
array([ 6,  8, 10])

标签:返回,常用,Python,where,random,np,array,Numpy,size
From: https://www.cnblogs.com/TTS-TTS/p/17038960.html

相关文章