计算鸢尾花花瓣长度的最大值,平均值,中值,均方差。
import numpy as np
from sklearn.datasets import load_iris
data = load_iris()
iris = data['data'][:,2]
print(iris)
d1 = np.max(iris)#最大值
d2 = np.min(iris)#最小值
d3 = np.mean(iris)#平均值
d4 = np.std(iris)#标准差
d5 = np.median(iris)#中位数
d6 = np.var(iris)#均方差
print('最大值:',d1,'最小值:',d2,'平均值:',d3,'标准差:',d4,'中位数:',d5,'均方差:',d6)
运行结果:
[1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 1.5 1.6 1.4 1.1 1.2 1.5 1.3 1.4 1.7 1.5 1.7 1.5 1. 1.7 1.9 1.6 1.6 1.5 1.4 1.6 1.6 1.5 1.5 1.4 1.5 1.2 1.3 1.5 1.3 1.5 1.3 1.3 1.3 1.6 1.9 1.4 1.6 1.4 1.5 1.4 4.7 4.5 4.9 4. 4.6 4.5 4.7 3.3 4.6 3.9 3.5 4.2 4. 4.7 3.6 4.4 4.5 4.1 4.5 3.9 4.8 4. 4.9 4.7 4.3 4.4 4.8 5. 4.5 3.5 3.8 3.7 3.9 5.1 4.5 4.5 4.7 4.4 4.1 4. 4.4 4.6 4. 3.3 4.2 4.2 4.2 4.3 3. 4.1 6. 5.1 5.9 5.6 5.8 6.6 4.5 6.3 5.8 6.1 5.1 5.3 5.5 5. 5.1 5.3 5.5 6.7 6.9 5. 5.7 4.9 6.7 4.9 5.7 6. 4.8 4.9 5.6 5.8 6.1 6.4 5.6 5.1 5.6 6.1 5.6 5.5 4.8 5.4 5.6 5.1 5.1 5.9 5.7 5.2 5. 5.2 5.4 5.1] 最大值: 6.9 最小值: 1.0 平均值: 3.758666666666666 标准差: 1.7585291834055212 中位数: 4.35 均方差: 3.092424888888889
用np.random.normal()产生一个正态分布的随机数组,并显示出来。
print(np.random.normal(1,5,50))
运行结果:
[-5.10198013e-01 -1.81127171e+00 5.34966309e-03 5.24510514e-01 2.07924729e+00 -3.45949650e-01 -1.87590835e+00 -5.90793739e+00 4.03057879e+00 -5.35822967e+00 -4.85137851e+00 3.66594079e-01 2.90050275e+00 3.98166421e+00 6.01702926e-01 -3.82470992e-01 1.42019409e+00 3.11379512e+00 1.58160501e+00 3.70511275e-01 1.26240090e+01 -2.34050982e-02 -3.31556855e+00 -8.31884546e-01 1.03108864e+01 -2.64570955e+00 5.03789132e-01 -1.54695868e+00 2.33496569e+00 4.48225666e+00 6.97529467e+00 5.93501594e-01 9.51437532e+00 -1.63662989e+00 2.78086368e+00 -3.39023516e+00 -5.36499527e+00 6.20385466e+00 7.60688118e+00 9.90523253e+00 -3.28345342e+00 1.13692427e+01 -6.43695936e-01 1.52830168e+00 3.08966939e+00 3.62968008e-01 -7.30428859e+00 7.38387038e+00 -3.37837186e+00 -9.59828248e+00]
用np.random.randn()产生一个正态分布的随机数组,并显示出来。
print(np.random.randn(5,5))
运行结果:
[[ 0.33772723 1.01557765 -0.90059905 0.07573804 -0.079598 ] [ 0.42330696 0.03920182 -0.26022139 1.71730775 1.29189732] [-3.30138842 -1.52347219 -1.76926508 -1.05615513 1.08341371] [ 0.47337674 -0.12343634 -0.46157369 0.06619216 0.92866926] [-0.70744157 -0.18383115 -1.66756331 0.81238919 -1.90095927]]
显示鸢尾花花瓣长度的正态分布图,曲线图,散点图。
正态分布图
import numpy as np
import matplotlib.pyplot as plt
mu = 1 #期望值为1
sigma = 3 #标准差为3
num = 10000 #个数为10000
rand_data = np.random.normal(mu,sigma,num)
print(rand_data.shape,type(rand_data))
count,bins,ignored = plt.hist(rand_data,30,normed = True)
plt.plot(bins,1/(sigma*np.sqrt(2*np.pi))*np.exp(-(bins-mu)**2/(2*sigma**2)),linewidth = 2,color = 'r')
plt.show()
运行结果:
曲线图
import numpy as np
import matplotlib.pyplot as plt
plt.plot(np.linspace(0,150,num=150),petal_length,'r')
plt.show()
运行结果:
散点图
plt.scatter(np.linspace(0,200,num=150),petal_length,alpha=1,marker='x',color = 'r')
plt.show()
运行结果: