Bugfix in liblinear2scipy

uschmitt | machine learning, python | Friday, May 22nd, 2009

Thanks to Nicolas Pinto who discovered a bug in my Python wrapper for liblinear. You can get the latest version as an archive or from our public subversion repository:

svn co http://public.procoders.net/liblinear2scipy/src/ liblinear2scipy

CUDA API mismatch on Ubuntu 8.04 box

uschmitt | cuda | Thursday, May 14th, 2009

After installing the latest CUDA driver I had some trouble on a  pristine Ubuntu 8.04 box. Starting CUDA Programs I got

Error: API mismatch: the NVIDIA kernel module has version 96.43.05, but this NVIDIA driver component has version 185.18.08.  Please make sure that the kernel module and all NVIDIA driver components have the same version.

Cause of this problem is the coexistence of a nvidia kernel module an the new installed CUDA driver.

In order to find the name of the module I typed

dpkg -l | grep nvidia

and the  second word in the output was ‘nvidia-kernel-common

The I removed this module with

sudo apt-get --purge remove nvidia-kernel-common

After rebooting my CUDA programms run without further problems.

Scaling a scipy.sparse matrix — revised

uschmitt | python | Thursday, April 16th, 2009

With some help from the scipy users mailing list I learned an alternative to my previously posted algorithm which should be much faster at the prize of some extra memory. Here it comes:

def divide_sparse_matrix(A, by):
 
    assert isinstance(A, sp.spmatrix), "wrong format"
 
    A = A.tocoo()
    A.data /= by[A.row, A.col]
    return A

Scaling a scipy.sparse matrix

uschmitt | python | Wednesday, April 8th, 2009

I’m using scipy.sparse to represent vector encoded documents. It has lot’s of nice methods and algorithms, but lacks some elementwise operations. Implementing some NNMA code with KL-divergence as distance measure I have to calculate terms like

Y/numpy.dot(A,X)

where Y is of type scipy.sparse.csr_matrix and the division operator has to be performed elementwise. One could convert Y to a dense numpy.array object, but this costs memory and is slower than the following solution which iterates over the nonzero elements of A: (more…)

Speeding up NNMA

uschmitt | machine learning, python, signal processing | Monday, March 30th, 2009

I observed that many NNMA / NMF algorithms speed up when one scales the input matrix such that  the l1-norms of the columns equal one.

This scaling of a nonnegative matrix A can be done in Python (using numpy) as follows:

     A /= A.sum(axis=0)

Did anybody know that ? I will try other lp norms these days.

Does everybody know data whitening ?

uschmitt | signal processing | Monday, March 30th, 2009

Data whitening is a crucial processing step in multivariate data analysis. It is a linear  transform which acts on multivariate data such that the resulting correlation matrix is the identity matrix. That is the components are uncorrelated and the variances equal one.

When looking for details I had to recognize that there are not much sources about how to whiten data. That is why I want to advertise this and that link to everybody who deals with multivariate data analysis.

Python 5 times faster ?

uschmitt | python | Sunday, March 29th, 2009

Google just started a project called “Unladen Swallow” which aims to speed Python up. The goal is to replace Pythons virtual machine to a LLVM based just in time compiler. You can find more information Here and There.

MIT switches to Python for education !

uschmitt | python | Thursday, March 26th, 2009

MIT moved from using Scheme to using Python for educating their undergrate students. Read more here.

New routines for nonnegative matrix approximation

uschmitt | machine learning, python | Thursday, February 26th, 2009

I added two algorithms to my nnma toolbox today:

  1. The original multiplicative update based algorithm NMF from  Lee and Seung
  2. Rank-one residue iteration (RRI) is a new algorithm from 2008 and is described here.

You can get the code from our subversion repository.

Bugfix in LIBLINEAR’s Python wrapper

uschmitt | machine learning, python | Monday, February 16th, 2009

You can get the newest version 1.1.3 of our wrapper here. I had to fix an issue concerning learning of problems with more than two classes.

Python is programming language of the year

uschmitt | python | Monday, February 16th, 2009

linuxquestions.org asked about the programming language of 2008 and Python won as in 2007 !

New version 1.1.1 of Python wrapper for LIBLINEAR released

uschmitt | others | Thursday, January 22nd, 2009

I just upraded our Python wrapper for liblinear. The new version number is 1.1.1, you can get it here. The only change was the addition of the two methods get_weights and get_bias to the class LinearSVM.

Most cryptic Python one-liner for inverting a dictionary ?

uschmitt | python | Monday, January 5th, 2009

Inverting a dictionary means exchanging keys and values, which only can work if your values are hashable and unique. So inverting

mydict = { a: 3, b: 5, c: 7 }

results in

inverted_mydict = { 3: a, 5: b, 7: c }

Can anybody compete with the following expression for inverting a Python dictionary named mydict ?

inverted_mydict = dict(zip(*zip(*mydict.items())[::-1]))

Did anybody say that Python code is easy to read and understand ;-) ?

Update: Using CUDA within Eclipse

uschmitt | others | Wednesday, December 17th, 2008

Do not despair if you had some trouble getting CUDA run with Eclipse as described in my last post. Due to some missing DLLs and  Microsofts muddle version of nmake some people had  inscrutable problems getting the minimal example run.

I fixed it and updated the post. So if you did not succeed yesterday, please make a new attempt !

HOWTO: Using CUDA within Eclipse

uschmitt | others | Tuesday, December 16th, 2008

The CUDA SDK provides a lot of nice examples for programming with CUDA. Regrettably all projects provided for Windows rely on Microsofts Visual Studio, Eclipse is not supported. As I like the idea of “One IDE for all” I try to get most of my work done with Eclipse (or VI, but that is another story). So here comes my HOWTO:

(more…)

RPy does not want to load package “mgcv”

uschmitt | machine learning, python | Wednesday, December 10th, 2008

