Shantanu's Blog

Database Consultant

March 28, 2019

 

Image blur

Here are the basic steps to blur the image.

import cv2
from matplotlib import pyplot as plt

# Import the image and convert to RGB
img = cv2.imread('Penguins.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

kernels = [5, 11, 17, 25, 55]
fig, axs = plt.subplots(nrows = 1, ncols = 5, figsize = (20, 20))
for ind, s in enumerate(kernels):
    img_blurred = cv2.blur(img, ksize = (s, s))
    ax = axs[ind]
    ax.imshow(img_blurred)
    ax.axis('off')
plt.show()




img_0 = cv2.blur(img, ksize = (37, 37))
img_1 = cv2.GaussianBlur(img, ksize = (37, 37), sigmaX = 0) 
img_2 = cv2.medianBlur(img, 37)
img_3 = cv2.bilateralFilter(img, 37, sigmaSpace = 75, sigmaColor =75)
# Plot the images
images = [img_0, img_1, img_2, img_3]
fig, axs = plt.subplots(nrows = 1, ncols = 4, figsize = (20, 20))
for ind, p in enumerate(images):
    ax = axs[ind]
    ax.imshow(p)
    ax.axis('off')
plt.show()



Labels:


March 16, 2019

 

Pandas case study 10

How to divide each element with the sum values in the row, except the values on the diagonal?

try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO

mymat = """
 a  5   2    3   2   0   1
 b  2   4    3   2   0   1
 c  3   4    3   2   0   3
 d  2   4    3   2   0   1
 e  0   4    3   2   0   8
 f  1   4    3   2   0   1
"""

u_cols = ['tag', 'a', 'b', 'c', 'd', 'e', 'f']

df = pd.read_csv(StringIO(mymat), sep='\s+', names=u_cols)

The expected output would be:

tag    a b c d e f
a 0.00 0.250000 0.375000 0.250000 0.0 0.125000
b 0.25 0.000000 0.375000 0.250000 0.0 0.125000
c 0.25 0.333333 0.000000 0.166667 0.0 0.250000
d 0.20 0.400000 0.300000 0.000000 0.0 0.100000
e 0.00 0.235294 0.176471 0.117647 0.0 0.470588
f 0.10 0.400000 0.300000 0.200000 0.0 0.000000

## set an index
df = df.set_index('tag')

## Fill Diagonal values with 0
np.fill_diagonal(df.values, 0)

## devide each value by sum of row
v = df.div(df.sum(axis=1), axis=0)

https://stackoverflow.com/questions/55107688/how-to-divide-the-selected-element-with-the-sum-values-in-the-row-except-the-va/55108196#55108196

Labels:


March 13, 2019

 

Deep learning explained

Sigmoid function will always return the values between 0 and 1

def sigmoid(x):
  return 1 / (1 + np.exp(-x))

Input can be multiplied by filter values. Bias can be added if required. The sigmoid value is returned which is fed to the next level.

def feedforward(weights, bias, inputs):
    total = np.dot(weights, inputs) + bia
    return sigmoid(total)

You can try with different bias values like 4, 32 and 35

feedforward(np.array([0, 1]), 4, np.array([2,3]))

As we can see from the following example, the sample data is changing and the change is reducing over each epoch.

feedforward(np.array([0, 1]), 0, np.array([2,3]))

feedforward(np.array([0, 1]), 0, np.array([0.9525741268224334,0.9525741268224334]))

feedforward(np.array([0, 1]), 0, np.array([0.7216325609518421,0.7216325609518421]))

feedforward(np.array([0, 1]), 0, np.array([0.6729664167640047,0.6729664167640047]))

feedforward(np.array([0, 1]), 0, np.array([0.6621670709858073,0.6621670709858073]))

feedforward(np.array([0, 1]), 0, np.array([0.6597470227463499,0.6597470227463499]))

Labels:


March 10, 2019

 

Naive Bayes explained

In order to understand naive bayes, let's import the wine data that comes with sklearn module. We will save all the columns as dataframe along with the target column. We will split the data into features + Target (X + y) and then split it up into train and test. Now fit the training data to create a model called "gnb" and then try to predict the test data. Since we already know the expected value, we can compare it with prediction outcome and then calculate the accuracy score.

from sklearn import datasets
wine = datasets.load_wine()

df_wine=pd.DataFrame(wine.data, columns=wine.feature_names)
df_wine['target'] = wine.target

X = df_wine.iloc[:, :-1]
y = df_wine.iloc[:, -1]

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.3, random_state=109)

gnb = GaussianNB()
gnb.fit(X_train, y_train)
y_pred = gnb.predict(X_test)

metrics.accuracy_score(y_test, y_pred)

As you can see the code is just 10 to 12 lines and it is very readable.

You will need to import the following modules for this exercise.

import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn import metrics

Here is another and very popular example of using naive bayes.

# Assigning features and label variables
weather = [
    'Sunny', 'Sunny', 'Overcast', 'Rainy', 'Rainy', 'Rainy', 'Overcast',
    'Sunny', 'Sunny', 'Rainy', 'Sunny', 'Overcast', 'Overcast', 'Rainy'
]
temp = [
    'Hot', 'Hot', 'Hot', 'Mild', 'Cool', 'Cool', 'Cool', 'Mild', 'Cool', 'Mild',
    'Mild', 'Mild', 'Hot', 'Mild'
]

