Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

2015-11-03

Named Entity Recognition using SpaCy in 5 minutes

Recently, I am looking it SpaCy, a startup and an NLP toolkit. It is fabulous on its speed. Today, I just gave it a try on NER. Just a few lines (as in iPython):

In [1]: import spacy.en
In [2]: parser = spacy.en.English()
In [12]: ParsedSentence = parser(u"alphabet is a new startup specializing in eating their own words on leaving china to fight for information freedom")

In [13]: print ParsedSentence.ents
()

In [14]: ParsedSentence = parser(u"Alphabet is a new startup specializing in eating their own words on leaving China to fight for information freedom")

In [15]: print ParsedSentence.ents
(Alphabet, China)

In [16]: for Entity in  ParsedSentence.ents:    
   ....:     print Entity.label, Entity.label_, ' '.join(t.orth_ for t in Entity)
   ....:     
349 ORG Alphabet
350 GPE China

I used only default settings. Apparently, the NER of SpaCy is very sensitive to case of words.

2015-05-27

Guide to CVXOPT's quadprog() for row-major and/or MATLAB-speaking minds

I am using CVXOPT now. My mind is very row-major, because I mostly program in C and Python. And my mind is also MATLAB-style, because my friend send me a code in MATLAB. Now I need to convert his code to CVXOPT in Python. Here are some thing you wanna pay attention.

1. Matrixes in CVXOPT are column-major


By the code:
G=cvxopt.matrix([[1.,1],[-1,2],[2,1],[-1,0],[0,-1]])
I thought I created a 5-by-2 matrix (5 horizontal rows and 2 vertical columns). However, I got a 2-by-5 matrix.

In [72]: G
Out[72]: <2x5 matrix, tc='d'>

In [73]: print G
[ 1.00e+00 -1.00e+00  2.00e+00 -1.00e+00  0.00e+00]
[ 1.00e+00  2.00e+00  1.00e+00  0.00e+00 -1.00e+00]

2. The matrixes must be of type float.


Make sure your matrixes are of type float, even though your coefficients are integers.

Earlier I created a matrix:
In [53]: q=cvxopt.matrix([[-2],[-6]])

Later I got the error like
TypeError: 'q' must be a 'd' matrix with one column

This is because the matrix is not of type float:
In [54]: q
Out[54]: <1x2 matrix, tc='i'>

To fix, simply make at least one element float, e.g., "1." Then the type code will become d.
In [89]: q
Out[89]: <1x2 matrix, tc='d'>


3. Generating the matrixes needed for your optimization problem.


First of all, the cvxopt formulates quadratic programming so much simpler than MATLAB. Here is how cvxopt formulates the problem:

$$ \begin{array}{ll}
\mbox{minimize} & (1/2) x^TPx + q^T x \\
\mbox{subject to} & G x \preceq h, \\
& Ax = b.
\end{array}
$$

The boundaries for all variables can be defined as part of the matrix G - just use eyes. E.g., the lower boundary constraints

$$x_1 > 1, x_2>2, x_3> 3
$$
is just
$$
\begin{bmatrix}
-1 & 0 & 0 \\
0 & -1 & 0 \\
0 & 0 & -1
\end{bmatrix}
\begin{bmatrix}
x_1\\
x_2 \\
x_ 3
\end{bmatrix}
< \begin{bmatrix} -1\\ -2\\ -3 \end{bmatrix} $$ Note that in either MATLAB's or cvxopt's formulation, the linear terms are always on the side of "smaller than or equal to". Hence, the minus one above. MATLAB formulations have two additional column arrays for upper and lower boundaries: $$ \begin{array}{ll} \mbox{minimize} & (1/2) x^THx + f^T x \\ \mbox{subject to} & A x \preceq b, \\ & A_{eq}x = b_{eq}, \\ & lb \preceq x \preceq ub. \end{array} $$ Apparently, there are lazy people who wants to have a straightforward conversion from MATLAB's formulation to cvxopt's. However, I am not sure whether that translation is out-dated because cvxopt changed their APIs. Here is an easier one.

