python-numpy-伯努利试验模拟-np.random.binomial--自定义bins的直方图
2018-03-16 20:50
1096 查看
def perform_bernoulli_trials(n, p): """Perform n Bernoulli trials with success probability p and return number of successes.""" # Initialize number of successes: n_success n_success = 0 # Perform trials for i in range(n): # Choose random number between zero and one: random_number random_number=np.random.random() # If less than p, it's a success so add one to n_success if random_number<p: n_success+=1 return n_success贷款违约率的模拟# Seed random number generator
np.random.seed(42)
# Initialize the number of defaults: n_defaults
n_defaults=np.empty(1000)
# Compute the number of defaults
for i in range(1000):
n_defaults[i] =perform_bernoulli_trials(100,0.05)
# Plot the histogram with default number of bins; label your axes
_ = plt.hist(n_defaults,normed=True)
_ = plt.xlabel('number of defaults out of 100 loans')
_ = plt.ylabel('probability')
# Show the plot
plt.show()ecdf曲线:# Compute ECDF: x, y
x,y=ecdf(n_defaults)
# Plot the ECDF with labeled axes
plt.plot(x,y,marker='.',linestyle='none')
plt.xlabel('x')
plt.ylabel('y')
# Show the plot
plt.show()
# Compute the number of 100-loan simulations with 10 or more defaults: n_lose_money
n_lose_money=np.sum(n_defaults>=10)
# Compute and print probability of losing money
print('Probability of losing money =', n_lose_money / len(n_defaults))另一种简便的方法:# Take 10,000 samples out of the binomial distribution: n_defaults
n_defaults=np.random.binomial(n=100,p=0.05,size=10000)
# Compute CDF: x, y
x,y=ecdf(n_defaults)
# Plot the CDF with axis labels
plt.plot(x,y,marker = '.',linestyle = 'none')
plt.xlabel('he number of defaults out of 100 loans,')
plt.ylabel('CDF')
# Show the plot
plt.show()画直方图,自定义bins# Compute bin edges: bins
bins = np.arange(0, max(n_defaults) + 1.5) - 0.5
# Generate histogram
plt.hist(n_defaults,bins=bins,normed=True)
# Set margins
plt.margins(0.02)
# Label axes
plt.xlabel('违约')
plt.ylabel('数目')
# Show the plot
plt.show()
相关文章推荐
- Python numpy包 np.random.shuffle(x) 数据集 batch 预处理
- python 正态分布随机数 numpy.random.randn 使用小技
- python中numpy.zeros(np.zeros)的使用方法
- [Python] Generating random numbers using numpy lib
- Python中运用random函数模拟用户登录验证码
- Python绘制直方图 Pygal模拟掷骰子
- python-numpy-指数分布模拟
- numpy:np.random.rand
- Python之Random.randint()与numpy.random.randint()的区别
- python中的np.random.normal
- 二项分布的实现(np.random.binomial)
- Python Numpy:找到list中的np.nan值方法
- numpy: np.random模块 探究(源码)
- python中random模块的randint与numpy.random模块的randint
- python numpy中*,np.dot(),np.multiply()区
- python - numpy.random 常用随机数
- Python:numpy中random使用
- python numpy.random生成随机数组
- python-numpy-正态分布的模拟--pdf图--cdf图---正态分布的拟合
- Python之NumPy(axis=0/1/2...)的透彻理解——通过np.sum(axis=?)实例进行说明