I had a problem using RPy2 on Windows today: When I wanted to import the “mgcv” package (it provides GAM regression methods) using

r.library("mgcv")

I got a traceback
(more…)

PLS1 Regression with Python

uschmitt | machine learning, numerics, python, signal processing | Tuesday, December 2nd, 2008

I had trouble to find a working implementation of PLS1-Regression in Python. Even the algorithm presented on  Wikipedia is faulty. Fortunately the algorithm is not very difficult, this paper helped me. It gives a nice overview over PLS algorithms and their properties. It was really interesting to read that PLS1 regression for X vs y with N components gives the same weigths as N cg iterations for minimizing

 \frac{1}{2} b^\top X^\top X b - b^\top X^\top y

Here comes the Python code: (more…)

CUDA: first benchmark

uschmitt | numerics | Thursday, November 27th, 2008

After developing in emulation mode I got a GeForce 8500 GT for about 50 EUR today. The first benchmark I tried was Monte Carlo simulations which speed up by a factor of 73 ! Monte Carlo is easy to parallelize, so I will try other algorithms soon…

Running this code in emulation mode is 200 times slower than running on the GPU, respectively 3 times slower than running directly on the CPU.

I will try to find out if this factor 3 is valid in general, so I could estimate the speed up just by switching from emulation to gpu mode without parallel coding for the cpu.

Even if CUDA will not impact cluster computing as I predicted in my last post, it improves computing time for little money.

Is CUDA the next big thing ???

uschmitt | numerics | Tuesday, November 25th, 2008

NIVIDIA sells a GPU based computer with the power of 250 standard PCs CPUs for below $ 10.000 ! CUDA is the framework for programming NVIDIAS GPUs in a C-like language with a certain abstraction of the GPU’s hardware. I think that lots of computer clusters will retire and your personal high-performance number chruncher will fit in your office soon. NVIDIA lists some applications using CUDA including the achieved speedup, which is noteworthy in most cases.

Interested in CUDA ? I found a nice series of tutorials about CUDA here. There are further resources about programming CUDA in the web, but I found no active mailing list or news group about it.

I started  learning CUDA for faster training of large scale support vector machines. As my company will keep the source closed, I can not provide the full implementation, but I will try to blog about problems, solutions and insights.

My first insight is that thinking in parallel algorithms is brain blasting and for sure one of the best methods for training and preserving your mental fitness :-)  First I was a bit tangled as I  did not expect to enter a subject where I feel like a total novice, but I recovered soon and found that thinking about parallel algorithms is big fun.

Stay tuned !

Code snippet: iterating over a grid of parameters

uschmitt | Urlaub, python | Monday, November 10th, 2008

I use the following code snippet when determining the best parameters of a learning algorithm by iterating over a grid of arbitrary typed parameters:

def make_param_grid(dd):
    """
        dd is a dict mapping parameter names to a list of possible values.
        this routine returns cartesion product  as a list of dictionaries
 
        eg:  dd = dict(N=[2,3], eps=[0.1, 0.001])
        delivers an iterator over the sequence
 
              dict (N=2, eps=0.1)
              dict (N=2, eps=0.001)
              dict (N=3, eps=0.1)
              dict (N=3, eps=0.001)   
     """
 
    def cartesian_product(lists):
        """ recursive calculation of cartesian product """
        if len(lists):
            for l in lists[0]:
                for c in cartesian_product(lists[1:]):
                   yield [l] + c
        else:
           yield []
 
    for p in cartesian_product( dd.values()):
        yield dict(zip(dd.keys(), p))

Vector space model: different definitions of IDF

uschmitt | machine learning | Thursday, November 6th, 2008

If discovered that there are (at least) two slightly different definitions for the IDF term when using vector space models. I wonder if anybody can say something about this difference.

(more…)

Rezepte sind umgezogen

uschmitt | others | Thursday, October 30th, 2008

Wer in diesem Blog nach Rezepten sucht, wollen wir auf uwe.ambloggen.de verweisen. Aus Gründen der Übersichtlichkeit haben wir die Koch-Beiträge ausgelagert.

Python wrapper for LIBLINEAR updated

uschmitt | machine learning, python | Friday, October 24th, 2008

It was really nice to notice how many people are interested in my Python module for wrapping LIBLINEAR.

Meanwhile I fixed a bug which let the Python interpreter crash when converting a large model to its string representation due to some problems with C++ streams.
Further I extended the API by a function for computing confusion matrices.

Look at the newest archive at http://public.procoders.net/liblinear2scipy/src/dist/

Numpy tricks

uschmitt | numerics, python | Wednesday, October 22nd, 2008

Numpy provides a lot of tricks for elegant and efficient matrix manipulations. I learned a new trick when looking for a nice method to sum consecutive rows of a matrix. (more…)

Cython based Python wrapper for LIBLINEAR

uschmitt | machine learning, python | Wednesday, October 22nd, 2008

LIBLINEAR is the fastest solver I know for training linear support vector machines. Concerning linear SVMs it  is much faster than the established libsvm library from the same authors. It performs well for high dimensional problems with many training examples which occur for example in text classification. LIBLINEAR is able to do multi class classification by training one to one models and provides five algorithms, including logistic regression.

I extended my Cython capabilities by using Cython for wrapping LIBLINEAR. I like Cython more and more and I want to thank all its authors for providing such a nice tool. Cython rocks !

For those interested in using LIBLINEAR from Python: You can get the Python module here.

Variable selection for linear regression

uschmitt | machine learning, numerics | Tuesday, October 14th, 2008

Trying to find relevant frequencies for regression based on NIR data I found a very interesting article about a new method called Least Angle Regression (LARS). I implemented one of the introduced methods called forward stagewise linear regression. This method is not as fast as LARS but very easy to implement.

I provide my Python/numpy based implementation at our public subversion repository, including some toy data and an example application.

Further Speed Up !!!

uschmitt | python | Friday, September 26th, 2008