Let the MATLAB version be
x = quadprog(H,f,A,b,Aeq,beq,lb,ub, ...)
This is how you do it in cvxopt:
import numpy
import cvxopt
import cvxopt.solvers
n = H.shape[1]   # n is the number of variables 

P = H
q = f
G = numpy.vstack([A, -numpy.eye(n), numpy.eye(n)])
h = numpy.vstack([b, -lb, ub])
A = Aeq
b = beq

sol = cvxopt.solvers.qp(cvxopt.matrix(P), cvxopt.matrix(q), cvxopt.matrix(G), cvxopt.matrix(h), cvxopt.matrix(A), cvxopt.matrix(b))
x = sol['x']

If you don't have lb nor/and ub, no need to have it/them in G and h.

Put things together

So, let's see an example. The example in MATLAB Optimization Toolbox can be solved in cvxopt as follows (in iPython shell):

In [81]: G=cvxopt.matrix([[1.,1],[-1,2],[2,1],[-1,0],[0,-1]])

In [82]: P=cvxopt.matrix([[1,-1],[-1,2.]])

In [83]: q=cvxopt.matrix([[-2,-6.]])

In [84]: h=cvxopt.matrix([2,2,3,0,0.])

In [85]: Solv=cvxopt.solvers.qp(P.T, q, G.T, h)
     pcost       dcost       gap    pres   dres
 0: -1.0389e+01 -8.2778e+00  2e+01  9e-01  1e+00
 1: -7.2856e+00 -9.9286e+00  3e+00  1e-16  4e-16
 2: -8.1161e+00 -8.6188e+00  5e-01  8e-17  2e-16
 3: -8.2068e+00 -8.2359e+00  3e-02  6e-17  3e-15
 4: -8.2220e+00 -8.2224e+00  3e-04  5e-17  1e-15
 5: -8.2222e+00 -8.2222e+00  3e-06  8e-17  6e-16
Optimal solution found.

In [86]: print Solv['x']
[ 6.67e-01]
[ 1.33e+00]

2012-06-30

VTK Polygons and other cells as vtkCellArray in Python

After hours of googling and playing with iPython, I finally figured out the way to access polygons or other cells in VTK files using Python.

The Python binding of vtk library seems missing a very important function for users to access cells/polygons in Python, as mentioned in a VTK mailing list post back to 2002 and another post in 2011.

A workaround I just found out is as follows. Suppose you have a VTK file called test.vtk containing the following data.

# vtk DataFile Version 2.0
Cube example
ASCII

DATASET POLYDATA
POINTS 8 float
0.0 0.0 0.0
1.0 0.0 0.0
1.0 1.0 0.0
0.0 1.0 0.0
0.0 0.0 1.0
1.0 0.0 1.0
1.0 1.0 1.0
0.0 1.0 1.0

POLYGONS 3 12
3 0 1 2 
3 4 5 6
3 7 4 2

Now I use interactions on iPython to demonstrate the accessing to POLYGONS.

First, we prepare the accessing.
In [1]: import vtk

In [2]: Reader = vtk.vtkDataSetReader()

In [3]: Reader.SetFileName('test.vtk')

In [4]: Reader.Update()

In [5]: Data = Reader.GetOutput()

In [6]: CellArray = Data.GetPolys()

In [7]: Polygons = CellArray.GetData()

Now check the number of cells/polygons and number of points in cells/polygons
In [8]: CellArray.GetNumberOfCells()
Out[8]: 3L

In [9]: Polygons.GetNumberOfTuples()
Out[9]: 12L

All cells/polygons can be accessed like this:
In [10]: for i in xrange(0,  Polygons.GetNumberOfTuples()):
   ....:         print Polygons.GetValue(i)
   ....: 
