In [1]:
import numpy as np
In [2]:
a = np.arange(10)
print (type (a))
In [3]:
b=a[np.newaxis, :]
In [4]:
print (b.shape)
In [5]:
A=np.array([[1,2,3], [1,3,2],[1,1,2]], dtype=float) #array creation
print(A)
print(A[...,1])#slicing
print (A[A > 1]) #boolean indexing
A.reshape(1,9)
a = np.array([np.nan, 1,2,np.nan,3,4,5])
print (a[~np.isnan(a)]) # removing nan
In [6]:
A.reshape(1,9)
Out[6]:
In [7]:
a = np.array([1,2,3,4])
b = np.array([[10,20,30,40], [1,2,3,4]])
c = a * b
print (c)
In [8]:
a = np.arange(0,60,5)
a = a.reshape(3,4)
print ('Original array is:')
print(a)
print ("\n")
a = a.T #if we want iter transpose
print ('Modified array is:')
i=0
for x in np.nditer(a): #it will take elementwise
#for x in a: ##it will take row wise
i=i+1
print(x)
print("total count is ",i) #Best way to print anything
In [9]:
##If the same elements are stored using F-style order, t
#efficient way of iterating over an array.
#c-style --> row wise iteration
#f-style --> column wise iteration
a = np.arange(0,60,5)
a = a.reshape(3,4)
print ('Original array is:')
print (a)
print ('\n')
print ('Transpose of the original array is:')
b = a.T
print( b)
print ('\n')
print ('Sorted in C-style order:')
c = b.copy(order = 'C')
print (c)
for x in np.nditer(c):
print (x)
print ('\n')
print ('Sorted in F-style order:')
c = b.copy(order = 'F')
print (c)
for x in np.nditer(c):
print (x)
In [10]:
print ('Sorted in C-style order:' )
for x in np.nditer(a, order = 'C'):
print (x,)
print ('\n' )
print ('Sorted in F-style order:' )
for x in np.nditer(a, order = 'F'):
print (x,)
In [11]:
## Modifying Array Values
print ('Original array is:')
print( a)
print ('\n')
for x in np.nditer(a, op_flags = ['readwrite']): ##op_flag default value 'read-only'
x[...] = 2*x
print ('Modified array is:')
print (a)
### other flags
##x_index, f_index,multi-ndex,external_loop
for x in np.nditer(a, flags = ['external_loop'], order = 'F'):
print (x,)
In [12]:
## Broadcasting iteration
a = np.arange(0,60,5)
a = a.reshape(3,4)
print ('First array is:' )
print (a )
print ('\n' )
print ('Second array is:' )
b = np.array([1, 2, 3, 4], dtype = int)
print (b )
print ('\n' )
print ('Modified array is:' )
for x,y in np.nditer([a,b]):
print ("%d:%d" % (x,y),)
In [13]:
a = np.arange(0,60,5)
a=a.reshape(3,4)
print(a)
print(a.ravel)
In [14]:
a = np.array([0,30,45,60,90])
print ('Array containing sine values:' )
sin = np.sin(a*np.pi/180)
print (sin )
print ('\n' )
print ('Compute sine inverse of angles. Returned values are in radians.' )
inv = np.arcsin(sin)
print (inv )
print ('\n'
)
print ('Check result by converting to degrees:' )
print (np.degrees(inv) )
print ('\n')
print ('arccos and arctan functions behave similarly:' )
cos = np.cos(a*np.pi/180)
print (cos )
print ('\n' )
print ('Inverse of cos:' )
inv = np.arccos(cos)
print (inv )
print ('\n' )
print ('In degrees:' )
print (np.degrees(inv) )
print ('\n' )
print ('Tan function:' )
tan = np.tan(a*np.pi/180)
print (tan)
print ('\n')
print ('Inverse of tan:' )
inv = np.arctan(tan)
print (inv )
print ('\n' )
print ('In degrees:' )
print (np.degrees(inv))
In [15]:
a = np.array([10,20,30])
b = np.array([3,5,7])
print ('Our array is:' )
print (a )
print("\n power 2:",np.power(a,2))
print("\n reciprocal 2:",np.reciprocal(a))
print("\n mod a/b:",np.mod(a,b))
print("\n remainder a/b:",np.remainder(a,b))
a = np.array([-5.6j, 0.2j, 11. , 1+1j])
print("\n imaginry", np.imag(a))
print("\n real", np.real(a))
print("\n complex conjugate", np.conj(a)) # complex conjugate
print("\n angle in rad", np.angle(a))
print("\n angle in degrees", np.angle(a, deg=True))
In [16]:
##NumPy - Statistical Functions
## amin, amax
### more functions mean(), median(), percentile()
a = np.array([[3,7,5],[8,4,3],[2,4,9]])
print("\n original array\n", a)
print("\n row wise min :", np.amin(a,1))
print("\n column wise min :", np.amin(a,0))
print("\n row wise max :", np.amax(a,1))
print("\n overall max :", np.amax(a))
print("\n overall min :", np.amin(a))
##The numpy.ptp() function returns the range (maximum-minimum) of values along an axis
print ('\n Applying ptp() function:' )
print (np.ptp(a) )
print ('\n Applying ptp() function along axis 1:' )
print (np.ptp(a, axis = 1) )
print ('\n Applying ptp() function along axis 0:')
print( np.ptp(a, axis = 0) )
b = np.array([1,2,3,4])
wts = np.array([4,3,2,1])
print ('Applying average() function again:' )
print (np.average(b,weights = wts) ) # weighted average
print("\n standard deviation of a ", np.std(a)) # std = sqrt(mean(abs(x - x.mean())**2))
print("\n variance of a ", np.var(a)) # var= mean(abs(x - x.mean())**2).
In [17]:
#dt = np.dtype([('name', 'str'),('age', int)])
dt = np.dtype([('name', 'S10'),('age', int)]) # S10 starts each string with b for bytes
a = np.array([("raju",21),("anil",25),("ravi", 17), ("amar",27)], dtype = dt)
print ('Our array is:' )
print( a )
print ('\n' )
print( 'Order by name:' )
print (np.sort(a, order = 'name', kind='heapsort'))
#print (np.sort(a, kind='mergesort', order = 'name')) ## default kind=quicksort()
In [18]:
##argsort gives indices of sorting
#numpy.lexsort() left for free time
x = np.array([3, 1, 2])
print ('Our array is:' )
print (x )
print ('\n' )
print ('Applying argsort() to x:' )
y = np.argsort(x)
print (y )
print ('\n' )
print ('Reconstruct original array in sorted order:' )
print (x[y])
print ('\n' )
print ('Reconstruct the original array using loop:' )
for i in y:
print( x[i])
print ("\n max value index is ", np.argmax(x) ) #gives index of max value
print ("\n min value index is ", np.argmin(x) ) #gives index of min value
a = np.array([[30,40,0],[0,20,10],[50,0,60]])
print ("\n Non-zero elements are ", np.nonzero(a))
#numpy.nonzero() function returns the indices of non-zero elements in the input
In [19]:
x = np.arange(12.).reshape(3, 4)
print ('Our array is:' )
print( x )
print ('Indices of elements > 3' )
y = np.where(x > 3) # gives tuple for values x and y
print("\n type of y ", type(y))
print (y )
print ('Use these indices to get elements satisfying the condition' )
print( x[y])
In [20]:
x = np.arange(9.).reshape(3, 3)
print ('Our array is:' )
print(x)
# define a condition
condition = np.mod(x,2) == 0
print ('Element-wise value of condition' )
print (condition )
print ('Extract elements using condition' )
print( np.extract(condition, x))
In [21]:
from matplotlib import pyplot as plt
a = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27])
#np.histogram(a,bins = [0,20,40,60,80,100])
hist,bins = np.histogram(a,bins = [0,20,40,60,80,100]) #bins provide range for calculation
print (hist)
print (bins)
%matplotlib inline
plt.hist(a,bins = [0,20,40,60,80,100]) # histogram using matplotlib
plt.show()
In [22]:
a = np.array([1,2,3,4,5])
np.save('outfile',a) #save as outfile.npy
b = np.load('outfile.npy') # load existing numpy file
print (b)
np.savetxt('out.txt',a) #save as text file
b = np.loadtxt('out.txt') #load as text file
print (b)
In [23]:
## K-means clustering example using Scipy
import scipy
from scipy.cluster.vq import kmeans,vq,whiten #vq-vector quantization
from numpy import vstack,array
from numpy.random import rand
# data generation with three features
data = vstack((rand(100,3) + array([.5,.5,.5]),rand(100,3)))
# whitening of data
data = whiten(data)
print("\n data \n", data)
# computing K-Means with K = 3 (2 clusters)
centroids,_ = kmeans(data,3)
print("Centroids are \n",centroids)
# assign each sample to a cluster
clx,_ = vq(data,centroids)
print("Cluster: \n", clx)
In [24]:
##Fourier transform using scipy
#Importing the fft and inverse fft functions from fftpackage
#same like we can calculate dct FFT and all
from scipy.fftpack import fft, ifft
#create an array with random n numbers
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
#Applying the fft function
y = fft(x)
print( y)
#FFT is already in the workspace, using the same workspace to for inverse transform
yinv = ifft(y)
print (yinv)
In [25]:
## Scipy Integration example
## refer https://www.tutorialspoint.com/scipy/scipy_integrate.htm
import scipy.integrate
from numpy import exp
f= lambda x:exp(-x**2)
i = scipy.integrate.quad(f, 0, 1)
#first number integral and the second estimate of absolute error
print( i)
## Double integration
from numpy import exp
from math import sqrt
f = lambda x, y : 16*x*y
g = lambda x : 0
h = lambda y : sqrt(1-4*y**2)
i = scipy.integrate.dblquad(f, 0, 0.5, g, h) # for tripple integration tplquad,for nth nquad
print (i)
In [26]:
##Scipy-Interpolation example
##Interpolation is the process of finding a value between two points on a line or a curve
from scipy import interpolate as intp
import matplotlib.pyplot as plt
x = np.linspace(0, 4, 12)
y = np.cos(x**2/3+4)
print (x,y)
f1 = intp.interp1d(x, y,kind = 'linear') ##i-D interpolation
f2 = intp.interp1d(x, y, kind = 'cubic')
xnew = np.linspace(0, 4,30)
plt.plot(x, y,'o', xnew, f1(xnew), '-', xnew, f2(xnew), '--')
plt.legend(['data', 'linear', 'cubic',], loc = 'best') #legend for multiple graph in single
##figure
plt.show()
In [27]:
from scipy.interpolate import UnivariateSpline
x = np.linspace(-3, 3, 50)
y = np.exp(-x**2) + 0.1 * np.random.randn(50)
plt.figure()
plt.plot(x, y, 'ro', ms = 5)
#plt.show() #uncomment if want result in seperate figure
spl = UnivariateSpline(x, y)
xs = np.linspace(-3, 3, 1000)
plt.plot(xs, spl(xs), 'g', lw = 3)
#plt.show()
spl.set_smoothing_factor(0.5)
plt.plot(xs, spl(xs), 'b', lw = 3)
plt.show()
In [28]:
##Scipy IO with matlab
import scipy.io as sio
#Save a mat file
vect = np.arange(10)
sio.savemat('array.mat', {'vect':vect})
#Now Load the File
mat_file_content = sio.loadmat('array.mat')
print (mat_file_content)
mat_content = sio.whosmat('array.mat') #checking content of file without loading it
print ("\n",mat_content)
In [29]:
#Linear equation solving usibg scipy
#importing the scipy and numpy packages
from scipy import linalg
import numpy as np
#Declaring the numpy arrays
a = np.array([[3, 2, 0], [1, -1, 0], [0, 5, 1]])
b = np.array([2, 4, -1])
#Passing the values to the solve function
x = linalg.solve(a, b)
#printing the result array
print (x)
y = linalg.det(A)
#printing the result
print ("Determinant of matrix a \n",y)
#Passing the values to the eig function
l, v = linalg.eig(a)
#printing the result for eigen values
print("Eigen values of matrix a \n", l)
#printing the result for eigen vectors
print("Eigen vectors of matrix a \n",v)
In [30]:
#Declaring the numpy array
a = np.random.randn(3, 2) + 1.j*np.random.randn(3, 2)
#Passing the values to the eig function
U, s, Vh = linalg.svd(a)
# printing the result
print (U, Vh, s)
In [31]:
import numpy as np
import matplotlib.pyplot as plt
from scipy.odr import *
import random
# Initiate some data, giving some randomness using random.random().
x = np.array([0, 1, 2, 3, 4, 5])
y = np.array([i**2 + random.random() for i in x])
# Define a function (quadratic in our case) to fit the data with.
def linear_func(p, x):
m, c = p
return m*x + c
# Create a model for fitting.
linear_model = Model(linear_func)
# Create a RealData object using our initiated data from above.
data = RealData(x, y)
# Set up ODR with the model and data.
odr = ODR(data, linear_model, beta0=[0., 1.])
# Run the regression.
out = odr.run()
# Use the in-built pprint method to give us results.
out.pprint()
No comments:
Post a Comment