Showing posts with label numpy. Show all posts
Showing posts with label numpy. Show all posts

Friday, September 7, 2018

LabelPropagation - How to avoid division by zero?

Leave a Comment

When using LabelPropagation, I often run into this warning (imho it should be an error because it completely fails the propagation):

/usr/local/lib/python3.5/dist-packages/sklearn/semi_supervised/label_propagation.py:279: RuntimeWarning: invalid value encountered in true_divide self.label_distributions_ /= normalizer

So after few tries with the RBF kernel, I discovered the paramater gamma has an influence.

EDIT:

The problem comes from these lines:

        if self._variant == 'propagation':             normalizer = np.sum(                 self.label_distributions_, axis=1)[:, np.newaxis]             self.label_distributions_ /= normalizer 

I don't get how label_distributions_ can be all zeros, especially when its definition is:

self.label_distributions_ = safe_sparse_dot( graph_matrix, self.label_distributions_) 

Gamma has an influence on the graph_matrix (because graph_matrix is the result of _build_graph() that call the kernel function). OK. But still. Something's wrong

OLD POST (before edit)

I remind you how graph weights are computed for the propagation: W = exp(-gamma * D), D the pairwise distance matrix between all points of the dataset.

The problem is: np.exp(x) returns 0.0 if x very small.
Let's imagine we have two points i and j such that dist(i, j) = 10.

>>> np.exp(np.asarray(-10*40, dtype=float)) # gamma = 40 => OKAY 1.9151695967140057e-174 >>> np.exp(np.asarray(-10*120, dtype=float)) # gamma = 120 => NOT OKAY 0.0 

In practice, I'm not setting gamma manually but I'm using the method described in this paper (section 2.4).

So, how would one avoid this division by zero to get a proper propagation ?

The only way I can think of is to normalize the dataset in every dimension, but we lose some geometric/topologic property of the dataset (a 2x10 rectangle becoming a 1x1 square for example)


Reproductible example:

In this example, it's worst: even with gamma = 20 it fails.

In [11]: from sklearn.semi_supervised.label_propagation import LabelPropagation  In [12]: import numpy as np  In [13]: X = np.array([[0, 0], [0, 10]])  In [14]: Y = [0, -1]  In [15]: LabelPropagation(kernel='rbf', tol=0.01, gamma=20).fit(X, Y) /usr/local/lib/python3.5/dist-packages/sklearn/semi_supervised/label_propagation.py:279: RuntimeWarning: invalid value encountered in true_divide   self.label_distributions_ /= normalizer /usr/local/lib/python3.5/dist-packages/sklearn/semi_supervised/label_propagation.py:290: ConvergenceWarning: max_iter=1000 was reached without convergence.   category=ConvergenceWarning Out[15]:  LabelPropagation(alpha=None, gamma=20, kernel='rbf', max_iter=1000, n_jobs=1,          n_neighbors=7, tol=0.01)  In [16]: LabelPropagation(kernel='rbf', tol=0.01, gamma=2).fit(X, Y) Out[16]:  LabelPropagation(alpha=None, gamma=2, kernel='rbf', max_iter=1000, n_jobs=1,          n_neighbors=7, tol=0.01)  In [17]:  

1 Answers

Answers 1

Basically you're doing a softmax function, right?

The general way to prevent softmax from over/underflowing is (from here)

# Instead of this . . .  def softmax(x, axis = 0):     return np.exp(x) / np.sum(np.exp(x), axis = axis, keepdims = True)  # Do this def softmax(x, axis = 0):     e_x = np.exp(x - np.max(x, axis = axis, keepdims = True))     return e_x / e_x.sum(axis, keepdims = True) 

This bounds e_x between 0 and 1, and assures one value of e_x will always be 1 (namely the element np.argmax(x)). This prevents overflow and underflow (when np.exp(x.max()) is either bigger or smaller than float64 can handle).

In this case, as you can't change the algorithm, I would take the input D and make D_ = D - D.min() as this should be numerically equivalent to the above, as W.max() should be -gamma * D.min() (as you're just flipping the sign). The do your algorithm with regards to D_

EDIT:

As recommended by @PaulBrodersen below, you can build a "safe" rbf kernel based on the sklearn implementation here:

def rbf_kernel_safe(X, Y=None, gamma=None):         X, Y = sklearn.metrics.pairwise.check_pairwise_arrays(X, Y)        if gamma is None:            gamma = 1.0 / X.shape[1]         K = sklearn.metrics.pairwise.euclidean_distances(X, Y, squared=True)        K *= -gamma        K -= K.max()       np.exp(K, K)    # exponentiate K in-place        return K  

And then use it in your propagation

LabelPropagation(kernel = rbf_kernel_safe, tol = 0.01, gamma = 20).fit(X, Y) 

Unfortunately I only have v0.18, which doesn't accept user-defined kernel functions for LabelPropagation, so I can't test it.

EDIT2:

Checking your source for why you have such large gamma values makes me wonder if you are using gamma = D.min()/3, which would be incorrect. The definition is sigma = D.min()/3 while the definition of sigma in w is

w = exp(-d**2/sigma**2)  # Equation (1) 

which would make the correct gamma value 1/sigma**2 or 9/D.min()**2

Read More

Thursday, May 31, 2018

Matplotlib canvas as numpy array artefacts

Leave a Comment

I want to convert a matplotlib figure into a numpy array. I have been able to do this by accessing the contents of the renderer directly. However, when I call imshow on the numpy array it has what looks like aliasing artefacts along the edges which aren't present in the original figure.

I've tried playing around with various parameters but can't figure out how to fix the artefacts from imshow. The differences in the images remain if I save the figures to an image file.

Note that what I want to achieve is a way to confirm that the content of the array is the same as the figure I viewed before. I think probably these artefacts are not present in the numpy array but are created during the imshow call. Perhaps approriate configuration of imshow can resolve the problem.

import matplotlib.pyplot as plt import numpy as np from matplotlib.patches import Rectangle import math  fig = plt.figure(frameon=False) ax = plt.gca() ax.add_patch(Rectangle((0,0), 1, 1, angle=45, color="red")) ax.set_xlim(-2,2) ax.set_ylim(-2,2) ax.set_aspect(1) plt.axis("off") fig.canvas.draw() plt.savefig("rec1.png") plt.show() X = np.array(fig.canvas.renderer._renderer)  fig = plt.figure(frameon=False) ax = plt.gca() plt.axis("off") plt.imshow(X) plt.savefig("rec2.png") plt.show() 

enter image description here

5 Answers

Answers 1

By adding the fig.tight_layout with padding of -1.08, I was able to get the exact image as the real image.

X = np.array(fig.canvas.renderer._renderer) fig = plt.figure(frameon=False) ax = plt.gca() plt.axis("off") plt.imshow(X) fig.tight_layout(pad=-1.08) plt.savefig("rec2.png") plt.show() 

Real Image

From numpy array

I hope that solves your problem, atleast till you find a better way. Cheers.

Answers 2

The best one I can think of is by using cv2 (openCV-python) library. My solution does require saving the image and in the case of color images, the decoded images will have the channels stored in B G R order.

import matplotlib.pyplot as plt import numpy as np from matplotlib.patches import Rectangle import math import cv2 #import openCV  fig = plt.figure(frameon=False) ax = plt.gca() ax.add_patch(Rectangle((0,0), 1, 1, angle=45, color="red")) ax.set_xlim(-2,2) ax.set_ylim(-2,2) ax.set_aspect(1) plt.axis("off") fig.canvas.draw() plt.savefig("rec1.png") plt.show()`  im = cv2.imread("rec1.png") print(type(im)) #prints numpy.ndarray  cv2.imshow("pic",im) #creates a window named pic, loads im cv2.waitKey(0) #has no time limit, window destroyed on any key press cv2.destroyAllWindows() 

Final result looks like

result

Since it is a numpy array, you can call methods on it for your comparison.

print(im.shape) #prints (288, 432, 3) 

Answers 3

The image that is shown in the second plot is plotted smaller than the first image; the reason is that the complete first figure's image is squeezed into a newly created smaller axes -- this would be obvious when not turning the axes off.

In order to make sure the second figure only shows the image itself, you may adjust the margins, such that there is no spacing between the figure edge and the axes, using subplots_adjust.

fig = plt.figure(frameon=False) fig.subplots_adjust(0,0,1,1) ax = plt.gca() plt.axis("off") plt.imshow(X) 

This produces the desired plot.

Note however that the array is not exactly the same due to antialiasing being applied when saving the png file. You may find out via

X = np.array(fig.canvas.renderer._renderer)/255. Y = plt.imread("rec1.png") print(np.all(X==Y))   ## This prints False 

Inversely speaking, if you want to have the same numpy array as the one that is saved, you should make sure to use the saved image itself.

plt.savefig("rec1.png") X = plt.imread("rec1.png") # use X from here onwards 

Answers 4

These are clearly resampling artefacts, which can be avoided by using plt.figimage which specifically adds a non-resampled image to the figure.

plt.figimage(X) plt.show() 

