Saturday, October 15, 2016

Signal Processing: Why do we need taper in FFT

When we try to study the frequency content of a signal, FFT is always the tool we use. Also, a lot of times, you hear others talking about 'we applied a XX taper before we conduct the FFT'. Why we need a taper before FFT? This week, we will talk about what is a taper, and why we need it. You can find all the script at Qingkai's Github. Let's first look at an example below:
In [1]:
import numpy as np
from scipy import fft, arange
import matplotlib.pyplot as plt
from scipy import signal
%matplotlib inline
plt.style.use('seaborn-poster')
In [2]:
def plotSpectrum(t, y,Fs):
    """
    Function to plot the time domain and frequency domain signal
    """
    n = len(y) # length of the signal
    k = arange(n)
    T = n/Fs
    frq = k/T # two sides frequency range
    frq = frq[range(n/2)] # one side frequency range

    Y = fft(y)/n # fft computing and normalization
    Y = Y[range(n/2)]    
    
    # plot time domain and frequency domain signal
    plt.subplot(2,1,1)
    plt.plot(t,y)
    plt.xlabel('Time')
    plt.ylabel('Amplitude')
    plt.subplot(2,1,2)
    plt.stem(frq,abs(Y),'r')
    plt.xlabel('Freq (Hz)')
    plt.ylabel('|Y(freq)|')
    plt.tight_layout()
    plt.show()

Example 1 (5 Hz sine wave)

Let's create a 5 Hz sine signal with a sampling rate 100 Hz (this is saying within 1 second, we have 100 data points to represent this sine signal). We can see the time domain signal in the following top figure with 5 cycles within 1 second. The bottom figure shows the FFT spectrum amplitude, and we see a very clear 5 Hz signal. So far so good, and it all looks normal.
In [3]:
Fs = 100.0  # sampling rate
Ts = 1.0/Fs # sampling interval
t = arange(0,1,Ts) # time vector
ff = 5;   # frequency of the signal
# create the signal
y = np.sin(2*np.pi*ff*t + 5)

plotSpectrum(t, y,Fs)

Example 2 (same 5 Hz sine wave, but a little shoter)

Using the same signal as the above, we just shrink the signal from 1 sec to 0.5 sec, as the top figure shows. But when we look at the FFT spectrum, somehow we are not getting the clear 5 Hz signal anymore. Instead, we have a large peak at 5 Hz, but also small peaks at other frequencies. What happened? We are pretty sure that the signal is a 5 Hz signal, where other frequency content comes from?
In [4]:
# let's extend the signal from 1s to 0.5s
t = arange(0,0.5,Ts)

# make sure we are still using 5 Hz as the frequency of the signal
ff = 5;
y = np.sin(2*np.pi*ff*t + 5)
plotSpectrum(t, y,Fs)

Why this happens

Well, if we look at the first example and second example more carefully, we will notice the difference: the start and end point of the signal in example 1 are all -1. But in the second example, the start point is -1, and the end point is 1. Is this the cause of the problem? Yes! When we conduct FFT on a finite length signal, we actually assume the signal repeat itself to a infinite length signal and connecting the end point with the start point (you can also think the signal is has a period of whole length). But in the second example, when we connect the signal, there is a discontinuity as the following figure shows. This kind of discontinuity in the signal usually introduces other frequency signals, and smear the true spectrum by spreading the peak to the surrounding frequencies. It is like the energy leak to other frequencies, so people call it spectrum leakage.

How can we reduce the leakage

This is where the taper or window function comes in. We can multiply a smooth window function to make the connecting points smoother, usually this window function is also called taper. A typical taper usually has a gradual decreasing of amplitude to zero towards the edge. For example, if we plot a cosine taper in the time and frequency domain, it will look like the following figure.

Cosine taper

In [5]:
n = len(t) # number of points
window = signal.cosine(n)
plotSpectrum(t, window,Fs)

Apply the taper

This windowing process consists of multiplying the time record by a finite-length window with an amplitude that varies smoothly and gradually toward zero at the edges. Let's apply the cosine taper to the signal, and we can see the signal now has 0 at both the start and end point. The FFT spectrum has less leakage than before.
In [6]:
# apply the taper to the signal
y_tapered = window * y 
plotSpectrum(t, y_tapered,Fs)

