Showing posts with label scikit-learn. Show all posts
Showing posts with label scikit-learn. Show all posts

Thursday, September 13, 2018

Feature extraction and take color histogram

Leave a Comment

I am working on an image processing feature extraction. I have a photo of a bird in which I have to extract bird area and tell what color the bird has. I used canny feature extraction method to get the edges of a bird.

How to extract only bird area and make the background to blue color?

openCv solution should also be fine.

enter image description here

import skimage import numpy as np %matplotlib inline import matplotlib.pyplot as plt  import os filename = os.path.join(os.getcwd(),'image\image_bird.jpeg') from skimage import io bird =io.imread(filename,as_grey=True) plt.imshow(bird) 

enter image description here

from skimage import feature edges = feature.canny(bird,sigma=1) plt.imshow(edges ) 

enter image description here

Actual bird image can be taken from bird link

2 Answers

Answers 1

  1. Identify the edges of your imageSobel edge map

  2. Binarize the image via automatic thresholdingbinarized edge map

  3. Use contour detection to identify black regions which are inside a white region and merge them with the white region. (Mockup, image may slightly vary) Mockup of the merged mask

  4. Use the created image as mask to color the background and color it final image This can be done by simply setting each background pixel (black) to its respective color.

As you can see, the approach is far from perfect, but should give you a general idea about how to accomplish your task. The final image quality might be improved by slightly eroding the map to tighten it to the contours of the bird. You then also use the mask to calculate your color histogram by only taking foreground pixels into account. Edit: Look here:

  1. Eroded mask

eroded mask

  1. Final image

Final image with eroded mask

Answers 2

According to this article https://www.pyimagesearch.com/2016/04/11/finding-extreme-points-in-contours-with-opencv/ and this question CV - Extract differences between two images

I wrote some python code as below. As my predecessor said it is also far from perfect. The main disadvantages of this code are constants value to set manually: minThres (50), maxThres(100), dilate iteration count and erode iteration count.

import cv2 import numpy as np  windowName = "Edges" pictureRaw = cv2.imread("bird.jpg")  ## set to gray pictureGray = cv2.cvtColor(pictureRaw,  cv2.COLOR_BGR2GRAY)  ## blur pictureGaussian = cv2.GaussianBlur(pictureGray, (7,7), 0)  ## canny edge detector - you must specify threshold values pictureCanny = cv2.Canny(pictureGaussian, 50, 100)  ## perform a series of erosions + dilations to remove any small regions of noise pictureDilate = cv2.dilate(pictureCanny, None, iterations=20) pictureErode = cv2.erode(pictureDilate, None, iterations=5)  ## find the nozero regions in the erode imask2 = pictureErode>0  ## create a Mat like pictureRaw canvas = np.full_like(pictureRaw, np.array([255,0,0]), dtype=np.uint8)  ## set mask  canvas[imask2] = pictureRaw[imask2] cv2.imwrite("result.png", canvas) 
Read More

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, August 9, 2018

Method to determine polygon surface rotation from top-down camera

Leave a Comment

I have a webcam looking down on a surface which rotates about a single-axis. I'd like to be able to measure the rotation angle of the surface.

The camera position and the rotation axis of the surface are both fixed. The surface is a distinct solid color right now, but I do have the option to draw features on the surface if it would help.

Here's an animation of the surface moving through its full range, showing the different apparent shapes:

enter image description here

My approach thus far:

  1. Record a series of "calibration" images, where the surface is at a known angle in each image
  2. Threshold each image to isolate the surface.
  3. Find the four corners with cv2.approxPolyDP(). I iterate through various epsilon values until I find one that yields exactly 4 points.
  4. Order the points consistently (top-left, top-right, bottom-right, bottom-left)
  5. Compute the angles between each points with atan2.
  6. Use the angles to fit a sklearn linear_model.linearRegression()

This approach is getting me predictions within about 10% of actual with only 3 training images (covering full positive, full negative, and middle position). I'm pretty new to both opencv and sklearn; is there anything I should consider doing differently to improve the accuracy of my predictions? (Probably increasing the number of training images is a big one??)

I did experiment with cv2.moments directly as my model features, and then some values derived from the moments, but these did not perform as well as the angles. I also tried using a RidgeCV model, but it seemed to perform about the same as the linear model.

3 Answers

Answers 1

If I'm clear, you want to estimate the Rotation of the polygon with respect to the camera. If you know the length of the object in 3D, you can use solvePnP to estimate the pose of the object, from which you can get the Rotation of the object.

Steps:

  1. Calibrate your webcam and get the intrinsic matrix and distortion matrix.

  2. Get the 3D measurements of the object corners and find the corresponding points in 2d. Let me assume a rectangular planar object and the corners in 3d will be (0,0,0), (0, 100, 0), (100, 100, 0), (100, 0, 0).

  3. Use solvePnP to get the rotation and translation of the object

The rotation will be the rotation of your object along the axis. Here you can find an example to estimate the pose of the head, you can modify it to suit your application

Answers 2

Your first step is good -- everything after that becomes way way way more complicated than necessary (if I understand correctly).

Don't think of it as 'learning,' just think of it as a reference. Every time you're in a particular position where you DON'T know the angle, take a picture, and find the reference picture that looks most like it. Guess it's THAT angle. You're done! (They may well be indeterminacies, maybe the relationship isn't bijective, but that's where I'd start.)

You can consider this a 'nearest-neighbor classifier,' if you want, but that's just to make it sound better. Measure a simple distance (Euclidean! Why not!) between the uncertain picture, and all the reference pictures -- meaning, between the raw image vectors, nothing fancy -- and choose the angle that corresponds to the minimum distance between observed, and known.

If this isn't working -- and maybe, do this anyway -- stop throwing away so much information! You're stripping things down, then trying to re-estimate them, propagating error all over the place for no obvious (to me) benefit. So when you do a nearest neighbor, reference pictures and all that, why not just use the full picture? (Maybe other elements will change in it? That's a more complicated question, but basically, throw away as little as possible -- it should all be useful in, later, accurately choosing your 'nearest neighbor.')

Answers 3

Another option that is rather easy to implement, especially since you've done a part of the job is the following (I've used it to compute the orientation of a cylindrical part from 3 images acquired when the tube was rotating) :

  1. Threshold each image to isolate the surface.
  2. Find the four corners with cv2.approxPolyDP(), alternatively you could find the four sides of your part with LineSegmentDetector (available from OpenCV 3).
  3. Compute the angle alpha, as depicted on the image hereunder compute alpha

When your part is rotating, this angle alpha will follow a sine curve. That is, you will measure alpha(theta) = A sin(theta + B) + C. Given alpha you want to know theta, but first you need to determine A, B and C.

  1. You've acquired many "calibration" or reference images, you can use all of these to fit a sine curve and determine A, B and C.
  2. Once this is done, you can determine theta from alpha.

Notice that you have to deal with sin(a+Pi/2) = sin(a). It is not a problem if you acquire more than one image sequentially, if you have a single static image, you have to use an extra mechanism.

Hope I'm clear enough, the implementation really shouldn't be a problem given what you have done already.

Read More

Sunday, May 13, 2018

Using Boosting tree to generate feature in sklearn

Leave a Comment

I am referring to this link to Feature Transformation using tree ensembles for the context.

