**SCIPY in Data Science:-**

Scipy is the special library of python which is used to perform an advanced mathematical operation using the different predefined methods.

It is the top layer of NumPy because NumPy is used to perform the basic mathematical operation, scipy mostly focus on linear algebra and other advanced mathematical function.

SCIPY was written as a SIGH PY word.

How we install scipy in the machine?

if you want to install scipy with core python or python shell then you can use the command

Q)Create Script to write File in Matlab format and load it using scipy library?

Note:- Numpy support only CSV, txt format data but scipy can write data in Matlab format which is used in many Matlab device systems.

Scipy, I/O package, has a wide range of functions for work with different files format which are Matlab, Arff, Wave, Matrix Market, IDL, NetCDF, TXT, CSV, and binary format.

Cubic root function in python:-

from scipy.special import Jn

#define exp10 function and pass value in its

exp = jn(2,3)

print(exp)

...............................................................................................................

It is the top layer of NumPy because NumPy is used to perform the basic mathematical operation, scipy mostly focus on linear algebra and other advanced mathematical function.

SCIPY was written as a SIGH PY word.

How we install scipy in the machine?

if you want to install scipy with core python or python shell then you can use the command

**python -m pip install scipy.**Q)Create Script to write File in Matlab format and load it using scipy library?

import numpy as np from scipy import io as scs array = np.zeros((4, 4)) scs.savemat('exm.mat', {'key': array}) data = scs.loadmat('exm.mat', struct_as_record=True) print(data['key'])

Note:- Numpy support only CSV, txt format data but scipy can write data in Matlab format which is used in many Matlab device systems.

Scipy, I/O package, has a wide range of functions for work with different files format which are Matlab, Arff, Wave, Matrix Market, IDL, NetCDF, TXT, CSV, and binary format.

## Special Function package:-

It provides multiple predefined methods to perform a mathematical operation using scipy.special.

SciPy special function includes Cubic Root, Exponential, Log sum Exponential, Lambert, Permutation and Combinations, Gamma, Bessel, hypergeometric, Kelvin, beta, parabolic cylinder, Relative Error Exponential, etc..

Cubic root function in python:-

scipy.special.cbrt(x)

Script to calculate cube using python:-

from scipy.special import cbrt #Find cubic root of 27 & 64 using cbrt() function cb = cbrt([27, 64]) #print value of cb print(cb)

Exponential function:-

from scipy.special import exp10 #define exp10 function and pass value in its exp = exp10([1,10]) print(exp)

### Permutations & Combinations:

SciPy also gives functionality to calculate Permutations and Combinations.

**Combinations -**scipy.special.comb(N,k

**)**

from scipy.special import comb #find combinations of 5, 2 values using comb(N, k) com = comb(5, 2, exact = False, repetition=True) print(com)

**It will add a number (n) to the result If repetition is true.**

**Permutations –**

scipy.special.perm(N,k)

from scipy.special import perm #find permutation of 5, 2 using perm (N, k) function per = perm(5, 2, exact = True) print(per)

### Log Sum Exponential Function

Log Sum Exponential computes the log of the sum exponential input element.

Syntax :

scipy.special.logsumexp(x)

from scipy.special import logsumexp

#define exp10 function and pass value in its

exp = logsumexp([2,3,4])

print(exp)

#define exp10 function and pass value in its

exp = logsumexp([2,3,4])

print(exp)

### Bessel Function

Nth integer order calculation function

Syntax :

scipy.special.jn()it uses this formula internally

#define exp10 function and pass value in its

exp = jn(2,3)

print(exp)

...............................................................................................................

## Linear Algebra with SciPy:-

- Linear Algebra of SciPy is an implementation of BLAS and ATLAS LAPACK libraries.
- Performance of Linear Algebra is very fast compared to BLAS and LAPACK.
- Linear algebra routine accepts two-dimensional array object and output is also a two-dimensional array.

from scipy import linalg import numpy as np #define square matrix two_d_array = np.array([ [4,5], [3,2] ]) #pass values to det() function linalg.det( two_d_array )

## Discrete Fourier Transform – scipy.fftpack

- DFT is a mathematical technique which is used in converting spatial data into frequency data.
- FFT (Fast Fourier Transformation) is an algorithm for computing DFT
- FFT is applied to a multidimensional array.
- Frequency defines the number of signals or wavelengths in a particular time period.