Note that this will not work with the %matplotlib inline in Jupyter Notebook, but it does work fine with %matplotlib notebook and with GUI backends.

Answers 5

Thanks to the comments who pointed out interpolation as the cause. I found the following code (adapted for Python 3) which displays the image in the way I want; identical to the first image but via the numpy array.

import PIL.Image from io import BytesIO import IPython.display import numpy as np def showarray(a, fmt='png'):     a = np.uint8(a)     f = BytesIO()     PIL.Image.fromarray(a).save(f, fmt)     IPython.display.display(IPython.display.Image(data=f.getvalue())) 

source: https://gist.github.com/kylemcdonald/2f1b9a255993bf9b2629

Read More

Saturday, May 19, 2018

Matplotlib equivalent of pygame flip

Leave a Comment

I have a program with rapid animations which works perfectly under pygame, and for technical reasons, I need to do the same using only matplotlib or an other widespread module.

The program structure is roughly:

pygame.init()         SURF = pygame.display.set_mode((500, 500)) arr = pygame.surfarray.pixels2d(SURF) # a view for numpy, as a 2D array while ok:     # modify some pixels of arr     pygame.display.flip() pygame.quit() 

I have no low level matplotlib experience, but I think it is possible to do equivalent things with matplotlib. In other words :

How to share the bitmap of a figure, modify some pixels and refresh the screen ?

Here is a minimal working exemple, which flips 250 frames per second (more than the screen ...) on my computer :

import pygame,numpy,time pygame.init() size=(400,400)         SURF = pygame.display.set_mode(size) arr = pygame.surfarray.pixels2d(SURF) # buffer pour numpy    t0=time.clock()  for counter in range(1000):         arr[:]=numpy.random.randint(0,0xfffff,size)         pygame.display.flip()       pygame.quit()  print(counter/(time.clock()-t0)) 

EDIT

What I try with indications in answers :

import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation  fig = plt.figure()   def f(x, y):     return np.sin(x) + np.cos(y)  x = np.linspace(0, 2 * np.pi, 400) y = np.linspace(0, 2 * np.pi, 400).reshape(-1, 1)  im = plt.imshow(f(x, y), animated=True)  count=0 t0=time.clock()+1 def updatefig(*args):     global x, y,count,t0     x += np.pi / 15.     y += np.pi / 20.     im.set_array(f(x, y))     if time.clock()<t0:         count+=1     else:         print (count)         count=0         t0=time.clock()+1          return im,  ani = animation.FuncAnimation(fig, updatefig, interval=50, blit=True) plt.show() 

But this only provides 20 fps....

4 Answers

Answers 1

If you want to animate a plot, then you can take a look at the animation functionality in matplotlib under matplotlib.animation.Animation. Here's a great tutorial - https://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial.

If you just want to periodically update an adhoc bitmap, I am not sure matplotlib is meant for what you are trying to achieve. From matplotlib docs:

Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.

If you would like to periodically update an adhoc image on the screen, you may want to look into GUI libraries for python. Here is a short summary of available options - https://docs.python.org/3/faq/gui.html. Tkinter is a pretty standard one and is shipped with python. You can use the ImageTk module in pillow to create/modify images for displaying via Tkinter - http://pillow.readthedocs.io/en/4.2.x/reference/ImageTk.html.

Answers 2

It should be noted that the human brain is capable of "seeing" up to a framerate of ~25 fps. Faster updates are not actually resolved.

Matplotlib

With matplotlib and its animation module the example from the question runs with 84 fps on my computer.

import time import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation  fig, ax = plt.subplots()   def f(x, y):     return np.sin(x) + np.cos(y)  x = np.linspace(0, 2 * np.pi, 400) y = np.linspace(0, 2 * np.pi, 400).reshape(-1, 1)  im = ax.imshow(f(x, y), animated=True) text = ax.text(200,200, "")  class FPS():     def __init__(self, avg=10):         self.fps = np.empty(avg)         self.t0 = time.clock()     def tick(self):         t = time.clock()         self.fps[1:] = self.fps[:-1]         self.fps[0] = 1./(t-self.t0)         self.t0 = t         return self.fps.mean()  fps = FPS(100)  def updatefig(i):     global x, y     x += np.pi / 15.     y += np.pi / 20.     im.set_array(f(x, y))     tx = 'Mean Frame Rate:\n {fps:.3f}FPS'.format(fps= fps.tick() )      text.set_text(tx)          return im, text,  ani = animation.FuncAnimation(fig, updatefig, interval=1, blit=True) plt.show() 

PyQtGraph

In pyqtgraph a higher framerate is obtained, it would run with 295 fps on my computer.

import sys import time from pyqtgraph.Qt import QtCore, QtGui import numpy as np import pyqtgraph as pg  class FPS():     def __init__(self, avg=10):         self.fps = np.empty(avg)         self.t0 = time.clock()     def tick(self):         t = time.clock()         self.fps[1:] = self.fps[:-1]         self.fps[0] = 1./(t-self.t0)         self.t0 = t         return self.fps.mean()  fps = FPS(100)  class App(QtGui.QMainWindow):     def __init__(self, parent=None):         super(App, self).__init__(parent)          #### Create Gui Elements ###########         self.mainbox = QtGui.QWidget()         self.setCentralWidget(self.mainbox)         self.mainbox.setLayout(QtGui.QVBoxLayout())          self.canvas = pg.GraphicsLayoutWidget()         self.mainbox.layout().addWidget(self.canvas)          self.label = QtGui.QLabel()         self.mainbox.layout().addWidget(self.label)          self.view = self.canvas.addViewBox()         self.view.setAspectLocked(True)         self.view.setRange(QtCore.QRectF(0,0, 100, 100))          #  image plot         self.img = pg.ImageItem(border='w')         self.view.addItem(self.img)          #### Set Data  #####################         self.x = np.linspace(0, 2 * np.pi, 400)         self.y = np.linspace(0, 2 * np.pi, 400).reshape(-1, 1)          #### Start  #####################         self._update()      def f(self, x, y):             return np.sin(x) + np.cos(y)      def _update(self):          self.x += np.pi / 15.         self.y += np.pi / 20.         self.img.setImage(self.f(self.x, self.y))          tx = 'Mean Frame Rate:\n {fps:.3f}FPS'.format(fps= fps.tick() )          self.label.setText(tx)         QtCore.QTimer.singleShot(1, self._update)   if __name__ == '__main__':      app = QtGui.QApplication(sys.argv)     thisapp = App()     thisapp.show()     sys.exit(app.exec_()) 

Answers 3

If you just need to animate a matplotlib canvas the animation framework is the answer. There's a simple example here that does basically what you ask.

If this is going to be part of a more complex application you probably want finer control over a specific backend.

Here's a quick attempt using Qt loosely based on this matplotlib example.

It's using a QTimer for the updates, probably there's also some idle callback in Qt you could attach to.

import sys  import numpy as np import matplotlib as mpl mpl.use('qt5agg') from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure from PyQt5 import QtWidgets, QtCore  size = (400, 400)  class GameCanvas(FigureCanvas):     def __init__(self, parent=None, width=5, height=4, dpi=100):         fig = Figure(figsize=(width, height), dpi=dpi)          self.axes = fig.gca()         self.init_figure()          FigureCanvas.__init__(self, fig)         self.setParent(parent)          timer = QtCore.QTimer(self)         timer.timeout.connect(self.update_figure)         timer.start(10)      def gen_frame(self):         return np.random.randint(0,0xfffff,size)      def init_figure(self):         self.img = self.axes.imshow(self.gen_frame())      def update_figure(self):         self.img.set_data(self.gen_frame())         self.draw()  class ApplicationWindow(QtWidgets.QMainWindow):     def __init__(self):         QtWidgets.QMainWindow.__init__(self)         self.main_widget = QtWidgets.QWidget(self)          dc = GameCanvas(self.main_widget, width=5, height=4, dpi=100)         self.setCentralWidget(dc)      def fileQuit(self):         self.close()      def closeEvent(self, ce):         self.fileQuit()  app = QtWidgets.QApplication(sys.argv) appw = ApplicationWindow() appw.show() sys.exit(app.exec_()) 

One thing you should be careful with is that imshow computes the image normalization on the first frame. In the subsequent frames it's calling set_data so the normalization stays the same. If you want to update it you can call imshow instead (probably slower). Or you could just fix it manually with vmin and vmax in the first imshow call and provide properly normalized frames.

Answers 4

Given you talked about using widespread modules, here's a proof of concept using OpenCV. It runs pretty fast here, up to 250-300 generated frames per second. It's nothing too fancy, just to show that maybe if you're not using any plotting feature matplotlib shouldn't really be your first choice.

