#font.sans-serif: Microsoft YaHei, DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
简单记录一下python修饰符@的理解和使用方法,一直没好好理解,现在卡住了。。。参考wiki的定义, A decorator is any callable Python object that is used to modify a function, method or class defination. The decorator syntax is pure syntactic sugar, using @ as the keyword.即python修饰符作为一种python对象,用来修饰函数、方法或者类。
参考Wiki,我们简单实现一个修饰符的样例,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
defcalculator(f):
print("Begin...")
a = 3.0
b = 2.0
f(a,b)
print("End")
@calculator
defcalc_add(a,b):
print("%.2f + %.2f = %.2f" % (a,b,a+b))
@calculator
defcalc_minus(a,b):
print("%.2f - %.2f = %.2f" % (a,b,a-b))
在ipython环境下执行,有如下结果,
1
2
3
4
5
6
Begin...
3.00 + 2.00 = 5.00
End
Begin...
3.00 - 2.00 = 1.00
End
所以,修饰符的用途,等价于如下情形,
1
2
3
4
5
6
7
>>> a = 3.0, b = 2.0
>>> print("Begin...")
>>> calc_add(a,b)
>>> print("End")
>>> print("Begin...")
>>> calc_minus(a,b)
>>> print("End")
最直观的理解就是decorator简化了calculator()中的部分代码。正如wiki中的解释:Decorators are a form of metaprogramming; they enhance the action of the function or method they decorate.
Happy new year!! Feel blue but still have to work.
I am gonna introduce the application of a famous package namely libsvm, which realizes the support vector machin (SVM) based algorithms and supports multiple programming languages. I have designed SVM based approaches for machine-learning tasks on MATLAB by the libsvm, which is very awsome. Now, it’s time to try it on python, though it has been encapsulated in the SciPy.
To use libsvm on python, you may follow the coming steps.
If it generates four svm- prefixed files as well as the library libsvm.so.2, then the installization is completed.
Now you can take a trial with provided python based utilities in the folder ./python. For instance,
1
2
3
4
5
6
7
8
9
10
11
12
>>> from svmutil import *
>>> y, x = svm_read_problem('../heart_scale') # load data
>>> m = svm_train(y[:200], x[:200], '-c 4') # train a SVM model
# This will output like,
*.*
optimization finished, #iter = 257
nu = 0.351161
obj = -225.628984, rho = 0.636110
nSV = 91, nBSV = 49
Total nSV = 91
>>> p_label, p_acc, p_val = svm_predict(y[200:], x[200:], m) # make a test
Accuracy = 84.2857% (59/70) (classification)
Note
As introduced by the README in the ./python folder, two .py scripts are provided, of which svm.py and svmutil.py are corresponding to low-level and high-level use of the interface. In my opinion, I suggest the users to directly use svmutil.py.
In addition, the python scripts rely on the libsvm.so.2, which should be added into the LD_LIBRARY_PATH or a package not find exception will be raised when import svm.