Specifically for below part of code, in the sample of the link, the method of (1) using Boosting tree to generate feature, then using LR to train, outperforms (2) using Boosting tree itself. Questions,

  1. Wondering if it is true in general case using Boosting tree to generate feature (and using another classifier to classify) is better than using Boosting tree to do classification itself?
  2. And also wondering why using Boosting tree to generate feature, then using LR to train, outperforms using Boosting tree itself?

    grd = GradientBoostingClassifier(n_estimators=n_estimator) grd_enc = OneHotEncoder() grd_lm = LogisticRegression() grd.fit(X_train, y_train) grd_enc.fit(grd.apply(X_train)[:, :, 0]) grd_lm.fit(grd_enc.transform(grd.apply(X_train_lr)[:, :, 0]), y_train_lr) 

1 Answers

Answers 1

Interesting sources are paper_1 and paper_2 and additional references in them.

So to answer your questions:

  1. Very general statement, looking at some experimental results in the above papers there seem to be some exceptions. However, most of the time it does improve the score.
  2. The main idea behind doing so is to map features into a space where samples are linearly separable. If it really is the case, then linear classifiers shine.
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, March 6, 2018

`ImportError: cannot import name _remove_dead_weakref` while importing from scikit learn

Leave a Comment

PROBLEM DESCRIPTION

I'm getting this error while calling a python script :

Traceback (most recent call last):   File "/path/t/file/file.py", line 61, in <module>     from sklearn.externals import joblib   File "/anaconda2/lib/python2.7/site-packages/sklearn/__init__.py", line 20, in <module>     import logging   File "/anaconda2/lib/python2.7/logging/__init__.py", line 26, in <module>     import sys, os, time, cStringIO, traceback, warnings, weakref, collections   File "/anaconda2/lib/python2.7/weakref.py", line 14, in <module>     from _weakref import ( ImportError: cannot import name _remove_dead_weakref Failed to load file 

As stated in the error log, this happens when I import :

from sklearn.externals import joblib 

NOTES

NOTE 1: calling import sklearn alone also produces this error.

NOTE 2: Running without any other import statements and the rest of the code in the file commented out also produces the error

NOTE 3: Objective-C code is calling this python file via the Python C API (https://docs.python.org/2/c-api/index.html). This works perfectly on another machine with the exact same specs and OS (see details below).

NOTE 4: There is no error if I call Python from the terminal then import sklearn OR from sklearn.externals import joblib (Without calling from objective-C)

NOTE 5: I don't think I have any virtual environments installed. I've tried calling pyenv, pyvenv and virtualenv on the terminal. Always getting -bash: pyvenv: command not found

DETAILS

Both machines I've tried this on are MacBook Pros with identical specs running Mac OS 10.13. (The code works on one of them and fails on the other)

I've tried this on the machine the code fails on :

I've added the following lines to both (a) the script called by the executable AND (b) on the python CLI on the terminal :

print ">>>>>>>>>"+str(sys.executable) print ">>>>>>>>>"+str(sys.version) print "++++++++++++++++++++++++++++++++++++++++++++++++++++" for p in sys.path:      print p 

Output from the script that's failing :

>>>>>>>>>/anaconda2/bin/python >>>>>>>>>2.7.10 (default, Feb  6 2017, 23:53:20)  [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] ++++++++++++++++++++++++++++++++++++++++++++++++++++ /anaconda2/lib/python27.zip /anaconda2/lib/python2.7 /anaconda2/lib/python2.7/plat-darwin /anaconda2/lib/python2.7/plat-mac /anaconda2/lib/python2.7/plat-mac/lib-scriptpackages /anaconda2/lib/python2.7/lib-tk /anaconda2/lib/python2.7/lib-old /anaconda2/lib/python2.7/lib-dynload /anaconda2/lib/python2.7/site-packages /anaconda2/lib/python2.7/site-packages/aeosa ~/Desktop/Test Software/Sources/*****/path/to/.py/file/*****/Classification 

Output on the terminal :

>>> sys.executable '/anaconda2/bin/python'  >>> sys.version '2.7.14 |Anaconda, Inc.| (default, Dec  7 2017, 11:07:58) \n[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)]'  >>> for p in sys.path: ...     print p ...   /anaconda2/lib/python27.zip /anaconda2/lib/python2.7 /anaconda2/lib/python2.7/plat-darwin /anaconda2/lib/python2.7/plat-mac /anaconda2/lib/python2.7/plat-mac/lib-scriptpackages /anaconda2/lib/python2.7/lib-tk /anaconda2/lib/python2.7/lib-old /anaconda2/lib/python2.7/lib-dynload /anaconda2/lib/python2.7/site-packages /anaconda2/lib/python2.7/site-packages/aeosa 

Basically, getting the same thing, except for the version, and that I'm (obviously) also seeing the path to the .py file in the search path.

2 Answers

Answers 1

Try to uninstall, then install again your package:

conda uninstall scikit-learn

Answers 2

Try following the below commands. I faced a similar issue I was able to resolve it using:

  1. sudo pip uninstall scikit-learn
  2. sudo pip install -U scikit-learn

Make sure following dependencies are met: Scikit-learn requires:

Python (>= 2.7 or >= 3.3) NumPy (>= 1.8.2), SciPy (>= 0.13.3)

Also checkout this Link.

For Note5: pyenv command does not exist in Python 2. You can use virtualenv instead.

Read More

Friday, March 2, 2018

Lime vs TreeInterpreter for interpreting decision tree

Leave a Comment

Lime source: https://github.com/marcotcr/lime

treeinterpreter source: tree interpreter

I am trying to understand how the DecisionTree made its predictions using Lime and treeinterpreter. While both claim they are able to interpret the decision tree in their description. It seems like both interpret the same DecisionTree in different ways. That is, the feature contribution order. How is that possible? if both are looking at the same thing and are trying to describe the same event but assign importance in difference order.

Who should we trust? Especially where the top feature does matter in prediction.

The code for tree

import sklearn import sklearn.datasets import sklearn.ensemble import numpy as np import lime import lime.lime_tabular from __future__ import print_function np.random.seed(1) from treeinterpreter import treeinterpreter as ti from sklearn.tree import DecisionTreeClassifier  iris = sklearn.datasets.load_iris()  dt = DecisionTreeClassifier(random_state=42)                 dt.fit(iris.data, iris.target)  n = 100   instances =iris.data[n].reshape(1,-1)  prediction, biases, contributions = ti.predict(dt, instances)   for i in range(len(instances)):     print ("prediction:",prediction)     print ("-"*20)      print ("Feature contributions:")     print ("-"*20)       for c, feature in sorted(zip(contributions[i],                                   iris.feature_names),                               key=lambda x: ~abs(x[0].any())):          print (feature, c) 

The code for lime

import sklearn import sklearn.datasets import sklearn.ensemble import numpy as np import lime import lime.lime_tabular from __future__ import print_function np.random.seed(1) from sklearn.tree import DecisionTreeClassifier  iris = sklearn.datasets.load_iris()  dt = DecisionTreeClassifier(random_state=42)                 dt.fit(iris.data, iris.target)  explainer = lime.lime_tabular.LimeTabularExplainer(iris.data, feature_names=iris.feature_names,                                                     class_names=iris.target_names,                                                     discretize_continuous=False)  n = 100   exp = explainer.explain_instance(iris.data[n], dt.predict_proba, num_features=4, top_labels=2)  exp.show_in_notebook(show_table=True,  predict_proba= True , show_predicted_value = True , show_all=False) 

Lets look first at the output of the tree.

enter image description here

so a it did correctly say it was a virginica. However by assigning the importance in

1) petal width (cm) then petal length (cm)

Now lets look at the output of lime

enter image description here

Yes, it does say the algorithm predicted virginica however looking at how it made that classification, we clearly see the following

1) petal length (cm) > petal width (cm) in lime instead of petal length (cm) < petal width (cm) as shown in tree