import sys                                                                                  import time                                                                                 import numpy as np                                                                          import cv2                                                                                   if sys.version_info >= (3, 3):                                                                  timer = time.perf_counter                                                               else:                                                                                           timer = time.time                                                                        def f(x, y):                                                                                    return np.sin(x) + np.cos(y)                                                             # ESC, q or Q to quit                                                                       quitkeys = 27, 81, 113                                                                      # delay between frames                                                                      delay = 1                                                                                   # framerate debug init                                                                      counter = 0                                                                                 overflow = 1                                                                                start = timer()                                                                              x = np.linspace(0, 2 * np.pi, 400)                                                          y = np.linspace(0, 2 * np.pi, 400).reshape(-1, 1)                                            while True:                                                                                     x += np.pi / 15.                                                                            y += np.pi / 20.                                                                             cv2.imshow("animation", f(x, y))                                                             if cv2.waitKey(delay) & 0xFF in quitkeys:                                                       cv2.destroyAllWindows()                                                                     break                                                                                    counter += 1                                                                                elapsed = timer() - start                                                                   if elapsed > overflow:                                                                          print("FPS: {:.01f}".format(counter / elapsed))                                             counter = 0                                                                                 start = timer()                                                                                                 
Read More

Thursday, April 26, 2018

Saving in a file an array or DataFrame together with other information

Leave a Comment

The statistical software Stata allows short text snippets to be saved within a dataset. This is accomplished either using notes and/or characteristics.

This is a feature of great value to me as it allows me to save a variety of information, ranging from reminders and to-do lists to information about how I generated the data, or even what the estimation method for a particular variable was.

I am now trying to come up with a similar functionality in Python 3.6. So far, I have looked online and consulted a number of posts, which however do not exactly address what I want to do.

A few reference posts include:

For a small NumPy array, I have concluded that a combination of the function numpy.savez() and a dictionary can store adequately all relevant information in a single file.

For example:

a = np.array([[2,4],[6,8],[10,12]]) d = {"first": 1, "second": "two", "third": 3}  np.savez(whatever_name.npz, a=a, d=d) data = np.load(whatever_name.npz)  arr = data['a'] dic = data['d'].tolist() 

However, the question remains:

Are there better ways to potentially incorporate other pieces of information in a file containing a NumPy array or a (large) Pandas DataFrame?

I am particularly interested in hearing about the particular pros and cons of any suggestions you may have with examples. The fewer dependencies, the better.

Thank you.

6 Answers

Answers 1

There are many options. I will discuss only HDF5, because I have experience using this format.

Advantages: Portable (can be read outside of Python), native compression, out-of-memory capabilities, metadata support.

Disadvantages: Reliance on single low-level C API, possibility of data corruption as a single file, deleting data does not reduce size automatically.

In my experience, for performance and portability, avoid pyTables / HDFStore to store numeric data. You can instead use the intuitive interface provided by h5py.

Store an array

import h5py, numpy as np  arr = np.random.randint(0, 10, (1000, 1000))  f = h5py.File('file.h5', 'w', libver='latest')  # use 'latest' for performance  dset = f.create_dataset('array', shape=(1000, 1000), data=arr, chunks=(100, 100)                         compression='gzip', compression_opts=9) 

Compression & chunking

There are many compression choices, e.g. blosc and lzf are good choices for compression and decompression performance respectively. Note gzip is native; other compression filters may not ship by default with your HDF5 installation.

Chunking is another option which, when aligned with how you read data out-of-memory, can significantly improve performance.

Add some attributes

dset.attrs['Description'] = 'Some text snippet' dset.attrs['RowIndexArray'] = np.arange(1000) 

Store a dictionary

for k, v in d.items():     f.create_dataset('dictgroup/'+str(k), data=v) 

Out-of-memory access

dictionary = f['dictgroup'] res = dictionary['my_key'] 

There is no substitute for reading the h5py documentation, which exposes most of the C API, but you should see from the above there is a significant amount of flexibility.

Answers 2

A practical way could be to embed meta-data directly inside the Numpy array. The advantage is that, as you'd like, there's no extra dependency and it's very simple to use in the code. However, this doesn't fully answers your question, because you still need a mechanism to save the data, and I'd recommend using jpp's solution using HDF5.

To include metadata in an ndarray, there is an example in the documentation. You basically have to subclass an ndarray and add a field info or metadata or whatever.

It would give (code from the link above)

import numpy as np  class ArrayWithInfo(np.ndarray):      def __new__(cls, input_array, info=None):         # Input array is an already formed ndarray instance         # We first cast to be our class type         obj = np.asarray(input_array).view(cls)         # add the new attribute to the created instance         obj.info = info         # Finally, we must return the newly created object:         return obj      def __array_finalize__(self, obj):         # see InfoArray.__array_finalize__ for comments         if obj is None: return         self.info = getattr(obj, 'info', None) 

To save the data through numpy, you'd need to overload the write function or use another solution.

Answers 3

I agree with JPP that hdf5 storage is a good option here. The difference between his solution and mine is mine uses Pandas dataframes instead of numpy arrays. I prefer the dataframe since this allows mixed types, multi-level indexing (even datetime indexing, which is VERY important for my work), and column labeling, which helps me remember how different datasets are organized. Also, Pandas provides a slew of built-in functionalities (much like numpy). Another benefit of using Pandas is it has a hdf creator built in (i.e. pandas.DataFrame.to_hdf), which I find convenient

When storing the dataframe to h5 you have the option of storing a dictionary of metadata as well, which can be your notes to self, or actual metadata that does not need to be stored in the dataframe (I use this for setting flags as well, e.g. {'is_agl': True, 'scale_factor': 100, 'already_corrected': False, etc.}. In this regard, there is no difference between using a numpy array and a dataframe. For the full solution see my original question and solution here.

Answers 4

jpp's answer is pretty comprehensive, just wanted to mention that as of pandas v22 parquet is very convenient and fast option with almost no drawbacks vs csv (accept perhaps the coffee break).

read parquet

write parquet

At time of writing you'll need to also

pip install pyarrow 

In terms of adding information you have the metadata which is attached to the data

import pyarrow as pa  import pyarrow.parquet as pq  import pandas as pd  import numpy as np    df = pd.DataFrame(np.random.normal(size=(1000, 10)))    tab = pa.Table.from_pandas(df)    tab = tab.replace_schema_metadata({'here' : 'it is'})    pq.write_table(tab, 'where_is_it.parq')    pq.read_table('where_is_it.parq')
which then yield a table

Pyarrow table 0: double 1: double 2: double 3: double 4: double 5: double 6: double 7: double 8: double 9: double __index_level_0__: int64 metadata -------- {b'here': b'it is'} 

To get this back to pandas:

tab.to_pandas() 

Answers 5

It's an interesting question, although very open-ended I think.

Text Snippets
For text snippets that have literal notes (as in, not code and not data), I really don't know what your use case is, but I don't see why I would deviate from using the usual with open() as f: ...

Small collections of various data pieces
Sure, your npz works. Actually what you are doing is very similar to creating a dictionary with everything you want to save and pickling that dictionary.

See here for a discussion of the differences between pickle and npz (but mainly, npz is optimized for numpy arrays).

Personally, I'd say if you are not storing Numpy arrays I would use pickle, and even implement a quick MyNotes class that is basically a dictionary to save stuff in it, with some additional functionality you may want.

Collection of large objects
For really big np.arrays or dataframes I have used before the HDF5 format. The good thing is that it is already built in into pandas and you can directly df.to_hdf5(). It does need underneath pytables -installation should be fairly painless with pip or conda- but using pytables directly can be a much bigger pain.

Again, this idea is very similar: you are creating an HDFStore, which is pretty much a big dictionary in which you can store (almost any) objects. The benefit is that the format utilizes space in a smarter way by leveraging repetition of similar values. When I was using it to store some ~2GB dataframes, it was able to reduce it by almost a full order of magnitude (~250MB).

One last player: feather
Feather is a project created by Wes McKinney and Hadley Wickham on top of the Apache Arrow framework, to persist data in a binary format that is language agnostic (and therefore you can read from R and Python). However, it is still under development, and last time I checked they didn't encourage to use it for long-term storage (since the specification may change in future versions), rather than just use it for communication between R and Python.

They both just launched Ursalabs, literally just weeks ago, that will continue growing this and similar initiatives.

Answers 6

You stated as the reasons for this question:

... it allows me to save a variety of information, ranging from reminders and to-do lists, to information about how i generated the data, or even what the estimation method for a particular variable was.

May I suggest a different paradigm than that offered by Stata? The notes and characteristics seem to be very limited and confined to just text. Instead, you should use Jupyter Notebook for your research and data analysis projects. It provides such a rich environment to document your workflow and capture details, thoughts and ideas as you are doing your analysis and research. It can easily be shared, and it's presentation-ready.

Here is a gallery of interesting Jupyter Notebooks across many industries and disciplines to showcase the many features and use cases of notebooks. It may expand your horizons beyond trying to devise a way to tag simple snippets of text to your data.

Read More

Tuesday, April 24, 2018

Does the performance of numpy differ depending on the operating system?

Leave a Comment

Reading the interesting book "From Python to Numpy" I met an example, the description of which is as follows:

Let's consider a simple example where we want to clear all the values from an array which has the dtype np.float32. How does one write it to maximize speed?

The provided results surprised me, and when I rechecked them I got a completely different behavior. So, I asked the author to double-check, but he received the same results as before (OS X 10) in the table below:

The variants were timed on three different computers: mine (Win10, Win7) and author's (OSX 10.13.3). With Python 3.6.4 and numpy 1.14.2, where each variant was timed for fixed 100 loops, best of 3.

Edit: This question is not about the fact that on different computers, with different characteristics, I get different times - this is obvious :) The question is that the behavior is very different on the two operating systems - which is not so obvious? (if it is of course so, I would be glad if someone could double-check).