Try different window

There are many different types of window function, how to choose them depends on your need or your problem at hand. In the following, I will plot some common window functions, you can get a sense of what they look like.

Blackman

In [7]:
window = signal.blackman(n)
plotSpectrum(t, window,Fs)

y_tapered = window * y 
plotSpectrum(t, y_tapered,Fs)

Hanning

In [8]:
window = signal.hanning(n)
plotSpectrum(t, window,Fs)

y_tapered = window * y 
plotSpectrum(t, y_tapered,Fs)

flattop

In [9]:
window = signal.flattop(n)
plotSpectrum(t, window,Fs)

y_tapered = window * y 
plotSpectrum(t, y_tapered,Fs)

Tukey

In [10]:
window = signal.tukey(n)
plotSpectrum(t, window,Fs)

y_tapered = window * y 
plotSpectrum(t, y_tapered,Fs)

Parzen

In [11]:
window = signal.parzen(n)
plotSpectrum(t, window,Fs)

y_tapered = window * y 
plotSpectrum(t, y_tapered,Fs)

Saturday, October 8, 2016

Machine Learning 2 - Types of Machine Learning




Continue from previous blog, we will talk about types of Machine Learning (ML) this week. 

Three types of common ML

Figure 0

1. Supervised Learning

Figure 1
Example: I try to teach a small baby to recognize apple from orange. I will first give it an orange, and tell it this is an orange. Then the baby will remember the features of this orange, i.e. shape, yellowish color, smell, texture, and so on. 
Next, I give the baby an apple, and tell it, this is an apple. Again, it remembers the features of the apple (red color, texture is smoother than the orange, a different smell). 
Finally, I give the baby another object, but not telling what this object is. The baby will compare the features of this object with that it memorized for the apple and orange, and see which one matches. 
More Explain:
For this example, the apple and orange recognition, is a classic classification problem. It has two classes: apple and orange. Features are the usually the most important part of the model building process. Note that, we give the baby an apple and orange, and tell it what the object is. This is the training data for building the model in the baby's mind. The fact we give it the true class of the object (apple or orange) is the label of the training data, this is also why it is called supervised learning. It is more like, I am a teacher, and gives the baby the true answer for it to learn. See more on WiKi. 

2. Unsupervised Learning