2) where sepal width and sepal length was predicted zero, lime claims of certain value, as shown in the uploaded images

What is happening here ?

The problem grows when the features are 1000+ where every digit does matter to take a decision.

1 Answers

Answers 1

Why is it possible for the two approaches to have different results?

Lime: A short explanation of how it works, taken from their github page:

Intuitively, an explanation is a local linear approximation of the model's behaviour. While the model may be very complex globally, it is easier to approximate it around the vicinity of a particular instance. While treating the model as a black box, we perturb the instance we want to explain and learn a sparse linear model around it, as an explanation. The figure below illustrates the intuition for this procedure. The model's decision function is represented by the blue/pink background, and is clearly nonlinear. The bright red cross is the instance being explained (let's call it X). We sample instances around X, and weight them according to their proximity to X (weight here is indicated by size). We then learn a linear model (dashed line) that approximates the model well in the vicinity of X, but not necessarily globally.

There is much more detailed information in various links on the github page.

treeinterpreter: An explanation of how this one works is available on http://blog.datadive.net/interpreting-random-forests/ (this is for regression; an example for classification, which works very similarly, can be found here).

In short: suppose we have a node that compares feature F to some value and splits instances based on that. Suppose that 50% of all instances reaching that node belong to class C. Suppose we have a new instance, and it ends up getting assigned to the left child of this node, where now 80% of all instances belong to class C. Then, the contribution of feature F for this decision is computed as 0.8 - 0.5 = 0.3 (plus additional terms if there are more nodes along the path to leaf that also use feature F).

Comparison: The important thing to note is that Lime is a model-independent method (not specific to Decision Trees / RFs), which is based on local linear approximation. Treeinterpreter, on the other hand, specifically operates in a similar manner to the Decision Tree itself, and really looks at which features are actually used in comparisons by the algorithm. So they're really fundamentally doing quite different things. Lime says "a feature is important if we wiggle it a bit and this results in a different prediction". Treeinterpreter says "a feature is important if it was compared to a threshold in one of our nodes and this caused us to take a split that drastically changed our prediction".


Which one to trust?

This is difficult to answer definitively. They're probably both useful in their own way. Intuitively, you may be inclined to lean towards treeinterpreter at first glance, because it was specifically created for Decision Trees. However, consider the following example:

  • Root Node: 50% of instances class 0, 50% class 1. IF F <= 50, go left, otherwise go right.
  • Left Child: 48% of instances class 0, 52% class 1. Subtree below this.
  • Right Child: 99% of instances class 0, 1% of instances class 1. Subtree below this.

This kind of setup is possible if the majority of instances go left, only some right. Now suppose we have an instance with F = 49 that got assigned to the left and ultimately assigned class 1. Treeinterpreter won't care that F was really close to ending up on the other side of the equation in the root node, and only assign a low contribution of 0.48 - 0.50 = -0.02. Lime will notice that changing F just a little bit would completely change the odds.

Which one is right? That's not really clear. You could say that F was really important because if it had been only a little bit different the prediction would be different (then lime wins). You could also argue that F did not contribute to our final prediction because we hardly got any closer to a decision after inspecting its value, and still had to investigate many other features afterwards. Then treeinterpreter wins.

To get a better idea here, it may help to also actually plot the learned Decision Tree itself. Then you can manually follow along its decision path and decide which features you think were important and/or see if you can understand why both Lime and treeinterpreter say what they say.

Read More

Tuesday, October 24, 2017

How do I get the components for LDA in scikit-learn?

Leave a Comment

When using PCA in sklearn, it's easy to get out the components:

from sklearn import decomposition pca = decomposition.PCA(n_components=n_components) pca_data = pca.fit(input_data) pca_components = pca.components_ 

But I can't for the life of me figure out how to get the components out of LDA, as there is no components_ attribute. Is there a similar attribute in sklearn lda?

4 Answers

Answers 1

In the case of PCA, the documentation is clear. The pca.components_ are the eigenvectors.

In the case of LDA, we need the lda.scalings_ attribute.

Example using iris data and sklearn:

import numpy as np import matplotlib.pyplot as plt from sklearn import datasets import pandas as pd from sklearn.preprocessing import StandardScaler from sklearn.discriminant_analysis import LinearDiscriminantAnalysis   iris = datasets.load_iris() X = iris.data y = iris.target #In general a good idea is to scale the data scaler = StandardScaler() scaler.fit(X) X=scaler.transform(X)  lda = LinearDiscriminantAnalysis() lda.fit(X,y)  x_new = lda.transform(X)     def myplot(score,coeff,labels=None):     xs = score[:,0]     ys = score[:,1]     n = coeff.shape[0]      plt.scatter(xs ,ys, c = y) #without scaling     for i in range(n):         plt.arrow(0, 0, coeff[i,0], coeff[i,1],color = 'r',alpha = 0.5)         if labels is None:             plt.text(coeff[i,0]* 1.15, coeff[i,1] * 1.15, "Var"+str(i+1), color = 'g', ha = 'center', va = 'center')         else:             plt.text(coeff[i,0]* 1.15, coeff[i,1] * 1.15, labels[i], color = 'g', ha = 'center', va = 'center')  plt.xlabel("LD{}".format(1)) plt.ylabel("LD{}".format(2)) plt.grid()  #Call the function.   # Important: here I think that lda.scalings_ contains the 2 eigenvectors (loadings of the variables). The shape is [n_features,n_components] so [4,2] in our case. So in the myplot function I plot for each variable i, the values that are in [i,0] and [i,1]. All these assuming that the lda.scalings_ contain the eigenvectors.  myplot(x_new[:,0:2], lda.scalings_)  plt.show() 

Verify that the lda.scalings_ are the eigenvectors:

print(lda.scalings_) print(lda.transform(np.identity(4))) 

Results

Results

Answers 2

There is an coef_ Attribute that probably contains what you are looking for. It should be documented. As this is a linear decision function, coef_ is probably the right name in the sklearn naming scheme.

You can also directly use the transform method to project data to the new space.

Answers 3

My reading of the code is that the coef_ attribute is used to weight each of the components when scoring a sample's features against the different classes. scaling is the eigenvector and xbar_ is the mean. In the spirit of UTSL, here's the source for the decision function: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/lda.py#L188

Answers 4

In PCA, the transform operation uses self.components_.T (see the code):

    X_transformed = np.dot(X, self.components_.T) 

In LDA, the transform operation uses self.scalings_ (see the code):

    X_new = np.dot(X, self.scalings_) 


Note the .T which transposes the array in the PCA, and not in LDA:

  • PCA: components_ : array, shape (n_components, n_features)
  • LDA: scalings_ : array, shape (n_features, n_classes - 1)
Read More

Wednesday, September 6, 2017

What's wrong with my implementation of Neural Networks?

Leave a Comment

enter image description hereI want to plot the learning error curve of a neural net with respect to the number of training examples. Here is the code :

import sklearn import numpy as np from sklearn.model_selection import learning_curve import matplotlib.pyplot as plt from sklearn import neural_network from sklearn import cross_validation  myList=[] myList2=[] w=[]  dataset=np.loadtxt("data", delimiter=",") X=dataset[:, 0:6] Y=dataset[:,6] clf=sklearn.neural_network.MLPClassifier(hidden_layer_sizes=(2,3),activation='tanh')  # split the data between training and testing X_train, X_test, Y_train, Y_test = cross_validation.train_test_split(X, Y, test_size=0.25, random_state=33)  # begin with few training datas X_eff=X_train[0:int(len(X_train)/150), : ] Y_eff=Y_train[0:int(len(Y_train)/150)]  k=int(len(X_train)/150)-1   for m in range (140) :       print (m)      w.append(k)      # train the model and store the training error     A=clf.fit(X_eff,Y_eff)     myList.append(1-A.score(X_eff,Y_eff))        # compute the testing error     myList2.append(1-A.score(X_test,Y_test))      # add some more training datas     X_eff=np.vstack((X_eff,X_train[k+1:k+101,:]))     Y_eff=np.hstack((Y_eff,Y_train[k+1:k+101]))     k=k+100  plt.figure(figsize=(8, 8)) plt.subplots_adjust() plt.title("Erreur d'entrainement et de test") plt.plot(w,myList,label="training error") plt.plot(w,myList2,label="test error") plt.legend() plt.show() 

However, I get a very strange result, with curves fluctuating, the training error very close to the testing error which does not appear to be normal. Where is the mistake? I can't understand why there are so many ups and downs and why the training error does not increase, as it would be expected to.Any help would be appreciated !

EDIT : the dataset I am using is https://archive.ics.uci.edu/ml/datasets/Chess+%28King-Rook+vs.+King%29 where I got rid of the classes having less than 1000 instances. I manually re-encoded the litteral data.

3 Answers

Answers 1

I think that the reason you're seeing this kind of curve is that the performance metric you are measuring is different from the performance metric that you are optimizing.

Optimization metric

The neural network minimizes a loss function, and in the case of tanh activiations, I assume you are using a modified version of the cross entropy loss. If you were to plot the loss over time, you would see a more monotonically decreasing error function like you expect. (Not actually monotonic because neural networks are non-convex, but that's beside the point.)

Performance metric

The performance metric that you are measuring is the percent accuracy, which is different from the loss. Why are these different? The loss function tells us how much error we have in a differentiable way (which is important for fast optimization methods). The accuracy metric tells us how well we predict, which is useful for application of the neural network.

Putting it together

Because you are plotting the performance of a related metric, you can expect that the plot will look similar to that of your optimized metric. However because they are not the same, you may be introducing some unaccounted-for variance in your plot (as evidenced by the plot you posted).

There are a couple of ways to fix this.

  1. Plot the loss instead of the accuracy. This doesn't actually fix your problem if you actually need the accuracy plot, but it will give you much more smooth curves.
  2. Plot an average over multiple runs. Save the accuracy plots over 20 independent runs of your algorithm (as in train the network 20 times), then average them together and plot this. That will greatly reduce the variance.

TL;DR

Don't expect the accuracy plot to always be smooth and monotonically decreasing, it won't be.

Answers 2

Randomize training set and repeat

If you would like a fair comparison of the effect of the number of training sample on the accuracy, I suggest to randomly pick n_samples from your training set instead of adding 100 samples to the previous batch. You would also repeat the fit N_repeat times for each n_samples value.

This would give something like this (not tested):

n_samples_array = np.arange(100,len(X_train),100) N_repeat = 10  for n_samples in n_samples_array:     print(n_samples)      # repeat the fit several times and take the mean     myList_tmp, myList2_tmp = [],[]     for repeat in range(0,N_repeat):         # Randomly pick samples         selection = np.random.choice(range(0,len(X_train)),n_samples,repeat=False)          # train the model and store the training error         A=clf.fit(X_train[selection],Y_train[selection])         myList_tmp.append(1-A.score(X_train[selection],Y_train[selection]))            # compute the testing error         myList2_tmp.append(1-A.score(X_test,Y_test))      myList.append(np.mean(myList_tmp))     myList2.append(np.mean(myList2_tmp)) 

Warm start

When you use the fit function, you restart the optimization from scratch. If you would like to see the improvement on your optimization when adding a few sample to the same previously trained network, you can use the option warm_start=True

As per the documentation:

warm_start : bool, optional, default False

When set to True, reuse the solution of the previous call to fit as initialization, otherwise, just erase the previous solution.

Answers 3

In addition to the previous answers you should also have in mind, that you might have to tweak the learning rate (by setting learning_rate = value in the initializer) of the network. If you choose the rate to big, you will jump from on local minimum to another or circle around these points, but won't actually converge (see the image below, taken from here).

Furthermore, please also plot the loss and not just the accuracy of your network. This will give you better insights about it.

Also, keep in mind, that you have to use a lot of training and test data to get a more or less "smooth" curve, or even a representative curve; if you are using just a few (maybe a few hundred) data points, the resulting metrics will not actually be very accurate, as they contain a lot of stochastic things. To solve this error you should not train the network with the same examples every time, but rather change the orders of your training data, and maybe split it up on different mini batches. I am very confident, that you can solve or even reduce your problem by trying to mind these aspects and to implement them.

Depending on your kind of problem, you should change the activation function to something different than the tanh function. Performing a classification, a OneHotEncoder might also be useful (if your data is not already one hot encoded); the sklearn framework is offering an implementation of this, too.

Read More

Wednesday, July 19, 2017

How to perform cluster with weights/density in python? Something like kmeans with weights?

Leave a Comment

My data is like this:

powerplantname, latitude, longitude, powergenerated A, -92.3232, 100.99, 50 B, <lat>, <long>, 10 C, <lat>, <long>, 20 D, <lat>, <long>, 40 E, <lat>, <long>, 5 

I want to be able to cluster the data into N number of clusters (say 3). Normally I would use a kmeans:

import numpy as np  import matplotlib.pyplot as plt from scipy.cluster.vq import kmeans2, whiten coordinates= np.array([            [lat, long],            [lat, long],             ...            [lat, long]            ]) x, y = kmeans2(whiten(coordinates), 3, iter = 20)   plt.scatter(coordinates[:,0], coordinates[:,1], c=y); plt.show() 

The problem with this is it does not account for any weighting (in this case, my powergenerated value) I want to ideally have my clusters taking the value "powergenerated" into account, trying to keep the clusters not only spatially close, but also have close to relatively equal total powergenerated.

Should I be doing this with kmeans (or some other method)? Or is there something else I should be using for this problem that would be better?

1 Answers

Answers 1

Or is there something else I should be using for this problem that would be better?

In order to take into account simultaneously the geographical distance among centrals and the generated power you should define a proper metric. The function below computes the distance between two points on Earth's surface from their latitudes and longitudes through the haversine formula and adds the absolute value of the generated power difference multiplied by a weighting factor. The value of the weight determines the relative influence of distance and power difference in the clustering process.

import numpy as np  def custom_metric(central_1, central_2, weight=1):     lat1, lng1, pow1 = central_1     lat2, lng2, pow2 = central_2      lat1, lat2, lng1, lng2 = np.deg2rad(np.asarray([lat1, lat2, lng1, lng2]))      dlat = lat2 - lat1     dlng = lng2 - lng1      h = (1 - np.cos(dlat))/2. + np.cos(lat1)*np.cos(lat2)*(1 - np.cos(dlng))/2.     km = 2*6371*np.arcsin(np.sqrt(h))      MW = np.abs(pow2 - pow1)      return km + weight*MW 

Should I be doing this with kmeans (or some other method)?

Unfortunately the current implementations of SciPy's kmeans2 and scikit-learn's KMeans only support Euclidean distance. An alternative method would consist in performing hierarchical clustering through the SciPy's clustering package to group the centrals according to the metric just defined.

Demo

Let us first generate mock data, namely feature vectors for 8 centrals with random values:

N = 8 np.random.seed(0) lat = np.random.uniform(low=-90, high=90, size=N) lng = np.random.uniform(low=-180, high=180, size=N) power = np.random.randint(low=5, high=50, size=N) data = np.vstack([lat, lng, power]).T 

The content of variable data yielded by the snippet above looks like this:

array([[   8.7864,  166.9186,   21.    ],        [  38.7341,  -41.9611,   10.    ],        [  18.4974,  105.021 ,   20.    ],        [   8.079 ,   10.4022,    5.    ],        [ -13.7421,   24.496 ,   23.    ],        [  26.2609,  153.2148,   40.    ],        [ -11.2343, -154.427 ,   29.    ],        [  70.5191, -148.6335,   34.    ]]) 

To divide those data into three different groups we have to pass data and custom_metric to the linkage function (check the docs to find out more on parameter method), and then pass the returned linkage matrix to the cut_tree function with n_clusters=3.

from scipy.cluster.hierarchy import linkage, cut_tree Z = linkage(data, method='average', metric=custom_metric) y = cut_tree(Z, 3).flatten() 

As a result we get the group membership (array y) for each central:

array([0, 1, 0, 2, 2, 0, 0, 1]) 

The results above depend on the value of weight. If you wish to use a value different to 1 (for example 250) you can change the default value like this:

def custom_metric(central_1, central_2, weight=250): 

Alternatively, you could set the parameter metric in the call to linkage to a lambda expression as follows: metric=lambda x, y: custom_metric(x, y, 250).

Finally, to gain a deeper insight into the hierarchical/agglomerative clustering you could plot it as a dendrogram:

from scipy.cluster.hierarchy import dendrogram dendrogram(Z) 

dendrogram

Read More

Monday, April 10, 2017

sklearn classification_report with input from pandas dataframe prduces: “TypeError: not all arguments converted during string formatting”

Leave a Comment

I am trying to run sklearn.metrics.classification_report with my data being in a Pandas dataframe. The dataframe df_joined looks like this and has a 100 rows:

Timestamp    Label       Pred 2016-10-05   29.75  30.781430 2016-10-06   30.35  31.379146 2016-10-07   31.59  31.174824 2017-02-13   29.63  29.875497 2017-02-14   29.60  29.923161 2017-02-15   30.22  30.257284 2017-02-16   30.12  30.374257 2017-02-17   30.09  30.357196 2017-02-20   31.03  30.971070 2017-02-21   31.05  30.930189 

I am now trying to print the classification_report by

print 'Classification Report:', '\n', sklearn.metrics.classification_report(df_joined[label],df_joined['Pred'] ) 

and I am getting the error:

File "\Python\WinPython-32bit-2.7.10.3\python-2.7.10\lib\site-packages\sklearn\utils\multiclass.py", line 106, in unique_labels raise ValueError("Unknown label type: %r" % ys)

TypeError: not all arguments converted during string formatting

I have been trying to use sklearn.metrics.classification_report(df_joined[label].values, df_joined['Pred'].values) instead but it produces the same error.

Has someone a idea where this is coming from?

2 Answers

Answers 1

I believe classification_report quantifies how well you have classified/predicted the label of a data point, not its actual value. A label can't be a float, all the examples in the sklearn documentation and the sklearn user guide uses integers for their labels.

The parameters also hints at this, as the alternative to passing a 1-d array is a specific array construct for labels only.

sklearn.metrics.classification_report(y_true, y_pred, labels=None,target_names=None, sample_weight=None, digits=2)  y_true : 1d array-like, or label indicator array / sparse matrix      Ground truth (correct) target values.  y_pred : 1d array-like, or label indicator array / sparse matrix      Estimated targets as returned by a classifier.  ... 

If your data would have been integer-labels, the exact dataframe format you passed would have worked fine:

# Does not raise an error  classification_report(df_joined['Label'].astype(int), df_joined['Pred'].astype(int)) 

You can read more about sklearn's different model evaluation tools in Model evaluation: quantifying the quality of predictions, and pick one that is suitable to evaluate your classifier.

Answers 2

What happens if you take them out as list types?

I.e.

print 'Classification Report:', '\n', sklearn.metrics.classification_report(df_joined['Label'].tolist(),df_joined['Pred'].tolist() )

Read More

Sunday, July 31, 2016

Scikit-learn SVM digit recognition

Leave a Comment

I want to make a program to recognize the digit in an image. I follow the tutorial in scikit learn .

I can train and fit the svm classifier like the following.

First, I import the libraries and dataset

from sklearn import datasets, svm, metrics  digits = datasets.load_digits() n_samples = len(digits.images) data = digits.images.reshape((n_samples, -1)) 

Second, I create the SVM model and train it with the dataset.

classifier = svm.SVC(gamma = 0.001) classifier.fit(data[:n_samples], digits.target[:n_samples]) 

And then, I try to read my own image and use the function predict() to recognize the digit.

Here is my image: enter image description here

I reshape the image into (8, 8) and then convert it to a 1D array.

img = misc.imread("w1.jpg") img = misc.imresize(img, (8, 8)) img = img[:, :, 0] 

Finally, when I print out the prediction, it returns [1]

predicted = classifier.predict(img.reshape((1,img.shape[0]*img.shape[1] ))) print predicted 

Whatever I user others images, it still returns [1]

enter image description here enter image description here

When I print out the "default" dataset of number "9", it looks like:enter image description here

My image number "9" :

enter image description here

You can see the non-zero number is quite large for my image.

I dont know why. I am looking for help to solve my problem. Thanks

6 Answers

Answers 1

My best bet would be that there is a problem with your data types and array shapes.

It looks like you are training on numpy arrays that are of the type np.float64 (or possibly np.float32 on 32 bit systems, I don't remember) and where each image has the shape (64,).

Meanwhile your input image for prediction, after the resizing operation in your code, is of type uint8 and shape (1, 64).

I would first try changing the shape of your input image since dtype conversions often just work as you would expect. So change this line:

predicted = classifier.predict(img.reshape((1,img.shape[0]*img.shape[1] )))

to this:

predicted = classifier.predict(img.reshape(img.shape[0]*img.shape[1]))

If that doesn't fix it, you can always try recasting the data type as well with

img = img.astype(digits.images.dtype).

I hope that helps. Debugging by proxy is a lot harder than actually sitting in front of your computer :)

Edit: According to the SciPy documentation, the training data contains integer values from 0 to 16. The values in your input image should be scaled to fit the same interval. (http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html#sklearn.datasets.load_digits)

Answers 2

1) You need to create your own training set - based on data similar to what you will be making predictions. The call to datasets.load_digits() in scikit-learn is loading a preprocessed version of the MNIST Digits dataset, which, for all we know, could have very different images to the ones that you are trying to recognise.

2) You need to set the parameters of your classifier properly. The call to svm.SVC(gamma = 0.001) is just choosing an arbitrary value of the gamma parameter in SVC, which may not be the best option. In addition, you are not configuring the C parameter - which is pretty important for SVMs. I'd bet that this is one of the reasons why your output is 'always 1'.

3) Whatever final settings you choose for your model, you'll need to use a cross-validation scheme to ensure that the algorithm is effectively learning