The setup was: Z = np.ones(4*1000000, np.float32)

| Variant                     | Windows 10 | Ubuntu 17.10 | Windows 7 | OSX 10.13.3 | |                             |       computer 1          |   comp 2  |    comp 3   | | --------------------------- | ------------------------- | --------- | ----------- | | Z.view(np.float64)[...] = 0 | 758 usec   | 1.03 msec    | 2.72 msec | 1.01 msec   | | Z.view(np.float32)[...] = 0 | 757 usec   | 1.01 msec    | 2.61 msec | 1.58 msec   | | Z.view(np.float16)[...] = 0 | 760 usec   | 1.01 msec    | 2.62 msec | 2.85 msec   | | Z.view(np.complex)[...] = 0 | 1.06 msec  | 1.02 msec    | 3.26 msec | 918 usec    | | Z.view(np.int64)[...] = 0   | 758 usec   | 1.03 msec    | 2.69 msec | 1 msec      | | Z.view(np.int32)[...] = 0   | 757 usec   | 1.01 msec    | 2.62 msec | 1.46 msec   | | Z.view(np.int16)[...] = 0   | 760 usec   | 1.01 msec    | 2.63 msec | 2.87 msec   | | Z.view(np.int8)[...] = 0    | 758 usec   | 773 usec     | 2.68 msec | 614 usec    | | Z.fill(0)                   | 747 usec   | 998 usec     | 2.55 msec | N/A         | | Z[...] = 0                  | 750 usec   | 1 msec       | 2.59 msec | N/A         | 

As you can see from this table, on Windows the results doesn't depend on the viewed type, but on OS X this hack highly affects the performance. Can you provide the insight why this happens?

Edit: As I wrote above three computers are different.

The specs of the first computer: Windows 10 and Ubuntu 17.10
CPU: Intel Xenon E5-1650v4 3.60GHz
RAM: 128GB DDR4-2400

The specs of the second computer: Windows 7
CPU: Intel Pentium P6100 2.00GHz
RAM: 4GB DDR3-1333

The specs of the third computer: I don't have this information :)

Link to the issue

Edit 2: Add results for the first computer on Ubuntu 17.10.

1 Answers

Answers 1

Keep in mind that Python is a very high-level programming language, Pandas being also a high-level framework.

What you're essentially given to work with is a high level API for many operations that you can perform with the language, without the need to worry about the underlying implementation.

If you were to work with a lower-level API, to assign an array to a variable you'd have to allocate some memory, create a structure to hold your data, link it together (probably using pointers to memory addresses). And you didn't even touch the actual chip, there's still virtual memory mapping being done between your API and the actual data being saved to the chip. And that complexity is applied to basically everything you're doing with Python & Pandas.

Yet, you only have to do arr = [1, 2, 3], and not worry about it.

Now Python is expected to work the same on every platform you run it - at least in most of the cases.

Now, after the boring introduction is behind us - the whole idea of "expose uniform API, don't worry about implementation" is widely spread in computer programming. There are some subtle implementation details that differ one operating system from another, which may or may not impact performance of your software. I don't expect that to be significant, but it's still there and worth mentioning.

For example, there's an old answer about np.dot function performance differing between Linux and Windows. The author has way more knowledge than me on this subject, and points out that that particular function is a wrapper around CBLAS routines, which will use fastest routines available on given platform.

That being said - pandas is a very complex library which aims to make data analysis as simple as possible, through exposing simple-to-use API to the programmer. I expect that there are a lot more places where Pandas does a great job using the best mechanisms available on your platform to perform its tasks as fast as it can.

Read More

Wednesday, March 21, 2018

Feature Selection using MRMR

Leave a Comment

I found two ways to implement MRMR for feature selection in python. The source of the paper that contains the method is:

https://www.dropbox.com/s/tr7wjpc2ik5xpxs/doc.pdf?dl=0

This is my code for the dataset.

import numpy as np import pandas as pd from sklearn.datasets import make_classification  from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all"  X, y = make_classification(n_samples=10000,                            n_features=6,                            n_informative=3,                            n_classes=2,                            random_state=0,                            shuffle=False)  # Creating a dataFrame df = pd.DataFrame({'Feature 1':X[:,0],                                   'Feature 2':X[:,1],                                   'Feature 3':X[:,2],                                   'Feature 4':X[:,3],                                   'Feature 5':X[:,4],                                   'Feature 6':X[:,5],                                   'Class':y})   y_train = df['Class'] X_train = df.drop('Class', axis=1) 

Method 1: Applying MRMR using pymrmr

Contains MID and MIQ

Which is published by the author The link is https://github.com/fbrundu/pymrmr

import pymrmr  pymrmr.mRMR(df, 'MIQ',6) 

['Feature 4', 'Feature 5', 'Feature 2', 'Feature 6', 'Feature 1', 'Feature 3']

or running using the second way

pymrmr.mRMR(df, 'MID',6) 

['Feature 4', 'Feature 6', 'Feature 5', 'Feature 2', 'Feature 1', 'Feature 3']

Both these methods, on the above dataset yields this 2 output. Another author on GitHub claims that you can use his version to apply the MRMR method. However when I use it for the same dataset I have a different result.

Method 2: Applying MRMR using MIFS

Github link

https://github.com/danielhomola/mifs

import mifs  for i in range(1,11):      feat_selector = mifs.MutualInformationFeatureSelector('MRMR',k=i)     feat_selector.fit(X_train, y_train)      # call transform() on X to filter it down to selected features     X_filtered = feat_selector.transform(X_train.values)      #Create list of features     feature_name = X_train.columns[feat_selector.ranking_]       print(feature_name) 

And if you run the above iteration for all different values of i, there will come no time where both methods actually yield the same feature selection output.

What seems to be the problem here ?

1 Answers

Answers 1

You'll probably need to contact either the authors of the original paper and/or the owner of the Github repo for a final answer, but most likely the differences here come from the fact that you are comparing 3 different algorithms (despite the name).

Minimum redundancy Maximum relevance algorithms are actually a family of feature selection algorithms whose common objective is to select features that are mutually far away from each other while still having "high" correlation to the classification variable.

You can measure that objective using Mutual Information measures, but the specific method to follow(i.e. what to do with the scores computed? In what order? What other post-processing methods will be used? ...) is going to be different from one author to another - even in the paper they are actually giving you two different implementations, MIQ and MID.

So my suggestion would be to just choose the implementation you are more comfortable with (or even better, the one that produces better results in your pipeline after conducting a proper validation), and just report which specific source did you choose and why.

Read More

Wednesday, March 7, 2018

How to achieve stratified K fold splitting for arbitrary number of categorical variables?

Leave a Comment

I have a dataframe of the form, df:

    cat_var_1    cat_var_2     num_var_1 0    Orange       Monkey         34 1    Banana        Cat           56 2    Orange        Dog           22 3    Banana       Monkey          6 .. 

Suppose the possible values of cat_var_1 in the dataset have the ratios- ['Orange': 0.6, 'Banana': 0.4] and the possible values of cat_var_2 have the ratios ['Monkey': 0.2, 'Cat': 0.7, 'Dog': 0.1].

How to I split the data into train, test and validation sets (60:20:20 split) such that the ratios of the categorical variables remain preserved? In practice, these variables can be of any number, not just two. Also, clearly, the exact ratios may never be achieved in practice, but we would like it to be as near as possible.

I have looked into the StratifiedKFold method from sklearn described here: how to split a dataset into training and validation set keeping ratio between classes? but this is restricted to evaluating on the basis of one categorical variable only.

Additionally, I would be grateful if you could provide the complexity of the solution you achieve.

1 Answers

Answers 1

You can pass df.cat_var_1+ "_" + df.cat_var_2 to argument y of StratifiedShuffleSplit.split():

But here is a method that use DataFrame.groupby:

import pandas as pd import numpy as np  nrows = 10000 p1 = {'Orange': 0.6, 'Banana': 0.4} p2 = {'Monkey': 0.2, 'Cat': 0.7, 'Dog': 0.1}  c1 = [key for key, val in p1.items() for i in range(int(nrows * val))] c2 = [key for key, val in p2.items() for i in range(int(nrows * val))] random.shuffle(c1) random.shuffle(c2)  df = pd.DataFrame({"c1":c1, "c2":c2, "val":np.random.randint(0, 100, nrows)})  index = [] for key, idx in df.groupby(["c1", "c2"]).groups.items():     arr = idx.values.copy()     np.random.shuffle(arr)     p1 = int(0.6 * len(arr))     p2 = int(0.8 * len(arr))     index.append(np.split(arr, [p1, p2]))  idx_train, idx_test, idx_validate = list(map(np.concatenate, zip(*index))) 
Read More