Figure 2
Example: Let's just give the baby many apples and oranges without telling it what the objects are. Then the baby just learn by itself, and put all the oranges into one box, and all the apples to another box, based on color, texture, and maybe smell. 
More Explain: In this example, we can see the difference from the previous example - there are no labels associated with the training data (the baby doesn't know which is apple, and which is orange). But it can learn by itself and find some interesting difference between the two, and put them into groups. Due to we don't teach the baby with the labels, this approach is called unsupervised learning. See more on WiKi. 

3. Reinforcement Learning

Figure 3
Figure 4
Example: The first time when a baby tries lemon, it is a memorable time. This is also an experience that the baby actively learning the world. It will understand that lemon tastes not good after a few tries. In contrasts, chocolate is different experience. After the baby tastes it, it will remember and ask for more soon. 
This is actually reinforcement learning. The baby learns from award (chocolate) or punishment (lemon) experience. 
More Explain: Reinforcement learning allows machines and software agents to automatically determine the ideal behavior within a specific context, in order to maximize its performance due to award or punishment. See more on WiKi. 

4 Others

There are also other types, as semi-supervised learning or transduction, which is kind of hybrid from supervised and unsupervised learning. I will not provide examples here. 

Another way to divide ML types

1 Classification

You can see the example for the supervised learning above. 

2 Regression

Figure 4
Example: If I ask you what is the height of a X month baby (from birth to two years old), how can you answer that? We can ask babies in different ages, and record their heights, and then whenever you ask me, for example, what is the height of a 18-month baby, we can plug in the 18 month, and find the corresponding height. This is a basic regression analysis. 
More Explain: Regression is a process for estimating the relationships among different variables (for the example here, the variables are age and height). See more on WiKi. 

3 Clustering

You can see the example for the unsupervised learning above. 

4 Dimensionality reduction

Figure 5
Example: We live in a 3 dimensional world, but when we plot on maps, it is much easier to plot them as a 2 dimension map instead of 3. 
More Explain: Dimensionality reduction is the process of reducing the number of random variables under consideration. See more on WiKi. 

Density Estimation

Figure 6Example: When you go fishing, there are two equal size lakes A and B. At lake A, you can easily have 10 fishes in one hour. But at lake B, you only get one fish in the same amount of time. Well, we can say that the density of the fish in lake A is probably higher than that of lake B. 
More Explain: Density estimation is the construction of an estimate, based on observed data, of an unobservable underlying probability density function. See more on WiKi. 
All the figures are from internet, I thank the authors for the figures!

Tuesday, October 4, 2016

Machine Learning 1 - What is machine learning and real world example

From this week, I will try to explain some basic machine learning concepts and algorithms in a more intuitive way without equations. Note, all these will based on my knowledge of machine learning, therefore, it can be inaccurate or even wrong, feel free to contact me if you find anything wrong, or have a better way to explain. 
Let's start today with the following few questions. 

What is Machine Learning (ML)?


As the name suggests, ML is the methods that enable machines or computers to learn from data we give them and then take decisions/actions. The famous definition from Tom Mitchell's book - 'Machine learning' is more formal if you want it.

To add a simple example, if we give thousands of images with cats or dos on it, and let the computer to learn from the characteristics of cats or dogs. After learning (of course, it is the machine learning), we give some new images to the computer, and ask it to decide whether it is dog or cat. This is an example of what is machine learning. We will give more examples about different types of machine learning next week.

Real world ML examples

Think about some daily stuff we take for granted, you will find ML is everywhere: 

1. Why ATM can recognize your handwriting on your check?

2. Why Amazon can recommend me with good books?

3. Why the camera can detect my face?


4. Why some emails be put into spam folder?

5. Why my bank call me about fraud?

6. Why self-driving car can drive by themselves?


7. Why google search engine can return what I want to search?

8. Why voice assistants (Siri) on my phone understand me?

9. Why advertising can target me correctly?

10. Why home robot is so smart?


All the figures are from internet, I thank the authors for the figures!

Sunday, September 25, 2016

Using datashader to visualize billions of data points

Visualization is the best way to explore and communicate insights about data. But many times, we find it is difficult to visualize if we have a lot of data points, the traditional visualization techniques break down. datashader is a tool developed by Continuum Analytics come to rescue. It is extremly easy and fast to use it to plot even billions of data points (see the examples or a video from Scipy 2016). 
This week, we will use datashader to plot the global seismicity for earthquakes larger than M2.0. To speed up the process, I downloaded the earthquake locations/times from the ANSS Catalog from 1898 to 2016, and save them as a csv file in the data folder (You can also grab the data directly using the APIs from my previous blog post). All together, we only have 1120244 earthquakes
And with a couple of lines, you can see we get a very nice looking map with the global seismicity. You can find the script and data at Qingkai's Github.
import pandas as pd
import datashader as ds
import datashader.transfer_functions as tf
from functools import partial
from datashader.utils import export_image
from datashader.colors import colormap_select, Greys9, Hot, viridis, inferno
# read in the earthquake data from file, note that I only read
# in 5 columns with Origin time, Latitude, Longitude, Depth, and
# Magnitude of the earthquakes
df_eq = pd.read_csv('./data/catalog.csv', usecols=[0,1,2,3,4])
# now let's plot them using a black background
background = "black"
export = partial(export_image, background = background)
cm = partial(colormap_select, reverse=(background!="black"))

cvs = ds.Canvas(plot_width=1600, plot_height=1000)
agg = cvs.points(df_eq, 'Longitude', 'Latitude')
export(tf.interpolate(agg, cmap = cm(Hot,0.2), how='eq_hist'),"global_seismicity")

Saturday, September 10, 2016

20 Data science questions - Part 2


Continue from last week's first 10 data science questions (part 1), here are the rest of the 10 questions:

Q11: What is selection bias, why is it important and how can you avoid it?
From Wikipedia, selection bias is the selection of individuals, groups or data for analysis in such a way that proper randomization is not achieved, thereby ensuring that the sample obtained is not representative of the population intended to be analyzed. There is a very interesting example on youtube. 
Selection bias can cause the researcher to reach wrong conclusion. I think the best way to avoid the selection bias is first to get to know the common bias and how it affects research. Here is a nice review of bias on evidence-based medicine. Though slightly different, a lot of the topics/concepts can be applied to other fields. as well. 
Q12: Give an example of how you would use experimental design to answer a question about user behavior.
I don't know how to answer this question, but will try based on my knowledge. To design an experiment to learn user behavior, I think it depends on the problem in hand. We need first understand the goal of the problem, i.e., what behavior we want to understand? And then find the factors that will affect the behavior. We then need brainstorm how to test these factors using experimental method. 

Q13: What is the difference between long and wide format data?
The long and wide format data are used to describe two different presentations for tabular data. In the long format, it is kind of like the key-value pairs to store the data, each subject (Iron man or Spider man) will have data in multiple rows. The wide format data, each subject will have all the variables in the same row but separated in different columns. It is easier to see in an example: 
long format
NameVariableValue
Iron manColorred
Iron manMaterialiron
Iron manPowernuclear
Iron manHeight5'8"
Spider manColorred
Spider manMaterialcloth
Spider manPowerfood
Spider manHeight5'10"
wide format
NameColorMaterialPowerHeight
Iron manredironnuclear5'8"
Spider manredclothfood5'10"
The wide format data usually will have problems when you want to visualize it with many variables. But it is very easy to convert between these two types data using python or R. 
Q14: What method do you use to determine whether the statistics published in an article (e.g. newspaper) are either wrong or presented to support the author's point of view, rather than correct, comprehensive factual information on a specific subject?
I think all the statistics used in newspaper or TV is to support the author's point. This is illustrated in the book How to lie with Statistics. 
It is difficult to tell whether the statistics is wrong, since we need reproduce the results if we are facing the question and want to solve it by ourselves. But many times, we can not re-do the work, so I don't have a better way to determine if the statistics are wrong. 
Q15: Explain Edward Tufte's concept of chart junk.
If you don't know Edward Tufte, then you should really get to know him and his famous books (see his webpage). I own 4 of his books - The Visual Display of Quantitative Information, Envisioning Information, Visual Explanations: Images and Quantities, Evidence and Narrative, and Beautiful Evidence. All of these books are great. His most classic book is 'The Visual Display of Quantitative Information', which will make your data visualization goes up to a new level. This chart junk is from this book:
The interior decoration of graphics generates a lot of ink that does not tell the viewer anything new. The purpose of decoration varies — to make the graphic appear more scientific and precise, to enliven the display, to give the designer an opportunity to exercise artistic skills. Regardless of its cause, it is all non-data-ink or redundant data-ink, and it is often chartjunk. 
What he means is the elements in the charts are unnecessary to convey the main information, or distract the viewer. See the following example from WiKi:
image
Q16: How would you screen for outliers and what should you do if you find one?
An outlier is an observation that is distant from the other observations. It may from two cases, (1) measurement error or (2) heavy tailed distribution. In the first case, we want to discard the outlier, but in the later case, it is part of the information that need special attention to. 
The way I usually to find an outlier is using the box plot, and if the data point is outside of the 1.5*IQR, I will treat it as an outlier. See more details here.
image
There are more discussions whether to drop the outliers here. 
Q17: How would you use either the extreme value theory, Monte Carlo simulations or mathematical statistics (or anything else) to correctly estimate the chance of a very rare event?
I don't know the extreme value theory, so will talk using the Monte Carlo simulations to estimate the chance of a very rare event. 
A very rare event is an event occurring with a very small probability. So if you use Monte Carlo directly, it will be really inefficient for sampling the rare events. For example, if the instance occur at the probability 10-9, then on average, we need a sample of size n = 109 to observe just a single occurrence of the event, and much more if we expect a reliable estimation of the mean and variance to obtain a sufficiently narrow confidence interval. 
Importance sampling (IS) is a powerful tool to reduce the variance of an estimator, that is increasing the occurrence of the rare event. The basic idea of importance sampling is to change the probability laws of the system under study to sample more frequently the events that are more important for the simulation. Of course, using this new distribution results in a biased estimator if no correction is applied. Therefore the simulation output needs to be translated in terms of the original measure, which is done by multiply a so-called likelihood ratio. See the details in chapter 2 of Rare Event Simulation using Monte Carlo Methods by Gerardo Rubino and Bruno Tuffin. 
Q18: What is a recommendation engine? How does it work?
A recommendation engine is a system that can predict a user's rating or preference based on the user's activities or other users' activities. One easy example is Amazon, when you browse the books, you always see 'Recommend books for you', and 'Other people may like this'. This is Amazon recommendation engine based on your browse history and other people's browse history. 
There are two common approaches: Collaborative filtering and Content-based filtering. 
Collaborative filtering
This approach is based on collecting and analyzing a large amount of information on users' behaviors, activities or preferences and predicting what users will like based on their similarity to other users (from WiKi). So the assumption here is that similar people tend to have similar behavior, if we know their past behaviors, we can predict their future behavior. For example, I love machine learning, always browse interesting machine learning books online. Another person also loves machine learning, and he has another set of books he usually browse. So if the system recommend a book I love from me about machine learning to this person, there's a high chance this person will love it as well. 
Therefore, in order to use this approach, the first thing we should do is to collect a lot of data from different users, and use them as the basis to predict future user behavior. The advantage of this method is that, we even don't need know the content of the product, all we need is collecting large dataset about users' activities. On the other hand, this is also the disadvantage of this approach, since we have to first collect a large dataset to make this approach work. Therefore, when you start a new business, you may need wait for a few years to start to recommend product to your users. 
Collaborative filtering In contrast, the collaborative filtering approach is based on understanding of your products and the profile of your user, i.e., information about what this user likes. Then the algorithm will recommend products that are similar to those that a user liked in the past. For example, I love Iron man movies, I watched Iron man I, II, III in the past. Therefore, if the algorithm recommends me a movie 'I, Robot', there's a high chance I will love it (of course, both are my favorite). But if the algorithm recommends me a love movie, I would say, there's still room to train the algorithm to be better. 
Collaborative filtering approach doesn't need collect large dataset as the first step. Instead, you can start to recommend product to your users from the very beginning after he starts to choose your product. But you can see that, you now have to learn the characteristics about your product, this is the trade!
Hybrid model Hybrid is always the best )^ We can also combine the two methods together, this is the Hybrid recommend system: by making content-based and collaborative-based predictions separately and then combining them; by adding content-based capabilities to a collaborative-based approach (and vice versa); or by unifying the approaches into one model. 
Q19: Explain what a false positive and a false negative are. Why is it important to differentiate these from each other?
This question seems duplicate with question 4 and 10, so I will skip this one. 

