scipy:scipy依赖于numpy,提供了更多的数学工具,包括矩阵运算、线性方程组求解、积分、优化、插值、信号处理、图像处理、统计等等。
scipy在numpy的基础上增加了大量用于数学计算、科学计算以及工程计算的模块,包括线性代数、常微分方程数值求解、信号处理、图像处理、稀疏矩阵等等。
SciPy主要模块:
constants:常数
special:特殊函数
optimize:数值优化算法
interpolate插值
integrate:数值积分
signal:信号处理
ndimage : 图像处理,包括filters滤波器处理、fourier傅里叶变换模块、 interpolation图像差值模块、measurements图像测量模块,morphology形态学图像处理模块
stats:统计
misc:提供了读取图像文件的方法和一些测试图像
io:提供了读取Matlab和Fortran文件的方法
scipy的constants模块包含了大量用于科学计算的常数
>>> from scipy import constants as C
>>> C.pi # 圆周率
3.141592653589793
>>> C.golden # 黄金比例
1.618033988749895
>>> C.c # 真空中的光速
299792458.0
>>> C.h # 普朗克常数
6.62606896e-34
>>> C.mile # 一英里等于多少米
1609.3439999999998
>>> C.inch # 一英寸等于多少米
0.0254
>>> C.degree # 一度等于多少弧度
0.017453292519943295
>>> C.minute # 一分钟等于多少秒
60.0
>>> C.g # 标准重力加速度
9.80665
scipy的special模块包含了大量函数库,包括基本数学函数、特殊函数以及numpy中的所有函数。
>>> from scipy import special as S
>>> S.cbrt(8) # 立方根
2.0
>>> S.exp10(3) # 10**3
1000.0
>>> S.sindg(90) # 正弦函数,参数为角度
1.0
>>> S.round(3.1) # 四舍五入函数
3.0
>>> S.round(3.5)
4.0
>>> S.round(3.499)
3.0
>>> S.comb(5,3) # 从5个中任选3个的组合数
10.0
>>> S.perm(5,3) # 排列数
60.0
>>> S.gamma(4) # gamma函数
6.0
>>> S.beta(10, 200) # beta函数
2.839607777781333e-18
>>> S.sinc(0) # sinc函数
1.0
>>> S.sinc(1)
3.8981718325193755e-17
中值滤波
>>> import random
>>> import numpy as np
>>> import scipy.signal as signal
>>> x = np.arange(0,100,10)
>>> random.shuffle(x) # 打乱顺序
>>> x
array([40, 0, 60, 20, 50, 70, 80, 90, 30, 10])
>>> signal.medfilt(x,3) # 一维中值滤波
array([ 0., 40., 20., 50., 50., 70., 80., 80., 30., 10.])
>>> x = np.random.randint(1,1000,(4,4))
>>> x
array([[ 26, 153, 954, 490],
[855, 45, 186, 75],
[133, 764, 667, 802],
[318, 82, 988, 743]])
>>> signal.medfilt(x, (3,3)) # 二维中值滤波
array([[ 0., 45., 75., 0.],
[ 45., 186., 490., 186.],
[ 82., 318., 667., 186.],
[ 0., 133., 667., 0.]])
>>> x = np.float32(x)
>>> signal.medfilt2d(x) # 二维中值滤波,速度快一些
# 只支持Int8、Float32和Float64
array([[ 0., 45., 75., 0.],
[ 45., 186., 490., 186.],
[ 82., 318., 667., 186.],
[ 0., 133., 667., 0.]], dtype=float32)
#lena图像二维滤波
import numpy as np
from PIL import Image
import scipy.signal as signal
im = Image.open('lea.jpg')
data = []
width, height = im.size
读取图像像素值
for h in range(height):
row = []
for w in range(width):
value = im.getpixel((w,h))
row.append(value)
data.append(row)
二维中值滤波
data = np.float32(data)
data = signal.medfilt2d(data, (5,5))
创建并保存结果图像
for h in range(height):
for w in range(width):
im.putpixel((w,h), int(data[h][w]))
im.save('result.jpg')
signal模块包含大量滤波函数、B样条插值算法等等。
一维信号的卷积运算:
>>> import numpy as np
>>> x = np.array([1, 2, 3])
>>> h = np.array([4, 5, 6])
>>> import scipy.signal
>>> scipy.signal.convolve(x, h) # 一维卷积运算
array([ 4, 13, 28, 27, 18])
#一维信号的卷积运算
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
sig = np.random.randn(1000)
autocorr = signal.fftconvolve(sig, sig[::-1], mode='full') # 卷积运算
fig, (ax_orig, ax_mag) = plt.subplots(2, 1)
ax_orig.plot(sig) # 原始信号
ax_orig.set_title('White noise')
ax_mag.plot(np.arange(-len(sig)+1,len(sig)), autocorr) # 卷积后的图像
ax_mag.set_title('Autocorrelation')
fig.tight_layout()
fig.show()
#一维信号的卷积运算
import numpy as np
from scipy import misc, signal
import matplotlib.pyplot as plt
face = misc.face(gray=True)
# 100个点,5是标准差sigma
kernel = np.outer(signal.gaussian(100, 5), signal.gaussian(100, 5))
blurred = signal.fftconvolve(face, kernel, mode='same')
fig, (ax_orig, ax_kernel, ax_blurred) = plt.subplots(1, 3,
figsize=(15, 6))
ax_orig.imshow(face, cmap='gray')
ax_orig.set_title('Original')
# 不显示坐标轴
ax_orig.set_axis_off()
ax_kernel.imshow(kernel, cmap='gray')
ax_kernel.set_title('Gaussian kernel')
ax_kernel.set_axis_off()
ax_blurred.imshow(blurred, cmap='gray')
ax_blurred.set_title('Blurred')
ax_blurred.set_axis_off()
fig.show()
二维图像卷积运算。
import numpy as np
from scipy import signal
from scipy import misc
import matplotlib.pyplot as plt
face = misc.face(gray=True)
scharr = np.array([[ -3-3j, 0-10j, +3 -3j],
[-10+0j, 0+ 0j, +10 +0j],
[ -3+3j, 0+10j, +3 +3j]]) # Gx + j*Gy
grad = signal.convolve2d(face, scharr, boundary='symm', mode='same')
fig, (ax_orig, ax_mag) = plt.subplots(1, 2, figsize=(10, 6))
ax_orig.imshow(face, cmap='gray')
ax_orig.set_title('Original')
ax_orig.set_axis_off()
ax_mag.imshow(np.absolute(grad), cmap='gray')
ax_mag.set_title('Gradient magnitude')
ax_mag.set_axis_off()
fig.show()
import numpy as np
from scipy import signal
from scipy import misc
import matplotlib.pyplot as plt
face = misc.face(gray=True)
hrow = np.float32(signal.gaussian(50, 6.0))
hcol = np.float32(signal.gaussian(80, 3.0))
image_new = signal.sepfir2d(face, hrow, hcol) # 行和列使用不同的滤波器进行卷积
fig, (ax_orig, ax_mag) = plt.subplots(1, 2, figsize=(10, 6))
ax_orig.imshow(face, cmap='gray')
ax_orig.set_title('Original')
ax_orig.set_axis_off()
ax_mag.imshow(image_new, cmap='gray')
ax_mag.set_title('Gaussian Blur')
ax_mag.set_axis_off()
fig.show()
模块ndimage提供了大量用于N维图像处理的方法
(1)图像滤波
>>> from scipy import misc
>>> from scipy import ndimage
>>> import matplotlib.pyplot as plt
>>> face = misc.face() # face是测试图像之一
>>> plt.figure() # 创建图形
>>> plt.imshow(face) # 绘制测试图像
>>> plt.show() # 原始图像
>>> blurred_face = ndimage.gaussian_filter(face, sigma=7) # 高斯滤波
>>> plt.imshow(blurred_face)
>>> plt.show()
>>> blurred_face1 = ndimage.gaussian_filter(face, sigma=1) # 边缘锐化
>>> blurred_face3 = ndimage.gaussian_filter(face, sigma=3)
>>> sharp_face = blurred_face3 + 6*(blurred_face3-blurred_face1)
>>> plt.imshow(sharp_face)
>>> plt.show()
>>> median_face = ndimage.median_filter(face, 7) # 中值滤波
>>> plt.imshow(median_face)
>>> plt.show()
(2)数学形态学
import numpy as np
from scipy import ndimage
import matplotlib.pyplot as plt
square = np.zeros((32,32)) #全0数组
square[10:20, 10:20] = 1 # 把其中一部分设置为1
x, y = (32*np.random.random((2, 15))).astype(np.int) # 随机位置
square[x,y] = 1 # 把随机位置设置为1
x, y = (32*np.random.random((2, 15))).astype(np.int)
square[x,y] = 0 # 把随机位置设置为0
plt.imshow(square) # 原始随机图像
plt.title('original image')
plt.show()
eroded_square = ndimage.binary_erosion(square) # 腐蚀运算
plt.imshow(eroded_square)
plt.title('eroded image')
plt.show()
dilated_square = ndimage.binary_dilation(square) # 膨胀运算
plt.imshow(dilated_square)
plt.title('dilated image')
plt.show()
open_square = ndimage.binary_opening(square) # 开运算
plt.imshow(open_square)
plt.title('opened image')
plt.show()
closed_square = ndimage.binary_closing(square) # 闭运算
plt.imshow(closed_square)
plt.title('closed image')
plt.show()
plt.imshow(ndimage.binary_fill_holes(square)) # 填充孔洞
plt.title('fill holes')
plt.show()
(3)图像测量
>>> ndimage.measurements.maximum(face) # 最大值
255
>>> ndimage.measurements.maximum_position(face) # 最大值位置
(242, 560, 2)
>>> ndimage.measurements.extrema(face) # 最小值、最大值及其位置
(0, 255, (0, 883, 2), (242, 560, 2))
>>> ndimage.measurements.mean(face) # 平均值
110.16274388631184
>>> ndimage.measurements.median(face) # 中值
109.0
>>> ndimage.measurements.center_of_mass(face) # 重心
(356.67522474359157, 469.24020108368114, 0.97399718955108483)
>>> ndimage.measurements.sum(face)
259906521
>>> ndimage.measurements.variance(face) # 方差
3307.17544034096
>>> ndimage.measurements.standard_deviation(face) # 标准差
57.508046744268405
>>> ndimage.measurements.histogram(face, 0, 255, 256) # 直方图
(4)使用scipy进行多项式计算与符号计算
>>> from scipy import poly1d
>>> p1 = poly1d([1,2,3,4])
# 输出结果中,第一行的数字为第二行对应位置项中x的指数
>>> print(p1)
3 2
1 x + 2 x + 3 x + 4
# 等价于p2=(x-1)(x-2)(x-3)(x-4)
>>> p2 = poly1d([1,2,3,4], True)
>>> print(p2)
4 3 2
1 x - 10 x + 35 x - 50 x + 24
# 使用z作为变量
>>> p3 = poly1d([1,2,3,4], variable='z')
>>> print(p3)
3 2
1 z + 2 z + 3 z + 4
# 把多项式中的变量替换为指定的值
>>> p1(0)
4
>>> p1(1)
10
# 计算多项式对应方程的根
>>> p1.r
array([-1.65062919+0.j , -0.17468540+1.54686889j,
-0.17468540-1.54686889j])
>>> p1(p1.r[0])
(-8.8817841970012523e-16+0j)
# 查看和修改多项式的系数
>>> p1.c
array([1, 2, 3, 4])
>>> print(p3)
3 2
1 z + 2 z + 3 z + 4
>>> p3.c[0] = 5
>>> print(p3)
3 2
5 z + 2 z + 3 z + 4
# 查看多项式最高阶
>>> p1.order
3
# 查看指定指数对应的项的系数
# 例如,在p1多项式中,指数为3的项的系数为1
>>> p1[3]
1
>>> p1[0]
4
# 加、减、乘、除、幂运算
>>> print(p1)
3 2
1 x + 2 x + 3 x + 4
>>> print(-p1)
3 2
-1 x - 2 x - 3 x - 4
>>> print(p2)
4 3 2
1 x - 10 x + 35 x - 50 x + 24
>>> print(p1 + 3)
3 2
1 x + 2 x + 3 x + 7
>>> print(p1+p2)
4 3 2
1 x - 9 x + 37 x - 47 x + 28
>>> print(p1-5)
3 2
1 x + 2 x + 3 x - 1
>>> print(p2 - p1)
4 3 2
1 x - 11 x + 33 x - 53 x + 20
>>> print(p1 * 3)
3 2
3 x + 6 x + 9 x + 12
>>> print(p1*p2)
7 6 5 4 3 2
1 x - 8 x + 18 x - 6 x - 11 x + 38 x - 128 x + 96
>>> print(p1*p2/p2)
(poly1d([ 1., 2., 3., 4.]), poly1d([ 0.]))
>>> print(p2/p1)
(poly1d([ 1., -12.]), poly1d([ 56., -18., 72.]))
# #多项式的幂运算
>>> print(p1 ** 2)
6 5 4 3 2
1 x + 4 x + 10 x + 20 x + 25 x + 24 x + 16
>>> print(p1 * p1)
6 5 4 3 2
1 x + 4 x + 10 x + 20 x + 25 x + 24 x + 16
# 一阶导数
>>> print(p1.deriv())
2
3 x + 4 x + 3
# 二阶导数
>>> print(p1.deriv(2))
6 x + 4
# 多项式的不定积分
# 一重不定积分,设常数项为0
>>> print(p1.integ(m=1, k=0))
4 3 2
0.25 x + 0.6667 x + 1.5 x + 4 x
# 二重不定积分,设常数项为3
>>> print(p1.integ(m=2, k=3))
5 4 3 2
0.05 x + 0.1667 x + 0.5 x + 2 x + 3 x + 3
(5)稀疏矩阵
稀疏矩阵的常见存储形式
bsr_matrix(arg1[, shape, dtype, copy, blocksize]) Block Sparse Row matrix
coo_matrix(arg1[, shape, dtype, copy]) A sparse matrix in COOrdinate format.
csc_matrix(arg1[, shape, dtype, copy]) Compressed Sparse Column matrix
csr_matrix(arg1[, shape, dtype, copy]) Compressed Sparse Row matrix
dia_matrix(arg1[, shape, dtype, copy]) Sparse matrix with DIAgonal storage
dok_matrix(arg1[, shape, dtype, copy]) Dictionary Of Keys based sparse matrix.
lil_matrix(arg1[, shape, dtype, copy]) Row-based linked list sparse matrix
>>> from scipy import sparse
>>> sparse.bsr_matrix([[1,0,0,0,0],[0,1,0,0,1]])
<2x5 sparse matrix of type '<class 'numpy.int32'>'
with 3 stored elements (blocksize = 1x1) in Block Sparse Row format>
>>> sparse.coo_matrix([[1,0,0,0,0],[0,1,0,0,1]])
<2x5 sparse matrix of type '<class 'numpy.int32'>'
with 3 stored elements in COOrdinate format>
>>> sparse.csc_matrix([[1,0,0,0,0],[0,1,0,0,1]])
<2x5 sparse matrix of type '<class 'numpy.int32'>'
with 3 stored elements in Compressed Sparse Column format>
>>> sparse.csr_matrix([[1,0,0,0,0],[0,1,0,0,1]])
<2x5 sparse matrix of type '<class 'numpy.int32'>'
with 3 stored elements in Compressed Sparse Row format>
>>> sparse.dia_matrix([[1,0,0,0,0],[0,1,0,0,1]])
<2x5 sparse matrix of type '<class 'numpy.int32'>'
with 4 stored elements (2 diagonals) in DIAgonal format>
>>> sparse.dok_matrix([[1,0,0,0,0],[0,1,0,0,1]])
<2x5 sparse matrix of type '<class 'numpy.int32'>'
with 3 stored elements in Dictionary Of Keys format>
>>> sparse.lil_matrix([[1,0,0,0,0],[0,1,0,0,1]])
<2x5 sparse matrix of type '<class 'numpy.int32'>'
with 3 stored elements in LInked List format>
sparse模块中用于创建稀疏矩阵的函数
eye(m[, n, k, dtype, format]) Sparse matrix with ones on diagonal
identity(n[, dtype, format]) Identity matrix in sparse format
kron(A, B[, format]) kronecker product of sparse matrices A and B
kronsum(A, B[, format]) kronecker sum of sparse matrices A and B
diags(diagonals[, offsets, shape, format, dtype]) Construct a sparse matrix from diagonals.
spdiags(data, diags, m, n[, format]) Return a sparse matrix from diagonals.
block_diag(mats[, format, dtype]) Build a block diagonal sparse matrix from provided matrices.
tril(A[, k, format]) Return the lower triangular portion of a matrix in sparse format
triu(A[, k, format]) Return the upper triangular portion of a matrix in sparse format
bmat(blocks[, format, dtype]) Build a sparse matrix from sparse sub-blocks
hstack(blocks[, format, dtype]) Stack sparse matrices horizontally (column wise)
vstack(blocks[, format, dtype]) Stack sparse matrices vertically (row wise)
rand(m, n[, density, format, dtype, ...])Generate a sparse matrix of the given shape and density with
uniformly distributed values.
random(m, n[, density, format, dtype, ...]) Generate a sparse matrix of the given shape and density
with randomly distributed values.
>>> x = sparse.eye(5) # 5行5列单位矩阵
>>> x
<5x5 sparse matrix of type '<class 'numpy.float64'>'
with 5 stored elements (1 diagonals) in DIAgonal format>
>>> x.data # 查看非0元素
array([[ 1., 1., 1., 1., 1.]])
>>> x.toarray() # 返回数组形式
array([[ 1., 0., 0., 0., 0.],
[ 0., 1., 0., 0., 0.],
[ 0., 0., 1., 0., 0.],
[ 0., 0., 0., 1., 0.],
[ 0., 0., 0., 0., 1.]])
>>> x.sin() # 支持正弦、余弦等运算
<5x5 sparse matrix of type '<class 'numpy.float64'>'
with 5 stored elements (1 diagonals) in DIAgonal format>
>>> x.mean() # 平均值
0.20000000000000001
>>> x.dot([1,2,3,4,5]) # 内积
array([ 1., 2., 3., 4., 5.])
>>> x.getrow(0) # 返回第0行
<1x5 sparse matrix of type '<class 'numpy.float64'>'
with 1 stored elements in Compressed Sparse Row format>
>>> x.getcol(0) # 返回第0列
<5x1 sparse matrix of type '<class 'numpy.float64'>'
with 1 stored elements in Compressed Sparse Row format>
保存与读取
save_npz(file, matrix[, compressed]) # 把矩阵保存为.npz格式的文件
load_npz(file)
查找稀疏矩阵中非0元素的位置与值
>>> x = sparse.bsr_matrix([[1,0,0,0,0],[0,1,0,0,1]])
>>> x.nonzero() # 非0元素位置,(0,0), (1,1), (1,4)
(array([0, 1, 1]), array([0, 1, 4], dtype=int32))
>>> sparse.find(x) # 非0元素位置和值
(array([0, 1, 1], dtype=int32), array([0, 1, 4], dtype=int32), array([1, 1, 1], dtype=int32))
>>> x = sparse.bsr_matrix([[1,0,0,0,1],[0,1,0,0,1]])
>>> x.nonzero() # (0,0), (0,4), (1,1), (1,4)
(array([0, 0, 1, 1]), array([0, 4, 1, 4], dtype=int32))
>>> sparse.find(x) # 非0元素位置和值
(array([0, 0, 1, 1], dtype=int32), array([0, 4, 1, 4], dtype=int32), array([1, 1, 1, 1], dtype=int32))
最大值与最小值
>>> x = sparse.bsr_matrix([[1,0,0,0,0],[0,1,0,0,1]])
>>> x.max()
1
>>> x.min(axis=0)
<1x5 sparse matrix of type '<class 'numpy.int32'>'
with 0 stored elements in COOrdinate format>
>>> x.min(axis=1)
<2x1 sparse matrix of type '<class 'numpy.int32'>'
with 0 stored elements in COOrdinate format>
>>> x.min(axis=1).toarray()
array([[0],
[0]], dtype=int32)
其他运算
>>> x = sparse.bsr_matrix([[1,0,0,0,0],[0,1,0,0,1]])
>>> x.multiply([1,2,3,4,5]) # 矩阵相乘
matrix([[1, 0, 0, 0, 0],
[0, 2, 0, 0, 5]])
>>> y = sparse.csr_matrix([[1,2,3,4,5]])
>>> x.multiply(y)
<2x5 sparse matrix of type '<class 'numpy.int32'>'
with 3 stored elements (blocksize = 1x1) in Block Sparse Row format>
>>> x.multiply(y).toarray()
array([[1, 0, 0, 0, 0],
[0, 2, 0, 0, 5]], dtype=int32)
>>> x.todense()
matrix([[1, 0, 0, 0, 0],
[0, 1, 0, 0, 1]], dtype=int32)
>>> x = sparse.bsr_matrix([[1,0,0,0,0],[0,1,0,0,1]])
>>> x
<2x5 sparse matrix of type '<class 'numpy.int32'>'
with 3 stored elements (blocksize = 1x1) in Block Sparse Row format>
>>> x.transpose() # 矩阵转置
<5x2 sparse matrix of type '<class 'numpy.int32'>'
with 3 stored elements (blocksize = 1x1) in Block Sparse Row format>
>>> sparse.bsr_matrix([0.51, 0.49, -0.500001]).sign().toarray() # 取符号
array([[ 1., 1., -1.]])
>>> x = sparse.random(3,5,0.5) # 随机矩阵,第3个参数表示非0元素的密度
>>> x.toarray()
array([[ 0.96027078, 0. , 0.28842422, 0. , 0. ],
[ 0. , 0.1771073 , 0. , 0. , 0.04098001],
[ 0.06608547, 0. , 0.3017647 , 0. , 0.19837188]])
>>> y = sparse.random(3,5,0.3)
>>> y.todense()
matrix([[ 0. , 0.55672121, 0. , 0. , 0. ],
[ 0.4066913 , 0. , 0. , 0. , 0. ],
[ 0. , 0.17136966, 0.32564523, 0. , 0. ]])
>>> z = x+y # 稀疏矩阵的加法运算
>>> z
<3x5 sparse matrix of type '<class 'numpy.float64'>'
with 10 stored elements in Compressed Sparse Row format>
>>> z.toarray()
array([[ 0.96027078, 0.55672121, 0.28842422, 0. , 0. ],
[ 0.4066913 , 0.1771073 , 0. , 0. , 0.04098001],
[ 0.06608547, 0.17136966, 0.62740993, 0. , 0.19837188]])
>>> x = sparse.random(3,5,0.5)
>>> x.toarray()
array([[ 0.37946435, 0.78761652, 0. , 0.26951776, 0. ],
[ 0. , 0. , 0.26013362, 0. , 0. ],
[ 0.33730413, 0.30455492, 0. , 0.29026851, 0. ]])
>>> x.sqrt().toarray() # 平方根
array([[ 0.61600677, 0.88747762, 0. , 0.519151 , 0. ],
[ 0. , 0. , 0.51003296, 0. , 0. ],
[ 0.5807789 , 0.55186495, 0. , 0.53876573, 0. ]])
>>> x.power(2).toarray() # 幂运算
array([[ 0.14399319, 0.62033978, 0. , 0.07263982, 0. ],
[ 0. , 0. , 0.0676695 , 0. , 0. ],
[ 0.11377407, 0.0927537 , 0. , 0.08425581, 0. ]])
>>> x.diagonal() # 对角线元素
array([ 0.37946435, 0. , 0. ])
>>> x.floor().toarray() # 向下取整
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])
>>> x.ceil().toarray() # 向上取整
array([[ 1., 1., 0., 1., 0.],
[ 0., 0., 1., 0., 0.],
[ 1., 1., 0., 1., 0.]])
>>> x.rint().toarray() # 四舍五入
array([[ 0., 1., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])
>>> x.ndim # 维数
2
>>> x.shape # 大小
(3, 5)
>>> x.sum() # 求和
2.6288598085296888
>>> x.sum(axis=1) # 横向求和
matrix([[ 1.43659863],
[ 0.26013362],
[ 0.93212756]])
>>> x.sum(axis=0) # 纵向求和
matrix([[ 0.71676847, 1.09217144, 0.26013362, 0.55978627, 0. ]])
>>> x = sparse.csr_matrix([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
>>> sparse.triu(x).toarray() # 返回上三角稀疏矩阵,第二个参数默认为0
array([[ 1, 2, 3, 4],
[ 0, 6, 7, 8],
[ 0, 0, 11, 12]], dtype=int32)
>>> sparse.triu(x,1).toarray() # 第二个参数为1,非0元素向右上方收缩
array([[ 0, 2, 3, 4],
[ 0, 0, 7, 8],
[ 0, 0, 0, 12]], dtype=int32)
>>> sparse.triu(x,2).toarray() # 再收缩多一些
array([[0, 0, 3, 4],
[0, 0, 0, 8],
[0, 0, 0, 0]], dtype=int32)
>>> sparse.triu(x,3).toarray() # 再收缩多一些
array([[0, 0, 0, 4],
[0, 0, 0, 0],
[0, 0, 0, 0]], dtype=int32)
>>> sparse.tril(x,3).toarray() # 返回下三角稀疏矩阵,整数表示向右上方扩展
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]], dtype=int32)
>>> sparse.tril(x,0).toarray()
array([[ 1, 0, 0, 0],
[ 5, 6, 0, 0],
[ 9, 10, 11, 0]], dtype=int32)
>>> sparse.tril(x,-1).toarray() # 第二个参数为负数,非0元素下左下方收缩
array([[ 0, 0, 0, 0],
[ 5, 0, 0, 0],
[ 9, 10, 0, 0]], dtype=int32)
WAV文件处理
import numpy as np
from scipy.io import wavfile
# 让音乐重复两次
def doubleMusic(srcMusic, dstMusic):
data = wavfile.read(srcMusic)
dataDouble = np.array(list(data[1])*2)
wavfile.write(dstMusic, data[0], dataDouble)
# 音量降低一半
def halfMusic(srcMusic, dstMusic):
data = wavfile.read(srcMusic)
wavfile.write(dstMusic, data[0], data[1]//2)
# 淡入淡出
def fadeInout(srcMusic, dstMusic):
sampleRate, musicData = wavfile.read(srcMusic)
length = len(musicData)
n = 10
start = length//10
factors = tuple(map(lambda num: round(num/start, 1),
range(start)))
factors = factors + (1,)*(length-start*2) + factors[::-1]
musicData = np.array(tuple(map(lambda data, factor:
[np.int16(data[0]*factor),
np.int16(data[1]*factor)],
musicData, factors)))
wavfile.write(dstMusic, sampleRate, musicData)
# 分离左右声道
def splitChannel(srcMusic):
sampleRate, musicData = wavfile.read(srcMusic)
left = []
right = []
for item in musicData:
left.append(item[0])
right.append(item[1])
wavfile.write('left.wav', sampleRate, np.array(left))
wavfile.write('right.wav', sampleRate, np.array(right))
# 数据压缩
from scipy.io import wavfile
def compressMusic(srcMusic):
sampleRate, musicData = wavfile.read(srcMusic)
wavfile.write('new.wav', sampleRate//5, musicData[::5])
compressMusic('wait for you.wav')
from sympy import Symbol, solve
x = Symbol('x')
y1 = 1-3**x
y2 = 8-2**x
y3 = 1-x**2
print(solve(y1))
print(solve(y2))
print(solve(y3))
转载:https://blog.csdn.net/qq_43406976/article/details/104740103
查看评论