Tuesday, January 23, 2018

How to efficiently pass function through?

Leave a Comment

Motivation

Take a look at the following picture.

enter image description here

Given are the red, blue, and green curve. I would like to find at each point on the x axis the dominating curve. This is shown as the black graph in the picture. From the properties of the red, green, and blue curve (increasing and constant after a while) this boils down to find the dominating curve on the very right hand side and then move towards the left hand side finding all intersection points and update the dominating curve.

This outlined problem should be solved T times. There is one final twist in the problem. The blue, green, and red curve of the next iteration are constructed via the dominating solution from the previous iteration plus some varying parameters. As an example in the picture above: The solution is the black function. This function is used to generate a new blue, green, and red curve. Then the problem start again to find the dominating one for these new curves etc.

Question in a nutshell
In each iteration I start at the fixed very right hand side and evaluate all three functions to see which is the dominating one. This evaluations are taking longer and longer over iteration. My feeling is that I don't pass optimally the old dominating function to construct the new blue, green, and red curve. Reason: I got in an earlier version a maximum recursion depth error. Other parts of the code where the value of the current dominating function (which is essential either the green, red, or blue curve) is required are also taking longer and longer with iteration.

For 5 iterations just evaluating the functions on one point on the very right hand side grows:

The results were produced via

test = A(5, 120000, 100000)  

And then running

test.find_all_intersections()  >>> test.find_all_intersections() iteration 4 to compute function values it took 0.0102479457855 iteration 3 to compute function values it took 0.0134601593018 iteration 2 to compute function values it took 0.0294270515442 iteration 1 to compute function values it took 0.109843969345 iteration 0 to compute function values it took 0.823768854141 

I would like to know why is this the case and if one can program it more efficiently.

Detailed Code explanation

I quickly summarize the most important functions. The complete code can be found further below. If there are any other questions regarding the code I'm more than happy to elaborate / clarify.

  1. Method u: For the recurring task of generating a new batch of the green, red, and blue curve above we need the old dominating one. u is the initialization to be used in the very first iteration.

  2. Method _function_template: The function generates versions of the green, blue, and red curve by using different parameters. It returns a function of a single input.

  3. Method eval: This is the core function to generate the blue, green, and red versions every time. It takes three varying parameters each iteration: vfunction which is the dominating function from the previous step, m, and s which are two parameters (flaots) affecting the shape of the resulting curve. The other parameters are the same in each iteration. In the code there are sample values for m and s for each iteration. For the more geeky ones: It's to approximate an integral where m and s are the expected mean and standard deviation of the underlying normal distribution. The approximation is done via Gauss-Hermite nodes / weights.

  4. Method find_all_intersections: This is the core method finding in each iteration the dominating one. It constructs a dominating function via a piece wise concatenation of the blue, green, and red curve. This is achieved via the function piecewise.

Here is the complete code

import numpy as np import pandas as pd from scipy.optimize import brentq import multiprocessing as mp import pathos as pt import timeit import math class A(object):     def u(self, w):         _w = np.asarray(w).copy()         _w[_w >= 120000] = 120000         _p = np.maximum(0, 100000 - _w)         return _w - 1000*_p**2      def __init__(self, T, upper_bound, lower_bound):         self.T = T         self.upper_bound = upper_bound         self.lower_bound = lower_bound      def _function_template(self, *args):         def _f(x):             return self.evalv(x, *args)         return _f      def evalv(self, w, c, vfunction, g, m, s, gauss_weights, gauss_nodes):         _A = np.tile(1 + m + math.sqrt(2) * s * gauss_nodes, (np.size(w), 1))         _W = (_A.T * w).T         _W = gauss_weights * vfunction(np.ravel(_W)).reshape(np.size(w),                                                              len(gauss_nodes))         evalue = g*1/math.sqrt(math.pi)*np.sum(_W, axis=1)         return c + evalue      def find_all_intersections(self):          # the hermite gauss weights and nodes for integration         # and additional paramters used for function generation          gauss = np.polynomial.hermite.hermgauss(10)         gauss_nodes = gauss[0]         gauss_weights = gauss[1]         r = np.asarray([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,                         1., 1., 1., 1., 1., 1., 1., 1., 1.])         m = [[0.038063407778193614, 0.08475713587463352, 0.15420895520972322],              [0.038212567720998125, 0.08509661835487026, 0.15484578903763624],              [0.03836174909668277, 0.08543620707856969, 0.15548297423808233],              [0.038212567720998125, 0.08509661835487026, 0.15484578903763624],              [0.038063407778193614, 0.08475713587463352, 0.15420895520972322],              [0.038063407778193614, 0.08475713587463352, 0.15420895520972322],              [0.03836174909668277, 0.08543620707856969, 0.15548297423808233],              [0.038212567720998125, 0.08509661835487026, 0.15484578903763624],              [0.038212567720998125, 0.08509661835487026, 0.15484578903763624],              [0.038212567720998125, 0.08509661835487026, 0.15484578903763624],              [0.038063407778193614, 0.08475713587463352, 0.15420895520972322],              [0.038212567720998125, 0.08509661835487026, 0.15484578903763624],              [0.038212567720998125, 0.08509661835487026, 0.15484578903763624],              [0.038212567720998125, 0.08509661835487026, 0.15484578903763624],              [0.03836174909668277, 0.08543620707856969, 0.15548297423808233],              [0.038063407778193614, 0.08475713587463352, 0.15420895520972322],              [0.038063407778193614, 0.08475713587463352, 0.15420895520972322],              [0.038212567720998125, 0.08509661835487026, 0.15484578903763624],              [0.03836174909668277, 0.08543620707856969, 0.15548297423808233],              [0.038212567720998125, 0.08509661835487026, 0.15484578903763624],              [0.038212567720998125, 0.08509661835487026, 0.15484578903763624]]          s = [[0.01945441966324046, 0.04690600929081242, 0.200125178687699],              [0.019491796104351332, 0.04699612658674578, 0.20050966545654142],              [0.019529101011406914, 0.04708607140891122, 0.20089341636351565],              [0.019491796104351332, 0.04699612658674578, 0.20050966545654142],              [0.01945441966324046, 0.04690600929081242, 0.200125178687699],              [0.01945441966324046, 0.04690600929081242, 0.200125178687699],              [0.019529101011406914, 0.04708607140891122, 0.20089341636351565],              [0.019491796104351332, 0.04699612658674578, 0.20050966545654142],              [0.019491796104351332, 0.04699612658674578, 0.20050966545654142],              [0.019491796104351332, 0.04699612658674578, 0.20050966545654142],              [0.01945441966324046, 0.04690600929081242, 0.200125178687699],              [0.019491796104351332, 0.04699612658674578, 0.20050966545654142],              [0.019491796104351332, 0.04699612658674578, 0.20050966545654142],              [0.019491796104351332, 0.04699612658674578, 0.20050966545654142],              [0.019529101011406914, 0.04708607140891122, 0.20089341636351565],              [0.01945441966324046, 0.04690600929081242, 0.200125178687699],              [0.01945441966324046, 0.04690600929081242, 0.200125178687699],              [0.019491796104351332, 0.04699612658674578, 0.20050966545654142],              [0.019529101011406914, 0.04708607140891122, 0.20089341636351565],              [0.019491796104351332, 0.04699612658674578, 0.20050966545654142],              [0.019491796104351332, 0.04699612658674578, 0.20050966545654142]]          self.solution = []          n_cpu = mp.cpu_count()         pool = pt.multiprocessing.ProcessPool(n_cpu)          # this function is used for multiprocessing         def call_f(f, x):             return f(x)          # this function takes differences for getting cross points         def _diff(f_dom, f_other):             def h(x):                 return f_dom(x) - f_other(x)             return h          # finds the root of two function         def find_roots(F, u_bound, l_bound):                 try:                     sol = brentq(F, a=l_bound,                                  b=u_bound)                     if np.absolute(sol - u_bound) > 1:                         return sol                     else:                         return l_bound                 except ValueError:                     return l_bound          # piecewise function         def piecewise(l_comp, l_f):             def f(x):                 _ind_f = np.digitize(x, l_comp) - 1                 if np.isscalar(x):                     return l_f[_ind_f](x)                 else:                     return np.asarray([l_f[_ind_f[i]](x[i])                                        for i in range(0, len(x))]).ravel()             return f          _u = self.u          for t in range(self.T-1, -1, -1):             print('iteration' + ' ' + str(t))              l_bound, u_bound = 0.5*self.lower_bound, self.upper_bound             l_ordered_functions = []             l_roots = []             l_solution = []              # build all function variations              l_functions = [self._function_template(0, _u, r[t], m[t][i], s[t][i],                                                    gauss_weights, gauss_nodes)                            for i in range(0, len(m[t]))]              # get the best solution for the upper bound on the very             # right hand side of wealth interval              array_functions = np.asarray(l_functions)             start_time = timeit.default_timer()             functions_values = pool.map(call_f, array_functions.tolist(),                                         len(m[t]) * [u_bound])             elapsed = timeit.default_timer() - start_time             print('to compute function values it took')             print(elapsed)              ind = np.argmax(functions_values)             cross_points = len(m[t]) * [u_bound]             l_roots.insert(0, u_bound)             max_m = m[t][ind]             l_solution.insert(0, max_m)              # move from the upper bound twoards the lower bound             # and find the dominating solution by exploring all cross             # points.              test = True              while test:                 l_ordered_functions.insert(0, array_functions[ind])                 current_max = l_ordered_functions[0]                  l_c_max = len(m[t]) * [current_max]                 l_u_cross = len(m[t]) * [cross_points[ind]]                  # Find new cross points on the smaller interval                  diff = pool.map(_diff, l_c_max, array_functions.tolist())                 cross_points = pool.map(find_roots, diff,                                         l_u_cross, len(m[t]) * [l_bound])                  # update the solution, cross points and current                 # dominating function.                  ind = np.argmax(cross_points)                 l_roots.insert(0, cross_points[ind])                 max_m = m[t][ind]                 l_solution.insert(0, max_m)                  if cross_points[ind] <= l_bound:                     test = False              l_ordered_functions.insert(0, l_functions[0])             l_roots.insert(0, 0)             l_roots[-1] = np.inf              l_comp = l_roots[:]             l_f = l_ordered_functions[:]              # build piecewise function which is used for next             # iteration.              _u = piecewise(l_comp, l_f)             _sol = pd.DataFrame(data=l_solution,                                 index=np.asarray(l_roots)[0:-1])             self.solution.insert(0, _sol)         return self.solution 