Example: Take a wave and show using the Matplotlib library. we take a simple periodic function example of sin(20 × 2Ï€t)

%matplotlib inline from matplotlib import pyplot as plt import numpy as np #Frequency in terms of Hertz fre = 5 #Sample rate fre_samp = 50 t = np.linspace(0, 2, 2 * fre_samp, endpoint = False ) a = np.sin(fre * 2 * np.pi * t) figure, axis = plt.subplots() axis.plot(t, a) axis.set_xlabel ('Time (s)') axis.set_ylabel ('Signal amplitude') plt.show()

You can see this. Frequency is 5 Hz and its signal repeats in 1/5 seconds – it's call as a particular time period.Now let us use this sinusoid wave with the help of DFT application.

%matplotlib inline from matplotlib import pyplot as plt from scipy import fftpack A = fftpack.fft(a) frequency = fftpack.fftfreq(len(a)) * fre_samp figure, axis = plt.subplots() axis.stem(frequency, np.abs(A)) axis.set_xlabel('Frequency in Hz') axis.set_ylabel('Frequency Spectrum Magnitude') axis.set_xlim(-fre_samp / 2, fre_samp/ 2) axis.set_ylim(-5, 110) plt.show()

# DATA SCIENCE ( 7 to 8 PM )

ReplyDelete# Program to Solve a System of Linear Equation

# A matrix is usually shown by a capital letter.

import numpy as np

from scipy import linalg as la # import scipy.linalg as la

A = np.array([[1,2,3],[0,4,5],[1,0,6]])

B = np.array([4,-11,1])

print("Solution for Linear Equation :-",la.solve(A,B))

# DATA SCIENCE ( 7 to 8 PM )

ReplyDelete# Program for Dot product and matrix multiplication.

import numpy as np

import scipy.linalg as la # from scipy import linalg as la

A = np.array([[1,2,3],[0,4,5],[1,0,6]])

B = np.array([4,-11,1])

Ainv = la.inv(A)

Dot_AB = np.dot(Ainv,B)

print("Dot product of A and B :- ",Dot_AB)

# DATA SCIENCE ( 7 to 8 PM)

ReplyDelete# Program to Find Î»(Eigenvalue) and v(Eigenvector).

# Av = Î»v

# Here A is square matrix ,v is Eigenvector and Î» is Eigenvalue ,which make this(Av = Î»v) equation true:

import numpy as np

import scipy.linalg as la # from scipy import linalg as la

A = np.array([[1,2,3],[0,4,5],[1,0,6]])

Î»,v = la.eig(A)

print("Î» is Eigenvalue :-",Î»,"\n")

print("v is Eigenvector :-\n",v)

# DATA SCIENCE ( 7 to 8 PM )

ReplyDelete# Cayley-Hamilton Theorem (2x2)

# The Cayley-Hamilton Theorem states that any square matrix satisfies its characteristic polynomial.

# This means that For a matrix A = [a b / c d] , A2 - (a + d)A + (ad - bc)I = O is true.

# I: Identity matrix , O: Zero matrix

import numpy as np

import scipy.linalg as la # from scipy import linalg as la

A = np.array([[1 ,2],[3, 4]])

trace_A = np.trace(A) # Matrix Trace, the sum of the diagonal elements.

det_A = la.det(A) # Determinant of a Matrix ((1*4)-(2*3) = -2)

I = np.eye(2) # Identity Matrix , n×n square matrix with ones on the main diagonal and zeros elsewhere.

print(A @ A - trace_A * A + det_A * I) # @ is an operator. It is named as __matmul__, designed to do matrix multiplication

ReplyDelete# Least squares is a standard approach to problems with more equations than unknowns.

# Least squares also known as overdetermined systems.

from scipy import linalg as la

import numpy as np

#Declaring the numpy arrays

A = np.array([[3,2],[1,-1,],[4,-5]])

B = np.array([[2,2,3,1],[4,5,6,7],[8,9,7,5]])

#Passing the values to the solve function

C,residuals,rank,s = np.linalg.lstsq(A,B)

print("C is the solution :-\n",C)

print("\nResiduals :-",residuals,"\nRank :-",rank,"\nSingular values :-",s)

#Residuals the sum, Rank the matrix rank of input A, and s the singular values of A.

## Post a Comment

If you have any doubt in programming or join online classes then you can contact us by comment .