"[Jupyter](http://jupyter.org/) is an interactive browser based notebook environment where we can combine text, code execution and visualization. It supports multiple programming languages through it's language specific kernel plugins. However, it is widely used with Python in scientific computing and data science communities. The availability of large number of high quality open source libraries useful for many tasks in scientific computing,numerical linear algebra, machine learning and visualization ensures that Python is being widely used in these fields. Jupyter notebooks are an excellent environment for learning and teaching because of the interactivity.\n",
"\n",
"In this short blogpost, I will explore few topics to illustrate the interactivity of the jupyter environment and the availability of high quality libraries in the python ecosystem.\n",
"- Montecarlo calculation of $\\pi$\n",
"- Image Compression using Singular value decomposition"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"# A note on installation of jupyter"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"Installation of jupyter and other important packages individually is cumbersome. Thanks to [Anaconda](https://www.anaconda.com/products/individual) we have Anaconda python distribution in which almost all of the useful packages are bundled. Install anaconda.\n",
"\n",
"But it is even better not setting up any python environment at all on your computer. Instead, you can use free online python environments- [colab notebooks](https://colab.research.google.com/) from google or [sagemaker studio lab notebook](https://studiolab.sagemaker.aws/) from aws. Watch [this video](https://www.youtube.com/watch?v=SP-WBt2b54o) from the twitter user [1littlecoder](https://twitter.com/1littlecoder) on getting started with sagemaker studio lab."
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
" # Montecarlo calculation of $\\pi$"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"I had earlier written about calculating the mathematical constant $\\pi$ using [montecarlo method](https://medium.com/@rameshputalapattu/life-of-pi-a-gophers-tale-2e6922b80792). It involves generating random points on a unit square and counting the number of points inside the unit quarter circle. We will write a function ```mc_pi``` to calculate $\\pi$. In that function, we will also visualize the process of montecarlo simulation using matplotlib library."
" plt.title(\"value of $\\pi$=\"+str( 4.0*np.sum(inside_circle)/float(ntrials)))\n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"We are able to write the function ```mc_pi``` without making use of any explicit ```for``` loops - thanks to vectorization features in numpy library. Due to a concept called broadcasting in numpy, we are able to subtract a vector from a scalar (1.0 - unit_circle_x**2 ) to compute the y co-ordinate of the unit circle. \n",
"\n",
"Now we will make use of ipywidgets module to pass the parameter interactively to the function ```mc_pi```. ipywidgets module provide widgets to generate the UI controls in the notebook itself with which the user can interact. We can drag the slider and observe how the value of pi calculated by mc_pi function changes with the number of trials."
"Now we will explore how to apply Singular Value Decomposition of a matrix to the problem of image compression. SVD decomposes a rectangular matrix $M$ to a three parts.\n",
"$M=U\\Sigma V^T$ -\n",
"- $U$ - matrix of left singular vectors in the columns\n",
"- $\\Sigma$ - diagonal matrix with singular values\n",
"- $V$ - matrix of right singular vectors in the columns\n",
"\n",
"SVD in effect involves reconstructing the original matrix as a linear combination of several rank one matrices. A rank one matrix can be expressed as a outer product of two column vectors. \n",
"A matrix of rank r will have r terms of these.\n",
"\n",
"Here $\\sigma_1,\\sigma_2,\\sigma_3 ...$ are singular values. $u_1,u_2,u_3 ...$ and $v_1,v_2,v_3 ...$ are left and right singular vectors respectively.\n",
"\n",
"Image compression using SVD involves taking advantage of the fact that very few of the singular values are large. Although images from the real world are of full rank, they have low effective rank which means that only few of the singular values of the SVD of images will be large."
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"### skimage image processing library\n",
"\n",
"We will use skimage image processing library (from sci-kit family of packages) for working with images in python. skimage has a module called data which makes available a set of images for exploration. We will load some images and convert them into a gray scale format. These images are stored in a python dict object gray_images."
"We will use ```numpy.linalg``` library's ```svd``` function to compute svd of a matrix in python. The svd function returns U,s,V .\n",
" - U has left singular vectors in the columns\n",
" - s is rank 1 numpy array with singular values\n",
" - V has right singular vectors in the rows -equivalent to $V^T$ in traditional linear algebra literature\n",
" \n",
"The reconstructed approximation of the original matrix is done using a subset of singular vectors as below in the ```compress_svd``` function . We use numpy array slicing to select k singular vectors and values. Instead of storing $m\\times n$ values for the original image, we can now store $k(m+n)+k$ values\n",
"The function ```compress_show_gray_images``` below takes in the image name (img_name) and number of singular values/vectors(k) to be used in the compressed reconstruction. It also plots the singular values and the image."
"Color images are represented in python as 3 dimensional numpy arrays - the third dimension to represent the color values (red,green blue). However, svd method is applicable to two dimensional matrices. So we have to find a way to convert the 3 dimensional array to 2 dimensional arrays, apply svd and reconstruct it back as a 3 dimensional array . There are two ways to do it. We will show both these methods below .\n",
" - reshape method\n",
" - Layer method\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"#### Reshape method to compress a color image\n",
"This method involves flattening the third dimension of the image array into the second dimension using numpy's reshape method .\n",
"The svd decomposition is applied on the resulting reshaped array and reconstructed with the desired number of singular values/vectors. The image array is reshaped back to the three dimensions by another call to reshape method.\n",
"Here is the interactive widget to explore image compression of color images using the reshape method. By dragging the slider to vary $k$, observe how image quality varies. Also, we can explore different images by selecting through the drop down widget."
"In the function ```compress_show_color_images_layer```, we treat a color image as a stack of 3 seperate two dimensional images (Red,blue and green layers) . We apply the truncated svd reconstruction on each two dimensional layer seperately.\n",
"\n",
"```image_reconst_layers = [compress_svd(image[:,:,i],k)[0] for i in range(3)]```\n",
"\n",
"And we put back the reconstructed layers together.\n",