① python怎麼使用cython
1. Cython是什麼?
它是一個用來快速生成Python擴展模塊(extention mole)的工具
語法是Python和c的混血
Cython作為一個Python的編譯器,在科學計算方面很流行,用於提高Python的速度,通過OpenMPI庫還可以進行吧並行計算。
2. Cython安裝(Windows)
我的環境是win7 x64, python27, vs2010
安裝的基礎是有一個c編譯器(這里以vs2010為例)
從http://cython.org下載安裝包,解壓到一目錄,進入該目錄,在cmd命令行中執行
python setup.py install
註:執行過程可能遇到問題:Windows下pip安裝包報錯:Microsoft Visual C++ 9.0 is required Unable to find vcvarsall.bat
解決方案:下載Microsoft Visual C++ Compiler for Python 2.7,點擊直接安裝即可。
3. 例子
例3.1:入門
創建hello.pyx,內容如下
def say_hello():
print "Hello World!"
創建setup.py,內容如下
from distutils.core import setup
from Cython.Build import cythonize
setup(name = 'Hello world app',
ext_moles = cythonize("hello.pyx"))
編譯Cython代碼
step1: 把.pyx文件被Cython便以為.c文件
step2: 把.c文件編譯為可導入的使用模塊.so(Windows下為.pyd)文件
1
2
python setup.py build
python setup.py install
註:可能出現問題:Unable to find vcvarsall.bat
原因:Python 2.7 會搜索 Visual Studio 2008.如果你電腦上沒有這個版本的話就會報錯。
如果裝的是vs2010,那麼在cmd命令行中執行
1
SET VS90COMNTOOLS=%VS100COMNTOOLS%
如果裝的是vs2010,那麼在cmd命令行中執行
1
SET VS90COMNTOOLS=%VS110COMNTOOLS%
執行
1
2
3
>>> import hello
>>> hello.say_hello()
Hello World!例3.2 通過靜態類型提高速度
在Cython中可以通過標記靜態類型來提高速度,凡是標記為靜態類型的部分都會將動態語言類型變為簡單的c代碼,從而提速。
但是如果濫用靜態類型,會降低可讀性,甚至因類型設置不當導致錯誤類型檢查造成速度降低。
例3.2.1 靜態類型變數
Python原生態代碼
compute.pyx
def f(x):
return x ** 2 - x
def integrate_f(a, b, N):
s = 0
dx = (b - a) / N
for i in range(N):
x += f(a + i * dx)
return s * dx
setup.py
from distutils.core import setup
from Cython.Build import cythonize
setup(
name = 'Hello world app',
ext_moles = cythonize("compute.pyx"),
)
test.py
import compute
import time
starttime = time.clock()
compute.integrate_f(3.2, 6.9, 1000000)
endtime = time.clock()
print "read: %f s" %(endtime - starttime)
執行
1
2
3
python setup.py build
python setup.py install
python test.py
結果
1
read: 0.332332 s
使用靜態變數替換後的代碼
compute2.pyx
def f(double x):
return x ** 2 - x
def integrate_f(double a, double b, int N):
cdef int i
cdef double s, dx
s = 0
dx = (b - a) / N
for i in range(N):
s += f(a + i * dx)
return s * d
setup2.py
from distutils.core import setup
from Cython.Build import cythonize
setup(
name = 'Hello world app',
ext_moles = cythonize("compute2.pyx"),
)
test2.py
import compute2
import time
starttime = time.clock()
compute2.integrate_f(3.2, 6.9, 1000000)
endtime = time.clock()
print "read: %f s" %(endtime - starttime)
執行
1
2
3
python setup.py build
python setup.py install
python test.py
結果
1
read: 0.109200s
結論
該測試用例,使用靜態類型速度是不使用靜態類型的3倍。
例3.2.2 靜態類型函數
把compute2.pyx中的函數變為
cdef double f(double x):
return x ** 2 - x
def integrate_f(double a, double b, int N):
cdef int i
cdef double s, dx
s = 0
dx = (b - a) / N
for i in range(N):
s += f(a + i * dx)
return s * dx
結果
1
read: 0.084859 s
結論:比例子3.2.1速度又快了
例3.3 調用C函數
cdef extern from "math.h":
double sin(double)
double cos(double)
cpdef double Sin(double x):
return sin(x)
cpdef double Cos(double x):
return cos(x)
cpdef: 對於Python可使用的函數使用(為了使得在以後的Python程序中調用Sin,Cos函數,用cpdef,而不用cdef)
cdef: 對於C可使用的函數使用
請注意,上面的代碼聲明了 math.h 里的函數,提供給 Cython 使用。C編譯器在編譯時將會看到 math.h 的聲明,但 Cython 不會去分析 math.h 和單獨的定義。
② 用python計算表格數據,分組
不知道理解題意是否正確,見如下代碼:
group1={}
group2={}
foriteminraw_items_list:
ifitem['prov1']notingroup1.keys():
group1[item['prov1']]=list()
else:
group1[item['prov1']].append((item['count'],item['value']))
ifitem['prov2']notingroup2.keys():
group2[item['prov2']]=list()
else:
group2[item['prov2']].append((item['count'],item['value']))
#
forgingroup1.keys():
value_list=group1[g]
count=0.0
value=0.0
forvinvalue_list:count+=v[0]
forvinvalue_list:value+=v[0]/count*v[1]
print'Averageofgroup1-%sis:%f'(g,value/len(value_list))
#averageofgroup2
#...
③ 有一張人臉的側臉圖像,如何用python及相關的庫來計算人臉轉過的角度。
這個很難辦到,不過可以通過判斷關鍵點的特點進行判斷,但是准確率不高
前言
很多人都認為人臉識別是一項非常難以實現的工作,看到名字就害怕,然後心懷忐忑到網上一搜,看到網上N頁的教程立馬就放棄了。這些人里包括曾經的我自己。其實如果如果你不是非要深究其中的原理,只是要實現這一工作的話,人臉識別也沒那麼難。今天我們就來看看如何在40行代碼以內簡單地實現人臉識別。
一點區分
對於大部分人來說,區分人臉檢測和人臉識別完全不是問題。但是網上有很多教程有無無意地把人臉檢測說成是人臉識別,誤導群眾,造成一些人認為二者是相同的。其實,人臉檢測解決的問題是確定一張圖上有木有人臉,而人臉識別解決的問題是這個臉是誰的。可以說人臉檢測是是人識別的前期工作。今天我們要做的是人臉識別。
所用工具
Anaconda 2——Python 2
Dlib
scikit-image
Dlib
對於今天要用到的主要工具,還是有必要多說幾句的。Dlib是基於現代C++的一個跨平台通用的框架,作者非常勤奮,一直在保持更新。Dlib內容涵蓋機器學習、圖像處理、數值演算法、數據壓縮等等,涉獵甚廣。更重要的是,Dlib的文檔非常完善,例子非常豐富。就像很多庫一樣,Dlib也提供了Python的介面,安裝非常簡單,用pip只需要一句即可:
pip install dlib
上面需要用到的scikit-image同樣只是需要這么一句:
pip install scikit-image
註:如果用pip install dlib安裝失敗的話,那安裝起來就比較麻煩了。錯誤提示很詳細,按照錯誤提示一步步走就行了。
人臉識別
之所以用Dlib來實現人臉識別,是因為它已經替我們做好了絕大部分的工作,我們只需要去調用就行了。Dlib裡面有人臉檢測器,有訓練好的人臉關鍵點檢測器,也有訓練好的人臉識別模型。今天我們主要目的是實現,而不是深究原理。感興趣的同學可以到官網查看源碼以及實現的參考文獻。今天的例子既然代碼不超過40行,其實是沒啥難度的。有難度的東西都在源碼和論文里。
首先先通過文件樹看一下今天需要用到的東西:
准備了六個候選人的圖片放在candidate-faces文件夾中,然後需要識別的人臉圖片test.jpg。我們的工作就是要檢測到test.jpg中的人臉,然後判斷她到底是候選人中的誰。另外的girl-face-rec.py是我們的python腳本。shape_predictor_68_face_landmarks.dat是已經訓練好的人臉關鍵點檢測器。dlib_face_recognition_resnet_model_v1.dat是訓練好的ResNet人臉識別模型。ResNet是何凱明在微軟的時候提出的深度殘差網路,獲得了 ImageNet 2015 冠軍,通過讓網路對殘差進行學習,在深度和精度上做到了比
CNN 更加強大。
1. 前期准備
shape_predictor_68_face_landmarks.dat和dlib_face_recognition_resnet_model_v1.dat都可以在這里找到。
然後准備幾個人的人臉圖片作為候選人臉,最好是正臉。放到candidate-faces文件夾中。
本文這里准備的是六張圖片,如下:
她們分別是
然後准備四張需要識別的人臉圖像,其實一張就夠了,這里只是要看看不同的情況:
可以看到前兩張和候選文件中的本人看起來還是差別不小的,第三張是候選人中的原圖,第四張圖片微微側臉,而且右側有陰影。
2.識別流程
數據准備完畢,接下來就是代碼了。識別的大致流程是這樣的:
3.代碼
代碼不做過多解釋,因為已經注釋的非常完善了。以下是girl-face-rec.py
# -*- coding: UTF-8 -*-
import sys,os,dlib,glob,numpy
from skimage import io
if len(sys.argv) != 5:
print "請檢查參數是否正確"
exit()
# 1.人臉關鍵點檢測器
predictor_path = sys.argv[1]
# 2.人臉識別模型
face_rec_model_path = sys.argv[2]
# 3.候選人臉文件夾
faces_folder_path = sys.argv[3]
# 4.需識別的人臉
img_path = sys.argv[4]
# 1.載入正臉檢測器
detector = dlib.get_frontal_face_detector()
# 2.載入人臉關鍵點檢測器
sp = dlib.shape_predictor(predictor_path)
# 3. 載入人臉識別模型
facerec = dlib.face_recognition_model_v1(face_rec_model_path)
# win = dlib.image_window()
# 候選人臉描述子list
descriptors = []
# 對文件夾下的每一個人臉進行:
# 1.人臉檢測
# 2.關鍵點檢測
# 3.描述子提取
for f in glob.glob(os.path.join(faces_folder_path, "*.jpg")):
print("Processing file: {}".format(f))
img = io.imread(f)
#win.clear_overlay()
#win.set_image(img)
# 1.人臉檢測
dets = detector(img, 1)
print("Number of faces detected: {}".format(len(dets)))
for k, d in enumerate(dets):
# 2.關鍵點檢測
shape = sp(img, d)
# 畫出人臉區域和和關鍵點
# win.clear_overlay()
# win.add_overlay(d)
# win.add_overlay(shape)
# 3.描述子提取,128D向量
face_descriptor = facerec.compute_face_descriptor(img, shape)
# 轉換為numpy array
v = numpy.array(face_descriptor)
descriptors.append(v)
# 對需識別人臉進行同樣處理
# 提取描述子,不再注釋
img = io.imread(img_path)
dets = detector(img, 1)
dist = []
for k, d in enumerate(dets):
shape = sp(img, d)
face_descriptor = facerec.compute_face_descriptor(img, shape)
d_test = numpy.array(face_descriptor)
# 計算歐式距離
for i in descriptors:
dist_ = numpy.linalg.norm(i-d_test)
dist.append(dist_)
# 候選人名單
candidate = ['Unknown1','Unknown2','Shishi','Unknown4','Bingbing','Feifei']
# 候選人和距離組成一個dict
c_d = dict(zip(candidate,dist))
cd_sorted = sorted(c_d.iteritems(), key=lambda d:d[1])
print "\n The person is: ",cd_sorted[0][0]
dlib.hit_enter_to_continue()
4.運行結果
我們在.py所在的文件夾下打開命令行,運行如下命令
python girl-face-rec.py 1.dat 2.dat ./candidate-faecs test1.jpg
由於shape_predictor_68_face_landmarks.dat和dlib_face_recognition_resnet_model_v1.dat名字實在太長,所以我把它們重命名為1.dat和2.dat。
運行結果如下:
The person is Bingbing。
記憶力不好的同學可以翻上去看看test1.jpg是誰的圖片。有興趣的話可以把四張測試圖片都運行下試試。
這里需要說明的是,前三張圖輸出結果都是非常理想的。但是第四張測試圖片的輸出結果是候選人4。對比一下兩張圖片可以很容易發現混淆的原因。
機器畢竟不是人,機器的智能還需要人來提升。
有興趣的同學可以繼續深入研究如何提升識別的准確率。比如每個人的候選圖片用多張,然後對比和每個人距離的平均值之類的。全憑自己了。
④ python中這題怎麼做
這題很簡單啊,搞得還要加註釋,不知道怎麼加了都,具體代碼自己看吧
#定義支付計算機類
classPayCalculator:
#初始化方法,設定每小時工資
def__init__(self):
self.pay_rate=100
#計算方法,輸入工作時長,返回應付工資
defcompute_pay(self,hours):
returnself.pay_rate*hours
#定義一個支付計算機類對象
a=PayCalculator()
#計算默認每小時工資時,10小時工作時長應付工資
print(a.compute_pay(10))
#設定每小時工資
a.pay_rate=20
print(a.compute_pay(10))
⑤ python作業 函數計算圖形面積之和
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from math import pi
import logging
class Geometrie(object):
"""docstring for Geometrie"""
def __init__(self):
pass
def say(self):
print self.__class__.__name__
def compute_area(self):
pass
def compute_circumference(self):
pass
def say_cirumfrerence(self):
print "%s 's cirumfrerence is: %f" % (self.__class__.__name__, self.compute_circumference())
def say_area(self):
print "%s 's cirumfrerence is: %f" % (self.__class__.__name__, self.compute_area())
class Ellipse(Geometrie):
"""docstring for Ellipse"""
def __init__(self,major_axis, minor_axis):
"""
major_axis is a
minor_axis is b
"""
super(Ellipse, self).__init__()
if not (isNum(major_axis) and isNum(minor_axis)):
raise Exception("TypeError: Please make sure the major:
{0!r} and minor {1!r} axis are correct.".format(major_axis, minor_axis))
else:
self.a=major_axis
self.b=minor_axis
def compute_circumference(self):
q=self.a+self.b
h=(abs((self.a-self.b)/(self.a-self.b)))**2
m=22/(7*pi)-1
n=(abs((self.a-self.b)/self.a))**(33.397)
return pi*q*(1+3*h/(10+(4-3*h)**(0.5)))*(1+m*n)
def compute_area(self):
return self.a*self.b*pi
class Square(Geometrie):
"""
docstring for Square"Geometrie
"""
def __init__(self, length, width):
super(Square,self).__init__()
if not (isNum(length) and isNum(width)):
raise Exception("TypeError: Please make sure the length:
{0!r} and width {1!r} axis are correct.".format(length, width))
else:
self.a = length
self.b = width
def compute_circumference(self):
return 2*(self.a+self.b)
def compute_area(self):
return self.a*self.b
class Circle(Geometrie):
"""docstring for Circle"""
def __init__(self, radius):
super(Circle, self).__init__()
if not (isNum(radius)):
raise Exception("TypeError: Please make sure the radius:
{0!r} is correct.".format(radius))
else:
self.r = radius
def compute_circumference(self):
return (2*self.r)*pi
def compute_area(self):
return pi*(self.r**2)
def isNum(value):
try:
value + 1
except TypeError:
return False
else:
return True
def main():
"""
docstring for main
"""
Es = Ellipse(2,1)
Es.say_cirumfrerence()
Es.say_area()
Sq = Square(2,1)
Sq.say_cirumfrerence()
Sq.say_area()
Cr = Circle(4)
Cr.say_cirumfrerence()
Cr.say_area()
if __name__ == '__main__':
main()
⑥ 在python函數里,不用return,怎麼把值送出來
題主好. 如果不用 return, 我們可以選擇利用傳遞參數的引用來『把值送出來』, 但這樣只能針對不變對象, 如字典, 列表, numpy 數組等等. 例如我們可以用如下代碼修改 numpy 數組:
mat = numpy.zeros((3,3))
compute_matrix( mat )
我們可以定義函數 compute_matrix 來修改參數 mat 的值, 並在這個函數結束後返回, 可以不用 return.
python 參數傳遞 (傳值或傳引用). 這篇博文將 python 中參數傳遞的情況, 什麼時候傳值什麼時候傳引用, 解釋地很清楚, 具體地:
如果函數收到的是一個可變對象(比如字典或者列表)的引用,就能修改對象的原始值--相當於通過「傳引用」來傳遞對象。
如果函數收到的是一個不可變對象(比如數字、字元或者元組)的引用,就不能直接修改原始對象--相當於通過「傳值'來傳遞對象。
⑦ python菜鳥求解…各位大大謝謝了!
compute_frequencies 是個函數名 下劃線可以做為變數名的一部分
for word,freq in freqs:
print word,freq
freqs是個iterable對象 例如[(1,2), (3,4)] for循環第一次取word=1,freq=2,列印;第二次word=3,freq=4,列印
word,freq 構成tuple類型對象 省去了括弧 和(word,freq)一樣
看你給的代碼 page=download page 好像有問題 方便的話把全部代碼貼上來吧
----------------
page=download page 這個應該有問題 你再好好看看書吧
⑧ python 已知本金,收益,年限,計算利率
利息=本金×利率×時間
--> 利率 = 利息 / (本金 * 時間)
'''
利率: x
本金: m
時間: t
利息: y
'''
def compute(m, y, t):
return y/(m*t)