3
0
1
2
3
4
5
6
3
7
4
2
Please note that the numbers (3's here) indicating sizes of cells (i.e., the numbers at the beginning of every line in Cell/Polygon segment in a VTK file) are also retrieved and printed.

If all your cells/polygons are of the same size, e.g., all triangles, here is an easy way.
In [11]: for i in xrange(0,  CellArray.GetNumberOfCells()):
   ....:         print [Polygons.GetValue(j) for j in xrange(i*3+1, i*3+4) ]
   ....: 
[0L, 1L, 2L]
[3L, 4L, 5L]
[6L, 3L, 7L]

2012-01-04

Adding two SCALARS in POINTDATA for one vtkPolyData object in VTK

by Forrest Sheng Bao http://fsbao.net

In VTK (either the file format or the library), we sometimes associate more than one scalars to points. I just figured out how to do this in VTK (in C++, similarly in its Python, Tcl or Java wrapper).

Suppose I have a vtkPolyData pointer
vtkPolyData* mesh;
and two vtkDoubleArray (you can consider a vtkDoubleArray as a list of scalars) pointers
vtkDoubleArray* depth; 
 vtkDoubleArray* curv; 

This is how I do it:

depth->SetName("Depth");
mesh->GetPointData()->SetScalars(depth);
curv->SetName("Curvature");
mesh->GetPointData()->AddArray(curv);

You may test this by writing mesh into a VTK-format file:

vtkPolyDataWriter* writer=vtkPolyDataWriter::New();
 writer->SetFileName("test_dump.vtk");
 
 writer->SetInput(mesh);
 writer->Update();
 writer->Write();
 writer->Delete();

My only question is whether the use of AddArray() function is correct. What is I wanna set a Normal? or a Tensor?

2009-11-26

lparse 1.1.1 conflicts with GCC 4.3.3

by Forrest Sheng Bao http://fsbao.net

An updated version for Ubuntu 9.10 is here: lparse 1.1.1 compiling conflicts with GCC 4.4.1 on Ubuntu Linux 9.10

If you are having problem compiling lparse 1.1.1 using GCC 4.3.3, specifically on Ubuntu 9.04, and your error happens to be like this
g++ -g -O3 -c instance.cc
In file included from instance.cc:23:
extern.h:86: error: previous declaration of ‘long int strtol(const char*, char**, int)’ with ‘C++’ linkage
/usr/include/stdlib.h:186: error: conflicts with new declaration with ‘C’ linkage
/usr/include/stdlib.h:186: error: declaration of ‘long int strtol(const char*, char**, int) throw ()’ throws different exceptions
extern.h:86: error: from previous declaration ‘long int strtol(const char*, char**, int)’
just do a simple step:
Open src/extern.h and comment the line
long int strtol(const char *nptr, char **endptr, int base); 
which is around line 86. strtol is a C++ standard library function used to convert numbers of different radixes (or bases). So it doesn't need to be redefined here.
This is my GCC version info:
$ gcc -v
Using built-in specs.
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu 4.3.3-5ubuntu4' --with-bugurl=file:///usr/share/doc/gcc-4.3/README.Bugs --enable-languages=c,c++,fortran,objc,obj-c++ --prefix=/usr --enable-shared --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --enable-nls --with-gxx-include-dir=/usr/include/c++/4.3 --program-suffix=-4.3 --enable-clocale=gnu --enable-libstdcxx-debug --enable-objc-gc --enable-mpfr --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 4.3.3 (Ubuntu 4.3.3-5ubuntu4) 

2006-10-22

the device named ``random"

#include 
#include
#include
#include

#include


int
main(void)
{

int i,j,randomfd;
int rand[100];

//for(i=0;i<10;i++)

//{

//srand(time(NULL)+getpid());

// printf("%d ",rand());


//} printf("\n");
randomfd=open("/dev/random",O_RDONLY);

if(!randomfd)
printf("open random device error\n");

for(i=0;i<100;i++)
{
read(randomfd,rand,10);
for(j=0;j<2;j++)
printf(" %d",rand[j]);
printf("\n");
}

}