play = [
    'No', 'No', 'Yes', 'Yes', 'Yes', 'No', 'Yes', 'No', 'Yes', 'Yes', 'Yes',
    'Yes', 'Yes', 'No'
]

df = pd.DataFrame({"play": play, "temp": temp, "weather": weather})

df_encoded = df.apply(LabelEncoder().fit_transform)

X = df_encoded[["weather", "temp"]]
y = df_encoded[["play"]]

model = GaussianNB()
model.fit(X, y)

predicted = model.predict([[0, 2]])  # 0:Overcast, 2:Mild
print("Predicted Value:", predicted)

All the 3 columns in this dataframe were categorical and as per machine learning rule, we need to change the text to numbers. LabelEncoder class will modify the data and create a new dataframe called "df_encoded" with numbers only columns. You can compare both the dataframes side by side using...

pd.concat([df, df_encoded], axis=1)

Labels: ,


March 09, 2019

 

neural networks using sklearn

sklearn supports neural networks as shown in the following code.

a) The first parameter, hidden_layer_sizes, is used to set the size of the hidden layers, creating three layers of 10 nodes each.

b) The second parameter to MLPClassifier specifies the number of iterations, or the epochs, that you want your neural network to execute. One epoch is a combination of one cycle of feed-forward and back propagation phase.

c) By default the 'relu' activation function is used with 'adam' cost optimizer. You can change these functions using the activation and solver parameters, respectively.

# create dataframe using IRIS database
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
names = ["sepal-length", "sepal-width", "petal-length", "petal-width", "Class"]
irisdata = pd.read_csv(url, names=names)

# Features and target split
X = irisdata.iloc[:, 0:4]
y = irisdata.iloc[:, 4]

# fit data using standard scaler
scaler = StandardScaler()
X = scaler.fit_transform(X)

# target values encoded to numeric
le = preprocessing.LabelEncoder()
y = le.fit_transform(y)

# Train test split
X_train, X_test, y_train, y_test = train_test_split(
    X, y, random_state=1, test_size=0.20
)

# Use MLP classifier class
mlp = MLPClassifier(hidden_layer_sizes=(10, 10, 10), max_iter=1000)
mlp.fit(X_train, y_train)
predictions = mlp.predict(X_test)

# Accuracy score is almost 100% only 1 error
confusion_matrix(y_test, predictions)
accuracy_score(y_test, predictions)
classification_report(y_test, predictions)

# Here are the modules imported:

import pandas as pd
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import (
    classification_report,
    confusion_matrix,
    accuracy_score,
)

Labels: ,


Archives

June 2001   July 2001   January 2003   May 2003   September 2003   October 2003   December 2003   January 2004   February 2004   March 2004   April 2004   May 2004   June 2004   July 2004   August 2004   September 2004   October 2004   November 2004   December 2004   January 2005   February 2005   March 2005   April 2005   May 2005   June 2005   July 2005   August 2005   September 2005   October 2005   November 2005   December 2005   January 2006   February 2006   March 2006   April 2006   May 2006   June 2006   July 2006   August 2006   September 2006   October 2006   November 2006   December 2006   January 2007   February 2007   March 2007   April 2007   June 2007   July 2007   August 2007   September 2007   October 2007   November 2007   December 2007   January 2008   February 2008   March 2008   April 2008   July 2008   August 2008   September 2008   October 2008   November 2008   December 2008   January 2009   February 2009   March 2009   April 2009   May 2009   June 2009   July 2009   August 2009   September 2009   October 2009   November 2009   December 2009   January 2010   February 2010   March 2010   April 2010   May 2010   June 2010   July 2010   August 2010   September 2010   October 2010   November 2010   December 2010   January 2011   February 2011   March 2011   April 2011   May 2011   June 2011   July 2011   August 2011   September 2011   October 2011   November 2011   December 2011   January 2012   February 2012   March 2012   April 2012   May 2012   June 2012   July 2012   August 2012   October 2012   November 2012   December 2012   January 2013   February 2013   March 2013   April 2013   May 2013   June 2013   July 2013   September 2013   October 2013   January 2014   March 2014   April 2014   May 2014   July 2014   August 2014   September 2014   October 2014   November 2014   December 2014   January 2015   February 2015   March 2015   April 2015   May 2015   June 2015   July 2015   August 2015   September 2015   January 2016   February 2016   March 2016   April 2016   May 2016   June 2016   July 2016   August 2016   September 2016   October 2016   November 2016   December 2016   January 2017   February 2017   April 2017   May 2017   June 2017   July 2017   August 2017   September 2017   October 2017   November 2017   December 2017   February 2018   March 2018   April 2018   May 2018   June 2018   July 2018   August 2018   September 2018   October 2018   November 2018   December 2018   January 2019   February 2019   March 2019   April 2019   May 2019   July 2019   August 2019   September 2019   October 2019   November 2019   December 2019   January 2020   February 2020   March 2020   April 2020   May 2020   July 2020   August 2020   September 2020   October 2020   December 2020   January 2021   April 2021   May 2021   July 2021   September 2021   March 2022   October 2022   November 2022   March 2023   April 2023   July 2023   September 2023   October 2023   November 2023  

This page is powered by Blogger. Isn't yours?