I’m pleased to see that the C Code generated from Cython is quite readable. Opening it in my editor, I noticed some  wrapper  and initalization code,  the original Python lines appear as comments, and knowing Pythons C-API helps but is not mandatory.

Studying the C code which was generated from the example from my last posting, I was able to accelerate it further. Here is the code from my last posting:

def count_words(document):
    wfs = dict()
    for w in document:
        wfs[w] = wfs.get(w,0)+1
    return wfs

I did not think that further improvements are possible. Looking at the C-Code I’ve seen that using the dictionary and looping over the list of words is done by calls to the C-API which ist not  as fast as a pure C/C++ implementation, eg using STL. But this kind of code generation is beyond Cythons capabilities.

However, the C code showed me that in each pass of the for loop, the method wfs.get was looked up again.  So I optimized the code, by moving this  lookup outside the loop:

def count_words(document):
    wfs = dict()
    get = wfs.get
    for w in document:
        wfs[w] = get(w,0)+1
    return wfs

After this modification the runtime decreased from 240 msec to 160 msec, that is 33% decrease in runtime.

Looking at the C code helped my at other places too, at least it gives you a deeper understanding how Python works behind the scenes. So, be brave and study what  Cython does with your code !

Cython speeds up !

uschmitt | python | Wednesday, September 24th, 2008

Just by moving the following snippet from Python to Cython resulted in remarkable better performance:

def count_words(document):
    wfs = dict()
    for w in document:
        wfs[w] = wfs.get(w,0)+1
    return wfs

Running with 300k words, the Cython version needs 240 msec in contrast to 2500 msec in pure Python ! I measured the performance with the profile module from Pythons  standard library.

Cython — first trials

uschmitt | python | Monday, September 22nd, 2008

In order to speed up some text processing tasks I played with Cython today. The website of Cython says:

Cython is a language that makes writing C extensions for the Python language as easy as Python itself. Cython is based on the well-known Pyrex, but supports more cutting edge functionality and optimizations.

My first task was to lower all strings in a given list, which I normally do using

words = map(lambda w: w.lower(), words)

If you want to know how I succeeded in speeding up this code snipped by a factor of three, continue reading.

(more…)

Stemming with Snowball — my first contact to Cython

uschmitt | python, signal processing | Thursday, September 18th, 2008

I had my first contact to Cython today when searching for fast implementations of stemming algorithms. Using my favorite search engine, I discovered Snowball.

The website says: “Snowball is a small string processing language designed for creating stemming algorithms for use in Information Retrieval”. Additional to C and Java bindings the project provides a Python module with fast  stemming algorithms for many languages.

I updated these Python bindings by moving from Pyrex to Cython, which accelerated the created Python extension module. According to the included benchmark script, the runtime decreased about 40%.

Furthermore I replaced the stemmer library by the current version provided at http://snowball.tartarus.org/download.php

The module can be accessed from our public subversion repository at http://public.procoders.net/PyStemmer-1.1.0/

Cython really looks like a nice thing and I will have a deeper look at it soon.

Teaching SVMs : interactive demonstration tool online again

uschmitt | machine learning, python | Thursday, September 11th, 2008

We developed a tool for teaching Support Vector Machines some time ago, which was broken due to version changes of underlying libraries. The tool is nice for teaching C-SVMs and for getting insights into the properties of different kernels and the effects of all involved parameters.

Today I adapted the demonstration tool to our new CSVM library and it is now online again.

You can check it out with SVN from http://public.procoders.net/svmtool/. You need Python and the packages  numpy, CSVM, wxPython and PythonCard (I used version 0.8.1) for running demotool.py . Windows users find  a zip archive (16MB !!!) here containing a standalone exe version: it runs without installing Python and the needed packages.

numpy docs are free now !

uschmitt | python | Thursday, September 4th, 2008

Just discovered at http://www.scipy.org/Documentation :

Guide to NumPy by Travis Oliphant the lead developer of NumPy. This e-book is a complete reference to NumPy, this is a nice documentation to all features of NumPy. It was fee-based but as of Aug 21, 2008 it is in the public domain.

And there is a website for documenting numpy at http://www.elisanet.fi/ptvirtan/tmp/numpy-refguide/index.xhtml which is described as

Large parts of this manual originate from Travis E. Oliphant’s book
“Guide to Numpy� (which generously entered
Public Domain in August 2008). The reference documentation for many of
the functions are written by numerous contributors and developers of
Numpy, both prior to and during the Numpy Documentation Marathon.

The Documentation Marathon is still ongoing. Please help us write
better documentation for Numpy by joining it! Instructions on how to
join and what to do can be found on the scipy.org website.

Building distutils based Python extensions on Windows without Visual Studio

uschmitt | python | Thursday, August 21st, 2008

I want to report on a solution to a common problem when building C based extensions on Windows: I tried to install  Cython with the well known command

python setup.py build

which failed with an  error message complaining the lack of Visual Studio 2003 on my machine:

error: Python was built with Visual Studio 2003;
extensions must be built with a compiler than can generate compatible binaries.
Visual Studio 2003 was not found on this system. If you have Cygwin installed,
you can try compiling with MingW32, by passing “-c mingw32″ to setup.py.

(more…)

Springer and CiteULike collaboration

uschmitt | Urlaub, taichi | Wednesday, August 20th, 2008

I discovered the following announcment today:

SpringerLink, one of the world’s largest scientific databases, has partnered with CiteULike, the social bookmarking website for researchers. The partnership will ensure that researchers will benefit from CiteULike’s reference management services.

Looks like a nice thing for managing interesting publications. I started using it today because I lost overview of lots of pdfs with cryptical  names in my local file system. Here is my account.

Python wrapper for C-SVM from libsvm

uschmitt | machine learning, python | Tuesday, August 19th, 2008