Q20: Which tools do you use for visualization? What do you think of Tableau? R? SAS? (for graphs). How to efficiently represent 5 dimension in a chart (or in a video)?
Since I am mostly using python in my daily life and research, so all the visualization tools are in python. 
Here are the ones I use most: 
  • matplotlib, most powerful and flexible package that can plot nice figures. A lot of the figures I generated for the papers are from it.
  • pandas, is not only an analysis tool, but the plotting capability is also really great. 
  • Seaborn, I use it mostly for the quick nice plot style. Since the new matplotlib added the different styles, I guess I will use it less. 
  • Bokeh, a very nice interactive plot package. I usually use it to generate the html interactive file for easily passing around.
  • Basemap, this is what I usually use for plotting maps.
  • cartopy, a nice package for quick map plotting.
  • folium, my favorite interactive map plotting package built on top of leaflet.
Here are some more nice package, I occasionally use.
* geoplotlib, a toolbox for visualizing geographical data and making maps.
* mpld3, another interactive plotting package that built on top of D3.
* pygal, another interactive plotting package. It can output figures as SVGs.
* ggplot, plot based on R's ggplot2.
* datashader, can create meaningful representations of large amounts of data.
* missingno, a package to deal with missing or messy data. 
I never used Tableau, R, SAS before, so I cannot say anything about them. 
For plotting high dimensional data, parallel coordinates is a popular option. image. 
Or the radar chart is another option. Pandas can be used to plot the parallel coordinates. 
Instead of plotting them directly, I usually first see if I can explain most of the data in lower dimensions, say 2 or 3 dimension by using Principle Component Analysis. 
There is a very nice discussion on Quora - 'What is the best way to visualize high-dimensional data'