ML Club sessions
Programming for AI

Two-day workshop, with GDSC · Epoch, IIT Hyderabad · Mar 18–19, 2023

A hands-on workshop on the most important libraries: NumPy, Pandas, Matplotlib, Seaborn, SciPy and scikit-learn, with many exercises.

Slide 1 of 217
1 / 217

Programming for AI

Two-day workshop, with GDSC · Epoch, IIT Hyderabad · Mar 18–19, 2023

A hands-on workshop on the most important libraries: NumPy, Pandas, Matplotlib, Seaborn, SciPy and scikit-learn, with many exercises.

  1. Programming for AI An Epoch-GDSC Collaboration
  2. Revisited! This time a bit faster :)
  3. Python Basics - Revisited! ❖Data Types: - Strings - Lists - Dictionary - Tuples - Sets ❖Membership : The in and not in operator ❖Functions ❖Lambda Expressions
  4. Variables and Datatypes - Python has no command for declaring a variable. - A variable is created the moment you first assign a value to it.
  5. Python Vs C/C++? Well, who is better?
  6. Python wins??? Wait, not yet!
  7. 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.
  8. 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 ?
  9. Ready for Binge Watching? The output :-
  10. Lists in Python vs Arrays in C - Code for reversing an array - Lot of inbuilt methods in Python - Easy and concise compared to C
  11. 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?
  12. 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
  13. 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
  14. 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.
  15. 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 !
  16. 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.
  17. 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.
  18. 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.).
  19. Functions in Python vs C - A simple code for adding 2 numbers - Lots of line in C - Simplified in Python
  20. 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
  21. - expressions! λ Syntax: lambda arguments : expression
  22. Intro to
  23. 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"]
  24. NumPy Arrays vs Normal Arrays - Is comparison even needed?
  25. NumPy Operations = Superset of List Operations Initialization: Accessing the items through index:
  26. Broadcasting - The term broadcasting refers to the ability of NumPy to treat arrays of different shapes during arithmetic operations. - Arithmetic operations on arrays are usually done on corresponding elements. If two arrays are of exactly the same shape, then these operations are smoothly performed.
  27. Example
  28. Slicing and Dicing ● To slice means to cut and to dice means to cut into very small uniform sections and the two actions are often performed sequentially. ● For example, a chef may first cut an onion into slices and then cut the slices up into dices. ● In data analysis, the term generally implies a systematic reduction of a body of data into smaller parts or views that will yield more information. ● The term is also used to mean the presentation of information in a variety of different and useful ways.
  29. Slicing again…you ready now?
  30. NumPy Arrays vs Lists: How are they represented internally?
  31. 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.
  32. 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
  33. (image slide)
  34. And that’s a wrap - Lists vs NumPy Arrays!
  35. Random Number Generation
  36. (image slide)
  37. 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.
  38. Random Arrays and Matrices - Let’s create NumPy array with random numbers
  39. 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.
  40. 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)
  41. np.random.choice np.random.choice(a, size=None, replace=True, p=None) - 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.
  42. 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)
  43. 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.
  44. - 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 :-|
  45. Probability Distributions
  46. 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!
  47. Gaussian Distribution - The Bell Curve!
  48. 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.
  49. 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 Workshop!
  50. Functions and Gradients
  51. 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.
  52. Trig Functions! .sin(), .cos(), .tan() .arcsin(), .arccos(), .arctan()
  53. Trigonometric functions .sinh(), .cosh(), .tanh() .degree(), .radian()
  54. Logarithmic functions .log(), .log2(), .log10() .exp(), .exp2()
  55. Additional functions .around(), .floor(), .ceil() .mod(a,b) Modulo function, prints remainder of elements in a with those in b element wise.
  56. .max(), .min() The maximum/minimum element in an array. .add(), .subtract(), .multiply(), .divide() Add, subtract, multiply, or divide two numpy arrays element wise.
  57. .conj(), .isreal() .maximum(), .minimum()
  58. 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.
  59. - .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.
  60. Gradients - np.gradient(fx,x) - This will output the approximate gradient calculated using numpy arrays of f(x) and x.
  61. Since gradients are calculated mathematically, they do have inaccuracies - but thankfully, they are rather low.
  62. Matrix Operations and Transformations
  63. 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.
  64. 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
  65. 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.
  66. 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.
  67. Reshaping np arrays reshape(): Returns the reshaped np array if possible.
  68. 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.
  69. C vs NumPy for matrix multiplication
  70. 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
  71. Matrix Multiplication - 1 matmul() method : Multiplies matrices just like you did in your JEE !
  72. Matrix Multiplication - 2 Another way of multiplying : :::;matrices: @ operator
  73. Matrix Transformations : Trace trace() method takes np array as input and outputs its trace.
  74. linalg.det() method takes np array as input and returns its determinant Matrix Transformations : Determinant
  75. Matrix Transformations : Transpose T attribute returns a matrix which is the transpose of the given Matrix.
  76. Matrix Transformations : Inverse linalg.inv() method takes matrix as input and return a matrix which is its inverse
  77. Matrix Transformation : Matrix Power linalg.matrix_power() takes a matrix and an integer as input and returns matrix raised to the power integer.
  78. Solving Linear Equation Quick Exercise! Given matrices A and B, can you calculate X such that AX = B using functions used so far ?
  79. Solving A linear equation Solving a linear equation can be cumbersome when the number of equations increases, numpy gets it done efficiently!
  80. Matrix Transformations : Stacking Stacking matrices in a new dimension has many uses. This can be implemented with the numpy stack() method
  81. 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 !!!
  82. Everything about
  83. (image slide)
  84. Pandas is a Powerful, Flexible, Fast and easy to use open source library which consists of Data Analysis and Manipulation Tools built on top of Python. It is used for working with Data sets and has many functions for exploring, cleaning, analyzing and manipulating data. What is Pandas? Its name has references to “Real Life Panda”, “Python Data Analysis” and “Panel Data” and was created in 2008.
  85. Pandas Series is a One Dimensional Array which can store data of different types like integers, floats, strings, python objects etc. It supports both integer-based and label- based indexing through which we access the elements. What are Pandas Series?
  86. Creating Pandas Series from np arrays, dictionaries With the index argument, we can name our own labels. Series Labels are the keys and the elements are values of the Dictionary.
  87. Accessing Elements of the Pandas Series We can access the Elements using the integral- index or label of the element and the [] operator. There are other ways also to access the elements of the Series which we will discuss later.
  88. Slicing the Pandas Series Accessing the Element of Pandas Series using its Label Accessing Elements of the Pandas Series
  89. What are Dataframes? Pandas Dataframe is a like 2D array or can be thought of as a table with rows and columns. In a Dataframe we can store various types of data ranging from integers, strings to datetime objects etc. Dataframe Table contains Series as its columns. We can perform Arithmetic operations, modifying the rows and columns of Dataframe etc.
  90. Creating Dataframe from Series Creating a Pandas Series ser1 from roll_name Dictionary Creating a Pandas Series ser2 from roll_marks Dictionary
  91. Creating Dataframe from Series Merging Series 1 and Series 2 into a DataFrame df
  92. loc(): loc() gets rows (and columns) with particular labels. Accessing Elements of Dataframe iloc(): iloc() gets rows (and columns) with integer locations
  93. df.shape Returns the dimensions of the Dataframe. df.dtypes Returns the Data types of each column of the Dataframe. df.index Returns the Index of the Dataframe. Attributes of DataFrame df.columns Returns the Column Labels of the Dataframe.
  94. df.values Returns the Dataframe in the form of numpy array. Attributes of DataFrame - Contd df.info Returns the summary of the Dataframe.
  95. Reading a Dataframe from CSV File or Excel File pd.read_csv(fileName) Reads a CSV File into a Dataframe.
  96. (image slide)
  97. Reading a Dataframe from CSV File or Excel File pd.read_excel(fileName) Reads an Excel File into a Dataframe.
  98. (image slide)
  99. Writing a Dataframe into a CSV File or Excel File df.to_excel(fileName) Writes the DataFrame into an Excel File with name as fileName. df.to_csv(fileName) Writes the DataFrame into a CSV File with name as fileName.
  100. Viewing the Data Frame df.tail(n) Returns the Last n rows of the Dataframe. df.head(n) Returns the First n rows of the Dataframe.
  101. df.loc() We can access using the Labels of the Rows or also using a Boolean array. Accessing Rows of a Data Frame
  102. Accessing Rows of a Data Frame - Contd df.iloc() We can access the Rows using its integer index.
  103. Dataframe General Functions df.describe() Returns the Statistical Description of the Numerical Columns in the DataFrame. Gives the Mean, Standard Deviation, Quartiles of Columns excluding Null Values.
  104. Dataframe General Functions df.info() Returns a Concise Summary of the DataFrame. Prints the dtypes of the Columns, index, Non Null Values in each Column and also memory used by the dataframe.
  105. Dataframe General Functions df.sample(n) Returns a Random Sample of n Rows(or Columns) from the Dataframe. random_state is the seed for the Random Number Generator and using this prevents from getting different samples for every run.
  106. Dataframe General Functions df.drop() Drops the Specified Row Labels or Column Labels from the Dataframe. inplace=True modifies the original dataframe by dropping the rows and columns.
  107. df.isna() Returns a Boolean Object of same size indicating whether the element is a Null Value (NaN) or Not. Detects missing values in the DataFrame. Using df.isna().sum() gives us the Number of Null Values in Each Column of the DataFrame. Dataframe General Functions
  108. (image slide)
  109. Dataframe General Functions df.dropna() Drops the Rows (or Columns) where there is a Null Value in the Dataframe. axis=’rows’ drops the rows having at least 1 NaN. inplace=True modifies the Original Dataframe.
  110. df.reset_index() Resets the Index of the Dataframe to the Default Index(0 to Rows-1). drop=True avoids adding the Old Index as a Column to the Dataframe. Dataframe General Functions
  111. Dataframe General Functions df[column].mean() Returns the Mean of a Numerical Column of the Dataframe. df[column].median() Returns the Median of a Numerical Column of the Dataframe. df[column].mode() Returns the Mode of a Column of the Dataframe.
  112. Dataframe General Functions df.fillna() Fills the NaN Values in the Dataframe using the given value. Generally NaN Values are filled using Mean, Median, Mode depending on the Column. inplace=True modifies the Original Dataframe.
  113. df.group_by() Groups the Dataframe by a column or series of columns and returns it. This is used to group large amounts of data and perform operations like mean, sum, max on them. Dataframe General Functions
  114. df.value_counts() Returns the Counts of Unique Rows in a Data Frame. For a Column, it gives the counts of unique elements. Dataframe General Functions
  115. df[col].unique() Returns all the Unique Elements of a Column as an array. df.nunique() Returns counts of unique elements in each column of Dataframe. Dataframe General Functions
  116. df.nlargest(n,columns) Returns the First n Rows ordered by columns values in descending order. Dataframe General Functions df.nsmallest(n,columns) Returns the First n Rows ordered by columns values in descending order.
  117. (image slide)
  118. Intro to
  119. Matplotlib? What is it? Matplotlib is one of the most popular data visualization libraries in Python and is widely used in scientific computing, data analysis, and machine learning. Matplotlib is a Python library used for creating static, interactive, and animated visualizations in Python. It provides a wide variety of customizable 2D and 3D plots, including line plots, scatter plots, bar plots, histograms, and more. Matplotlib is compatible with many libraries like numpy,pandas,seaborn,scipy
  120. (image slide)
  121. Functional plots - Plot is created by calling a function and the resulting plot is displayed
  122. (image slide)
  123. Multiple plots
  124. (image slide)
  125. Figure objects
  126. (image slide)
  127. Sub plots
  128. (image slide)
  129. Appearance options
  130. TeX Markup
  131. Histogram
  132. (image slide)
  133. Bar Charts
  134. (image slide)
  135. Scatterplots
  136. 3D - Surface
  137. (image slide)
  138. Heat-map
  139. (image slide)
  140. A Deep Dive into
  141. SEABORN ● Seaborn is a data visualization library built on top of Matplotlib. ● often used as it makes attractive visualizations and works easily with Pandas. Why Seaborn when Matplotlib ? Seaborn helps you explore and understand your data and internally performs the necessary statistical aggregation to produce informative plots. While in Matplotlib you often had to write multiple lines of code to create a plot, Seaborn makes assumptions on what you want which often translates into getting the same plot with 1 line of code. NOTE : Seaborn was built on top of Matplotlib, meaning it can be further powered up with Matplotlib functionalities.
  142. Matplotlib, Seaborn or both ??
  143. Matplotlib V/S Seaborn Harder Syntax : can be personalized but it’s difficult to figure out what settings are required to make plots more attractive. Simplicity and Aesthetics : It comes with numerous customized themes and high-level interfaces, intuitive syntax Matplotlib does not provide options for advanced parameters such as hue and palettes. Hue is used to specify the third dimension in the chart, and palettes are used to define beautiful colors to the charts. USE Matplotlib for the most basic exploratory analysis that only you will probably see USE this when you want your exploratory analysis to look pretty for other people, offers a great balance between effort and beauty
  144. (image slide)
  145. A simple scatter plot in Matplotlib ● Code for simple scatter plot in matplotlib. The Output :- As you can see, this scatter plot is pretty basic. So let’s improve it by adding labeling and a title, and changing the plot’s color.
  146. Seaborn, better than Matplotlib ? We can achieve the same plot in Seaborn with just one line of code
  147. Matplotlib Seaborn Observe that we used (hue = species) in seaborn, hence using the column ‘species’ for color encoding
  148. Distribution plot - displot ● Provides a way to look at a univariate distribution. ● A univariate distribution provides a distribution for one variable ● Kernel Density Estimation with a Histogram is provided ● kde=False removes the KDE (more on this later) ● Bins define how many buckets to divide the data up into between intervals
  149. Syntax and plot tips = sns.load_dataset('tips') # Seaborn comes with built in data sets! sns.displot(tips['total_bill'], stat = 'density', kde = True) It can be seen that the total bill is approximately normally distributed, symmetric about the mean showing that total bills near the mean (~20) are more frequent than extreme high or low bills.
  150. Exercise Time?
  151. Let’s see how to do this!
  152. KDE Plot ● A kernel density estimate (KDE) plot is a method for visualizing the distribution of observations in a dataset, analogous to a histogram ● KDE represents the data using a continuous probability density curve ● A histogram aims to approximate the underlying probability density function that generated the data by binning and counting observations ● While a KDE plot smooths the observations, producing a continuous density estimate.
  153. Syntax and an example plot
  154. Joint plot ● Draw a plot of two variables with bivariate and univariate graphs. ● A way of understanding the relationship between two variables and the distribution of individuals of each variable ● Jointplot compares 2 distributions and plots a scatter plot by default ● With kind you can create a regression line with kind='reg'
  155. Syntax and example plot sns.jointplot(x='speeding', y='alcohol', data=crash_df, kind='reg') Observe the linear relationship :- As people tend to speed they also tend to drink & drive or vice-versa
  156. Pairplots ● Plot pairwise relationships in a dataset across an entire dataframe (for the numerical columns) and supports a color hue argument (for categorical columns). ● By default, this function will create a grid of Axes such that each numeric variable in data will by shared across the y-axes across a single row and the x-axes across a single column. ● The diagonal plots are treated differently: a univariate distribution plot is drawn to show the marginal distribution of the data in each column. ● With hue you can pass in a categorical column and the charts will be colorized
  157. Syntax: sns.pairplot(tips_df, hue='sex', diag_kind='kde') Plot :
  158. Categorical Data Plots ● Count plot - allow you to get aggregate data off a categorical feature in your data, the estimator is counting the number of occurrences ● Bar plot - A general plot that allows you to aggregate the categorical data based off some function, by default the mean (of a quantitative variable.) More for you to explore - Boxplot etc.
  159. Count plots sns.countplot(x='sex', data=tips_df) In the dataset ‘tips’, we see that number of males who gave tips are more than females
  160. Bar Plots Look similar to count plots, but instead of the count of observations in each category, they show the mean of a quantitative variable among observations in each category. # x - categorical, y = numerical sns.barplot(x='sex',y='total_bill',data=tips) Recall, mean is the default estimator Estimate total bill amount based on sex
  161. Ready for another exercise ?
  162. The Nation wants to know!!
  163. Matrix Plots Heatmaps ● Plot rectangular data as a color-encoded matrix. ● In order for a heatmap to work properly, your data should already be in a matrix form, the sns.heatmap function basically just colors it in for you ● Example :
  164. Example Heatmap, cool isn’t it ? ● (annot = True) ensures that the value of correlation is reflected in the box
  165. Time to get your hands dirty one last time …
  166. The Reveal ..
  167. Regression Plots ● The two functions that can be used to visualize a linear fit are regplot() and lmplot(). ● In the simplest invocation, both functions draw a scatterplot of 2 variables, x and y ● Then, it fits the regression model y ~ x and plot the resulting regression line and a 95% confidence interval for that regression. ● lmplot() has data as a required parameter and the x and y variables must be specified as strings. lmplot() has hue as a parameter.
  168. An example regression plot We can plot a regression plot studying whether total bill effects the tip. “Hue” is used to show separation based off of categorical data (here, ‘sex’) We see that males tend to tip slightly more Code : - -
  169. Scientific Python
  170. Background ●Scipy is basically the same as numpy except that it has a variety of scientific functions, probability distributions and optimization methods. ●We will majorly cover these topics.
  171. Gaussian distribution - Meet our old friend! In statistics, a normal distribution or Gaussian distribution is a type of continuous probability distribution for a real-valued random variable. The probability density function for the gaussian distribution is given by Here, 𝜇 is the mean of the distribution and is the standard 𝛔 deviation of the distribution.
  172. Skewness Its a measure of skewness of a distribution Formula for calculating skewness is given by This will give you a number. The value of skewness for gaussian distribution is 0, but if we sample data points from the distribution then it may not be 0.
  173. Kurtosis Kurtosis is a measure of whether the distribution is too peaked. A positive value for the kurtosis indicates a distribution more peaked than normal. In contrast, a negative kurtosis indicates a shape flatter than normal.
  174. Sampling A certain number of samples are drawn from the distribution. Statistics like mean, variance, skewness and kurtosis can be calculated for these samples. Note - these numbers won’t be the same for samples and population!
  175. Finding roots of functions Let’s find the roots of the function f(x) = x² - 5x + 6
  176. Optimizing functions We’ll find the minima of this function f(x) = x² + 2cos(x) + 4x
  177. Optimizing functions f(x,y) = x² + y² + 6
  178. A Brief Introduction to
  179. Types of problems in ML
  180. Some Jargon!
  181. Flow of training a model in scikit-learn ● Importing the datasets ● Splitting the datasets in train and test datasets ● Importing the machine learning model using scikit-learn ● Fitting the training dataset into the model (training phase) ● Predicting using the test dataset (testing phase) ● Validating the accuracy of the model using scikit-metrics.
  182. Importing the Datasets ● We use the iris dataset for our classification. It has four features -> sepal length in cm, sepal width in cm, petal length in cm and petal width in cm. ● It outputs has 3 classes -> Iris Setosa, Iris Versicolour and Iris Virginica
  183. Train-Test Split Split arrays or matrices into random train and test subsets.
  184. Logistic Regression
  185. Logistic Regression
  186. Training Data Score and Prediction
  187. Accuracy of the Model
  188. Confusion Matrix for evaluating the performance of Binary classification ● A confusion matrix is a table that tells us how many actual values and predicted values exist for different classes predicted by the model.
  189. What’s a Confusion Matrix?? True Positive: When a female is pregnant, and we predicted that she is pregnant True Negative: When a male is not pregnant, and we predicted that he is not pregnant False Negative: When a female is pregnant, but we predict that she is not pregnant. Also called Type 2 error. False Positive: A male cannot be pregnant, but we predict he is pregnant. Also called Type 1 error
  190. Confusion Matrix
  191. K-Nearest Neighbours
  192. Working of kNN model
  193. Coding kNN
  194. Confusion Matrix
  195. Decision Tree
  196. Working of Decision Tree
  197. Coding Decision Tree
  198. (image slide)
  199. Accuracy and Confusion Matrix
  200. Random Forest
  201. Coding Random Forest
  202. Coding Random Forest
  203. AdaBoost
  204. Coding AdaBoost
  205. Coding AdaBoost
  206. The Final Exercise!
  207. Now, what’s your problem @ Epoch? ● First, we will create a dataset by defining our own condition. ● Then, we will run a Logistic Regression algorithm to try and find the condition. ● Finally, we will compare the condition that we set with the condition that the computer returned.
  208. Index <choice> must be replaced with any integer of your own choice. <fill> represents a variable, and you have to replace it with the correct variable that would complete the code.
  209. Unravelling the Mystery! We are creating a dataset with a linear classifier, which is the linear equation that we defined as part of generating the dataset. Logistic regression is a linear classifier, and it is capable of approximating this equation, given enough data as input.
  210. The Solution - Demystified! We can compare the coefficients of our predefined equation and the coefficients generated by the algorithm, and we will find that they are approximately in the same ratio. This shows that the model was able to learn the classification.
  211. Coding the Exercise
  212. (image slide)
  213. Resources! 1. Python Documentation 2. NumPy Documentation 3. Pandas Documentation 4. Matplotlib Documentation 5. Seaborn Documentation 6. SciPy Documentation 7. Scikit-learn Documentation
  214. Social Media - Epoch Follow our social media handles for regular updates Instagra m Twitter YouTube WhatsAp p
  215. Social Media - GDSC Follow our social media handles for regular updates Instagra m Twitter
  216. Any Questions or Suggestions?
  217. Thank You!