I provide a simple Python module for training a C-SVM at our public subversion repository. I had to write an own wrapper of libsvms C-SVM for some reasons:

  1. There are SVM implementations for Python, but I wanted a lightweight solution which plays well with numpy instead of a full framework such as Orange.
  2. There is a libsvm wrapper in scipy.sandbox, but I did not succeed in building it, further it is based on ctypes.
  3. I wanted to improve my f2py skills by wrapping libsvm. ctypes is great but f2py handles platform dependent compiler setup easyly and converts numpy arrays to C arrays automatically.
  4. I had to modify code, because training in libsvm can not be stopped by providing an upper limit to the number of iterations performed. And I wanted to control output of libsvm during training.

Please ask me in case of problems.

TaiJi in der medizinischen Forschung

Achim | taichi | Sunday, August 17th, 2008

Beruflich habe ich viel mit der Aufbereitung medizinischer Publikationen zu tun. Ein öffentlich zugängliches Ergebnis dieser Bemühungen kann man unter www.biomedexperts.com sehen. Als Martin im Forum für Wu Tai Chi darauf hingewiesen hatte, daß sich in PubMed jede Menge Information zu Tai Chi und Medizin finden lassen, war es für mich daher naheliegend, mal “unseren” Zugang zu PubMed zu testen. Auf Martins Wunsch hin will ich das Ergebnis hier kurz vorstellen:

BiomedExperts ist dazu gedacht, Experten zu bestimmten Themen zu finden. Nach ein paar Fehlversuchen finde ich ‘raus, daß ich doch bitte die Schreibweise “TaiJi” verwenden möge. Dann liefert die Anwendung folgende Definition:

One of the MARTIAL ARTS and also a form of meditative exercise using methodically slow circular stretching movements and positions of body balance.

Für medizinische Software schonmal gar keine schlechte Definition. Zu dem bekomme ich ein Übersichtskarte, wo auf der Welt wieviel zum Thema TaiChi veröffentlicht wurde (Ein Klick auf die Bilder zeigt eine größere Version an).

Dazu gibt’s eine Liste der Wissenschaftler, die sich mit dem Thema beschäftigt haben. Die zwei Spalten rechts geben an, wieviele Publikationen der Experte zum Thema TaiChi veröffentlich hat und wieviele er insgesamt hat. Liegen die Zahlen dicht beieinaner, ist anzunehmen, daß TaiChi zu den Spezialgebieten des Experten gehört - muß aber nicht sein.

Die einzelnen Experten lassen sich aufklappen. Die Details sind im folgenden Screenshot zu sehen:

Ganz links ist die Liste der Publikationen zum Thema TaiChi zu sehen. Die Titel sind direkt mit PubMed verlinkt. Rechts in den zwei Spalten ist zu sehen, womit der Experte sich allgemein beschäftigt. Einmal im Kontext von TaiChi und einmal allgemein. Hier kann man z.B. sehr schön sehen, daß der Experte aus meinem Beispiel sich vorwiegend mit TaiChi im Zusammenhang mit Herzkreislauferkrankungen beschäftigt. Andere Forschungen gehen eher in Richtung Sturzprävention.

Ich denke, daß dieser Zugang zu medizinischer Forschung für den einen oder anderen recht spannend sein könnte - und komme somit aber auch zu einem kleine Haken: BiomedExperts ist zwar kostenlos, bietet aber KEINEN direkten Zugang zu den wissenschaftlichen Veröffentlichungen! Alle Links gehen zu PubMed, wo teilweise Volltexte verfügbar sind, oft aber nur Abstracts. Wer sich intensiv mit aktuellen Veröffentlichungen beschäftigen will, braucht immer noch - in der regel kostenpflichtigen - Zugang zu den Publikationen. BiomedExperts macht nur das finden leichter. ;-)

Falls der/die eine oder andere neugierig geworden ist, stehe ich bei Fragen gerne zur Verfügung.

Sparse nonnegative matrix approximation

uschmitt | machine learning, python, signal processing | Tuesday, August 12th, 2008