There's a lot of Machine Learning theory behind this, but, as a good start, I would really recommend to have a look at SVM - scikit-learn for a more in-depth description of how the SVC implementation in sickit-learn works, and GridSearchCV for a simple technique for parameter setting.

Answers 3

It's just a guess but... The Training set from Sk-Learn are black numbers on a white background. And you are trying to predict numbers which are white on a black background...

I think you should either train on your training set, or train on the negative version of your pictures.

I hope this help !

Answers 4

If you look at: http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html#sklearn.datasets.load_digits

you can see that each point in the matrix as a value between 0-16.

You can try to transform the values of the image to between 0-16. I did it and now the prediction works well for the digit 9 but not for 8 and 6. It doesn't give 1 any more.

from sklearn import datasets, svm, metrics import cv2 import numpy as np  # Load digit database digits = datasets.load_digits() n_samples = len(digits.images) data = digits.images.reshape((n_samples, -1))  # Train SVM classifier classifier = svm.SVC(gamma = 0.001) classifier.fit(data[:n_samples], digits.target[:n_samples])  # Read image "9" img = cv2.imread("w1.jpg") img = img[:,:,0]; img = cv2.resize(img, (8, 8))  # Normalize the values in the image to 0-16 minValueInImage = np.min(img) maxValueInImage = np.max(img) normaliizeImg = np.floor(np.divide((img - minValueInImage).astype(np.float),(maxValueInImage-minValueInImage).astype(np.float))*16)  # Predict predicted = classifier.predict(normaliizeImg.reshape((1,normaliizeImg.shape[0]*normaliizeImg.shape[1] ))) print predicted 

