ML Club sessions
Python for ML

Community session, with GDSC · Epoch, IIT Hyderabad · Feb 5, 2023

A hands-on session that builds on the Introduction to Python series by Lambda. It introduces NumPy and ends with a fun exercise on matrix transformations.

Slide 1 of 108
1 / 108

Python for ML

Community session, with GDSC · Epoch, IIT Hyderabad · Feb 5, 2023

A hands-on session that builds on the Introduction to Python series by Lambda. It introduces NumPy and ends with a fun exercise on matrix transformations.

  1. Python for ML An Epoch-GDSC Collaboration
  2. Introducing GDSC Club ❖GDSC stands for Google Developer Student Club ❖It has the following domains: ➢Web Development ➢Cloud Computing ➢Machine Learning ❖This our first session from GDSC Club. ❖Python for ML Session
  3. Revisited!
  4. Python Basics - Revisited! ❖Data Types: - Strings - Lists - Dictionary - Tuples - Sets ❖Membership : The in and not in operator ❖Functions ❖Lambda Expressions
  5. Variables and Datatypes - Python has no command for declaring a variable. - A variable is created the moment you first assign a value to it.
  6. Python Vs C/C++? Well, who is better?
  7. Python wins??? Wait, not yet!
  8. No strings attached! Strings in python are surrounded by either single quotation marks, or double quotation marks. Slicing: Return a range of characters by using the slice syntax.
  9. Lists = Arrays? Lists are used to store multiple items in a single variable. Can include any datatype Lists are created using square brackets: Can you predict the output ?
  10. Ready for Binge Watching? The output :-
  11. Lists in Python vs Arrays in C - Code for reversing an array - Lot of inbuilt methods in Python - Easy and concise compared to C
  12. A simple task for counting the number of of occurrence of a particular element in an array is so much longer in C than in Python ! Look it for yourself ! Python wins??? Wait, not yet! - Now, yes - Maybe?
  13. Inbuilt Functions in Lists Due to the popularity of lists, it has a lot of in-built methods (which you can explore ) listed as append() Adds an element at the end of the list copy() Returns a copy of the list count() Returns the number of elements with the specified value index() Returns the index of the first element with the specified value insert() Adds an element at the specified position pop() Removes the element at the specified position remove() Removes the item with the specified value reverse() Reverses the order of the list sort() Sorts
  14. List Comprehension Use list comprehension when you want to create a new list based on the values of an existing list. It offers shorter syntax compared to using for loops to create a new list
  15. Tuples A tuple is a collection which is ordered and immutable(unchangeable) Tuples are fixed size in nature whereas lists are dynamic. In other words, a tuple is immutable whereas a list is mutable.
  16. More on Tuples You can't add elements to a tuple. Tuples have no append method. You can't remove elements from a tuple. You can find elements in a tuple, since this doesn’t change the tuple. Why tuples when there is lists ? Or when to use tuples? - Faster than lists. If you're defining a constant set of values and all you would do with it is iterate through it, use a tuple instead of a list. - Makes your code safer if you “write-protect” data that does not need to be changed. Using a tuple is like having an implied assert statement that this data is constant. Tuples are like Jee Advanced Ranks, you can't change them ! Ok, but one paper can not decide my future ! 😉
  17. Sets - The one we see in Math? Yes! Sets are defined by unique elements and are unordered Note: Set items are unchangeable, but you can remove items and add new items.- When to use a set : If you just need to know whether or not a value is present , but without ordering (and you don't need to store duplicates) Use a set. What might be the Output ?
  18. Example Output:
  19. Dictionaries - Not the Oxford one! - used to store data values in {key:value} pairs. - is ordered , changeable and do not allow duplicates in the sense that you can not repeat keys.
  20. Dictionaries >> Two Lists - You can also access items of a dictionary using its key name e.g d[‘Raj’] - Dictionaries can have any data type in the value - Each key must be immutable. Values maybe mutable. - This allows lists to be the values of a key. Lists cannot be keys. Why not two lists but a dict? Easier and faster because it uses key - value mapping format, something 2 lists being used parallely can’t.
  21. The ‘in’ and "not in" Operator in Python The in keyword can also be used to check if a value is present in a sequence (list, range, string etc.).
  22. Functions in Python vs C - A simple code for adding 2 numbers - Lots of line in C - Simplified in Python
  23. Lists as argument to function! - Note that multiplying a list with a number k will repeat the items of the list as the size of the number k
  24. - expressions! λ Syntax: lambda arguments : expression
  25. Intro to
  26. Numpy Vs Lists What is numpy? NumPy is a Python library used for working with arrays. Various functions of linear algebra, fourier transform, and matrices make numpy arrays a powerful tool. Example: my_numpy_array = [1,2,3] What is a list? A Python list is a collection that is ordered and changeable. Example: Var = ["Epoch", "IIT", "Hyderabad"]
  27. NumPy Arrays vs Normal Arrays - Is comparison even needed?
  28. NumPy Operations = Superset of List Operations Initialization: Accessing the items through index:
  29. Slicing again…you ready now?
  30. NumPy vs Lists - Faceoff: Memory Comparison Memory(in bytes) list consumes: 120 Memory(in bytes) NumPy array consumes: 8 List consumes 15.0 times memory than a numpy array of same size
  31. NumPy vs Lists - Faceoff: Time Comparison Code Text List after adding 3: [3, 4, 5, 6, 7] Numpy after adding 3: [3 4 5 6 7] Comparing the time consumed by lists and numpy arrays for addition operation Lists: 0.004734516143798828 Numpy_Array 0.0003457069396972656 Numpy arrays are 13 times faster
  32. NumPy Arrays vs Lists: How are they represented internally?
  33. NumPy Arrays are faster and memory efficient - Explained! 1. NumPy arrays, unlike lists, are kept in a single continuous location in memory, allowing programs to access and manipulate them quickly. Having them in contiguous memory locations helps reduce latencies in finding the next element and traversal is made faster this way! 2. Lists are internally implemented using the Linked List Data Structure. In order to store the pointers for addresses of the previous and next elements in the list, some extra memory is taken. In NumPy, since they are allocated memory continuously, there is no need to have their pointers to point us to the address of the next locations.
  34. The Vectorization Hack! Vectorization is the process of converting an algorithm from operating on a single value at a time to operating on a set of values at one time. Advantages of Vectorized Implementation 1. Our code runs efficiently 2. Our code becomes simpler and easy to debug
  35. (image slide)
  36. And that’s a wrap - Lists vs NumPy Arrays!
  37. Random Number Generation
  38. (image slide)
  39. Random Numbers - Python defines a set of functions that are used to generate or manipulate random numbers through the random module. - np.random rand(shape) - It produce random values in a given shape from a uniform distribution.
  40. Random Arrays and Matrices - Let’s create NumPy array with random numbers
  41. Can we generate negative random numbers too? Yes! What if we want random negative numbers too? - np.random.randn(shape) - Returns random numbers sample from a “standard normal” distribution.
  42. Random Integers - All the above method generates random floating point numbers, but what if you want random integers. - np.random.randint(low, high=None, size=None, dtype=int) - Low = 0 (default)
  43. The G.O.A.T Debate! - Messi vs Ronaldo
  44. NumPy’s say on the G.O.A.T Debate :) - Let’s see what numpy has to say about!! - np.random.choice(a, size=None, replace=True, p=None)
  45. The G.O.A.T Debate! - Messi vs Ronaldo No Intro Needed now!!
  46. NumPy’s say on the G.O.A.T Debate :) - Let’s see what NumPy has to say about it:
  47. Messi Fans - This is for you! - Let’s cheat the system - The parameter p defines the probabilities associated with each entry in a. If not given, the sample assumes a uniform distribution over all entries in a.
  48. Cricket Fans - It’s your turn now :) - Quick Exercise !! - Make your favourite cricketer win the game 😉 - Fill the “p” parameter to make the event certain
  49. np.arange - Let’s generate some organized numbers now - np.arange(start, stop, step): - allows you to define the step size and infers the number of steps(the number of values you get)
  50. np.linspace - np.linspace(start, stop, num) - It allows you to define how many values you get including the specified min and max value - How it is different from np.arange()? - You do not need to specify the step size in np.linspace. It calculates the step size according to the number of points you want.
  51. - np.shuffle(x) - Modify a sequence in-place by shuffling its contents. ● From shuffling our spotify playlist to shuffling our arrays, we have came a long way. np.shuffle: Nah, not the Dance Club :-|
  52. Probability Distributions
  53. Probability Distributions: Gaussian Distribution Gaussian/Normal distribution - The probability density for the Gaussian distribution is - The function has its peak at the mean, and its “spread” increases with the standard deviation. This implies that normal is more likely to return samples lying close to the mean, rather than those far away. Saw this in Modern Physics right? It’s not that scary as it looks!
  54. Random Sampling from Distributions - np.random.normal(loc = 0.0, scale = 1.0, size = None) - It generates random numbers from a normal distribution. - Here, loc is the mean of the distribution and scale = variance of the distribution. - Confusing?? Let’s plot it !!
  55. Other Distributions! There are still a lot of distributions that NumPy offers like: 1. np.random.weibull() 2. np.random.poisson() 3. np.random.binomial() 4. np.random.uniform() 5. etc., These are left for you to explore ! And stay tuned for the Math for ML session!
  56. Intro to
  57. Plotting - Let’s get started! - We use matplotlib for plotting figures in python. - Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. - plt.hist(x,bins, density) : Plot the histogram of the data - plt.plot() : Plot the curve in the figure - We will see this in more details in the upcoming slides
  58. Gaussian Distribution - The Bell Curve!
  59. Cricketing Analyst - Tutorials! - Let’s plot some interesting data. - I extracted out the scores of Virat Kohli in the last 6 ODI innings. Let begin our journey to Cricket Analyst and plot the data. - plt.bar(x, height, width = 0.8, align = “center”) : Plots the bar graph of the data x - We generate the x using np.linspace and Virat score is the height of our bars.
  60. Plotting - Important Functions - plt.title() - gives a title to the graph - plt.xlabel() - gives a label to the x-axis - plt.ylabel() - gives a label to the y-axis
  61. The plt.plot() function! - plt.plot(x, y, color, marker, linestyle, linewidth, label) - Plot y versus x as lines - Color - To specify a colour to our line plot - Linestyle - To customize our line - Linewidth - To customize our line width - Label - To label our line
  62. plt.grid() - plt.grid() - Plots the gridlines in the graph
  63. Can we plot multiple plots in a single figure? Yes! - Multiple plots in a single figure
  64. plt.legend(): Yeah Virat is a legend, but this is different! - plt.legend() - Plots the legend box in the figure
  65. Upcoming Legend? Tendulkar?? Sara Shubman Gill - Exercise Time! Plot the bar graph of Shubman Gill’s scores
  66. Scatter Plots! - plt.scatter(x, y, marker, color) - Plots the scatter plot of x v/s y with varying markers.
  67. The Final Plot!
  68. Functions and Gradients
  69. Mathematical Functions - Wait, we gonna see Cal - 1? Absolutely not! Mathematical functions in numpy are special because they can be used to perform operations element-wise on either python lists or numpy arrays.
  70. Trig Functions! .sin(), .cos(), .tan() .arcsin(), .arccos(), .arctan()
  71. Trigonometric functions .sinh(), .cosh(), .tanh() .degree(), .radian()
  72. Logarithmic functions .log(), .log2(), .log10() .exp(), .exp2()
  73. Additional functions .around(), .floor(), .ceil() .mod(a,b) Modulo function, prints remainder of elements in a with those in b element wise.
  74. .max(), .min() The maximum/minimum element in an array. .add(), .subtract(), .multiply(), .divide() Add, subtract, multiply, or divide two numpy arrays element wise.
  75. .conj(), .isreal() .maximum, .minimum
  76. A few interesting functions .cbrt() - returns the cube root of a number. It is one of the few ways in python that allows you to take the real cube root of a negative number - Most functions return the complex root instead.
  77. .where() Allows you to set your own conditions and returns result from the first array if true, else returns the value from the second array.
  78. Gradients np.gradient(fx,x) will output the approximate gradient calculated using numpy arrays of f(x) and x.
  79. Since gradients are calculated mathematically, they do have inaccuracies - but thankfully, they are rather low.
  80. Matrix Operations and Transformations
  81. Matrices or Multi-Dimensional Arrays Let's cover some basic functions to create numpy matrices 1. Matrices from 2D or 3D or ND Lists. 2. Ones, Zeros,and Identity.
  82. array() Method: It takes a 2D or 3D or ND List and returns a Numpy Multidimensional Array or Matrix. Creating Matrices using NumPy array method
  83. zeros(): Returns a Numpy Array of all zeros of given shape. Creating Matrices using NumPy Functions ones(): Returns a Numpy Array of all ones of given shape. identity(): Returns a 2D Identity Square Matrix of given Rows, Columns.
  84. Shape of np array shape: Returns the number of elements in each dimension of the np array. ndim: Returns the Number of Dimensions of the np array.
  85. Reshaping np arrays reshape(): Returns the reshaped np array if possible.
  86. Matrix Transformations : Addition Now we will look at a function to add two matrices: add() method : Takes Two numpy matrices of same size and adds them.
  87. C vs NumPy for matrix multiplication
  88. Matrix Transformations : Multiplication Now we will look at a function to multiply two matrices: element wise matrix multiplication : Multiplies matrices element by element just as add() does
  89. Matrix Multiplication - 1 matmul() method : Multiplies matrices just like you did in your JEE !
  90. Matrix Multiplication - 2 Another way of multiplying : :::;matrices: @ operator
  91. Matrix Transformations : Trace trace() method takes np array as input and outputs its trace.
  92. linalg.det() method takes np array as input and returns its determinant Matrix Transformations : Determinant
  93. Matrix Transformations : Transpose T attribute returns a matrix which is the transpose of the given Matrix.
  94. Numpy’s Reaction when you calculate inverse of a matrix on your own
  95. Matrix Transformations : Inverse linalg.inv() method takes matrix as input and return a matrix which is its inverse
  96. Matrix Transformation : Matrix Power linalg.matrix_power() takes a matrix and an integer as input and returns matrix raised to the power integer.
  97. Solving Linear Equation Quick Exercise! Given matrices A and B, can you calculate X such that AX = B using functions used so far ?
  98. Solving A linear equation Solving a linear equation can be cumbersome when the number of equations increases, numpy gets it done efficiently!
  99. Matrix Transformations : Stacking Stacking matrices in a new dimension has many uses. This can be implemented with the numpy stack() method
  100. Other Functions There are still a lot functionalities that NumPy offers like: Important Statistical Functions: mean(), median(), var()[For variance] ,std() [Standard Deviation] Functions for expanding and squeezing dimensions: squeeze(), expand_dims() These are left for you to explore !!!
  101. Fun Exercise Alright! Now we have an exercise for you, implement what you've learnt, follow the instructions below and have fun.
  102. Let’s Begin ! Task #1 Task #3 Task #2 Task #4
  103. Look at what you just created! After stacking the matrices that you guys created and displaying the image associated with it using plt.imshow(), this is what you get…..
  104. Resources! 1. Python Documentation 2. NumPy Documentation 3. Matplotlib Documentation
  105. Social Media - Epoch Follow our social media handles for regular updates Instagra m Twitter YouTube WhatsAp p
  106. Social Media - GDSC Follow our social media handles for regular updates Instagra m Twitter
  107. Any Questions or Suggestions?
  108. Thank You!