2 Answers

Answers 1

Let's start by changing the code to output the current iteration:

_u = self.u for t in range(0, self.T):     print(t)     lparams = np.random.randint(self.a, self.b, 6).reshape(3, 2).tolist()     functions = [self._function_template(_u, *lparams[i])                  for i in range(0, 3)]     # evaluate functions     pairs = list(itertools.combinations(functions, 2))     fval = [F(diff(*pairs[i]), self.a, self.b) for i in range(0, 3)]     ind = np.sort(np.unique(np.random.randint(self.a, self.b, 10)))     _u = _temp(ind, np.asarray(functions)[ind % 3]) 

Looking into the line causing the behaviour,

fval = [F(diff(*pairs[i]), self.a, self.b) for i in range(0, 3)] 

functions of interest would be F and diff. The latter being straightforward, the former:

def F(f, a, b):     try:         brentq(f, a=a, b=b)     except ValueError:         pass 

Hmm, swallowing exceptions, let's see what happens if we:

def F(f, a, b):     brentq(f, a=a, b=b) 

Immediately, for the first function and on the first iteration, an error is thrown:

ValueError: f(a) and f(b) must have different signs

Looking at the docs this is a prerequisite of the root finding function brentq. Let's change the definition once more to monitor this condition on each iteration.

def F(f, a, b):     try:         brentq(f, a=a, b=b)     except ValueError as e:         print(e) 

The output is

i f(a) and f(b) must have different signs f(a) and f(b) must have different signs f(a) and f(b) must have different signs 

for i ranging from 0 to 57. Meaning, the first time the function F ever does any real work is for i=58. And it keeps doing so for higher values of i.

Conclusion: it takes longer for these higher values, because:

  1. the root is never calculated for the lower values
  2. the number of calculations grows linear for i>58

Answers 2

Your code is really far too complex to explain your problem - strive for something simpler. Sometimes you have to write code just to demonstrate the problem.

I'm taking a stab, based purely on your description rather than your code (although I ran the code and verified) . Here's your problem:

method eval: This is the core function to generate the blue, green and red versions every time. It takes three varying parameters each iteration: vfunction which is the dominating function from the previous step, m and s which are two parameters (flaots) affecting the shape of the resulting curve.

Your vfunction parameter is more complex on each iteration. You are passing a nested function built up over previous iterations, which causes a recursive execution. Each iteration increases the depth of the recursive call.

How can you avoid this? There's no easy or built in way. The simplest answer is - assuming the inputs to these functions are consistent - to store the functional result (i.e. the numbers) rather than the function themselves. You can do this as long as you have a finite number of known inputs.

If the inputs to the underlying functions aren't consistent then there's no shortcut. You need to repeatedly evaluate those underlying functions. I see that you're doing some piecewise splicing of the underlying functions - you can test whether the cost of doing so exceeds the cost of simply taking the max of each of the underlying functions.

The test that I ran (10 iterations) took a few seconds. I don't see that as a problem.

Read More

Thursday, December 28, 2017

Why are numpy functions so slow on pandas series / dataframes?

Leave a Comment

Consider a small MWE, taken from another question:

DateTime                Data 2017-11-21 18:54:31     1 2017-11-22 02:26:48     2 2017-11-22 10:19:44     3 2017-11-22 15:11:28     6 2017-11-22 23:21:58     7 2017-11-28 14:28:28    28 2017-11-28 14:36:40     0 2017-11-28 14:59:48     1 

The goal is to clip all values with an upper bound of 1. My answer uses np.clip, which works fine.

np.clip(df.Data, a_min=None, a_max=1) array([1, 1, 1, 1, 1, 1, 0, 1]) 

Or,

np.clip(df.Data.values, a_min=None, a_max=1) array([1, 1, 1, 1, 1, 1, 0, 1]) 

Both of which return the same answer. My question is about the relative performance of these two methods. Consider -

df = pd.concat([df]*1000).reset_index(drop=True)  %timeit np.clip(df.Data, a_min=None, a_max=1) 1000 loops, best of 3: 270 µs per loop  %timeit np.clip(df.Data.values, a_min=None, a_max=1) 10000 loops, best of 3: 23.4 µs per loop 

Why is there such a massive difference between the two, just by calling values on the latter? In other words...

Why are numpy functions so slow on pandas objects?

4 Answers

Answers 1

Yes, it seems like np.clip is a lot slower on pandas.Series than on numpy.ndarrays. That's correct but it's actually (at least asymptomatically) not that bad. 8000 elements is still in the regime where constant factors are major contributors in the runtime. I think this is a very important aspect to the question, so I'm visualizing this (borrowing from another answer):

# Setup  import pandas as pd import numpy as np  def on_series(s):     return np.clip(s, a_min=None, a_max=1)  def on_values_of_series(s):     return np.clip(s.values, a_min=None, a_max=1)  # Timing setup timings = {on_series: [], on_values_of_series: []} sizes = [2**i for i in range(1, 26, 2)]  # Timing for size in sizes:     func_input = pd.Series(np.random.randint(0, 30, size=size))     for func in timings:         res = %timeit -o func(func_input)         timings[func].append(res)  %matplotlib notebook  import matplotlib.pyplot as plt import numpy as np  fig, (ax1, ax2) = plt.subplots(1, 2)  for func in timings:     ax1.plot(sizes,               [time.best for time in timings[func]],               label=str(func.__name__)) ax1.set_xscale('log') ax1.set_yscale('log') ax1.set_xlabel('size') ax1.set_ylabel('time [seconds]') ax1.grid(which='both') ax1.legend()  baseline = on_values_of_series # choose one function as baseline for func in timings:     ax2.plot(sizes,               [time.best / ref.best for time, ref in zip(timings[func], timings[baseline])],               label=str(func.__name__)) ax2.set_yscale('log') ax2.set_xscale('log') ax2.set_xlabel('size') ax2.set_ylabel('time relative to {}'.format(baseline.__name__)) ax2.grid(which='both') ax2.legend()  plt.tight_layout() 

enter image description here

It's a log-log plot because I think this shows the important features more clearly. For example it shows that np.clip on a numpy.ndarray is faster but it also has a much smaller constant factor in that case. The difference for large arrays is only ~3! That's still a big difference but way less than the difference on small arrays.

However, that's still not an answer to the question where the time difference comes from.

The solution is actually quite simple: np.clip delegates to the clip method of the first argument:

>>> np.clip?? Source:    def clip(a, a_min, a_max, out=None):     """     ...     """     return _wrapfunc(a, 'clip', a_min, a_max, out=out)  >>> np.core.fromnumeric._wrapfunc?? Source:    def _wrapfunc(obj, method, *args, **kwds):     try:         return getattr(obj, method)(*args, **kwds)     # ...     except (AttributeError, TypeError):         return _wrapit(obj, method, *args, **kwds) 

The getattr line of the _wrapfunc function is the important line here, because np.ndarray.clip and pd.Series.clip are different methods, yes, completely different methods:

>>> np.ndarray.clip <method 'clip' of 'numpy.ndarray' objects> >>> pd.Series.clip <function pandas.core.generic.NDFrame.clip> 

Unfortunately is np.ndarray.clip a C-function so it's hard to profile it, however pd.Series.clip is a regular Python function so it's easy to profile. Let's use a Series of 5000 integers here:

s = pd.Series(np.random.randint(0, 100, 5000)) 

For the np.clip on the values I get the following line-profiling:

%load_ext line_profiler %lprun -f np.clip -f np.core.fromnumeric._wrapfunc np.clip(s.values, a_min=None, a_max=1)  Timer unit: 4.10256e-07 s  Total time: 2.25641e-05 s File: numpy\core\fromnumeric.py Function: clip at line 1673  Line #      Hits         Time  Per Hit   % Time  Line Contents ==============================================================   1673                                           def clip(a, a_min, a_max, out=None):   1674                                               """   ...   1726                                               """   1727         1           55     55.0    100.0      return _wrapfunc(a, 'clip', a_min, a_max, out=out)  Total time: 1.51795e-05 s File: numpy\core\fromnumeric.py Function: _wrapfunc at line 55  Line #      Hits         Time  Per Hit   % Time  Line Contents ==============================================================     55                                           def _wrapfunc(obj, method, *args, **kwds):     56         1            2      2.0      5.4      try:     57         1           35     35.0     94.6          return getattr(obj, method)(*args, **kwds)     58                                                59                                               # An AttributeError occurs if the object does not have     60                                               # such a method in its class.     61                                                62                                               # A TypeError occurs if the object does have such a method     63                                               # in its class, but its signature is not identical to that     64                                               # of NumPy's. This situation has occurred in the case of     65                                               # a downstream library like 'pandas'.     66                                               except (AttributeError, TypeError):     67                                                   return _wrapit(obj, method, *args, **kwds) 

But for np.clip on the Series I get a totally different profiling result:

%lprun -f np.clip -f np.core.fromnumeric._wrapfunc -f pd.Series.clip -f pd.Series._clip_with_scalar np.clip(s, a_min=None, a_max=1)  Timer unit: 4.10256e-07 s  Total time: 0.000823794 s File: numpy\core\fromnumeric.py Function: clip at line 1673  Line #      Hits         Time  Per Hit   % Time  Line Contents ==============================================================   1673                                           def clip(a, a_min, a_max, out=None):   1674                                               """   ...   1726                                               """   1727         1         2008   2008.0    100.0      return _wrapfunc(a, 'clip', a_min, a_max, out=out)  Total time: 0.00081846 s File: numpy\core\fromnumeric.py Function: _wrapfunc at line 55  Line #      Hits         Time  Per Hit   % Time  Line Contents ==============================================================     55                                           def _wrapfunc(obj, method, *args, **kwds):     56         1            2      2.0      0.1      try:     57         1         1993   1993.0     99.9          return getattr(obj, method)(*args, **kwds)     58                                                59                                               # An AttributeError occurs if the object does not have     60                                               # such a method in its class.     61                                                62                                               # A TypeError occurs if the object does have such a method     63                                               # in its class, but its signature is not identical to that     64                                               # of NumPy's. This situation has occurred in the case of     65                                               # a downstream library like 'pandas'.     66                                               except (AttributeError, TypeError):     67                                                   return _wrapit(obj, method, *args, **kwds)  Total time: 0.000804922 s File: pandas\core\generic.py Function: clip at line 4969  Line #      Hits         Time  Per Hit   % Time  Line Contents ==============================================================   4969                                               def clip(self, lower=None, upper=None, axis=None, inplace=False,   4970                                                        *args, **kwargs):   4971                                                   """   ...   5021                                                   """   5022         1           12     12.0      0.6          if isinstance(self, ABCPanel):   5023                                                       raise NotImplementedError("clip is not supported yet for panels")   5024                                              5025         1           10     10.0      0.5          inplace = validate_bool_kwarg(inplace, 'inplace')   5026                                              5027         1           69     69.0      3.5          axis = nv.validate_clip_with_axis(axis, args, kwargs)   5028                                              5029                                                   # GH 17276   5030                                                   # numpy doesn't like NaN as a clip value   5031                                                   # so ignore   5032         1          158    158.0      8.1          if np.any(pd.isnull(lower)):   5033         1            3      3.0      0.2              lower = None   5034         1           26     26.0      1.3          if np.any(pd.isnull(upper)):   5035                                                       upper = None   5036                                              5037                                                   # GH 2747 (arguments were reversed)   5038         1            1      1.0      0.1          if lower is not None and upper is not None:   5039                                                       if is_scalar(lower) and is_scalar(upper):   5040                                                           lower, upper = min(lower, upper), max(lower, upper)   5041                                              5042                                                   # fast-path for scalars   5043         1            1      1.0      0.1          if ((lower is None or (is_scalar(lower) and is_number(lower))) and   5044         1           28     28.0      1.4                  (upper is None or (is_scalar(upper) and is_number(upper)))):   5045         1         1654   1654.0     84.3              return self._clip_with_scalar(lower, upper, inplace=inplace)   5046                                              5047                                                   result = self   5048                                                   if lower is not None:   5049                                                       result = result.clip_lower(lower, axis, inplace=inplace)   5050                                                   if upper is not None:   5051                                                       if inplace:   5052                                                           result = self   5053                                                       result = result.clip_upper(upper, axis, inplace=inplace)   5054                                              5055                                                   return result  Total time: 0.000662153 s File: pandas\core\generic.py Function: _clip_with_scalar at line 4920  Line #      Hits         Time  Per Hit   % Time  Line Contents ==============================================================   4920                                               def _clip_with_scalar(self, lower, upper, inplace=False):   4921         1            2      2.0      0.1          if ((lower is not None and np.any(isna(lower))) or   4922         1           25     25.0      1.5                  (upper is not None and np.any(isna(upper)))):   4923                                                       raise ValueError("Cannot use an NA value as a clip threshold")   4924                                              4925         1           22     22.0      1.4          result = self.values   4926         1          571    571.0     35.4          mask = isna(result)   4927                                              4928         1           95     95.0      5.9          with np.errstate(all='ignore'):   4929         1            1      1.0      0.1              if upper is not None:   4930         1          141    141.0      8.7                  result = np.where(result >= upper, upper, result)   4931         1           33     33.0      2.0              if lower is not None:   4932                                                           result = np.where(result <= lower, lower, result)   4933         1           73     73.0      4.5          if np.any(mask):   4934                                                       result[mask] = np.nan   4935                                              4936         1           90     90.0      5.6          axes_dict = self._construct_axes_dict()   4937         1          558    558.0     34.6          result = self._constructor(result, **axes_dict).__finalize__(self)   4938                                              4939         1            2      2.0      0.1          if inplace:   4940                                                       self._update_inplace(result)   4941                                                   else:   4942         1            1      1.0      0.1              return result 

I stopped going into the subroutines at that point because it already highlights where the pd.Series.clip does much more work than the np.ndarray.clip. Just compare the total time of the np.clip call on the values (55 timer units) to one of the first checks in the pandas.Series.clip method, the if np.any(pd.isnull(lower)) (158 timer units). At that point the pandas method didn't even start at clipping and it already takes 3 times longer.

However several of these "overheads" become insignificant when the array is big:

