import math as m
import numpy as np
m.ceil(4.1)
5
m.ceil(4.99)
5
a = 4.1
b = 4.99
m.floor(a)
4
# redius to degress
m.degrees(2*m.pi)
360.0
m.radians(360)
6.283185307179586
m.exp(1)
2.718281828459045
m.fabs(-0.1)
0.1
m.factorial(4)
24
m.fsum([1,2,3])
6.0
m.fmod(20,3)
2.0
m.log(100,10)
2.0
m.sqrt(100)
10.0
m.pi
3.141592653589793
m.pow(2,3)
8.0
2**3
8
#线性代数实验
b = np.arange(1,12,2)
b
array([ 1, 3, 5, 7, 9, 11])
c = b.reshape(2,3)
c
array([[ 1, 3, 5],
[ 7, 9, 11]])
d = np.array(
[[0, 1, 2],
[2, 3, 4],
[5, 6, 7],
[3, 4, 6]])
d
array([[0, 1, 2],
[2, 3, 4],
[5, 6, 7],
[3, 4, 6]])
d.shape
(4, 3)
d.shape[0]
4
d.shape[1]
3
d
array([[0, 1, 2],
[2, 3, 4],
[5, 6, 7],
[3, 4, 6]])
d.T
array([[0, 2, 5, 3],
[1, 3, 6, 4],
[2, 4, 7, 6]])
A = np.arange(6).reshape(2,3)
A
array([[0, 1, 2],
[3, 4, 5]])
B = np.arange(6).reshape(3,2)
B
array([[0, 1],
[2, 3],
[4, 5]])
np.matmul(A,B)
array([[10, 13],
[28, 40]])
np.matmul(B,A)
array([[ 3, 4, 5],
[ 9, 14, 19],
[15, 24, 33]])
print(A*A)
[[ 0 1 4]
[ 9 16 25]]
print(A + A)
[[ 0 2 4]
[ 6 8 10]]
#矩阵求逆
A = np.arange(4).reshape(2,2)
A
array([[0, 1],
[2, 3]])
np.linalg.inv(A)
array([[-1.5, 0.5],
[ 1. , 0. ]])
#矩阵的特征值与特征向量
from scipy.linalg import eig
import numpy as np
import matplotlib.pyplot as plt
A = np.array(
[[1, 2],
[2, 1]])
A
array([[1, 2],
[2, 1]])
evals, evecs = eig(A)
evecs = evecs[:,0],evecs[:,1]
print('特征值为',evals,' 特征向量为', evecs)
特征值为 [ 3.+0.j -1.+0.j] 特征向量为 (array([0.70710678, 0.70710678]), array([-0.70710678, 0.70710678]))
fig, ax = plt.subplots()
for spine in ['left', 'bottom']:
ax.spines[spine].set_position('zero')
ax.grid(alpha = 0.4)
xmin, xmax = -3, 3
ymin, ymax = -3, 3
ax.set(xlim=(xmin, xmax), ylim=(ymin, ymax))
for v in evecs:
ax.annotate(text="", xy=v, xytext=(0, 0),
arrowprops=dict(facecolor='blue',
shrink=0,
alpha=0.6,
width=0.5))
x = np.linspace(xmin, xmax, 3)
for v in evecs:
a = v[1]/v[0]
ax.plot(x, a*x, 'r-', lw=0.4)
plt.show()
#求行列式
A
array([[1, 2],
[2, 1]])
print(np.linalg.det(A))
-2.9999999999999996
奇异值分解
#导入科学计算模块
import numpy as np
import matplotlib.pyplot as plt
#输入关键词
words = ["books","dad","stock","value","singular","estate","decomposition"]
#样本向量化,用来表示8个句子
X=np.array([[0,2,1,0,0,0,0],[2,0,0,1,0,1,0],[1,0,0,0,0,0,1],[0,0,1,0,0,0,0],[0,
1,0,0,0,0,0],[0,0,0,1,1,0,1],[0,1,0,0,1,0,0],[0,0,0,0,1,1,1]])
#进行SVD分解
U,s,Vh = np.linalg.svd(X)
#输出左奇异矩阵及shape
print('U = ',U)
print('U.shape',U.shape)
#输出奇异矩阵及shape
print('s = ',s)
print('s.shape',s.shape)
#输出右奇异矩阵及shape
print('Vh = ',Vh)
print('Vh.shape',Vh.shape)
U = [[-1.87135757e-01 -7.93624528e-01 2.45011855e-01 -2.05404352e-01
-3.19189120e-16 -5.57732834e-15 -2.57394431e-01 -4.08248290e-01]
[-6.92896814e-01 2.88368077e-01 5.67788037e-01 2.22142537e-01
2.54000254e-01 5.86234773e-15 -2.21623012e-02 -5.55111512e-17]
[-3.53233681e-01 1.22606651e-01 3.49203461e-02 -4.51735990e-01
-7.62000762e-01 -1.17246955e-14 2.72513448e-01 8.32667268e-17]
[-2.61369658e-02 -1.33189110e-01 7.51079037e-02 -6.44727454e-01
5.08000508e-01 -1.74851395e-14 3.68146235e-01 4.08248290e-01]
[-8.04993957e-02 -3.30217709e-01 8.49519758e-02 2.19661551e-01
-2.54000254e-01 6.03562003e-15 -3.12770333e-01 8.16496581e-01]
[-3.95029694e-01 1.56123876e-02 -5.28290830e-01 -6.82340484e-02
1.27000127e-01 -7.07106781e-01 -2.09360158e-01 -8.32667268e-17]
[-2.02089013e-01 -3.80395849e-01 -2.12899198e-01 4.80790894e-01
2.22044605e-16 1.29304240e-14 7.33466480e-01 1.11022302e-16]
[-3.95029694e-01 1.56123876e-02 -5.28290830e-01 -6.82340484e-02
1.27000127e-01 7.07106781e-01 -2.09360158e-01 -2.77555756e-17]]
U.shape (8, 8)
s = [2.85653844 2.63792139 2.06449303 1.14829917 1. 1.
0.54848559]
s.shape (7,)
Vh = [[-6.08788345e-01 -2.29949618e-01 -7.46612474e-02 -3.80854846e-01
-3.47325416e-01 -3.80854846e-01 -4.00237243e-01]
[ 2.65111314e-01 -8.71088358e-01 -3.51342402e-01 1.15234846e-01
-1.32365989e-01 1.15234846e-01 5.83153945e-02]
[ 5.66965547e-01 1.75382762e-01 1.55059743e-01 1.91316736e-02
-6.14911671e-01 1.91316736e-02 -4.94872736e-01]
[-6.48865369e-03 2.52237176e-01 -7.40339999e-01 1.34031699e-01
2.99854608e-01 1.34031699e-01 -5.12239408e-01]
[-2.54000254e-01 -2.54000254e-01 5.08000508e-01 3.81000381e-01
2.54000254e-01 3.81000381e-01 -5.08000508e-01]
[ 0.00000000e+00 7.90632607e-15 -2.28822292e-14 -7.07106781e-01
8.96165835e-15 7.07106781e-01 -1.53872902e-14]
[ 4.16034348e-01 -1.71550021e-01 2.01922906e-01 -4.22112199e-01
5.73845817e-01 -4.22112199e-01 -2.66564648e-01]]
Vh.shape (7, 7)
#规定坐标轴范围
plt.figure(0)
plt.axis([-0.8, 0.2, -0.8, 0.8])
for i in range(len(words)):
plt.text(U[i, 0], U[i, 1], words[i])
plt.show()
奇异值分解-图像压缩
import numpy as no
from pylab import *
import matplotlib.pyplot as plt
# 读取并保存灰度图像
img = imread('lena.jpg')[:,:,0]
plt.savefig('./lena_gray')
plt.gray()
plt.figure(0)
plt.imshow(img)
<matplotlib.image.AxesImage at 0x186553acb20>
<Figure size 432x288 with 0 Axes>
#读取并打印照片的长宽
m, n = img.shape
print(m ,n)
print(img.shape)
size = m * n
411 630
(411, 630)
# 将图片进行奇异值分解
U, s, Vh = np.linalg.svd(img)
# 将奇异值矩阵整理成对角阵
s = resize(s, [m,1])*eye(m,n)
# 取前k个向量压缩图像
k = 20
# 进行图像压缩
img_compress = np.dot(U[:,0:k],np.dot(s[0:k,0:k], Vh[0:k,:]))
plt.savefig('./lena_compress')
# 绘制压缩后的图像
plt.figure(1)
plt.imshow(img_compress)
print('img size', img.shape)
print('img_compress size', img_compress.shape)
img size (411, 630)
img_compress size (411, 630)
概率论实验
# 导入相应的库
import numpy as np
import scipy as sp
# 准备一组数据
ll = [[1,2,3,4,5,6], [3,4,5,6,7,8]]
b = [1,3,5,6]
#求所有元素均值
np.mean(ll)
4.5
#按列求均值
np.mean(ll,0)
array([2., 3., 4., 5., 6., 7.])
#按行求均值
np.mean(ll,1)
array([3.5, 5.5])
# 求b的方差
np.var(b)
3.6875
# 按行求方差
np.var(ll,1)
array([2.91666667, 2.91666667])
# 求标准差
np.std(ll)
1.9790570145063195
# 求b的协方差(样本方差,除以1/(N-1))
b = np.array(b)
c = b - np.mean(b)
print(np.sum(c*c)/(len(b)-1))
print(np.cov(b))
4.916666666666667
4.916666666666666
# 计算相关系数
Vb = [2,6,10,12]
Vc = [1,3,5,6]
np.corrcoef(Vb, Vc)
array([[1., 1.],
[1., 1.]])
二项分布
from scipy.stats import binom, norm, beta, expon
import numpy as np
import matplotlib.pyplot as plt
#n,p分别表示成功的次数和单次成功的概率,size表示实验次数
binom_sim = binom.rvs(n=10, p=0.5, size=1000000)
print('Data:', binom_sim)
print('Data Max:', np.max(binom_sim))
print('Data Mean:', np.mean(binom_sim))
print('Data Std:', np.std(binom_sim, ddof=1))
Data: [4 3 3 ... 5 4 6]
Data Max: 10
Data Mean: 5.000228
Data Std: 1.5807145367442053
#绘制直方图,x指定每个bin(箱子)分布的数据,对应x轴,binx是总共有几条带状图,normed值密度,也就是每个条状图的占比比例,默认为1
plt.hist(binom_sim, bins=10, density=True)
plt.xlabel('x')
plt.ylabel('density')
plt.show()
泊松分布实现
#观察事物平均发生m次的条件下,实际发生x次的概率P(X=x)可用下式表示:P(X=x) = ((m^x)/x!)*e^(-m)
import numpy as np
import matplotlib.pyplot as plt
#产生10000个 lamda = 2的泊松分布数据
X = np.random.poisson(lam=2, size=100000)
print(X)
print(np.mean(X))
print(np.max(X))
[3 3 5 ... 1 1 3]
1.99916
10
plt.hist(X, bins=10, density=True, range=[0,15])
plt.show()
正态分布
from scipy.stats import norm
import numpy as np
import matplotlib.pyplot as plt
# 生成随机数
X = np.random.normal(0,1,1000000)
mu = np.mean(X)
sigma = np.std(X)
print(mu, sigma)
print(np.max(X))
x = np.arange(-5,5,0.01)
y = norm.pdf(x, mu, sigma)
6.678083311634179e-05 0.9990922834989507
4.89772263589778
#绘制随机变量X的直方图
plt.hist(X, bins=50, density=True)
plt.plot(x,y)
plt.grid()
plt.show()
应用
图像加噪声
# 载入原始图片
from numpy import *
from scipy import *
import numpy as np
import cv2
original_img = cv2.imread('lena.jpg')
print(original_img.shape)
cv2.namedWindow('original image')
cv2.imshow('original image', original_img)
k = cv2.waitKey(0)
#灰度处理原始照片
gray_image = cv2.cvtColor(original_img, cv2.COLOR_BGR2GRAY)
print(gray_image.shape)
cv2.imshow('gray image', gray_image)
k = cv2.waitKey(0)
#加入高斯噪声
import matplotlib.pyplot as plt
image = np.array(gray_image/255.0, dtype=float)
percent = 0.01 #图像加入噪声的比例
num = int(image.shape[0]*image.shape[1]*percent)
for i in range(num):
temp1 = np.random.randint(image.shape[0])
temp2 = np.random.randint(image.shape[1])
mean = 0
std = 0.22
noise = np.random.normal(mean, std, 1)
image[temp1][temp2] += noise
out = image
if out.min() < 0:
low_clip = -1
else:
low_clip = 0
out = np.clip(out, low_clip, 1)
Gaussian_image = np.uint8(out*255)
cv2.imshow('Gaussian image', Gaussian_image)
k = cv2.waitKey(0)
(411, 630, 3)
(411, 630)