【python】np.random.uniform生成随机数、np.ones和 np.empty

本文详细介绍了NumPy库中生成随机数的方法,包括uniform函数的使用及其参数解析,以及如何通过ones和empty函数创建特定形状和类型的数组。同时,提供了多个代码示例帮助理解。

1、用法:numpy.random.uniform(low,high,size)

返回:随机生成指定范围的浮点数,从一个均匀分布[low,high)中随机采样,定义域是左闭右开,包含low,不包含high,ndarray类型,其形状与size中描述一致.

参数介绍:   
    low: 采样下界,float类型,默认值为0;
    high: 采样上界,float类型,默认值为1;
    size: 输出样本数目,为 int 或元组(tuple)类型,例如,size=(m,n,k), 则输出m*n*k个样本,缺省时输出1个值。

ndarray类型,表示一个N维数组对象,其有一个shape(表维度大小)和dtype(说明数组数据类型的对象),用zeros和ones函数可以创建数据全0或全1的数组,原型:

>>e = np.random.uniform(-4, 4, 6)
>>f = np.random.uniform(-4, 4, 4)
>>print(e)
>>print(f)
    [ 2.60056202 -0.39751136  3.79597526 -2.07039056  1.09381118 -3.00810278]
    [ 0.31837218 -1.95136013 -1.50040964 -2.36572997]

python中生成随机数的函数还有:

随机整数:random.randint(a,b):返回随机整数x,a<=x<=b

random.randrange(start,stop,[step]):返回一个范围在(start,stop,step)之间的随机整数,不包括结束值。

随机实数:random.random( ):返回0到1之间的浮点数

2、numpy.ones(shape,dtype=None,order='C'),

其中,shape表数组形状(m*n),dtype表类型,order表是以C还是fortran形式存放数据。

>>print('\nnp.ones([2,3])生成的array=\n{}'.format(np.ones([2,3])))
    np.ones([2,3])生成的array=
    [[ 1.  1.  1.]
     [ 1.  1.  1.]]

3、用法:numpy.empty(shape, dtype=float, order='C')

返回:给定shape,dtype 和 order的任意空数组,shape 为整型数据或整型tuple

>>print('\nnp.empty([2,3])生成的array=\n{}'.format(np.empty([2,3])))
>>print('\nnp.empty([2,3],dtype=int)生成的array=\n{}'.format(np.empty([2,3],dtype=int)))
    np.empty([2,3])生成的array=
    [[ 0.  0.  0.]
     [ 0.  0.  0.]]

    np.empty([2,3],dtype=int)生成的array=
    [[ 2300     0     0]
     [  436 65541     0]]

#“//”表示整型数据除法,并对余数采用四舍五入
>>print(249//4)
    62
>>print(245//4)
    61
   
#维度可以直接相加
import numpy as np
images = np.empty([196] + [64,64,64] + [1], dtype=np.float32)
print(images.shape)

ans = (196, 64, 64, 64, 1) 

参考:https://blog.youkuaiyun.com/HHTNAN/article/details/78590780

import math import numpy as np import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.optim as optim import tikzplotlib def my_bisection(f, a, b, P, tol): # approximates a root, R, of f bounded # by a and b to within tolerance # | f(m) | < tol with m the midpoint # between a and b Recursive implementation # check if a and b bound a root if (f(a) > P and f(b) > P) or (f(a) < P and f(b) < P): raise Exception( "The scalars a and b do not bound P") # get midpoint m = (a + b)/2 if np.abs(f(m)-P) < tol: # stopping condition, report m as root return m elif f(m) > P and f(m) < f(a): # case where m is an improvement on a. # Make recursive call with a = m return my_bisection(f, m, b, P, tol) elif f(m) < P and f(m) > f(b): # case where m is an improvement on b. # Make recursive call with b = m return my_bisection(f, a, m, P, tol) def AWGN_channel(x, sigma2): noise = np.sqrt(sigma2) * np.random.randn(x.size) return x + noise’ def AWGNdemapper(y, const, varN): apps = np.exp(-np.abs(np.transpose([y])-const)**2/(2*varN)) return apps / np.transpose([np.sum(apps, 1)]) def sampler(prob, n): samples = np.empty(0) for idx, p in enumerate(prob): occurrences = np.round(n * p) samples = np.concatenate((samples, np.ones(occurrences.astype(int)) * idx)) indexes = np.random.permutation(samples.shape[0]) return samples[indexes] def xesmd(apps, idx): ‘’’ Estimates symbolwise equivocation from reference symbols indices and a posteriori probabilities. ‘’’ eq = -np.log(np.take_along_axis(apps, idx[:, None], axis=1) / np.transpose([np.sum(apps, 1)])) eq[eq==np.inf] = 1000 return np.mean(eq) n = 100_000 SNR_dBs = np.arange(5,25) 16 QAM M = 4 alphabet = np.arange(-3,4,2) alphabet = alphabet / np.sqrt(np.mean(alphabet**2)) indices = np.random.choice(np.arange(M), n) symbols = alphabet[indices] mi_16 = [] for snrdB in SNR_dBs: sigma2 = 1/(10**(snrdB/10)) sigma2 = sigma2 y = AWGN_channel(symbols, sigma2) apps = AWGNdemapper(y, alphabet, sigma2) xe = xesmd(apps, indices) mi_16.append(2*(2 - xe / np.log(2))) 64 QAM M = 8 alphabet = np.arange(-7,8,2) alphabet = alphabet / np.sqrt(np.mean(alphabet**2)) indices = np.random.choice(np.arange(M), n) symbols = alphabet[indices] print('Power: ',np.mean(np.square(symbols))) mi_64 = [] for snrdB in SNR_dBs: sigma2 = 1/(10**(snrdB/10)) sigma2 = sigma2 y = AWGN_channel(symbols, sigma2) apps = AWGNdemapper(y, alphabet, sigma2) xe = xesmd(apps, indices) mi_64.append(2*(3 - (xe) / np.log(2))) def power_for_shaping(shaping): alphabet = np.arange(-7,8,2) # alphabet = alphabet / np.sqrt(np.mean(alphabet**2)) scaling = (alphabet[1]-alphabet[0])/2 denominator = np.sum(np.exp(-shaping*np.square(alphabet))) probs = 1/denominator * np.exp(-shaping*np.square(alphabet)) power = np.sum(np.square(np.arange(-7,8,2)*(scaling))*probs) return power power = [] for i in np.arange(0,1,0.1): power.append(power_for_shaping(i)) plt.plot(np.arange(0,1,0.1), power) M = 8 shaping = 2.5 alphabet = np.arange(-7,8,2) alphabet = alphabet / np.sqrt(np.mean(alphabet**2)) scaling = (alphabet[1]-alphabet[0])/2 scaling = 0.21821789023599236 print('Scaling: ', scaling) denominator = np.sum(np.exp(-shapingnp.square(alphabet))) probs = 1/denominator * np.exp(-shapingnp.square(alphabet)) power = np.sum(np.square(np.arange(-7,8,2)*(scaling))*probs) print('Power: ', power) indices = sampler(probs, n).astype(int) norm_factor = np.sqrt(np.sum(np.square(alphabet) * probs)) alphabet = alphabet / norm_factor symbols = alphabet[indices] scaling = (alphabet[1]-alphabet[0])/2 print('Scaling: ', scaling) H = np.sum(-np.log2(probs)*probs) print('Entropy: ',H) power = np.mean(symbols2) print('Power: ', power) plt.rcParams[‘figure.figsize’] = [4, 4] plt.hist(symbols, bins=100) plt.show() mi_mb_64 = [] for snrdB in SNR_dBs: sigma2 = 1/(10(snrdB/10)) sigma2 = sigma2 y = AWGN_channel(symbols, sigma2) apps = AWGNdemapper(y, alphabet, sigma2) xe = xesmd(apps, indices) mi_mb_64.append((H - (xe) / np.log(2))) 256 QAM M = 16 alphabet = np.arange(-15,16,2) alphabet = alphabet / np.sqrt(np.mean(alphabet**2)) indices = np.random.choice(np.arange(M), n) symbols = alphabet[indices] print('Power: ',np.mean(np.square(symbols))) mi_256 = [] for snrdB in SNR_dBs: sigma2 = 1/(10**(snrdB/10)) sigma2 = sigma2 y = AWGN_channel(symbols, sigma2) apps = AWGNdemapper(y, alphabet, sigma2) xe = xesmd(apps, indices) mi_256.append(2*(4 - (xe) / np.log(2))) Plot plt.rcParams[‘figure.figsize’] = [8, 6] plt.plot(SNR_dBs, mi_16, label = ‘16QAM’) plt.plot(SNR_dBs, mi_64, label = ‘64QAM’) plt.plot(SNR_dBs, mi_mb_64, label = ‘64-MB’) plt.plot(SNR_dBs, mi_256, label = ‘256QAM’) plt.plot(SNR_dBs, np.log2(1+10**(SNR_dBs/10)), color=‘black’, label=‘Capacity’) plt.legend() plt.grid() plt.title(‘AIR of QAM constellation’) plt.ylabel(‘bits per channel use’) plt.xlabel(‘SNR in dB’) tikzplotlib.save(“QAM_MI.tex”) SNR_dBs = np.arange(5,25) plt.plot(SNR_dBs, np.log2(1+10**(SNR_dBs/10)), color=‘black’, label=‘ C ( P / σ 2 ) C(P/σ 2 )’) plt.plot(SNR_dBs, np.log2(1+10**(SNR_dBs/10)) - 0.5np.log2((np.pinp.e)/6) , linestyle=‘dashed’, color=‘C1’, label=‘ C ( P / σ 2 ) − 1 2 log ⁡ 2 π e 6 C(P/σ 2 )− 2 1 ​ log 2 ​ 6 πe ​ ’) plt.grid() plt.ylabel(‘bits per channel use’) plt.xlabel(‘SNR in dB’) plt.xlim([5, 25]) plt.ylim([1, 8]) plt.title(‘AWGN channel capacity gap’) plt.legend() tikzplotlib.save(“SNR_GAP.tex”) f = lambda x: -np.log10(x) P = 0.4 p1 = my_bisection(f, 0.2, 0.8, P, 0.1) print(“P1 =”, p1) p01 = my_bisection(f, 0.2, 0.8, P, 0.01) print(“P01 =”, p01) print(“f(r1) =”, f(p1)) print(“f(r01) =”, f(p01)) 解释代码,并进行注释,请注意,可以对代码进行规范化,但不要修改原本的结构。另外,将原本的信噪比SNR_dBs = np.arange(5,22)修改为仅包含5,10,15,20.增加星座点可视化,可参考下列代码: 星座图可视化 plt.figure(figsize=(4, 4)) 计算二维网格点(实部+虚部,本例为实数调制) alph = alphabet_norm.detach().numpy() a = np.array([(d, c) for c in np.flip(alph) for d in alph]) 计算联合概率 joint_probs = (probs.reshape(-1, 1) * probs.reshape(1, -1)).flatten().detach().numpy() 绘制散点图(点大小表示概率) plt.scatter(a[:, 0], a[:, 1], s=joint_probs * 2000, alpha=0.6) plt.title(“Constellation Diagram”) plt.xlabel(“In-phase”) plt.ylabel(“Quadrature”) 保存为TikZ格式(用于LaTeX文档) tikzplotlib_save(f"aref_pcs_{SNR_dB}dB.tex") plt.show()
08-13
import math import numpy as np import matplotlib.pyplot as plt def AWGN_channel(x, sigma2): noise = np.sqrt(sigma2) * np.random.randn(x.size) return x + noise def AWGNdemapper(y, const, varN): apps = np.exp(-np.abs(np.transpose([y]) - const) ** 2 / (2 * varN)) return apps / np.transpose([np.sum(apps, 1)]) def sampler(prob, n): samples = np.empty(0) for idx, p in enumerate(prob): occurrences = np.round(n * p) samples = np.concatenate((samples, np.ones(occurrences.astype(int)) * idx)) indexes = np.random.permutation(samples.shape[0]) return samples[indexes] def xesmd(apps, idx): ''' Estimates symbolwise equivocation from reference symbols indices and a posteriori probabilities. ''' eq = -np.log(np.take_along_axis(apps, idx[:, None], axis=1) / np.transpose([np.sum(apps, 1)])) eq[eq == np.inf] = 1000 return np.mean(eq) n = 100_000 SNR_dBs = np.arange(5,22) np.arange(0,2.5,0.01).shape M = 8 plots_dict = np.empty(shape=(17,25000)) for idx, shaping in enumerate(np.arange(0,2.5,0.0001)): alphabet = np.arange(-7,8,2) alphabet = alphabet / np.sqrt(np.mean(alphabet**2)) scaling = (alphabet[1]-alphabet[0])/2 # scaling = 0.21821789023599236 # print('Scaling: ', scaling) denominator = np.sum(np.exp(-shaping*np.square(alphabet))) probs = 1/denominator * np.exp(-shaping*np.square(alphabet)) power = np.sum(np.square(np.arange(-7,8,2)*(scaling))*probs) # print('Power: ', power) indices = sampler(probs, n).astype(int) norm_factor = np.sqrt(np.sum(np.square(alphabet) * probs)) alphabet = alphabet / norm_factor symbols = alphabet[indices] scaling = (alphabet[1]-alphabet[0])/2 # print('Scaling: ', scaling) H = np.sum(-np.log2(probs)*probs) # print('Entropy: ',H) power = np.mean(symbols**2) # print('Power: ', power) # plt.rcParams['figure.figsize'] = [4, 4] # plt.hist(symbols, bins=100) # plt.show() for jdx, snrdB in enumerate(SNR_dBs): sigma2 = 1/(10**(snrdB/10)) sigma2 = sigma2 y = AWGN_channel(symbols, sigma2) apps = AWGNdemapper(y, alphabet, sigma2) xe = xesmd(apps, indices) plots_dict[jdx][idx] = (2*(H - (xe) / np.log(2))) print(np.max(plots_dict, 1).tolist()) mb = np.max(plots_dict, 1) mb = [2.0193916630846918, 2.2654022278277393, 2.5231306887622242, 2.7943201472250596, 3.0806359602235873, 3.3809640408051758, 3.69383842699387, 4.010358520455199, 4.318829495451576, 4.61704902872525, 4.895880050688773, 5.151007989533582, 5.376996748960784, 5.569021543421744, 5.722730806499707, 5.841398311333901, 5.9200053405287045] from numpy import genfromtxt my_data = genfromtxt('/home/ddeandres/Projects/internship_pcs/documentation/figs/mb_8_ask.csv', delimiter=',') plt.plot(my_data[:,0], my_data[:,1]) # Plot plt.rcParams['figure.figsize'] = [8, 6] for value in plots_dict: # print(key, value) plt.plot(SNR_dBs, mb) plt.plot(my_data[:,0], 2*my_data[:,1]) plt.plot(SNR_dBs, np.log2(1+10**(SNR_dBs/10)), color='black', label='Capacity') plt.grid() 解释代码,并进行注释,请注意,可以对代码进行规范化,但不要修改原本的结构。另外,将原本的信噪比SNR_dBs = np.arange(5,22)修改为仅包含5,10,15,20.增加星座点可视化,可参考下列代码: 3. 星座图可视化 plt.figure(figsize=(4, 4)) # 计算二维网格点(实部+虚部,本例为实数调制) alph = alphabet_norm.detach().numpy() a = np.array([(d, c) for c in np.flip(alph) for d in alph]) # 计算联合概率 joint_probs = (probs.reshape(-1, 1) * probs.reshape(1, -1)).flatten().detach().numpy() # 绘制散点图(点大小表示概率) plt.scatter(a[:, 0], a[:, 1], s=joint_probs * 2000, alpha=0.6) plt.title(“Constellation Diagram”) plt.xlabel(“In-phase”) plt.ylabel(“Quadrature”) # 保存为TikZ格式(用于LaTeX文档) tikzplotlib_save(f"aref_pcs_{SNR_dB}dB.tex") plt.show()
最新发布
08-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值