s = pd.Series(np.random.randint(0, 100, 1000000))  %lprun -f np.clip -f np.core.fromnumeric._wrapfunc -f pd.Series.clip -f pd.Series._clip_with_scalar np.clip(s, a_min=None, a_max=1)  Timer unit: 4.10256e-07 s  Total time: 0.00593476 s File: numpy\core\fromnumeric.py Function: clip at line 1673  Line #      Hits         Time  Per Hit   % Time  Line Contents ==============================================================   1673                                           def clip(a, a_min, a_max, out=None):   1674                                               """   ...   1726                                               """   1727         1        14466  14466.0    100.0      return _wrapfunc(a, 'clip', a_min, a_max, out=out)  Total time: 0.00592779 s File: numpy\core\fromnumeric.py Function: _wrapfunc at line 55  Line #      Hits         Time  Per Hit   % Time  Line Contents ==============================================================     55                                           def _wrapfunc(obj, method, *args, **kwds):     56         1            1      1.0      0.0      try:     57         1        14448  14448.0    100.0          return getattr(obj, method)(*args, **kwds)     58                                                59                                               # An AttributeError occurs if the object does not have     60                                               # such a method in its class.     61                                                62                                               # A TypeError occurs if the object does have such a method     63                                               # in its class, but its signature is not identical to that     64                                               # of NumPy's. This situation has occurred in the case of     65                                               # a downstream library like 'pandas'.     66                                               except (AttributeError, TypeError):     67                                                   return _wrapit(obj, method, *args, **kwds)  Total time: 0.00591302 s File: pandas\core\generic.py Function: clip at line 4969  Line #      Hits         Time  Per Hit   % Time  Line Contents ==============================================================   4969                                               def clip(self, lower=None, upper=None, axis=None, inplace=False,   4970                                                        *args, **kwargs):   4971                                                   """   ...   5021                                                   """   5022         1           17     17.0      0.1          if isinstance(self, ABCPanel):   5023                                                       raise NotImplementedError("clip is not supported yet for panels")   5024                                              5025         1           14     14.0      0.1          inplace = validate_bool_kwarg(inplace, 'inplace')   5026                                              5027         1           97     97.0      0.7          axis = nv.validate_clip_with_axis(axis, args, kwargs)   5028                                              5029                                                   # GH 17276   5030                                                   # numpy doesn't like NaN as a clip value   5031                                                   # so ignore   5032         1          125    125.0      0.9          if np.any(pd.isnull(lower)):   5033         1            2      2.0      0.0              lower = None   5034         1           30     30.0      0.2          if np.any(pd.isnull(upper)):   5035                                                       upper = None   5036                                              5037                                                   # GH 2747 (arguments were reversed)   5038         1            2      2.0      0.0          if lower is not None and upper is not None:   5039                                                       if is_scalar(lower) and is_scalar(upper):   5040                                                           lower, upper = min(lower, upper), max(lower, upper)   5041                                              5042                                                   # fast-path for scalars   5043         1            2      2.0      0.0          if ((lower is None or (is_scalar(lower) and is_number(lower))) and   5044         1           32     32.0      0.2                  (upper is None or (is_scalar(upper) and is_number(upper)))):   5045         1        14092  14092.0     97.8              return self._clip_with_scalar(lower, upper, inplace=inplace)   5046                                              5047                                                   result = self   5048                                                   if lower is not None:   5049                                                       result = result.clip_lower(lower, axis, inplace=inplace)   5050                                                   if upper is not None:   5051                                                       if inplace:   5052                                                           result = self   5053                                                       result = result.clip_upper(upper, axis, inplace=inplace)   5054                                              5055                                                   return result  Total time: 0.00575753 s File: pandas\core\generic.py Function: _clip_with_scalar at line 4920  Line #      Hits         Time  Per Hit   % Time  Line Contents ==============================================================   4920                                               def _clip_with_scalar(self, lower, upper, inplace=False):   4921         1            2      2.0      0.0          if ((lower is not None and np.any(isna(lower))) or   4922         1           28     28.0      0.2                  (upper is not None and np.any(isna(upper)))):   4923                                                       raise ValueError("Cannot use an NA value as a clip threshold")   4924                                              4925         1          120    120.0      0.9          result = self.values   4926         1         3525   3525.0     25.1          mask = isna(result)   4927                                              4928         1           86     86.0      0.6          with np.errstate(all='ignore'):   4929         1            2      2.0      0.0              if upper is not None:   4930         1         9314   9314.0     66.4                  result = np.where(result >= upper, upper, result)   4931         1           61     61.0      0.4              if lower is not None:   4932                                                           result = np.where(result <= lower, lower, result)   4933         1          283    283.0      2.0          if np.any(mask):   4934                                                       result[mask] = np.nan   4935                                              4936         1           78     78.0      0.6          axes_dict = self._construct_axes_dict()   4937         1          532    532.0      3.8          result = self._constructor(result, **axes_dict).__finalize__(self)   4938                                              4939         1            2      2.0      0.0          if inplace:   4940                                                       self._update_inplace(result)   4941                                                   else:   4942         1            1      1.0      0.0              return result 

There are still multiple function calls, for example isna and np.where, that take a significant amount of time, but overall this is at least comparable to the np.ndarray.clip time (that's in the regime where the timing difference is ~3 on my computer).

The takeaway should probably be:

  • Many NumPy functions just delegate to a method of the object passed in, so there can be huge differences when you pass in different objects.
  • Profiling, especially line-profiling, can be a great tool to find the places where the performance difference comes from.
  • Always make sure to test differently sized objects in such cases. You could be comparing constant factors that probably don't matter except if you process lots of small arrays.

Used versions:

Python 3.6.3 64-bit on Windows 10 Numpy 1.13.3 Pandas 0.21.1 

Answers 2

Just read the source code, it's clear.

def clip(a, a_min, a_max, out=None):     """a : array_like Array containing elements to clip."""     return _wrapfunc(a, 'clip', a_min, a_max, out=out)  def _wrapfunc(obj, method, *args, **kwds):     try:         return getattr(obj, method)(*args, **kwds)     #This situation has occurred in the case of     # a downstream library like 'pandas'.     except (AttributeError, TypeError):         return _wrapit(obj, method, *args, **kwds)  def _wrapit(obj, method, *args, **kwds):     try:         wrap = obj.__array_wrap__     except AttributeError:         wrap = None     result = getattr(asarray(obj), method)(*args, **kwds)     if wrap:         if not isinstance(result, mu.ndarray):             result = asarray(result)         result = wrap(result)     return result 

rectify:

after pandas v0.13.0_ahl1,pandas has it's own implement of clip.

Answers 3

There are two parts to the performance difference to be aware of here:

  • Python overhead in each library (pandas being extra helpful)
  • Difference in numeric algorithm implementation (pd.clip actually calls np.where)

Running this on a very small array should demonstrate the difference in Python overhead. For numpy, this is understandably very small, however pandas does a lot of checking (null values, more flexible argument processing, etc) before getting to the heavy number crunching. I've tried to show a rough breakdown of the stages which the two codes go through before hitting C code bedrock.

data = pd.Series(np.random.random(100)) 

When using np.clip on an ndarray, the overhead is simply the numpy wrapper function calling the object's method:

>>> %timeit np.clip(data.values, 0.2, 0.8)        # numpy wrapper, calls .clip() on the ndarray >>> %timeit data.values.clip(0.2, 0.8)            # C function call  2.22 µs ± 125 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) 1.32 µs ± 20.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) 

Pandas spends more time checking for edge cases before getting to the algorithm:

>>> %timeit np.clip(data, a_min=0.2, a_max=0.8)   # numpy wrapper, calls .clip() on the Series >>> %timeit data.clip(lower=0.2, upper=0.8)       # pandas API method >>> %timeit data._clip_with_scalar(0.2, 0.8)      # lowest level python function  102 µs ± 1.54 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) 90.4 µs ± 1.01 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) 73.7 µs ± 805 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) 

Relative to overall time, the overhead of both libraries before hitting C code is pretty significant. For numpy, the single wrapping instruction takes as much time to execute as the numeric processing. Pandas has ~30x more overhead just in the first two layers of function calls.

To isolate what is happening at the algorithm level, we should check this on a larger array and benchmark the same functions:

>>> data = pd.Series(np.random.random(1000000))  >>> %timeit np.clip(data.values, 0.2, 0.8) >>> %timeit data.values.clip(0.2, 0.8)  2.85 ms ± 37.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) 2.85 ms ± 15.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)  >>> %timeit np.clip(data, a_min=0.2, a_max=0.8) >>> %timeit data.clip(lower=0.2, upper=0.8) >>> %timeit data._clip_with_scalar(0.2, 0.8)  12.3 ms ± 135 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) 12.3 ms ± 115 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) 12.2 ms ± 76.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) 

The python overhead in both cases is now negligible; time for wrapper functions and argument checking is small relative to the calculation time on 1 million values. However there is a 3-4x speed difference which can be attributed to numeric implementation. By investigating a bit in the source code, we see that the pandas implementation of clip actually uses np.where, not np.clip:

def clip_where(data, lower, upper):     ''' Actual implementation in pd.Series._clip_with_scalar (minus NaN handling). '''     result = data.values     result = np.where(result >= upper, upper, result)     result = np.where(result <= lower, lower, result)     return pd.Series(result)  def clip_clip(data, lower, upper):     ''' What would happen if we used ndarray.clip instead. '''     return pd.Series(data.values.clip(lower, upper)) 

The additional effort required to check each boolean condition separately before doing a conditional replace would seem to account for the speed difference. Specifying both upper and lower would result in 4 passes through the numpy array (two inequality checks and two calls to np.where). Benchmarking these two functions shows that 3-4x speed ratio:

>>> %timeit clip_clip(data, lower=0.2, upper=0.8) >>> %timeit clip_where(data, lower=0.2, upper=0.8)  11.1 ms ± 101 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) 2.97 ms ± 76.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) 

I'm not sure why the pandas devs went with this implementation. np.clip may be a newer API function that previously required a workaround. There is also a little more to it than I've gone into here, since pandas checks for various case before running the final algorithm, and this is only one of the implementations that may be called.

Answers 4

The reason why the performance differs is because numpy first tends to search for pandas implementation of the function using getattr than doing the same in builtin numpy functions when a pandas object is passed.

Its not the numpy over the pandas object that is slow, its the pandas version.

When you do

np.clip(pd.Series([1,2,3,4,5]),a_min=None,amax=1)   

_wrapfunc is being called :

# Code from source  def _wrapfunc(obj, method, *args, **kwds):     try:         return getattr(obj, method)(*args, **kwds) 

Due to _wrapfunc's getattr method :

getattr(pd.Series([1,2,3,4,5]),'clip')(None, 1) # Equivalent to `pd.Series([1,2,3,4,5]).clip(lower=None,upper=1)` # 0    1 # 1    1 # 2    1 # 3    1 # 4    1 # dtype: int64 

If you go through the pandas implementation there is a lot of pre checking work that is done. Its the reason why the functions which has the pandas implementation done via numpy has such difference in speed.

Not only clip, functions like cumsum,cumprod,reshape,searchsorted,transpose and much more uses pandas version of them than numpy when you pass them a pandas object.

It might appear numpy is doing the work over those objects but under the hood its the pandas function.

Read More