Answers 5

Hi in addition to @carrdelling respond, i will add that you may use the same training set, if you normalize your images to have the same range of value. For example you could binaries your data ( 1 if > 0, 0 else ) or you could divide by the maximum intensity in your image to have an arbitrary interval [0;1].

Answers 6

You probably want to extract features relevant to to your data set from the images and train your model on them. One example I copied from here.

surf = cv2.SURF(400) kp, des = surf.detectAndCompute(img,None)

But the SURF features may not be the most useful or relevant to your dataset and training task. You should try others too like HOG or others.

Remember this more high level the features you extract the more general/error-tolerant your model will be to unseen images. However, you may be sacrificing accuracy in your known samples and test cases.

Read More

Sunday, June 19, 2016

How is cv_values_ computed in sklearn.linear::RidgeCV?

Leave a Comment

The reproducible example to fix the discussion:

from sklearn.linear_model import RidgeCV from sklearn.datasets import load_boston from sklearn.preprocessing import scale   boston = scale(load_boston().data) target = load_boston().target  import numpy as np alphas = np.linspace(1.0,200.0, 5) fit0 = RidgeCV(alphas=alphas, store_cv_values = True, gcv_mode='eigen').fit(boston, target) fit0.alpha_ fit0.cv_values_[:,0] 