In addition to the fast FNMAI algorithm, I implemented an algorithm for sparse nonnegative matrix approximation called NNSC. Both are included in the py_nnma package which can be accessed from our public svn repository, the address is  http://public.procoders.net/nnma

    For further information about the NNSC algorithm look at this publication.

    Python replaces Matlab (at least for me)

    uschmitt | python | Monday, August 11th, 2008

    The emergence of Matlab during the last decade of the 20th century highly changed the way we develop, implement and test numerical algorithms:

    • In the old days we used C, sometimes  Fortran or C++.  We spent a lot of  time in writing low-level functions and debugging memory leaks. Matlab helped us a lot.
    • Debugging numerical algorithms is hard, because dumping a 100 times 100 matrix will not really give you the information you are looking for. Therefore visualization of data is very important for developing numerical code  efficiently. Gnuplot helped us, but Matlab provided nice interactive 3d graphics and a tight integration.

    We naturally moved away from  cumbersome ‘waterfall method‘ alike planing and coding  to some agile ‘lets try things out - we only need a few minutes’ . Matlab gave us the ability to play with  data and algorithms.

    (more…)

    Installing and upgrading Wordpress with Subversion

    uschmitt | others | Thursday, August 7th, 2008

    This article explains how to install und upgrade Wordpress with Subversion (SVN), which reduces the work for future updates: “svn up” is much nicer than “download->ftp->unzip”. I just upgraded this blog and had no problems at all.

    Python calling C code: py_ica moves from ctypes to f2py

    uschmitt | python, signal processing | Tuesday, August 5th, 2008

    Due to some problems when deploying my py_ica module to several platforms I changed the way the C-code is called from Python:

    • The existing version of py_ica uses ctypes. ctypes is great, but leaves you alone when writing a Makefile to handle compiling your shared module on different platforms with different compiler sets.
    • I discovered that f2py is not only for wrapping FORTRAN code, it plays well with C code too ! See  http://www.scipy.org/Cookbook/f2py_and_NumPy The f2py and distutils framework provide nice abstractions of the underlying platform and compiler tool set.

    (more…)

    Python module for nonnegative matrix approximation (NNMA)

    uschmitt | machine learning, python, signal processing | Monday, July 28th, 2008

    NNMA is a matrix decomposition and approximation method which got some attention during the last years and has many applications as in

    Sometimes NNMA is called nonnegative matrix factorization (NMF) which is not fully correct in most cases.

    I discovered NNMA in the book Programming Collective Intelligence: Building Smart Web 2.0 Applications” from O’Reilly which is a great book that shows interesting applications and good explanations of important data mining techniques (but talks about NMF and not NNMA ;-) )

    Looking for a recent solver, I found the algorithm FNMA/I described in

    Dongmin Kim, Suvrit Sra, Inderjit S. Dhillon:
    "Fast Projection-Based Methods for the Least Squares Nonnegative Matrix
    Approximation Problem", Statistical Analysis and Data Mining, 2008


    which is supposed to be very fast. The algorithm is  easy to implement,  especially if you use matlab, or even better numpy. I provide the numpy based solver plus some sample data and scripts here. In order to test the implementation I took 400 images of handwritten digits 0-9 and decomposed the data into 15 components. The result looks like this:

    The data and the correspondig script is included in the download.

    How to blog mathematical formulas in Wordpress

    uschmitt | others | Thursday, July 24th, 2008

    Showing mathematical formulas in wordpress based blogs is easy if you have this plugin installed. I discovered it yesterday for writing this posting.

    If you post you inclulde forumulas in LaTeX code like this

    $$ \sum_{i=0}^\infty q^i = \frac{1}{1-q}$$

    which is rendered as

    \sum_{i=0}^\infty q^i= \frac{1}{1-q}

    The author says:

    This plugin use the public latex server(default is the service
    provided by wordpress.com) which means you don't need to install
    any Latex module in your own server which is hard for newbie

    For more information about \LaTeX look here.

    Nonnegative least squares : A Recipe for calling numerical FORTRAN code from Python

    uschmitt | numerics, python | Wednesday, July 23rd, 2008

    Searching the web for  a python based solver for a non negative least squares problem

     ||A x - b ||_2 \to \min \quad \textrm{with} \quad x\ge 0
    I found some Fortran code from www.netlib.org only. F2PY is a great tool but due to compiler issues it did not work in my case. So I used ctypes, which was easy because numpy has a sub module ctypeslib which provides some nice convenience routines for using ctypes together with numpy.

    I tried  to document my code well in order to provide a recipe for calling Fortran code with numpy’s arrays. You can browse the code in our subversion repository.

    The full code is available from here. You need a FORTRAN compiler like the free g77. If you use Windows I recommend the cygwin environment which ships with g77.

    Buch: Programmieren in C

    uschmitt | others | Tuesday, July 22nd, 2008

    Here comes spam: Ich möchte hier auf das Buch “Programmieren in C - eine mathematikorientierte Einführung” aufmerksam machen, schließlich bin ich einer der beiden Autoren :-)

    Das Buch richtet sich in erster Linie an Studenten vor dem Vordiplom, und ist speziell auf die Umsetzung mathematischer Verfahren ausgerichtet. Das hört sich jetzt trocken an, ist es aber nicht. Am Ende des Buches werden alle erworbenen Kenntnisse zusammen gebracht um Planetenbahnen zu berechnen und darzustellen, sowie Warteschlangen an Supermarktkassen zu simulieren.

    Eine Website zum Buch gibt es auch, und wer mal reinschauen möchte, kann dies auf Google Booksearch tun.

    compute *sorted* eigenvalues and eigenvectors with numpy

    uschmitt | python | Monday, July 21st, 2008

    numpy is great for linear algebra as it provides not only the almighty data container type array, but also  lots of elegant functions for working with array ’s and routines for several matrix decompositions as cholesky, qr or svd.

    Unfortunately the eigenvectors returned from routines like linalg.eig oder linalg.eigh are not sorted.
    But here comes numpys argsort() function to our rescue: It computes a permutation which sorts a given vector instead of sorting the vector itself.

    So we can compute a PCA with little code:

    from numpy import *
     
    def pca(data):
        """ assume one sample per column """
        values, vecs = linalg.eigh(cov(data))
        perm = argsort(-values)  # sort in descending order
        return values[perm], vecs[:, perm]

    Distributing ctypes based modules

    uschmitt | python | Monday, July 21st, 2008

    Ctypes is great. I use it a lot for speeding up numerical computations, and numpy provides some nice helpers which ease the usage of ctypes when passing multidimensional data.

    I had some problems when writing a setup script for distributing a ctypes based module: the first problem was to get my dll into the site-packages folder of my python installation. get_python_lib from distutils.sysconfigs helps, and my setup.py looks like this:

    from distutils.core import setup
    from distutils.sysconfig import get_python_lib
    import glob
    setup(name="py_ica",
        ...
        py_modules=["py_ica"],
        data_files=[(get_python_lib(), ["wrap_ica.dll"]), ]
    )

    This script installs py_ica.py and wrap_ica.dll to the site-packages/ folder.

    The other problem was how to find the dll when loading with ctypes.CDLL

    import os.path
    ctypes.CDLL(os.path.join(os.path.dirname(__file__), "./wrap_ica.dll"))

    If you load your DLL like this, your python module will find it in your local development folder as well as after installation with python setup.py install.

    Both solutions are platform independent, so don’t be disguided by the .dll extensions appearing in the example  code.

    PythonMagickWand on PyPi

    Achim | python | Sunday, July 20th, 2008

    Today I have created my first python egg! It’s a PythonMagickWand egg and can be found on PyPi. I have also created a first version of a Sphinx based documentation which can be found in our subversion repository.

    Get process listening on a certain port

    Achim | others | Saturday, July 19th, 2008

    The following command was quite useful to me, to figure out which process was running on port 8080 on my Mac OS X:

    sudo lsof -i :8080

    Tar file scanner for tar archives with *many* files

    uschmitt | python | Friday, July 18th, 2008

    In comp.lang.python Terry Caroll stated a memory problem when iterating over the file information of a 4GB tar file. This is because the standard libs tarfile module caches all header blocks which results in  memory consumption linear to the number of files in the archive. The module tarfile_scanner solves this problem. Its purpose is  iteratring over the file infos inside the tar file, other functionalities as untaring oder adding files are not implemented.

    Update of ICA packages

    uschmitt | python, signal processing | Thursday, July 17th, 2008

    Thanks to Scott Grant I found an error in the Python ICA module concerning installation.
    I provide the following updates:

    For further information about this module  please look at the first announcement of the module.

    Europython 2008 - Ende

    Achim | python | Wednesday, July 9th, 2008

    Heute hab’ ich noch einen sehr guten, spannenden Vortrag gehört und ein weitere steht noch auf dem Plan. Danach geht’s dann ab zum Flughafen, d.h. mit diesem Posting endet der Europython-Bericht. Gegen 21 Uhr sollten wir in Frankfurt landen und hoffentlich zwischen 23 und 24 Uhr wieder in SB sein.

    Nochmal viele Grüße aus Litauen,
    Achim

    Europython 2008 - Skybar

    Achim | python | Wednesday, July 9th, 2008

    Nach einem sehr leckeren Conferenz Dinner hat’s uns gestern Abend - nach kurzer Verdauungspause - in die …

    … im 22. Stock verschlagen. Immerhin war die Fahrt mit dem Fahrstuhl vom 17. Stock aus recht schnell. Nach unten nerven die Aufzüge mittlerweile nämlich extrem. Der Eingang wird dem Namen durchaus gerecht.

    Auch die Aussicht kann sich sehen lassen:

    Europython 2008 - Hans Rosling

    Achim | python | Tuesday, July 8th, 2008

    Heute waren die Vorträg für meinen Geschmack ein gutes Stück spannender. Details dazu will sicher niemand wissen - außer zu einem. Die heutige Keynote wurde von Hans Rosling gehalten. Hans Rosling? Hat mir vorher auch nicht viel gesagt. Wer’s genau wissen will kann bei Wikipedia nachlesen.

    Den Vortrag in aller Kürze widergeben kann ich natürlich nicht, aber hier gibt’s eine Aufzeichnung von einer früheren Präsentation. Im Prinzip hat Hans Rosling mit seinem Team langweilige, trockene Statsitiken visuell so aufbereitet, daß man z.B. sehen kann, daß es die angebliche Lücke zwischen armen und reichen Ländern in dem Sinne nicht mehr gibt.

    Ich kann nur sagen: Es war wohl der beeindruckendste Vortrag, den ich bisher gehört habe. Wer sich auch nur ein bißchen dafür interessiert, was auf unserer Welt passiert und wie die Zusammenhänge sind, sollte sich den Vortrag anhören!

    Europython 2008 - Vilnius oder “Fragen hilft!”

    Achim | python | Tuesday, July 8th, 2008

    Montag wollten wir den einzigen freien Abend nutzen und hatten beschlossen - was auch sonst - die lokale Küche zu testen. Im Reiseführer standen ein paar Restaurants, die lokales Essen anbieten und die sich recht nett anhörten. Uwe wollte einfach los. Ich hab’ dann nochmal an der Rezeption nachgefragt und man hat uns heftig von unserem Topkandidaten abgeraten. Zur Empfehlung eines besseren Restaurants gab’s dann noch einen Stadtplan.

    Das mit dem Stadtplan ist so ‘ne Sache. Die Straßennamen sind hier so kompliziert, daß ich mir nicht mal vorstellen kann, wie man sie aussprechen soll. Worte ohne Vokale wollen sich in meinem Kopf nicht in Laute verwandeln lassen. Daher ist die Zeit, die mein Blick vom Straßenschild bis auf den Plan braucht in der Regel länger als die Zeit, die ich mir den Namen behalten kann. Das macht die Suche schwer! Glücklicherweise können doch einige Einheimische Englisch sprechen. Taxifahrer übrigens nicht!

    Auf dem Weg zum Restaurant haben wir uns kurz wie zu Hause gefühlt:

    Wenn man die richtige Straße gefunden hat, sieht die Altstadt auch richtig nett aus:

    Ein richtiger Fotograph hätte hier unglaubliches Potential um den Gegensatz zwischen reich und arm zu dokumentieren. Jede Menge Häuserfasaden sind super schön restauriert aber ein Blick durch einen Torbogen in den Hinterhof offenbart, um was für Baracken es sich eigentlich handelt. Das ist überall so. Fühlt sich irgendwie komisch an.

    Da wir an dieser Stelle schon ‘ne Weile zu Fuß unterwegs waren fällt mir noch ein kultureller Unterschied ein: Die Frau an der Rezeption meinte ganz selbstverständlich “Ach, das sind nur 20 Minuten zu Fuß!”. Bei uns bekäme man eher ein warnendes “Das sind aber 20min zu Fuß!” zu hören.

    Das Essen an sich war ziemlich lecker, erinnert aber teilweise durchaus an saarländische Küche. Wer Details wissen will muß sich an Uwe wenden. Der hat da mehr Ahnung von.

    Der Rückweg war etwas länger als 20min. Trotz Stadtplan sind wir erstmal zielsicher in die falsche Richtung gelaufen. An einer großen Kreuzung waren wir dann arg verunsichert und haben den nächstbesten Jugentlichen gefragt. Der hat uns erklärt, daß wir komplett falsch sind und hat angeboten uns zu führen, weil er eh in die Richtung muß. Tja was soll ich sagen: Wir waren wirklich absolut falsch und mußten den ganzen Weg nochmal zurück.

    Europython 2008 - Nachtrag Tag 2

    Achim | python | Tuesday, July 8th, 2008

    Wo soll ich anfangen? Montag war recht anstregend. Deshalb bin ich mit meinem Bericht etwas in Verzug. Asche über mein Haupt! Aber den ganzen Tag Vorträge anhören macht müder als man so denkt. Vorab ein paar Worte zu euren Kommentaren (im Blog und via Mail), über die ich mich natürlich sehr gefreut habe:

    • Ich bin mit Uwe auf der Europython. Einer Konferenz für Programmierer … Pythonprogrammierer um genau zu sein! ;-)
    • Wir besuchen keine Clubs! ;-) Mir ist nur aufgefallen, daß es recht viele davon gibt. Und nochmal: Das Foto vom ersten Club hab’ ich DIREKT vor unserem Hotel gemacht. Dem angeblich besten Konferenzhotel in der Hauptstadt!
    • Es wundert mich ja, daß jemand Fotos von Menschen auf einer Konferenz mit IT Freaks sehen will!? Bilder folgen weiter unten.

    Soviel dazu. Jetzt wieder schön der Reihe nach: Über das reichhaltige Frühstück hatte ich ja kurz berichtet. Aber es kam in der Pause zwischen den Vorträgen noch besser …


    Um unsere Versorgung muß sich also niemand Sorgen machen. Und nein, wir sind nicht zum Spaß hier. Das ist Arbeit. Aber wer denken will, muß essen! Somit kommen wir zu den ersten Menschen, die ich einfach mal so hier einfüge. Keine Ahnung, warum Marc die sehen wollte!?

    Aus dem zweiten Bild könnte man ein Ratespiel machen: Wer findet alle Laptops?!

    Der Mac links unten ist übrigens kein Product Placement. Ca. jeder zweite hier benutzt einen Mac. Viele scheinen irgendwelche lebenswichtigen Funktionen damit zu steuern. Die können ihren Rechner (unabhängig von der Marke) auch während eines Vortrags nicht ausschalten, geschweige denn loslassen. Die Versuchung jemand mal seinen Rechner wegzunehmen ist groß, aber man will ja keine bleibenen Schäden verursachen.

    Die Vorträge an diesem Tag waren eher schwach, von daher gibt’s da wenig zu berichten. Würde euch aber wohl eh nicht interessieren. Abends haben wir dann die Stadt erkundet. Dazu gleich mehr …

    Europython Frühstück

    Achim | python | Monday, July 7th, 2008

    Nicht, daß wir nur zum Essen hier wären. Aber nach so einem Frühstück kann der Tag ruhig kommen …




    Europython 2008 Anreise

    Achim | python | Sunday, July 6th, 2008

    Viele Grüße aus Litauen! Nach einer kleinen Erkundungstour in der Umgebung des Hotels sind wir wieder in unserem Hotelzimmer gelandet und ich versuche mal die ersten Eindrück zusammen zu fassen. Irgendwie gibt’s schon mehr zu berichten, als ich für den ersten Abend erwartet hätte. Aber schön der Reihe nach …

    Die Anfahr nach Frankfurt war soweit unproblematisch. Das Boarding ging pünktlich los, aber dann gab’s im Flugzeug die erste schlechte Nachricht: Auf Grund des Ferienbegins sind wir auf zugewiesene Zeitslots angwiesen, was bedeutet, daß wir erst ca. eine Stunde später starten dürfen. Wir sollten aber schonmal an Bord kommen, für den Fall, daß es kurzfristig Änderungen gibt. Zum Glück trat dieser Fall dann auch ‘ne Viertelstunde später ein: Wir dürfen doch schon starten!

    In Vilnius stellt sich dann die große Frage: Auf Nummer sicher gehen und für 50 Lt (ca. 15 Euro) mit dem Taxi in’s Hotel fahren oder für 1,5 Lt (ca. 45 Cent) mit dem Bus? Als dekadenter Stier hätte ich natürlich das Taxi genommen. Beim Verlassen des Flughafens steht aber gerade die richtige Busline bereit und wir nehmen diese. Ich nutze meine Chance, eine gute Tat für diesen Tat zu vollbringen: Großzügig spendiere ich einem netten Kanadier seine Busfahrt in’s Zentrum, da er nur Euros dabei hat. Wir plaudern ein bißchen, wobei ich im Gegensatz zu Uwe nicht mitbekommen, daß der Kanadier gar nicht zur Europython will. Im nachhinein erklärt das auch den seltsamen Blick als ich mich mit “see you tomorrow” verabschiede …

    Unittelbar vor dem Hotel muß ich das erste Bild machen:

    Diese Lokalität liegt unmittelbar vor unserem Hotel, dem angeblich größten Konferenzhotel in der Hauptstadt von Litauen! Da kann sich jetzt jeder seinen Teil denken.

    Im Hotel gab’s dann die zweite schlechte Nachricht: Unser Zimmer wurde storniert - warum auch immer. Nach einem kurzen Adrenalinschub kam Gott sei Dank schnell die Entwarnung: Es waren noch Zimmer frei!

    Wir packen aus, stellen erfreut fest, daß das WLAN funktioniert und machen uns dann auf Erkundungstour. Da es schon langsam dunkel wird, ist das mit dem Fotographieren so ‘ne Sache. Hier trotzdem schon mal ein paar Eindrücke:

    Unser Hotel …

    Eine Häuserzeile auf der anderen Seite des Flußes. Von weitem sieht hier vieles ziemlich alt und cool aus, aus der Nähe dann eher verfallen und verkommen …

    Wer kann sowas ausprechen?

    Der Bedarf an solchen Locations scheint hier recht hoch zu sein. Sonderbarer Weise ist das der einzige Fall, in dem ich grob erraten konnte, was die Wörter wohl heißen sollen …

    Die Busse hier dürfen nicht frei fahren, sondern müssen an die Leine. Fand ich witzig …

    Soweit erstmal … to be continued tomorrow! ;-)

    Bad Gastein 2008 - 4. + 5. Tag

    Achim | Urlaub | Tuesday, January 15th, 2008

    Endlich: Schnee und Sonne!!!

    Seid gestern haben wir endlich Schnee und Sonne! Deshalb gab’s gestern auch keinen neuen Eintrag: Die Kombination aus frischer Höhenluft und der anschließenden Sauna war einfach zu heftig. Ich hab’ lange nicht mehr so tief und fest geschlafen! ;-)

    Das Wetter ist hier echt krass. Wir wohnen in einer Wolke, die wie ein Wattebausch in Tal liegt. Fährt man mit dem Auto ein Stück bergauf, steht man plötzlich unter blauem Himmel in perfektem Sonneschein. Leider läßt sich sowas nicht auf Bildern festhalten, was mich nicht davon abgehalten hat, ein paar Fotos zu machen:







    Auf dem letzten Bild kann man die Wolkenwand erkennen, die nicht über die Berge kommt. Schafft sie’s doch, ist’s hier ruck zuck um mit dem schönen Wetter. Ich find’s immer wieder beeindruckend, sowas von ‘nem Berg aus zu beobachten. :-)

    Viele Grüße,
    Achim

    Bad Gastein 2008 - 3. Tag

    Achim | Urlaub | Sunday, January 13th, 2008

    Schnee und Nebel …

    Nach dem üblen Wetter gestern, bin ich heute immerhin in einem verschneiten Skiort wach geworden. Dummerweise hingen die Wolken so tief, daß Skifahren nicht wirklich möglich war. Naja, möglich wär’s wohl gewesen, aber ich bin doch eher ein Schönwetterskifahrer! ;-)

    Natürlich hab’ ich auch wieder ein paar Bilder gemacht:

    Ich hoffe mal, daß morgen Schnee und Wetter gut sind. Man wird sehen …

    Viele Grüße,
    Achim

    PythonMagickWand

    Achim | python | Sunday, January 13th, 2008

    Thanks to all people which gave feedback on my first version of PythonMagickWand. This kind of feedback encourages me to continue work on the project. As mentioned in my first post, I only tested on Mac OS X. It seems that the methods are split over different libraries on other platforms. I already have an idea on how to implemented a solution for that, but I need some help. I’m only able to test on Mac OS X and on Windows, so I would need somebody for testing on various linux systems. I’m also no ImageMagick expert. I usually use IM to resize images or to change the image format. If you ask questions like “Are the Pixel Iterator Methods implemented?” it’s hard for me to answer, because I don’t know anything about pixel iterator methods. And probably I will not take the time to find out, what pixel iterator methods are.

    If you want some methods, which are part of the MagickWand API, to be implemented, just give me an example and some test data. I think it’s quite easy to guess how the code should look like in PythonMagickWand. And even if it’s not perfect, it will make my job much easier.

    For the time being, I’ll use this blog to communicate news about the project. So if you want to be informed about news, you should come back from time to time or you could consume the RSS feed of the python category.

    regards,
    Achim

    PS.: I think my python code is much better than my english. So any corrections are very welcome! ;-)

    Bad Gastein 2008 - 2. Tag

    Achim | Urlaub | Saturday, January 12th, 2008

    Zu gerne hätte ich heute ein paar cool Schneebilder von der Piste gepostet. Leider wird daraus nichts, weil’s hier heute stürmig war und geregnet hat. Dirk hat also recht: Bißchen grün für einen Skiurlaub. Oben soll’s aber noch genug Schnee geben. Ich hoffe also auf morgen! Und was die “hocherschaftliche Unterkunft” angeht: Die Wohnungen selbst sind eher solide, nüchtern und praktisch - aber absolut ok! Jeder der mein Zimmer kennt, wird verstehen, daß davon keine Fotos machen werde. ;-)

    Schneebilder gibt’s also nicht. Bloggen wollte ich aber trotzdem - was soll man im Skiurlaub ohne Schnee sonst auch machen? Ich bin also losgezogen und hab’ ein paar Bilder geschossen. Der Ausgang auf der Rückseite des Hauses führt mich direkt auf die Kaiser-Wilhelm-Promenade. Und wen finde ich da? Ja, es ist wirklich Kaiser Wilhelm I ;-)

    Auf der Promenade hat man schon einen recht schönen Blick in’s Tal. Leider kommt das auf dem Bild nicht richtig ‘rüber, aber wo ich’s schonmal fotographiert habe, muß das Bild auch hier ‘rein:

    Als nächstes kam ich dann zur Enttäuschung des Tages:

    Dieses Café macht normal unglaublich leckeren Nougat-Krokant, auf den ich mich schon gefreut hatte. Tja - den gibt’s erst ab Februar wieder. Und dafür laufe ich im Regen in der Gegend ‘rum. Werfen wir noch einen kurzen Blick in’s Tal:

    Wenig später kommt man dann an den “Dorfwasserfall”:

    Der kommt leider auf dem Bild auch nicht wirklich gut ‘rüber, aber ich hab’ selten einen Skiort gesehen, der in ein dermaßen enges, steiles Tal gebaut wurde. Warscheinlich kamen deshalb auch so viele wichtige Leute hierher, auf die man mächtig stolz ist:

    Nicht erkannt? Ich auch nicht, aber natürlich gibt’s eine Auflösung:

    Auf andere ist man stolz, auch wenn sie nicht da waren, sondern nur Briefe geschrieben haben:

    Zum Abschluß fand ich folgende zwei Schilder so dicht nebeneinander einfach nur witzig:

    Das war’s für heute. Ich hoffe auf Schnee und schönes Wetter. Dann gibt’s morgen Bilder von der Piste.

    Viele Grüße,
    Achim

    Bad Gastein 2008

    Achim | Urlaub | Friday, January 11th, 2008

    Unserem Blog mehr Aufmerksamkeit zukommen zu lassen, war