Archive for the ‘Python’ Category


September 24, 2017 Leave a comment
  • # Preparation
    sudo apt-get install python-numpy python-matplotlib ipython
    # Assume that you already have mkvirtualenv wrapper
    mkvirtualenv ml
    workon ml
    pip install pandas
  • # NUMPY
    import numpy as np
    ## Matrix And Vector
    vector = np.array([1,2])
    matrix = np.array([[1,2],[3,4]])
    identity = np.ones((2,2))
    zeros = np.zeros((2,2))
    random = np.random.randn(2,2)
    inverse = np.linalg.inv(matrix)
    determinant = np.linalg.det(matrix)
    transpose = matrix.T
    diagonal = np.diag([1,2,3])
    inner = np.inner(matrix, matrix) or
    outer = np.outer(matrix, matrix)
    ## Find angle of two vectors
    a = np.array([1,2])
    b = np.array([2,1])
    cosAB = / (np.sqrt(sum(a*a)) * (np.sqrt(sum(b*b))) )
    cosAB = / (np.linalg.norm(a) * np.linalg.norm(b) )
    radAngle = np.arccos(cosAB)
    ## Linear Equation
    A = np.array([[1,2],[3,4]])
    b = np.array([1,2])
    solution = np.linalg.inv(A).dot(b)
    solution = np.linalg.solve(A,b)
  • # PANDAS
    import pandas as pd
    ## Load data
    dframe = pd.read_csv("filename", header=None)
    ## Adding column and Fill data based on ref column
    dframe["new_column"] = dframe.apply(lambda row: some_function(dframe["ref_column"]), axis=1)
    ## Merge data frame
    df1 = pd.read_csv("file1")
    df2 = pd.read_csv("file2")
    df = pd.merge(df1, df2, on="selected_column")
  • # MAT PLOT
    import matplotlib.pyplot as plt
    ## Line plot
    x = np.linspace(0, 10, 200)
    y = np.sin(x)
    ## Scatter plot
    M = pd.read_csv("filename", header=None).as_matrix()
    x = M[:,0]
    y = M[:,1]
    ## Histogram
    x = np.random.randn(1000)
    ## Digit reader from mnist
    df = pd.read_csv("train.csv")
    M = df.as_matrix()
    label_1 = M[0,0]
    digit_1 = M[0,1:]
    digit_1 = digit_1.reshape(28,28)
    plt.imshow(digit_1, cmap="gray")


Categories: Python

Setup Python Virtual Environment

April 17, 2017 Leave a comment

When working on multiple python projects, perhaps we need to isolate package dependencies that needed for each project, so that dependency changes on one project does not make other project stop working.

Here’s example how to setup python virtual environment on linux mint.

$ sudo apt-get install python-pip
$ pip install setuptools virtualenv virtualenvwrapper

Add following code in ~/.profile

export WORKON_HOME=$HOME/.virtualenvs
source /usr/local/bin/

Execute following command

$ source ~/.profile

Done! It’s time to test.

  1. Create Virtual Environment for project 1: eg env1 (skip this if env1 already created)
    $ mkvirtualenv env1
  2. Activate virtual anvironment (eg: env1)
    $ workon env1
  3. Install package dependencies to current environment (eg: django)
    (env1)$ pip install django
  4. To get info about installed package:
    (env1)$ pip freeze
  5. Deactivate to exit from current virtual environment
    (env1)$ deactivate
  6. Get available virtual environments
    $ workon
  7. Remove virtual environment
    $ rmvirtualenv env1


Categories: Linux, Python

Simple Example using Unit Testing in Python

March 13, 2015 Leave a comment

This is simple example how to use unit testing in python. For example, you want to create module that generate fibonacci numbers and want to test whether the module is working properly or not.

Below is simple script for module to generate fibonacci numbers :

# Fibonacci numbers module
def fib2(n): # return Fibonacci series up to n
    result = []
    a, b = 0, 1
    while b < n:
        a, b = b, a+b
    return result

def main():
    print fib2(100)

if __name__ == '__main__' : main()

And here simple script to test that module:

import fibonacci
import unittest

class TestFibonacciFunctions(unittest.TestCase):

    def test_series_100(self):
        print('\nTest Series 100')
        wanted_result = [1,1,2,3,5,8,13,21,34,55,89]
        test_result = fibonacci.fib2(100)

    def test_series_50(self):
        print('\nTest Series 50')
        wanted_result = [1,1,2,3,5,8,13,21,34]
        test_result = fibonacci.fib2(50)

if __name__ == '__main__' : unittest.main()

Run script with command


You will get following output if the wanted_result and test_result are equal

Test Series 100
Test Series 50
Ran 2 tests in 0.000s

Categories: Programming, Python