The question: what formula is used to compute fit0.cv_values_?

Edit:

@Abhinav Arora answer below seems to suggests that fit0.cv_values_[:,0][0], the first entry of fit0.cv_values_[:,0] would be

(fit1.predict(boston[0,].reshape(1, -1)) - target[0])**2 

where fit1 is a ridge regression with alpha = 1.0, fitted to the data-set from which observation 0 was removed.

Let's see:

1) create new dataset with first row of original dataset removed:

from sklearn.linear_model import Ridge boston1 = np.delete(boston, (0), axis=0) target1 = np.delete(target, (0), axis=0) 

2) fit a ridge model with alpha = 1.0 on this truncated dataset:

fit1 = Ridge(alpha=1.0).fit(boston1, target1) 

3) check the MSE of that model on the first data-point:

(fit1.predict(boston[0,].reshape(1, -1)) - target[0])**2 

it is array([ 37.64650853]) which is not the same as what is produced by the fit0.cv_values_[:,0], ergo:

fit0.cv_values_[:,0][0] 

which is 37.495629960571137

What gives?

2 Answers

Answers 1

Quoting from the Sklearn documentation:

Cross-validation values for each alpha (if store_cv_values=True and cv=None). After fit() has been called, this attribute will contain the mean squared errors (by default) or the values of the {loss,score}_func function (if provided in the constructor).

Since you have not provided any scoring function in the constructor and also not provided anything for the cv argument in the constructor, this attribute should store the mean squared error for each sample using Leave-One out cross validation. The general formula for Mean Squared Error is

Mean Squared Error

where the Y (with the cap) is the prediction of your regressor and the other Y is the true value.

In your case, you are doing Leave-One out cross validation. Therefore, in every fold you have only 1 test point and thus n = 1. So, in your case doing a fit0.cv_values_[:,0] will simply give you the squared error for every point in your training data set when it was a part of the test fold and when the value of alpha was 1.0

Hope that helps.

Answers 2

Let's look - it's open source after all

The first call to fit makes a call upwards to its parent, _BaseRidgeCV (line 997, in that implementation). We haven't provided a cross-validation generator, so we make another call upwards to _RidgeGCV.fit. There' plenty of math in the documentation of this function, but we're so close to the source that I'll let you go and read about it.

Here's the actual source

    v, Q, QT_y = _pre_compute(X, y)     n_y = 1 if len(y.shape) == 1 else y.shape[1]     cv_values = np.zeros((n_samples * n_y, len(self.alphas)))     C = []      scorer = check_scoring(self, scoring=self.scoring, allow_none=True)     error = scorer is None      for i, alpha in enumerate(self.alphas):         weighted_alpha = (sample_weight * alpha                           if sample_weight is not None                           else alpha)         if error:             out, c = _errors(weighted_alpha, y, v, Q, QT_y)         else:             out, c = _values(weighted_alpha, y, v, Q, QT_y)         cv_values[:, i] = out.ravel()         C.append(c) 

Note the un-exciting pre_compute function

def _pre_compute(self, X, y):     # even if X is very sparse, K is usually very dense     K = safe_sparse_dot(X, X.T, dense_output=True)     v, Q = linalg.eigh(K)     QT_y = np.dot(Q.T, y)     return v, Q, QT_y 

Abinav has explained what's going on on a mathematical level -it's simply accumulating the weighted mean squared error. The details of their implementation, and where it differs from your implementation, can be evaluated step-by-step from the code

Read More

Friday, May 6, 2016

Appropriate Deep Learning Structure for multi-class classification

Leave a Comment

I have the following data

         feat_1    feat_2 ... feat_n   label gene_1   100.33     10.2  ... 90.23    great gene_2   13.32      87.9  ... 77.18    soso .... gene_m   213.32     63.2  ... 12.23    quitegood 

The size of M is large ~30K rows, and N is much smaller ~10 columns. My question is what is the appropriate Deep Learning structure to learn and test the data like above.

At the end of the day, the user will give a vector of genes with expression.

gene_1   989.00 gene_2   77.10 ... gene_N   100.10 

And the system will label which label does each gene apply e.g. great or soso, etc...

By structure I mean one of these:

  • Convolutional Neural Network (CNN)
  • Autoencoder
  • Deep Belief Network (DBN)
  • Restricted Boltzman Machine

3 Answers

Answers 1

To expand a little on @sung-kim 's comment:

  • CNN's are used primarily for problems in computer imaging, such as classifying images. They are modelled on animals visual cortex, they basically have a connection network such that there are tiles of features which have some overlap. Typically they require a lot of data, more than 30k examples.
  • Autoencoder's are used for feature generation and dimensionality reduction. They start with lots of neurons on each layer, then this number is reduced, and then increased again. Each object is trained on itself. This results in the middle layers (low number of neurons) providing a meaningful projection of the feature space in a low dimension.
  • While I don't know much about DBN's they appear to be a supervised extension of the Autoencoder. Lots of parameters to train.
  • Again I don't know much about Boltzmann machines, but they aren't widely used for this sort of problem (to my knowledge)

