Python常用包學習(三)——scipy
scipy主要是用於處理科學計算中的常見問題:插值、積分、優化、影象處理、統計、特殊函式等;
scipy主要是與numpy合作使用,有效的處理numpy中的資料;
下文只是一個簡介,幫助大家瞭解一下這個包,如果想深入瞭解,可以檢視如下頁面:
#!/usr/bin/env python
# _*_ UTF-8 _*_
import scipy
import numpy as np
'''1、IO操作:'''
from scipy import io as spio
# 資料的讀入和讀出:
# a = np.ones((3,3))
# spio.savemat('file.mat', {'a':a})
# data = spio.loadmat('file.mat', struct_as_record=True)
# print(data['a'])
# 圖片讀取:
# data = misc.imread('111.png')
# print(data.shape)
# 匯入txt檔案:
# np.loadtxt()
# np.savetxt()
# 智慧匯入txt、csv::
# np.genfromtxt()
# np.recfromcsv()
# 高速儲存資料:
# np.save()
# np.load()
'''2、特殊函式:'''
from scipy import special
# 貝塞爾函式:
# special.jn()
# 橢圓函式:
# special.ellipj()
'''3、線性代數運算:'''
from scipy import linalg
# 主要用到scipy.linalg:
# 行列式運算:
# arr = np.array([[1,2],[3,4]])
# print(linalg.det(arr))
# 求逆矩陣:
# iarr = linalg.inv(arr)
# print(iarr)
# 奇異值分解:
# arr = np.arange(9).reshape((3,3))+np.diag([1,0,1])
# print(arr)
# uarr, spec, vharr = linalg.svd(arr)
# print(uarr)
# print(spec)
# print(vharr)
# 通過svd的運算資料獲取到原始資料矩陣:
# sarr = np.diag(spec)
# svd_mat = uarr.dot(sarr).dot(vharr)
# print(svd_mat)
# 快速傅立葉變換:
# time_step = 0.02
# period = 5
# time_vec = np.arange(0, 20, time_step)
# sig = np.sin(2*np.pi/period*time_vec)+0.5*np.random.randn(time_vec.size)
# print(sig)
'''4、優化和擬合:'''
# 主要是根據一些函式來確定最優質,或者通過資料來確認函式的一些引數:
# 找到最小值或等式的數值解的問題
from scipy import optimize
import matplotlib.pyplot as plt
# def f(x):
# return x**2 + 10*np.sin(x)
# x = np.arange(-10, 10, 0.1)
# plt.plot(x, f(x))
# plt.show()
# 找到最優值:0為初始點
# print(optimize.fmin_bfgs(f, 0, disp=0))
# 如果不知道初始值改怎麼設定,則可以給定一個範圍grid,然後蠻力運算所有範圍內的值:
# grid = (-10, 10, 0.1)
# xmin_global = optimize.brute(f, (grid,))
# print(xmin_global)
# 找到區域性最小值(0,10)範圍內:
# xmin_local = optimize.fminbound(f, 0, 10)
# print(xmin_local)
# 找到f(x)=0的根:2為初始值
# root = optimize.fsolve(f, 2)
# print(root)
# 曲線擬合:
# 最小二乘法來進行擬合:
# xdata = np.linspace(-10, 10, num=20)
# ydata = f(xdata)+np.random.randn(xdata.size)
# def f2(x, a, b):
# return a*x**2 + b*np.sin(x)
# guess = [2,2] # 初始值
# params, params_covariance = optimize.curve_fit(f2, xdata, ydata, guess)
# print(params)
# print(params_covariance)
'''5、統計與隨機數'''
from scipy import stats
# 直方圖與概率密度函式:
# a = np.random.normal(size=1000)
# bins = np.arange(-4, 5)
# # print(bins)
# histogram = np.histogram(a, bins=bins, normed=True)[0]
# bins = 0.5*(bins[1:]+bins[:-1])
# print(bins)
# b = stats.norm.pdf(bins)
# plt.plot(bins, histogram)
# plt.plot(bins, b)
# plt.show()
# 求中位數(也叫做50百分位點):
# a = np.random.normal(size=1000)
# print(np.median(a))
# 計算90百分位點:
# print(stats.scoreatpercentile(a, 90))
# b = np.random.normal(1,1,size=10)
# T檢驗來決定兩個樣本是否顯著性差異:
# print(stats.ttest_ind(a,b))
# pvalue:是指兩個過程相同的概率,越接近0,兩個過程越可能有不同的均值;越接近1,這兩個過程幾乎完全一樣;
# statistic:與兩個隨機過程之間成比例,並且幅度和差異之間顯著程度有關。
'''6、插值:'''
# 從各個樣本點穿過,即將各個點串聯在一起
from scipy import interpolate as iplt
# 原始的值:
# x = np.linspace(0, 4, 12)
# y = np.cos(x**2/3+4)
# print(x)
# print(y)
# plt.plot(x, y, 'o')
# plt.show()
# f1 = iplt.interp1d(x, y, kind='cubic')
# f2 = iplt.interp1d(x, y, kind='cubic')
# 新的值插入到x,y中,然後建立新的函式f1;
# xnew = np.linspace(0, 4, 300)
# 在xy的基礎上插入新的值,然後建立新的函式f1
# plt.plot(x, y, 'o', xnew, f1(xnew)) # , '-', xnew, f2(xnew), '--'
# plt.legend(['data','linear','cubic','nearest'], loc='best')
# plt.show()
'''7、積分計算:'''
from scipy.integrate import quad
# res, err = quad(np.sin, 0, np.pi/2)
# res:積分值;
# err:積分值絕對誤差估計值;
'''8、影象處理'''
from scipy import ndimage
from scipy import misc
from scipy.misc import imread, imsave, imresize
from scipy.spatial.distance import pdist, squareform, cdist
# 影象的幾何變換:
# img = imread("111.png")
# img_type = img.dtype
# print(img_type)
# img_shape = img.shape
# print(img_shape) # [高, 寬, 通道]
# img_tint = img*[1, 0.9, 0.9]
# img_resize = imresize(img, (5, 5))
# print(type(img_resize))
# l1 = np.array([1,2,3,4])
# l2 = np.array([3,47,8,10])
# np.savetxt('1111',(l1, l2))
# print(img_resize)
# imsave("111_color.png", img_resize)
# np.savetxt("1111.txt", img_resize)
'''9、計算兩點之間的距離:'''
# x1 = np.array([[1,1]])
# x2 = np.array([[4,5]])
# distance = cdist(x1, x2, "euclidean")
# print(distance)