导航:首页 > 编程语言 > pythoncompute

pythoncompute

发布时间:2022-05-04 21:58:03

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)

阅读全文

与pythoncompute相关的资料

热点内容
压缩包制作后照片顺序怎么改 浏览:680
fibonacci数列算法 浏览:775
产品经理要和程序员吵架吗 浏览:252
grub2命令行 浏览:618
无法获取加密卡信息 浏览:774
云服务器网卡充值 浏览:509
编程就是软件 浏览:49
服务器如何添加权限 浏览:437
引用指针编程 浏览:851
手机加密日记本苹果版下载 浏览:63
命令行括号 浏览:176
java程序升级 浏览:490
排序算法之插入类 浏览:227
gcccreate命令 浏览:73
海尔监控用什么app 浏览:64
系统盘被压缩开不了机 浏览:984
linuxredis30 浏览:541
狸窝pdf转换器 浏览:696
ajax调用java后台 浏览:906
活塞式压缩机常见故障 浏览:615