As with all modelling problems though, I would suggest starting from the most basic model to look for signal. Perhaps a good place to start is Logistic Regression before you worry about deep learning.

If you have got to the point where you want to try deep learning, for whatever reasons. Then for this type of data a basic feed-forward network is the best place to start. In terms of deep-learning, 30k data points is not a large number, so always best start out with a small network (1-3 hidden layers, 5-10 neurons) and then get bigger. Make sure you have a decent validation set when performing parameter optimisation though. If your a fan of the scikit-learn API, I suggest that Keras is a good place to start

One further comment, you will want to use a OneHotEncoder on your class labels before you do any training.

EDIT

I see from the bounty and the comments that you want to see a bit more about how these networks work. Please see the example of how to build a feed-forward model and do some simple parameter optisation

import numpy as np from sklearn import preprocessing from keras.models import Sequential from keras.layers.core import Dense, Activation, Dropout  # Create some random data np.random.seed(42) X = np.random.random((10, 50))  # Similar labels labels = ['good', 'bad', 'soso', 'amazeballs', 'good'] labels += labels labels = np.array(labels) np.random.shuffle(labels)  # Change the labels to the required format numericalLabels = preprocessing.LabelEncoder().fit_transform(labels) numericalLabels = numericalLabels.reshape(-1, 1) y = preprocessing.OneHotEncoder(sparse=False).fit_transform(numericalLabels)  # Simple Keras model builder def buildModel(nFeatures, nClasses, nLayers=3, nNeurons=10, dropout=0.2):     model = Sequential()     model.add(Dense(nNeurons, input_dim=nFeatures))     model.add(Activation('sigmoid'))     model.add(Dropout(dropout))     for i in xrange(nLayers-1):         model.add(Dense(nNeurons))         model.add(Activation('sigmoid'))         model.add(Dropout(dropout))     model.add(Dense(nClasses))     model.add(Activation('softmax'))      model.compile(loss='categorical_crossentropy', optimizer='sgd')      return model  # Do an exhaustive search over a given parameter space for nLayers in xrange(2, 4):     for nNeurons in xrange(5, 8):         model = buildModel(X.shape[1], y.shape[1], nLayers, nNeurons)         modelHist = model.fit(X, y, batch_size=32, nb_epoch=10,                               validation_split=0.3, shuffle=True, verbose=0)         minLoss = min(modelHist.history['val_loss'])         epochNum = modelHist.history['val_loss'].index(minLoss)         print '{0} layers, {1} neurons best validation at'.format(nLayers, nNeurons),         print 'epoch {0} loss = {1:.2f}'.format(epochNum, minLoss) 

Which outputs

2 layers, 5 neurons best validation at epoch 0 loss = 1.18 2 layers, 6 neurons best validation at epoch 0 loss = 1.21 2 layers, 7 neurons best validation at epoch 8 loss = 1.49 3 layers, 5 neurons best validation at epoch 9 loss = 1.83 3 layers, 6 neurons best validation at epoch 9 loss = 1.91 3 layers, 7 neurons best validation at epoch 9 loss = 1.65 

Answers 2

Deep learning structure would be recommended if you were dealing with raw data and wanted to find features, that work towards your classification goal, automatically. But based on the names of your columns and their number (only 10) it seems that you have your features already engineered.

For this reason you could just go with a standard multi-layer neural network and use supervised learning (back propagation). Such network would have the number of inputs matching the number of your columns (10), followed by a number of hidden layers, and then followed by an output layer with the number of neurons matching the number of your labels. You could experiment with using different number of hidden layers, neurons, different neuron types (sigmoid, tanh, rectified linear etc.) and so on.

Alternatively you could use the raw data (if it's available) and then go with DBNs (they're known to be robust and achieve good results across different problems) or auto-encoders.

Answers 3

If you expect the output to be thought of like scores for a label (as I understood from your question), try a supervised multi-class logistic regression classifier. (the highest score takes the label).

If you're bound to use deep-learning.

A simple feed-forward ANN should do, supervise learning through back propagation. Input layer with N neurons, and one or two hidden layers can be added, not more than that. There is no need to go 'deep' and add more layers for this data, there is risk to overfit the data easily with more layers, if you do so it can be tricky to figure out what the problem is, and the test accuracy will be affected greatly.

Simply plotting or visualizing the data i.e with t-sne can be a good start, if you need to figure out which features are important (or any correlation that may exist).

you can then play with higher powers of those feature dimensions/ or add increased weight to their score.

For problems like this, deep-learning probably isn't very well suited. but a simpler ANN architecture like this should work well depending on the data.

Read More

Sunday, April 24, 2016

How to get feature names selected by feature elimination in sklearn pipeline?

Leave a Comment

I am using recursive feature elimination in my sklearn pipeline, the pipeline looks something like this:

from sklearn.pipeline import FeatureUnion, Pipeline from sklearn import feature_selection from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.svm import LinearSVC  X = ['I am a sentence', 'an example'] Y = [1, 2] X_dev = ['another sentence']  # classifier LinearSVC1 = LinearSVC(tol=1e-4,  C = 0.10000000000000001) f5 = feature_selection.RFE(estimator=LinearSVC1, n_features_to_select=500, step=1)  pipeline = Pipeline([     ('features', FeatureUnion([        ('tfidf', TfidfVectorizer(ngram_range=(1, 3), max_features= 4000)),         ('custom_features', CustomFeatures())])),     ('rfe_feature_selection', f5),     ('clf', LinearSVC1),     ])  pipeline.fit(X, Y) y_pred = pipeline.predict(X_dev) 

How can I get the feature names of features selected by the RFE? RFE should select the best 500 features, but I really need to take a look at what features have been selected.

EDIT:

I have a complex Pipeline which consists of multiple pipelines and feature unions, percentile feature selection and at the end Recursive Feature Elimination:

fs = feature_selection.SelectPercentile(feature_selection.chi2, percentile=90) fs_vect = feature_selection.SelectPercentile(feature_selection.chi2, percentile=80) f5 = feature_selection.RFE(estimator=svc, n_features_to_select=600, step=3)  countVecWord = TfidfVectorizer(ngram_range=(1, 3), max_features=2000, analyzer=u'word', sublinear_tf=True, use_idf = True, min_df=2, max_df=0.85, lowercase = True) countVecWord_tags = TfidfVectorizer(ngram_range=(1, 4), max_features= 1000, analyzer=u'word', min_df=2, max_df=0.85, sublinear_tf=True, use_idf = True, lowercase = False)  pipeline = Pipeline([         ('union', FeatureUnion(                 transformer_list=[                  ('vectorized_pipeline', Pipeline([                     ('union_vectorizer', FeatureUnion([                          ('stem_text', Pipeline([                             ('selector', ItemSelector(key='stem_text')),                             ('stem_tfidf', countVecWord)                         ])),                          ('pos_text', Pipeline([                             ('selector', ItemSelector(key='pos_text')),                             ('pos_tfidf', countVecWord_tags)                         ])),                      ])),                         ('percentile_feature_selection', fs_vect)                     ])),                   ('custom_pipeline', Pipeline([                     ('custom_features', FeatureUnion([                          ('pos_cluster', Pipeline([                             ('selector', ItemSelector(key='pos_text')),                             ('pos_cluster_inner', pos_cluster)                         ])),                          ('stylistic_features', Pipeline([                             ('selector', ItemSelector(key='raw_text')),                             ('stylistic_features_inner', stylistic_features)                         ])),                       ])),                         ('percentile_feature_selection', fs),                         ('inner_scale', inner_scaler)                 ])),                  ],                  # weight components in FeatureUnion                 # n_jobs=6,                  transformer_weights={                     'vectorized_pipeline': 0.8,  # 0.8,                     'custom_pipeline': 1.0  # 1.0                 },         )),          ('rfe_feature_selection', f5),         ('clf', classifier),         ]) 

I'll try to explain the steps. The first Pipeline consists of vectorizers and is called "vectorized_pipeline", all of these have a function "get_feature_names". The second Pipeline consists of my own features, I have implemented them with fit, transform and get_feature_names functions as well. When I use the suggestion of @Kevin, I get an error that 'union' (which is the name of my top element in the pipeline) does not have get_feature_names function:

support = pipeline.named_steps['rfe_feature_selection'].support_ feature_names = pipeline.named_steps['union'].get_feature_names() print np.array(feature_names)[support] 

Also, when I try to get feature names from individual FeatureUnions, like this:

support = pipeline.named_steps['rfe_feature_selection'].support_ feature_names = pipeline_age.named_steps['union_vectorizer'].get_feature_names() print np.array(feature_names)[support] 

I get a key error:

feature_names = pipeline.named_steps['union_vectorizer'].get_feature_names() KeyError: 'union_vectorizer' 

1 Answers

Answers 1

You can access each step of the Pipeline with the attribute named_steps, here's an example on the iris dataset, that only selects 2 features, but the solution will scale.

from sklearn import datasets from sklearn import feature_selection from sklearn.svm import LinearSVC  iris = datasets.load_iris() X = iris.data y = iris.target  # classifier LinearSVC1 = LinearSVC(tol=1e-4,  C = 0.10000000000000001) f5 = feature_selection.RFE(estimator=LinearSVC1, n_features_to_select=2, step=1)  pipeline = Pipeline([     ('rfe_feature_selection', f5),     ('clf', LinearSVC1)     ])  pipeline.fit(X, y) 

With named_steps you can access the attributes and methods of the transform object in the pipeline. The RFE attribute support_ (or the method get_support()) will return a boolean mask of the selected features:

support = pipeline.named_steps['rfe_feature_selection'].support_ 

Now support is an array, you can use that to efficiently extract the name of your selected features (columns). Make sure your feature names are in a numpy array, not a python list.

import numpy as np feature_names = np.array(iris.feature_names) # transformed list to array  feature_names[support]  array(['sepal width (cm)', 'petal width (cm)'],        dtype='|S17') 

EDIT

Per my comment above, here is your example with the CustomFeautures() function removed:

from sklearn.pipeline import FeatureUnion, Pipeline from sklearn import feature_selection from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.svm import LinearSVC import numpy as np  X = ['I am a sentence', 'an example'] Y = [1, 2] X_dev = ['another sentence']  # classifier LinearSVC1 = LinearSVC(tol=1e-4,  C = 0.10000000000000001) f5 = feature_selection.RFE(estimator=LinearSVC1, n_features_to_select=500, step=1)  pipeline = Pipeline([     ('features', FeatureUnion([        ('tfidf', TfidfVectorizer(ngram_range=(1, 3), max_features= 4000))])),      ('rfe_feature_selection', f5),     ('clf', LinearSVC1),     ])  pipeline.fit(X, Y) y_pred = pipeline.predict(X_dev)  support = pipeline.named_steps['rfe_feature_selection'].support_ feature_names = pipeline.named_steps['features'].get_feature_names() np.array(feature_names)[support] 
Read More

Monday, April 11, 2016

Orthogonal matching pursuit regression - am I using it wrong?

Leave a Comment

I am trying out this method as a regularized regression, as an alternative to lasso and elastic net. I have 40k data points and 40 features. Lasso selects 5 features, and orthogonal matching pursuit selects only 1.

What could be causing this? Am I using omp the wrong way? Perhaps it is not meant to be used as a regression. Please let me know if you can thing of anything else I may be doing wrong.

1 Answers

Answers 1

Orthogonal Matching Pursuit seems a bit broken, or at least very sensitive to input data, as implemented in scikit-learn.

Example:

import sklearn.linear_model  import sklearn.datasets  import numpy  X, y, w = sklearn.datasets.make_regression(n_samples=40000, n_features=40, n_informative=10, coef=True, random_state=0)  clf1 = sklearn.linear_model.LassoLarsCV(fit_intercept=True, normalize=False, max_n_alphas=1e6)  clf1.fit(X, y)  clf2 = sklearn.linear_model.OrthogonalMatchingPursuitCV(fit_intercept=True, normalize=False) clf2.fit(X, y)  # this is 1e-10, LassoLars is basically exact on this data  print numpy.linalg.norm(y - clf1.predict(X))  # this is 7e+8, OMP is broken print numpy.linalg.norm(y - clf2.predict(X)) 

Fun experiments:

  • There are a bunch of canned datasets in sklearn.datasets. Does OMP fail on all of them? Apparently, it works okay on the diabetes dataset...

  • Is there any combination of parameters to make_regression that would generate data that OMP works for? Still looking for that one... 100 x 100 and 100 x 10 fail in the same way.

Read More

Monday, March 21, 2016

Extracting attributes from images using Scikit-image

Leave a Comment

I've been using scikit-image to classify road features with some success. See below: image processed by scikit-image. I am having trouble doing the next step which is to classify the features. For example, let's say these features are located in the box (600, 800) and (1400, 600).

The code I'm using to extract the information is:

from skimage import io, segmentation as seg color_image = io.imread(img)   plt.rcParams['image.cmap'] = 'spectral' labels = seg.slic(color_image, n_segments=6, compactness=4) 

The objective is to have a table in the following form:

Image, feature_type, starting_pixel, ending_pixel 001    a             (600, 600),     (1300, 700)  002    b             (600, 600),     (1100, 700) 002    undefined     (700, 700),     (900, 800) 

feature_type would be based on colours, ideally shoulders would be one colour, trees and brush would be another, etc.

How can I extract the data I need? (i.e: have scikit break the image into different components where I know the location of each component. I can then pass each component to a classifier which will identify what each component is) Thanks!

1 Answers

Answers 1

It is the first time I try that package.. I tried with a simpler image and I get more or less the right results:

smallimg.jpg

from skimage import io, segmentation as seg import matplotlib as plt import numpy as np color_image = io.imread('smallimg.jpg') labels = seg.slic(color_image, n_segments=4, compactness=4) for section in np.unique(labels):     rows, cols = np.where(labels == section)     print("Image="+str(section))     print("Top-Left pixel = {},{}".format(min(rows), min(cols)))     print("Bottom-Right pixel = {},{}".format(max(rows), max(cols)))     print("---") 

Output:

Image=0 Top-Left pixel = 3,1 Bottom-Right pixel = 15,18 --- Image=1 Top-Left pixel = 26,1 Bottom-Right pixel = 34,18 --- Image=2 Top-Left pixel = 43,1 Bottom-Right pixel = 52,16 --- Image=3 Top-Left pixel = 0,0 Bottom-Right pixel = 59,19 --- 

Notice that the right-most pixel is not precisely what I mean because of the gradient. The last segment is the white background.

I tried with your image but I think you will have to get the segmentation right. I would use n_segments=7 if you want to get the 6 images + background.

I also see in the documentation about compactness: "This parameter depends strongly on image contrast and on the shapes of objects in the image.". So what you want could be difficult to achieve.

If you are plotting the six pictures on the image you show above, why don't you get those coordinates when you plot the pictures instead of applying segmentation to the end result?

Read More