<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Smruti Ranjan Pradhan on Medium]]></title>
        <description><![CDATA[Stories by Smruti Ranjan Pradhan on Medium]]></description>
        <link>https://medium.com/@smruti-ranjan?source=rss-12b8175d050b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gWlGR1120QzVwRpTHCtL5g.jpeg</url>
            <title>Stories by Smruti Ranjan Pradhan on Medium</title>
            <link>https://medium.com/@smruti-ranjan?source=rss-12b8175d050b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 07:24:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@smruti-ranjan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Machine Learning in Ed-Tech]]></title>
            <link>https://medium.com/almabetter/machine-learning-in-ed-tech-68d6d13e2f22?source=rss-12b8175d050b------2</link>
            <guid isPermaLink="false">https://medium.com/p/68d6d13e2f22</guid>
            <category><![CDATA[edtech]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[e-learning-solutions]]></category>
            <dc:creator><![CDATA[Smruti Ranjan Pradhan]]></dc:creator>
            <pubDate>Sun, 13 Jun 2021 06:13:25 GMT</pubDate>
            <atom:updated>2021-06-13T16:54:39.898Z</atom:updated>
            <content:encoded><![CDATA[<p>Contributors : F M Nurul, Rohan Roney, Smruti Ranjan, Roopesh Valluru</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/0*ydj-GxepU8baci_v.jpg" /></figure><h3><strong>What is E-learning ?</strong></h3><p>The Internet has become one of the vital ways to make available resources for research and learning for both teachers and students to share and acquire information. Technology-based e-learning encompasses the use of the internet and other important technologies to produce materials for learning, teach learners, and also regulate courses in an organization. Typically, e-learning is conducted on the Internet, where students can access their learning materials online at any place and time.</p><h3><strong>Why is E-learning important?</strong></h3><ol><li>It is flexible when issues of time and place are taken into consideration. Every student has the luxury of choosing the place and time that suits him/her. The adoption of e-learning provides the institutions as well as their students or learners the much flexibility of time and place of delivery or receipt of according to learning information.</li><li>E-learning enhances the efficacy of knowledge and qualifications via ease of access to a huge amount of information.</li><li>It is able to provide opportunities for relations between learners by the use of discussion forums. Through this, e-learning helps eliminate barriers that have the potential of hindering participation including the fear of talking to other learners. E-learning motivates students to interact with other, as well as exchange and respect different point of views. E-learning eases communication and also improves the relationships that sustain learning. E-Learning makes available extra prospects for interactivity between students and teachers during content delivery.</li><li>E-learning is cost effective in the sense that there is no need for the students or learners to travel. It is also cost effective in the sense that it offers opportunities for learning for maximum number of learners with no need for many buildings.</li><li>E-learning always takes into consideration the individual learners differences. Some learners, for instance prefer to concentrate on certain parts of the course, while others are prepared to review the entire course.</li><li>E-learning helps compensate for scarcities of academic staff, including instructors or teachers as well as facilitators, lab technicians etc.</li><li>The use of e-Learning allows self-pacing. For instance the asynchronous way permits each student to study at his or her own pace and speed whether slow or quick. It therefore increases satisfaction and decreases stress</li></ol><h3><strong>Shortcomings of E-learning?</strong></h3><p>Let us look a some of the shortcomings of E-learning :</p><ol><li>E-learning as a method of education makes the learners undergo contemplation, remoteness, as well as lack of interaction or relation. It therefore requires a very strong motivation and time management skills in order to reduce such effects.</li><li>With respect to clarifications, explanations, and interpretations, the e-learning method may be less effective that traditional methods of learning. The learning process is much easier face-to-face with instructors or teachers.</li><li>When it comes to improvement of learner’s communication skills, e-learning may have a negative effect. Though learners might have an excellent academic knowledge, they may not possess the needed skills to deliver their acquired knowledge to others.</li><li>Since tests and assessments in e-learning are frequently supervised by proxy, it may be difficult, if not impossible, to control or regulate activities such as cheating.</li><li>E-learning may also be subject to piracy, plagiarism, cheating, inadequate selection skills, and inappropriate use of of copy and paste.</li></ol><p>Despite the shortcomings, it is essential to use the data analytics and machine learning tools to improve the state of e-learning by personalizing content and resources to students’ needs and progress. ML has to intervene so as to make content of the e-learning platforms more fun and interactive, using the insights obtained by analyzing past user-content engagement data. With the onset of pandemic worldwide and increasing commuting restrictions, there has been an increasing demand to improve the standard of imparting online education on a mass scale. Ed-tech companies now need to put extra efforts in building their trust among students, as more and more students are going online for their studies.</p><h3><strong>Impact of ML in E-learning</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*Dcn4Xi2KMdHxf7ln.png" /></figure><p>Machine learning for education. So, what does it bring? It is already changing the global landscape of online education. As per the research report released by Technavio, the global market of online courses based on machine learning technologies will grow with the CAGR higher than 16% by 2022! This rapid growth is bound to happen due to affordable large volume data storage and its efficient processing. From the perspective of making the e-learning process more engaging and result-driven, machine learning and artificial intelligence are already turning it into a more convenient way of getting the knowledge as compared to usual courses or corporate training. What are the features that they can offer to both sides of the process — students and universities?</p><h4><strong>Learning process customization and personalization</strong></h4><p>Machine learning and education processes are closely interconnected. ML algorithms analyze how the students perceive and explore the information they are given. It helps the system to either draw the user back and go through some learning points again or let them step further. ML also helps the teachers to monitor and trace the learning process individually. As compared to traditional methods in classrooms, where the goal is to deliver the course, but not ensure that everyone got it, ML gives an advantage of more profound information perception. This type of learning is offered by <a href="https://www.magicedtech.com/">Edtech</a> and <a href="https://www.getmagicbox.com/">MagicBox</a> learning systems.</p><h4><strong>All-round content analysis</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eCMGv0QFjzDAS4Ov.jpg" /></figure><p>Using machine learning in education helps to move the industry of online learning to the new level by making the content more up-to-date and relevant to an exact request. How? ML technologies analyze the content of online courses and help to figure out whether the quality of the offered information meets the applicable standards on one hand, and on the other, it shows how the users perceive the data and do they understand what is taught. Hence users receive the information under their personal needs and abilities, and the overall learning process improves greatly.</p><p>Have a quick look at Udemy, one of the world’s largest educational marketplaces, which connects students and instructors and offers over 150K different courses. It boasts a great feature of personalized recommendations. By answering several simple questions, its users get an optimized set of different courses and relevant content upon their request. The feature is a good contribution to platform usability.</p><h4><strong>Better Grading</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*5OqICCv_7vpOVjjM.jpg" /></figure><p>There is another application of machine learning in education that deals with scores and grading. As each online course reflects the learning abilities of a large number of students, they have a lot of experience in grading them. ML technologies turn the grading process into a couple of seconds issue. We’re speaking more of the exact sciences in this perspective. There are spheres, where machines cannot replace teachers, but even in those cases, they can help to improve the existing grading and evaluating approaches.</p><p>In addition to that, applying machine learning in education today is the easiest way to detect cases of plagiarism. The application of ML technologies in this sphere turned out to be highly revenue-generating. Would you believe that a company that uses ML technology to reveal plagiarism costs $1.735 billion? A year ago a project called Turnitin was purchased by a privately held media company exactly at this price.</p><h4><strong>Personal e-learning courses</strong></h4><p>Here both machine learning and artificial intelligence help to give each student a personal course. It is compiled based on the exact user’s request — rather a time-saving solution! The program gives precise answers to the users whenever they need support.</p><p>As still machines cannot replace humans, this kind of studying is applicable only for those disciplines, where there are exact answers and it will not help to explain some philosophical questions, for example. But the amount of data it can offer to precise requests is astronomical! Have a glance at the <a href="https://www.wizcabin.com/example-courses/">Wizcabin</a> project, in which the e-learning automation tool converts its users’ storyboards automatically into interactive courses.</p><h4><strong>Time-consuming tasks automatization</strong></h4><p>Administrative work is extremely important and extremely boring. Let the machines do this kind of task! ML helps to automate scheduling and content delivery processes and free your time and resources for other, more engaging parts of e-learning process development.</p><h3>What are the Challenges Faced by Artificial Intelligence and Machine Learning in Education?</h3><p>The use of machine learning for education enhancement and optimization leads to outstanding results! But there are not only benefits but also serious risks of machine learning and artificial intelligence application in e-learning. If these technologies could solve all the problems and replace the traditional system of education, it would already have happened. What are the problems of ML and AI in the education sector today?</p><h4><strong>1. Prediction accuracy</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RTHzwjfdcufitCi6" /></figure><p>Machine learning for education algorithms analyze the interests of online students, make predictions about their further needs, and give recommendations on courses. The statistical tools here cannot always reflect real needs. Let’s imagine, we see a student, who sits in a noisy place like a cafe or some workspace, and he chooses a text format of information delivery, as right at the moment it suits him better. We cannot say that he would make the same choice at home.</p><p>Thus, the student’s preferences are not that vivid for machine learning and prediction scenario is not 100% accurate. The reason for that is that ML doesn’t have enough data for use. To make predictions, people use information that they see every day, remember from the past, dealing with it during some period. To make this information digitally accessible, we need to collect and describe almost every moment of a student’s life, which seems to be impossible in today’s world.</p><p>Furthermore, it is not that easy to recommend a course and be sure that you offer the content that is really needed. Quite often learning management systems rely on the student’s job title and role, the department he\she works in and some skills they list. Their existing experience and the true level of knowledge are not always reflected correctly by a machine and here such things as instructor observations and feedback from peers and managers cannot be done by a machine with the same accuracy a human can render.</p><h4><strong>2. Human factor and old-fashioned approach to e-learning</strong></h4><p>The methodologies used by teachers and professors are highly adaptive when used in a classroom. When it comes to the remote educational process, we face an issue of behavior patterns and individual approach. The real-life process allows us to see how two different people perceive the same data and amend the approach if needed.</p><p>IT systems can measure the progress of each student and correct the learning plan, but they cannot invent the methodology on their own, and in some cases the approach that ML and AI are taught is not the best and rather old-fashioned.</p><p>In future this issue can become a great driver of methodologies further development as many non-vivid problems of the present system will become obvious and IT systems will offer even greater education methodologies. Until it didn’t happen, the human factor here is an issue.</p><h4><strong>3. Adaptive learning development costs</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*EV-KFQrH__rAg56i.jpg" /></figure><p>This is the model when machine learning is used to run the interaction between student and e-learning platform, analyze the unique needs of each user and offer customized resources and learning activities. No doubt this is a great technology and in the nearest years it will be more widely introduced by the key e-learning web platforms.</p><p>But as for today, the development of this approach is quite costly and time-consuming. The most expensive part here is the granularity of content. This system requires constant updating and monitoring, as the developers need to understand how deep the information adaptation of each learner should be — curriculum, course, or model level? Rules and predictions also need continuous attention of developers, and these things altogether form quite a big budget.</p><h4><strong>4. Data cleansing</strong></h4><p>Speaking about technological challenges, it’s worth mentioning the problem of data cleansing. The process of figuring out which data is incorrect or unnecessary and its removal is crucial for making the educational content relevant and up-to-date.</p><p>But which data and in which volume is needed to improve the learning process? What are the criteria for its relevance? The methodologies are still not perfect and today they cannot replace humans in these processes.</p><h3>Examples of ML Applications in Education</h3><p>Moving forward from descriptions to examples, let’s check it out, how are machine learning and education interconnected? Who is creating these applications and how do they work?</p><ul><li>Content Technologies, Inc. — one of the world’s leading AI and ML technologies developers that render solutions for business processes automation and intelligent instruction design, is offering two platforms that are interesting to look at. The first one is called <a href="http://cram101.com/facts101/wwwroot/hm.asp">Cram101</a>. The web platform uses ML to segment the content of textbooks and outline the most useful parts of it, create study guides, make chapter summaries, and multiple choice practice tests.</li><li>Quite a similar service is offered by JustTheFacts101 service. It also highlights the most significant parts of the text and makes the summaries of chapters. Then it archives the data and makes it available on Amazon.</li><li>The e-learning platform called <a href="https://www.netexlearning.com/">Netex Learning</a> makes it possible for the educators to create digital curriculum, and offer different content across platforms and integrate different forms of information delivery — video\audio\texts. The company has also invested in the development of personalized learning cloud platform, that is applicable in the workplaces, where employers can design customizable learning systems with apps; gamification and simulations; virtual courses; self-assessments and others.</li><li>A company called <a href="https://otter.ai/">OTTER</a> is offering a great service based on AI. They’ve developed an application that allows users to set the keywords in advance of recording a class or a course. It’s great to support for getting exactly what you need in a nice summary.</li></ul><h3>Companies That Use Machine Learning for Education Projects</h3><p>Machine learning is widely used in many spheres. Let’s have a quick look at a couple of examples of how it is applied in education projects by businesses.</p><ul><li>A Swedish EdTech company called <a href="https://hubert.ai/">Hubert.ai</a> has developed an assessment system that they call a cognitive assistant. Its goal is to turn the surveys into speaking tests by asking students follow-up questions. It uses machine learning algorithms to make a deep text analysis that automatically categorizes feedback. It helps to make an assessment in education much more engaging and effective.</li><li>Getting ready for school examinations becomes much easier with ML and AI technologies. A project called <a href="https://www.mobymax.com/">MobyMax</a> uses these technologies to compile a highly adaptive curriculum for K-8 subjects.</li><li>It provides personalized lessons for each student based on their individual needs and helps to fix learning gaps. The users have their personal lesson plans and practice sheets. The application also features different contests, certificates, games, and daily smiles to motivate students not to stop their studies.</li><li>A popular education tools platform called Quizlet Learn has developed a service for students based on machine learning algorithms, that help not only to study but also to prepare for different tests. It does this by creating tailored study plans based on current knowledge levels and upcoming test dates. The core of this algorithm is books and paper summarization and the creation of smaller study guides for textbooks and revision materials.</li></ul><h3>Conclusion</h3><p>The most competitive feature of any educational project today is the ability to offer customized content in an engaging format with personal guidance and support. Some 10 or 15 years ago, which is nothing for the conservative sphere of education, the online world wouldn’t be capable of offering this kind of education.</p><p>Massive implementation of machine learning in education has changed this situation and it has completely replaced humans in many spheres of the learning process. It’s not only better data processing that they can do but a real enhancement of the e-learning industry. The content becomes more relevant, place, and time do not matter anymore, students have virtual assistants that guide them all way long.</p><p>The capabilities of these technologies and their potential make them the most significant tools of transforming the whole e-learning industry and bringing the tomorrow of e-learning closer!</p><p>Our digital product development team knows how to make these technologies work for you and turn your e-learning project into the most annoying competitor to the websites that you benchmark today!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68d6d13e2f22" width="1" height="1" alt=""><hr><p><a href="https://medium.com/almabetter/machine-learning-in-ed-tech-68d6d13e2f22">Machine Learning in Ed-Tech</a> was originally published in <a href="https://medium.com/almabetter">AlmaBetter</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Preprocessing Concepts]]></title>
            <link>https://medium.com/almabetter/data-preprocessing-concepts-a51dca507c8f?source=rss-12b8175d050b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a51dca507c8f</guid>
            <category><![CDATA[data-preprocessing]]></category>
            <dc:creator><![CDATA[Smruti Ranjan Pradhan]]></dc:creator>
            <pubDate>Sun, 06 Jun 2021 15:20:05 GMT</pubDate>
            <atom:updated>2021-06-06T17:04:45.758Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3khD68XqeLpvt6s8.png" /></figure><p>The goal of this article is to make you understand the basic step performed before any machine learning process. The process of refining data and make it ready enough to make our machine algorithms understand and analyze the data in the required format.</p><p><strong>What is Data Preprocessing ?</strong></p><p>A generic idea of a typical dataset might feel like some of kind of table with huge number of rows and columns. However. This isn’t the case in most of the real life data. Data comes in numerous formats, such as structured tables, texts, images, audio files and videos.</p><p>However machines are not equipped to understand these complex data forms except for 1s and 0s. So feeding in images and asking our machines do the rest of the task for us might not be a good idea. Therefore we need to pre-process these complex data forms and transforms them into a language that computers and machines can understand. In any Machine Learning process, Data Preprocessing is that step in which the data gets transformed, or Encoded, to bring it to such a state that now the machine can easily parse it. In other words, the features of the data can now be easily interpreted by the algorithm.</p><p><strong>What are features ?</strong></p><p>A given dataset is nothing but a collection of data objects, which are often known as a samples or observations. Data objects are described by a number of features, that capture the most basic characteristics of an object, such as the count of a given physical entity or date and time of an event, etc.. Features are often called as variables or attributes. For example, power, mileage and color could be considered as features of a beautiful car. However these could belong to different data types, and we might have to deal with them differently.</p><p>Features can be of different types such as :</p><ul><li><strong>Categorical :</strong> Categorical variables are those features that have discrete countable set of values. For example, the day of a week can be a categorical variable with values ranging from Sunday to Saturday. Another example is could be the possibility of an event occuring (binary) : True or False</li><li><strong>Numerical : </strong>These are those features which are continuous in nature. They consist of numbers. For example, number hours you sleep in a da, or the speed at which you drive your bicycle.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/0*acazj0XuR9jKisie.png" /></figure><p>Now that we have learnt about the basics about different data forms, lets focus on different steps of data preprocessing.</p><blockquote><strong>Dealing with missing values</strong></blockquote><p>Because data is often taken from multiple sources which are normally not too reliable and that too in different formats, more than half our time is consumed in dealing with data quality issues when working on a machine learning problem. It is simply unrealistic to expect that the data will be perfect. There may be problems due to human error, limitations of measuring devices, or flaws in the data collection process. Let’s go over a few of them and methods to deal with them :</p><p>It is very much usual to have missing values in your dataset. It may have happened during data collection, or maybe due to some data validation rule, but regardless missing values must be taken into consideration.</p><ul><li>Eliminate rows with missing data :<br>Simple and sometimes effective strategy. Fails if many objects have missing values. If a feature has mostly missing values, then that feature itself can also be eliminated.</li><li>Estimate missing values :<br>If only a reasonable percentage of values are missing, then we can also run simple interpolation to fill in those values. However, most common method of dealing with missing values is by filling them in with the mean, median or mode value of the respective feature.</li></ul><blockquote><strong><em>Feature Encoding</em></strong></blockquote><p>As mentioned before, the whole purpose of data preprocessing is to <em>encode</em> the data in order to bring it to such a state that the machine now understands it.</p><p>Feature encoding is basically performing transformations on the data such that it can be easily accepted as input for machine learning algorithms while still retaining its original meaning.</p><p>There are some general norms or rules which are followed when performing feature encoding. For Continuous variables :</p><ul><li><strong>Nominal</strong> : Any one-to-one mapping can be done which retains the meaning. For instance, a permutation of values like in One-hot encoding.</li><li><strong>Ordinal </strong>: An order-preserving change of values. The notion of small, medium and large can be represented equally well with the help of a new function, that is, &lt;new_value = f(old_value)&gt; — For example, {0, 1, 2} or maybe {1, 2, 3}.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/0*IR8xHKpCa5_s05_O.png" /><figcaption>One-hot encoding of data</figcaption></figure><p>For Numeric variables:</p><ul><li>Simple mathematical transformation like using the equation &lt;new_value = a*old_value + b&gt;, a and b being constants. For example, Fahrenheit and Celsius scales, which differ in their Zero values size of a unit, can be encoded in this manner.</li></ul><blockquote><strong>Dealing with Text data</strong></blockquote><ul><li><strong>Tokenization</strong> : We need to convert our text document comprising of sentences and paragraphs into a collection of words/ phrases/ tokens before performing any kind of further text processing. Tokenization can be performed in different ways based on the maximum and minimum number of words you want in your tokens. Tokenization in which a token consists of only one word is known as 1-gram tokenizer. Similarly, the tokenizer which splits our texts such that each token consists of maximum of n number words, is known as n-gram tokenizer.</li><li><strong>Removing punctuation</strong> : Every literature has some punctuation for the readers to understand and comprehend. However including punctuation in our machine learning model might be a very bad idea since punctuation hold no physical significance when it comes to figuring out topics and understanding sentiments of texts. Also often including punctuation in text might trick the model to interpret ‘fun.’ with a full-stop and ‘fun’ without a full-stop as two different features leading to multi-collinearity and unnecessary expansion of feature set. Hence it is always a good idea to remove the punctuation.</li><li><strong>Removing stop words</strong> : Stop words are nothing but the most frequently occurring redundant words in any literature. ‘the’, ‘is’, ‘have’, ‘shouldn’t’ etc are some of the examples of stop words in English literature. Since these words hold no physical significance so far, it is often imperative to do a stop word removal procedure, especially when the feature set is already too high dimensional.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/0*QTALDhj6z7gxDtpz.jpg" /></figure><ul><li><strong>Removing high and low frequency words :</strong> Even after removal of stop words, the feature set might still be huge due to the vastness of vocabulary in the literature. It might be then a good idea to remove the words with high frequency from the documents, since such words might not contribute much to the classification or clustering task at hand due to the same reasons that hold true for stop words. Similarly too low frequency words used across different documents might also not convey much about the nature of documents or sentiment of texts.</li><li><strong>Stemming and Lemmatisation</strong> : In most literature, we see words coming from same root, but have different forms based on the tense, sentence structure and parts of speech. For example, transforming and transformation come from same root word ‘transform’. However they two have two different forms based on their use cases. In these cases, it is essential we stem the word to its origin such that the two words are not considered as different feature by the models. There is a fine line between stemming and lemmatisation. While stemming doesn’t ensure a meaningful word as an output due to lack of knowledge about context during stemming, lemmatisation does. In machine learning stemming is done by following certain set of rules predefined by algorithms such as Porter stemmer, Lancaster stemmer and Snowball stemmer. For example, the word ‘family’ gets transformed to ‘famili’ after using Porter stemmer, which doesn’t have a meaning as such. Unlike stemming, lemmatisation attempts to select the correct lemma depending on the context.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WrFtdEl77ZOn4lE8.png" /></figure><ul><li>Text vecorization : Finally we need to make our textual data ready for training by converting them into vectors with the help of algorithms such as word2vec, count and tf-idf vectorizer. The basic idea behind such algorithms is to find out list of all unique words in all the documents combined. And then, for each document, create a vector with each component representing the some function of the frequency of that particular word/ feature in that particular document.</li></ul><p>And this is how we preprocess various data forms before feeding into our final machine learning model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a51dca507c8f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/almabetter/data-preprocessing-concepts-a51dca507c8f">Data Preprocessing Concepts</a> was originally published in <a href="https://medium.com/almabetter">AlmaBetter</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Natural Language Processing]]></title>
            <link>https://medium.com/almabetter/natural-language-processing-811ecc486b29?source=rss-12b8175d050b------2</link>
            <guid isPermaLink="false">https://medium.com/p/811ecc486b29</guid>
            <category><![CDATA[stemming]]></category>
            <category><![CDATA[tfidf-vectorizer]]></category>
            <category><![CDATA[count-vectorizer]]></category>
            <category><![CDATA[lemmatization]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Smruti Ranjan Pradhan]]></dc:creator>
            <pubDate>Thu, 29 Apr 2021 16:12:26 GMT</pubDate>
            <atom:updated>2021-04-29T18:27:53.752Z</atom:updated>
            <content:encoded><![CDATA[<h4>Teaching machines to understand words and sentiments</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rEyd2IlaXp9uV7GV.jpeg" /></figure><h3><strong>What is Natural Language Processing ?</strong></h3><p>Natural language processing, in short NLP, is a comprehensive field of study in machine learning that deals with teaching the machine to learn patterns from written texts and documents. There are numerous ways that we will discussing in this article through which the computer learns to make assumptions about certain object/ document just by interpreting the associated textual data. Through the help NLP, currently we are able to detect sentiments, find keywords and topic associated with articles, build recommender systems based on textual reviews and so on.</p><h3><strong>How are machines so smart ?</strong></h3><p>It isn’t as complicated as it may have sounded in first go. In basic natural language processing systems, algorithms interpret the frequency of words in a particular document as a feature. So if a document has, lets say, 10000 unique words with certain term frequency, then we’ve got 10000 unique features. The machine learning model then tries to build on the relevance of each of each feature based on the term frequency. However the frequency of certain words might be a misleading feature to judge a particular document, because some words such as ‘the’, ‘have’, ‘they’ etc occur multiple times in English literature irrespective of type of document class. Hence we need to run a couple of preprocessing steps before fitting any model to our textual data set.</p><h3><strong>Preprocessing Texts</strong></h3><ul><li><strong>Tokenization</strong> : We need to convert our text document comprising of sentences and paragraphs into a collection of words/ phrases/ tokens before performing any kind of further text processing. Tokenization can be performed in different ways based on the maximum and minimum number of words you want in your tokens. Tokenization in which a token consists of only one word is known as 1-gram tokenizer. Similarly, the tokenizer which splits our texts such that each token consists of maximum of n number words, is known as n-gram tokenizer.</li><li><strong>Removing punctuation</strong> : Every literature has some punctuation for the readers to understand and comprehend. However including punctuation in our machine learning model might be a very bad idea since punctuation hold no physical significance when it comes to figuring out topics and understanding sentiments of texts. Also often including punctuation in text might trick the model to interpret ‘fun.’ with a full-stop and ‘fun’ without a full-stop as two different features leading to multi-collinearity and unnecessary expansion of feature set. Hence it is always a good idea to remove the punctuation.</li><li><strong>Removing stop words</strong> : Stop words are nothing but the most frequently occurring redundant words in any literature. ‘the’, ‘is’, ‘have’, ‘shouldn’t’ etc are some of the examples of stop words in English literature. Since these words hold no physical significance so far, it is often imperative to do a stop word removal procedure, especially when the feature set is already too high dimensional.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/0*dQ6Nz5o-dj7qrezS.jpg" /></figure><ul><li><strong>Removing high and low frequency words :</strong> Even after removal of stop words, the feature set might still be huge due to the vastness of vocabulary in the literature. It might be then a good idea to remove the words with high frequency from the documents, since such words might not contribute much to the classification or clustering task at hand due to the same reasons that hold true for stop words. Similarly too low frequency words used across different documents might also not convey much about the nature of documents or sentiment of texts.</li><li><strong>Stemming and Lemmatisation</strong> : In most literature, we see words coming from same root, but have different forms based on the tense, sentence structure and parts of speech. For example, transforming and transformation come from same root word ‘transform’. However they two have two different forms based on their use cases. In these cases, it is essential we stem the word to its origin such that the two words are not considered as different feature by the models. There is a fine line between stemming and lemmatisation. While stemming doesn’t ensure a meaningful word as an output due to lack of knowledge about context during stemming, lemmatisation does. In machine learning stemming is done by following certain set of rules predefined by algorithms such as Porter stemmer, Lancaster stemmer and Snowball stemmer. For example, the word ‘family’ gets transformed to ‘famili’ after using Porter stemmer, which doesn’t have a meaning as such. Unlike stemming, lemmatisation attempts to select the correct lemma depending on the context.</li></ul><figure><img alt="Introduction to Stemming vs Lemmatization (NLP) | LaptrinhX" src="https://cdn-images-1.medium.com/proxy/1*ES5bt7IoInIq2YioQp2zcQ.png" /></figure><p>Now that we are over with pre-processing the text, we are left with one last very important step before using it for any machine learning task such classification or clustering.</p><h3>Text Vectorization</h3><p>As we have already discussed that in NLP, we treat unique words in final processed text as our feature set, and their counts in the document as the values of the features. <strong>Count Vectorizer</strong> is a well known algorithm in scikit-learn that deals with converting textual data into feature vectors. What it essentially does is find out list of all unique words in all the documents combined. And then, for each document, creates a vector with each component representing the number of counts of that particular word/ feature in that particular document.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w0_OvJEiO9-IYtaY.png" /></figure><p>However, count vectorizer is not always a good choice for vectorization of the texts. There might be some words that are specific to a given document and not quite frequent in other documents. Its intuitive that the words need to gain more weightage compared to the words that are equally frequent in all the documents. It is here <strong>tf-idf vectorizer</strong> has an important role to play. ‘tf’ stands for term frequency and ‘idf’ stands for inverse document frequency. It not only takes in account the term frequency of certain word in a given document, but also the inverse of frequency of documents with that particular word. Higher the document frequency lower weightage the word has in a particular document. To normalize and limit the explosion of inverse document frequency we use a log transformation of inverse document frequency in actual formula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/0*-6a9yBC4ojo6D2Nx.png" /></figure><p>Now that we are done with vectorization of our texts and documents, its time to put our processed feature set into various machine learning tasks based on the problem statement.</p><h3>Modelling</h3><p>Let us consider a simple task of teaching our machine learning model to differentiate between positive and negative tweets. We are a given a set of labelled data containing the tweets made by well known celebrities, sports persons and politicians in India. And somebody has already done the herculean task of labeling them. Now its time to teach the machine to tell us the sentiment of any further tweet made, so as to automate the process of sentiment analysis in future. This is of course a quite common task performed in industries today.</p><p>We can process the data as mentioned above. As per the use case, we can choose to keep the main text and hashtags, while choosing to remove the @mentions. We remove any unnecessary punctuation and stop words. Since tweets are generally short and to the point we might not need to remove high and low frequency words. We can choose to lemmatize our text and then move to vectorize them as well. After we’re done with pre processing, we can choose to pass our vectorized features as independent variables and positive and negative tags as target variables through a supervised learning algorithm such as Support vector machines. The evaluation metric is based on the problem statement. If our objective is to recognize all the negative tweets correctly and reduce false negative rates, recall is the evaluation metric we are looking for.</p><p>There could be another use cases of the tweets. We might want to know what are the top keywords that the current tweets are talking about. To do that we might want to find out the words that are most frequently used in most of the tweets. There are advanced algorithms such as Latent Dirichlet Algorithm (LDA) that specifically deals with finding the topics that different tweets are talking about. We might want to consider talking about it in detail in some later article. Apart from that, clustering problems are quite common in NLP wherein we want to categorize texts based on some similarity between topics in the texts.</p><p>I hope, with the help of this article, you were able to gain some useful insight into the world of Natural language processing. Until next time, Bye !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=811ecc486b29" width="1" height="1" alt=""><hr><p><a href="https://medium.com/almabetter/natural-language-processing-811ecc486b29">Natural Language Processing</a> was originally published in <a href="https://medium.com/almabetter">AlmaBetter</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unsupervised Clustering Algorithms]]></title>
            <link>https://medium.com/almabetter/unsupervised-clustering-algorithms-1da5f99cdbe?source=rss-12b8175d050b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1da5f99cdbe</guid>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[k-means-clustering]]></category>
            <category><![CDATA[hierarchical-clustering]]></category>
            <category><![CDATA[dendrogram]]></category>
            <dc:creator><![CDATA[Smruti Ranjan Pradhan]]></dc:creator>
            <pubDate>Sun, 25 Apr 2021 06:51:59 GMT</pubDate>
            <atom:updated>2021-04-26T12:51:56.581Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/730/0*Acy-9E6RZqNf5GpR.png" /></figure><p><strong>What is Clustering ?</strong></p><p>Clustering is the process of assembling a set of observations under different groups based on some similarity criteria. Clustering is very essential in Machine learning since it helps to categorize our data set and helps us to understand our data well without the help of any sort of labeling of data. These algorithms do this by identifying underlying patterns in the feature set. However, different algorithms take different approach towards clustering the data points. The most common and widely used clustering algorithm is K-Means Clustering. But discussing about the algorithms in detail, let me introduce you to the method by which we measure the similarity between the observations</p><p><strong>Similarity criteria</strong></p><p>The similarity between the observations in the data set is generally done by distance metrics. There are three well-known and widely used distance metrics, namely, Manhattan, Euclidean and Minkowski distance.</p><p>If (x1, x2, …, xn) and (y1, y2, …, yn) are two given data points/ observations :</p><p>Manhattan Distance :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/137/0*7aLW13ytHqcsTu79.png" /></figure><p>Euclidean Distance :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/183/0*984r7WNuzz-A8xqD.png" /></figure><p>Minkowski Distance with order of norm = p :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/0*ONefZvg0fPU94vge.png" /></figure><p>The smaller is the value of a distance metric, the higher is the similarity between the two observations.</p><p><strong>K-Means Clustering</strong></p><p>The idea behind the algorithm is to group all the points to one of the K clusters with K cluster centroids. The entire clustering algorithm is based on the concept of Expectation-Maximization.</p><p>Steps involved in the algorithm :</p><ol><li>Randomly initialize k cluster centers/ centroids</li><li>E-step : Calculate the distance of all the observations from each of the cluster centroids and assign the observations to the cluster to which the particular observation has the minimum distance.</li><li>M-step : Calculate the mean/ median of all the observations in a cluster and reassign the cluster centroid to the mean/ median value</li><li>Repeat steps 2 and 3 until there is no further reassignment of observations to any alternative cluster</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hJLKa_6VRboLFviJ.png" /></figure><p>However, the most important downside of this algorithm is that the algorithm is prone to find local optimum based on the starting points of cluster centroids. An effective solution to this issue is to repeat the algorithm for multiple times and take the results of that particular run which has the minimum Sum Squared Error (SSE). Sum squared error is defined as the sum of the distances of all the observations from their respective cluster centers.</p><p>One other down-side of this algorithm is that it tends to form globular clusters and are not suitable for grouping clusters with non-globular structures. To address these issues, we have other clustering algorithms known as hierarchical clustering algorithms.</p><p><strong>Hierarchical Clustering</strong></p><p>These clustering algorithms are based on the concept of hierarchy. It tries to find a hierarchical pattern in the unlabeled data. There are two kinds of hierarchical clustering :</p><ol><li>Agglomerative Clustering : This algorithm takes a bottom up approach and takes each observation in the data set belonging to a unique cluster and then tries to club them based on some similarity criteria until the algorithm appropriate number of clusters.</li><li>Divisive Clustering : This algorithm takes a top down approach in which all the observations are considered as one cluster and then the clusters are divided based on the most dissimilar clusters/ observations.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*9vzbDH5HRtXrG2uJ.png" /></figure><p><strong>What is Proximity Matrix ?</strong></p><p>A matrix that stores the distances between each points. The distance can be based on any distance metric. If we have n observations in our data set, proximity matrix is of size n x n, with diagonal elements equal to 0.</p><p><strong>Steps involved in Agglomerative Hierarchical clustering :</strong></p><ol><li>Each observation is assigned to a unique cluster</li><li>We look for the smallest distance between two points/clusters in the proximity matrix and club the points/ clusters with the minimum distance between them and update the proximity matrix accordingly. The distance can be calculated based on any one of the different kind of linkages, namely, single, complete, average linkages.</li><li>Repeat the above step up until we get a single cluster.</li></ol><p><strong>Types of Linkages :</strong></p><ul><li><strong>Single-linkage</strong>: In this linkage method, the distance between two clusters is defined as the shortest possible distance between any two points of opposite clusters. Single linkage clustering is best to use when we try to find non-globular clustering pattern in data</li><li><strong>Complete-linkage</strong>: In this linkage method, the distance between two clusters is defined as the longest possible distance between any two points of opposite clusters. Complete linkages are robust to possible noise present in the data between two clusters.</li><li><strong>Average-linkage</strong>: In this linkage method the distance between two clusters is defined as the average of all distances calculated between each point in one cluster and every other point in the other cluster. Average linkage is to robust to possible noise in the data.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*J7NC8aFszDIITxZz.png" /></figure><p><strong>What is a Dendrogram ?</strong></p><p>A Dendrogram is a pictorial representation of the hierarchical tree formed as a result of hierarchical clustering. It aptly represents the clusters formed at different stages of the algorithm. It also gives a rough idea about the pint at which we need to terminate algorithm in order to get the right number of clusters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z68TrRcuAjBLRi9X.png" /></figure><p><strong>Advantages of Hierarchical Clustering</strong></p><ol><li>Unlike K-means clustering, hierarchical clustering does not take number of clusters as input. Te algorithm is smart enough to recognize the right number of clusters in the data.</li><li>Unlike K-means clustering, this algorithm can find non-globular clustering patterns in data in addition to globular ones.</li></ol><p>However the biggest disadvantage of this algorithm is that, the performance of this algorithm degrades with increasing number of observations in the data set, since it becomes computationally expensive to calculate the huge n x n proximity matrix.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1da5f99cdbe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/almabetter/unsupervised-clustering-algorithms-1da5f99cdbe">Unsupervised Clustering Algorithms</a> was originally published in <a href="https://medium.com/almabetter">AlmaBetter</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linear Regression — A Beginner’s Guide]]></title>
            <link>https://medium.com/almabetter/linear-regression-a-beginners-guide-1c1cf68bb1f2?source=rss-12b8175d050b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c1cf68bb1f2</guid>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[regularization]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Smruti Ranjan Pradhan]]></dc:creator>
            <pubDate>Tue, 06 Apr 2021 23:25:50 GMT</pubDate>
            <atom:updated>2021-04-22T15:21:34.678Z</atom:updated>
            <content:encoded><![CDATA[<h3>Linear Regression — A Beginner’s Guide</h3><p>Understanding and building a custom ML algorithm from scratch in python</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7zBtwZ5PPpOzLjKz.jpeg" /></figure><p>Whenever we talk about machine learning models in general, the very first and most simplistic model that comes to our mind is the Linear Regression model. Although its quite simple and easy to understand, it has applications in a wide variety of problem statements. Every data scientist, once in a while, uses this algorithm to solve complex business problems at hand. It is widely popular in the data science community due to its simplicity and effectiveness in real life use cases.</p><p>My goal is to make you understand the basics of this algorithm and also make you feel proud of yourself by helping you build the entire algorithm from scratch in python. Lets get started right away !</p><p>Linear Regression as the name suggests is used for regression tasks. The goal of this algorithm to quantify the linear dependence of a particular dependent variable on the independent variable. In order to achieve this, the model suggests a straight line fit that minimizes the squared error between the actual dependent variable values and the predicted ones. Lets take an example to understand this more clearly.</p><p>Lets say you have a lot of interest in investing in stocks. You have been monitoring the market price of a certain stock for a couple of months now. You observe that for the past few months, the stock shows an increasing trend. And now, based on the data you have, you want to predict what the stock price is going to be after about a month. You also observe that the increase in stock price almost proportional to the number of days. It is here you need to apply linear regression to come up with a linear equation that appropriately describes the change of stock price with number of days. Consequently you will also be able to predict the price after about a month, if the current trend persists.</p><p>Now given a particular data set where a target/dependent variable is linearly dependent Y on the independent variable X, lets see how we can come up with the linear red line in the above figure, that approximately predicts the value of Y given a particular X.</p><p>Let us take a classic example of uni-variate function Y, which is a function of X, i.e. we have a data set with only one independent variable X and dependent variable Y. Let X take values from 0 to 10. While Y is a function of X plus some noise.</p><pre>import numpy as np<br>import matplotlib.pyplot as plt</pre><pre>X = np.arange(0,10,.05)<br>y = X + np.random.normal(loc=0.0, scale=1.5, size=len(X))<br>X = X[..., np.newaxis]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*QSoAj3UnBkGbk-wBS-ZGQw.png" /></figure><p>The linear model that we are going to fit to this data is given by :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/173/0*wwdAVUtsqxhh2KEK.png" /></figure><p>A more general form of linear model with k-feature set is given by :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/0*nhTIXxfDAGP1jyJU.png" /></figure><p>The goal is to come up with appropriate value of model parameters (β0,β1,…,βk) such that variation of predicted Y from actual Y is minimum. The loss function that we use here to calculate the variation of predicted Y from actual Y is given by :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/0*uom_eunU0D5SC8j9.png" /></figure><p>where n is the total number of observations. This loss function differs from the Mean Squared Error (MSE) by a factor of 1/2.</p><p>We do not usually perform training on the entire data set. Instead we split the data set into two, namely training and test data set. We train the model using training data set and then check the performance of the model using test data set.</p><p>Since we need to minimize the loss function with respect to the model parameters, we need,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/0*b0NEd7X0BeI5jvDn.png" /></figure><p>where k is the total number of features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/0*gzuNKEG4rWi8nMMg.png" /></figure><p>These equations are also known as the normal equations. A model with k independent variables has k+1 such parameters to optimize where β0 is the bias term while β1. β2,…,βk are weights associated with each of the variables. Consequently we get k+1 such normal equations to solve for the k+1 parameters (β0,β1,…,βk). Solving these equations leads us towards finding appropriate values for (β0,β1,…,βk) such that the loss function is minimized. However, this is a quite straightforward analytical approach.</p><p>There is an iterative approach to solve this problem as well. Although there are numerous such algorithms that gradually lead us to the global minima of the loss function through iterations, the most commonly used one is the Gradient descent algorithm. We’ll be discussing this approach in detail and eventually use it to build our linear regression model in python.</p><p><strong>Gradient descent algorithm</strong></p><p>This optimization algorithm gradually converges the values of model parameters (β0,β1,…,βn) towards global minimum of the loss function. The parameters are updated after each training epoch in following manner :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/0*1peusUxAHIw_2N4b.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/0*lP7c-sjsOM7dGfyU.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/0*NKmD2PUBywRc-gHD.png" /></figure><p>where α is the learning rate of the optimization algorithm.</p><p>Usually, a smaller learning parameter α is used in order to avoid overshooting the global minima. However too low values for α might also lead the linear model to get stuck in a local minima. We need to figure out a sweet spot that is perfect for the algorithm to converge to the global minima.</p><p>The above discussed algorithm is also known as batch gradient descent algorithm, since the model parameters are updated only after predicting the values for all the observations in the data set. However there is a slightly better optimization algorithm that often gives better results although being computationally expensive sometimes, which is called the stochastic gradient descent. In this method, the model parameters are updated after predicting for the target variables for each of the observations. Stochastic gradient descent is nothing but batch gradient descent with batch size = 1.</p><p>Now lets try to implement this in python by creating a Linear Regression class.</p><pre>class Linear_Regression:</pre><pre>  def __init__(self, learn_rate = 0.001, num_epochs=500):<br>    self.num_epochs = num_epochs<br>    self.learn_rate = learn_rate</pre><pre>  def fit(self, X, y, batch_size=1):<br>    assert len(X.shape) == 2<br>    assert X.shape[0] == y.shape[0]</pre><pre>    self.sample_size, self.feature_size = X.shape<br>    self.weights = np.random.random(self.feature_size+1)<br>    self.batch_per_epoch = self.sample_size//batch_size + 1\<br>        if self.sample_size//batch_size else self.sample_size//batch_size</pre><pre>    for _ in range(self.num_epochs):<br>      for i in range(self.batch_per_epoch):<br>        output = self.predict(X[i*batch_size:(i+1)*batch_size,:])<br>        error = output — y[i*batch_size:(i+1)*batch_size]<br>        self.weights[1:] -= self.learn_rate*error.dot(X[i*batch_size:(i+1)*batch_size,:])<br>        self.weights[0] -= self.learn_rate*np.sum(error)<br>        self.coef_, self.intercept_ = self.weights[1:], self.weights[0]</pre><pre>  def predict(self, X):<br>    return np.dot(self.weights[1:],np.transpose(X)) + self.weights[0]</pre><pre>  def fit_predict(self, X, y, batch_size=1):<br>    self.fit(X, y, batch_size)<br>    return self.predict(X)</pre><p>Now we will implement our custom Linear regression algorithm on our uni-variate data where X is the only independent variable and Y is the target variable. Before doing that we need to split our data set in to train and test sets, preferably in 70–30 ratio.</p><pre>from sklearn.model_selection import train_test_split<br>X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.3,shuffle=True)</pre><p>Having split the data, now we would like to train the data using our train data set, and try to plot the regression line along with train data set</p><pre>lr_model = Linear_Regression()<br>y_train_pred = lr_model.fit_predict(X_train, y_train)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*yvRUruvCfOC8AJfUy2oEsQ.png" /></figure><p>Now lets see how our model performs on test data set :</p><pre>y_test_pred = lr_model.predict(X_test)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*JLkCxkRk245WwND7USBUxA.png" /></figure><p>Lets look at some evaluation metrics to see how our model has performed. Lets look at MSE and r2-score.</p><pre>MSE (train) =  1.6409363739199418 <br>R-squared (train) =  0.8153303325365319</pre><pre>MSE (test) =  1.918687920414487 <br>R-squared (test) =  0.8139978314290932</pre><p>We observe that the model performs equally well on test data set as in the train data set. But unfortunately, in most real life scenarios, in the process of building a model for our data set, we run into over-fitting our train data set due to numerous factors such as high model complexity or having a small data set. The model ends up learning the noise in the data set and hence performs very poorly on a novel test data set. To avoid such issues, we have a method called regularization that helps to generalize our model.</p><p>Regularization is a method that involves penalizing our model parameters for trying to over-fitting the training data set. The loss function, which earlier involved just the mean squared error term, is now added by an extra positive factor as a penalty to the model parameters for trying too hard to learn the training features:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/0*4QgOaUoOMT2W7D23.png" /></figure><p>where λ is known as the regularization strength and k is the total number of features in data set. λ is the measure of penalty we incur on our model parameters. The role of λ is to shrink the magnitude of weights of certain model parameters such that the dominance of certain features over the output variable decreases by considerable amount. A higher λ penalizes the model parameters severely and tries to generalize the model for unseen data by introducing bias into the system. However a low λ corresponds to a model with high variance and low bias. This type of regularization is also known as L2-regularization. We also have L1 regularization wherein the cost function is given by :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/0*d-6_o6bsAX2SsfmT.png" /></figure><p>For the time being, lets use L2-Regularization to generalize our data. Given cost function for L2 regularization technique, the update function for the model parameters are given by :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/0*OGpuDnh6ESYEy87O.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/0*Q4zAZcV7OIUGXC2G.png" /></figure><p>Now, lets implement the following L2-regularization technique in our Linear Regression algorithm.</p><pre>class Linear_Regression:</pre><pre>  def __init__(self, learn_rate = 0.001, num_epochs=500, lamda=0):<br>    self.num_epochs = num_epochs<br>    self.learn_rate = learn_rate<br>    self.lamda = lamda</pre><pre>  def fit(self, X, y, batch_size=1):<br>    assert len(X.shape) == 2<br>    assert X.shape[0] == y.shape[0]</pre><pre>    self.sample_size, self.feature_size = X.shape<br>    self.weights = np.random.random(self.feature_size+1)<br>    self.batch_per_epoch = self.sample_size//batch_size + 1\<br>        if self.sample_size//batch_size else self.sample_size//batch_size</pre><pre>    for _ in range(self.num_epochs):<br>      for i in range(self.batch_per_epoch):<br>        output = self.predict(X[i*batch_size:(i+1)*batch_size,:])<br>        error = output — y[i*batch_size:(i+1)*batch_size]<br>        self.weights[1:] = (1-2*self.learn_rate*self.lamda)*self.weights[1:] - self.learn_rate*error.dot(X[i*batch_size:(i+1)*batch_size,:])<br>        self.weights[0] = (1-2*self.learn_rate*self.lamda)*self.weights[0] - self.learn_rate*np.sum(error)<br>        self.coef_, self.intercept_ = self.weights[1:], self.weights[0]</pre><pre>  def predict(self, X):<br>    return np.dot(self.weights[1:],np.transpose(X)) + self.weights[0]</pre><pre>  def fit_predict(self, X, y, batch_size=1):<br>    self.fit(X, y, batch_size)<br>    return self.predict(X)</pre><p>Let us try to train our training data using regularized linear regression we just defined :</p><pre>lr_model = Linear_Regression(lamda=0.1)<br>y_train_pred = lr_model.fit_predict(X_train, y_train)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*m_T5-rTSPeKmFV6QYQo_Dw.png" /></figure><pre>y_test_pred = lr_model.predict(X_test)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*dyA4s8rqrAo_Vr65MJpxQw.png" /></figure><pre>MSE (train) =  1.6435681949373844 <br>R-squared (train) =  0.8150341495035764</pre><pre>MSE (test) =  1.9183774145855326 <br>R-squared (test) =  0.8140279326023612</pre><p>With regularization introduced into the model, we observe that the R2-scores of regularized model on train and test data sets, although negligible, shows some improvement as compared to standard Linear Regression model. Since, the data set deals with a single feature in deciding the value for our target variable, we don’t observe a significant improvement in results by using regularization. However in complex models, where model training often leads to over-fitting, we might actually see a significant improvement in R2-scores after using regularization techniques.</p><p>Now let me briefly discuss what are the different built-in modules present in python libraries that are used to train our models using linear regression and regularization techniques.</p><pre>from sklearn.linear_model import LinearRegression <br>from sklearn.linear_model import Lasso, Ridge, ElasticNet</pre><p>Scikit-learn (sklearn) is a well-known library in python which is widely used by data scientists. It consists of a large number of machine learning algorithms that are used for different purposes. One of them is Linear Regression which is the standard algorithm with no regularization as such. However, Lasso Regression is nothing but linear regression with L1 regularization. Ridge is the linear regression algorithm with L2-regularization. While ElasticNet is a special kind of regularized linear regression algorithm which utilizes a weighted sum of both L1 and L2 regularization.</p><p>Before closing off, I would like to highlight upon a couple of factors that we need to keep in mind while using any Linear regression algorithm to model our data. These criterion will ensure that we find the best fit model for our data set :</p><ol><li>Linear Assumption : Linear Regression assumes that the relationship between our independent and dependent is linear. It does not support anything else. This may be obvious, but it is good to remember when you have a lot of attributes. You may need to transform data to make the relationship linear.</li><li>Check for Residuals and homoscedasticity : The mean of residuals (difference between predicted and actual target variable ) must be close to 0 as much as possible. Also, the variance around the regression line should be same for all values of predictor variable.</li><li>Check for Multi-collinearity : There should not be any multi-collinearity in the regression model. Multi-collinearity generally occurs when there are high correlations between two or more independent variables.</li><li>Gaussian Distributions : Linear Regression will make more reliable predictions if our independent and dependent variables have a Gaussian distribution.</li><li>Re-scaling inputs : Linear Regression often make more reliable predictions if you re-scale input variables using standardization or normalization.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c1cf68bb1f2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/almabetter/linear-regression-a-beginners-guide-1c1cf68bb1f2">Linear Regression — A Beginner’s Guide</a> was originally published in <a href="https://medium.com/almabetter">AlmaBetter</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Introduction to Machine Learning]]></title>
            <link>https://medium.com/almabetter/an-introduction-to-machine-learning-77fcdab678a5?source=rss-12b8175d050b------2</link>
            <guid isPermaLink="false">https://medium.com/p/77fcdab678a5</guid>
            <category><![CDATA[introduction]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[supervised-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <dc:creator><![CDATA[Smruti Ranjan Pradhan]]></dc:creator>
            <pubDate>Wed, 31 Mar 2021 10:17:18 GMT</pubDate>
            <atom:updated>2021-04-17T08:33:22.991Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*ZNIidca7V2ygHxGS" /></figure><p><strong>What is Machine Learning ?</strong></p><p>The phrase ‘Machine Learning’ roots from two words : ‘Machine’ and ‘Learning’. Learning is the process of acquiring information on how to do certain tasks and improving the performance based on the experience. When this process of learning is performed by a machine by the help of intelligent algorithms, its called machine learning. Although it might seem odd to the first timers, machines can be taught to do certain task similar to humans. With the advancements in scientific research and technology, this process of learning has been made increasingly faster. There has been an increasing demand of job automation in lot of companies, so as to decrease the workload and increase the work efficiency of companies. However these demands need to be met with carefully optimized AI that does the assigned tasks with minimal errors possible. Therefore, the study of machine learning tools is every essential to be able to come up with the best machine learning models for the problem statements at hand.</p><p><strong>Types of Learning</strong></p><p>The study of human behaviour and cognition has helped us to learn certain facts about learning processes in humans. This in turn has helped scientists to come up with algorithms that replicate these processes in machines. There are 3 such broad ways in which machine can learn to perform certain tasks. They are :</p><ul><li>Supervised Learning</li><li>Unsupervised Learning</li><li>Reinforcement Learning</li></ul><p><strong>Supervised Learning</strong></p><p>As the name suggests, this type of learning needs supervision. As in, there has to be a supervisor who has a prior idea of the task at hand. With its guidance, the trainee has to be taught until perfection with minimal errors. Similar to how a one or two-year old baby is taught about the things in its environment, a machine too is taught how to classify or identify certain datasets.</p><p>A two-year old baby, when shown an flying aeroplane in the sky for the first time, might associate with a flying bird. However when corrected over time, he learns to differentiate between an aeroplane and a bird by subconsciously analyzing different features each of them possess.</p><p>Similarly, a machine learning model too can be taught to correct its parameters as it learns to correctly identify/classify the datasets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ktenkQZqGQkhrYSc.jpg" /></figure><p>Every supervised learning dataset has two major components :</p><ul><li>Training dataset : A training dataset consists of a certain number of observations ( lets say m ) with definite number of features ( lets say n ).</li><li>Desired output : Each of the m observations with n features in training dataset has a desired output value.</li></ul><p>The goal of any supervised machine learning algorithm is to come up with an approximate map f(θ) from the training dataset to the desired output. In this process of finding an approximate map, the algorithm builds a model with certain parameters θ. These parameters can be seen as weights given to different features by the model in order to minimize the difference between the predicted and desired output.</p><p>Broadly, there are two different kinds of tasks performed using supervised learning, namely,</p><ul><li>Classification : The desired output has discrete output labels. Each of the observation belongs to on of these output labels. The job of machine learning algorithm is to come up with a model that accurately predicts the category each of the observation in the training or test data belong to. Eg. : Spam mail detection, Credit card fraud detection, Image classification etc.</li><li>Regression : The desired output can take continuous values. The machine learning task is to come up with a model that predicts the approximate value of the the output. The goal is to minimize the error between the desired and predicted ones. Eg.: Real estate prediction, Weather Forecasting etc.</li></ul><p>Example : Spam mail detection is beautiful example of supervised classification task. We might have noticed how effectively google classifies certain emails in our inbox as spam and sends them to spam folder. The google spam detection engine here uses a supervised classification algorithm where it takes input from the user and other sources and builds a model that detects if a given mail is spam or not based on the features such as frequency of certain words, total word count, number of misspellings and so on.</p><p><strong>Unsupervised Learning</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*U3dK3srZaOaFddmM" /></figure><p>Unlike supervised Learning, where we have a desired output for the observations in the training dataset, the dataset this type of learning uses has no desired output. Although we don’t have labels for the observations in the dataset, we might still need to analyze the data and draw inferences from them. In cases like these, unsupervised learning algorithm comes into play. The main goal of the learning algorithm is to identify patterns in the training dataset and classify them into certain categories. Such an analysis of dataset helps in number of tasks such as :</p><ul><li>Clustering : This task is performed to categorize unlabelled dataset into certain number of clusters based on their likelihood/similarity index of observations with each other. This technique comes in handy on number of occasions when we segment our dataset into number of categories and analyze them separately. Eg. : Document Identification, Customer Segmentation, delivery store optimization</li><li>Anomaly detection : Similar to clustering, anomaly detection also uses unsupervised dataset to come up with a set of anomalous observations that have some features quite different from the cluster of non-anomalous observations. Eg. : Insurance Fraud detection, Faulty equipment detection</li><li>Dimensionality reduction : Often in datasets, there are certain features that are highly correlated and hence are redundant, unnecessarily making the machine learning models computationally expensive. Also, it might be difficult to visualize a large number of features simultaneously. Such issues can be addressed by reducing the number of features in the dataset. Such task can be done by projecting the existing high dimensional feature set onto a lower dimension without affecting the variance in the datasets and retaining most of it. Since these tasks only need to look at the feature set and not on the desired output labels, these come under Unsupervised Learning tasks.</li></ul><p>Example : Engine fault detection is a nice example of anomaly detection using unsupervised learning. There could be number of features that might seem to differ from the usual set of values, when there is a fault in a certain engine. These machine learning techniques are helpful in identifying these outliers and declaring those engines as faulty and unfit for use.</p><p><strong>Reinforcement Learning</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yW5FzLDisYlEuPlA.jpg" /></figure><p>Reinforcement learning describes a class of problems where an agent operates in an environment and must learn to operate using feedback. The use of an environment means that there is no fixed training dataset, rather a goal or set of goals that an agent is required to achieve, actions they may perform, and feedback about performance toward the goal. It is similar to supervised learning in that the model has some response from which to learn, although the feedback may be delayed and statistically noisy, making it challenging for the agent or model to connect cause and effect.</p><p>An example of a reinforcement problem is playing a game where the agent has the goal of getting a high score and can make moves in the game and received feedback in terms of punishments or rewards. Impressive recent results include the use of reinforcement in Google’s AlphaGo in out-performing the world’s top Go player. Some popular examples of reinforcement learning algorithms include Q-learning, temporal-difference learning, and deep reinforcement learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77fcdab678a5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/almabetter/an-introduction-to-machine-learning-77fcdab678a5">An Introduction to Machine Learning</a> was originally published in <a href="https://medium.com/almabetter">AlmaBetter</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hypothesis Testing]]></title>
            <link>https://medium.com/almabetter/hypothesis-testing-602fcb022a70?source=rss-12b8175d050b------2</link>
            <guid isPermaLink="false">https://medium.com/p/602fcb022a70</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[inferential-statistics]]></category>
            <category><![CDATA[hypothesis-testing]]></category>
            <dc:creator><![CDATA[Smruti Ranjan Pradhan]]></dc:creator>
            <pubDate>Tue, 23 Mar 2021 14:23:55 GMT</pubDate>
            <atom:updated>2021-04-17T08:33:36.176Z</atom:updated>
            <content:encoded><![CDATA[<h4>How good are your assumptions?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eKJufdSbd82WuxTh.jpg" /></figure><p>Considering the current pandemic scenario, we might want to know whether a certain new drug developed by a pharmaceutical company will be able to reduce the number of active cases in the world. Of course before trying the following drug on a mass scale, the government might be interested in the effectiveness of the drug based on the results from a couple of thousands of test cases.</p><p>For example, When testing the new vaccine on a random sample of 2500 previously uninfected people, its found that these people are 70 % less likely to contract to COVID-19 compared to those who did not take the vaccine.</p><p>Now, the question is : Is this significant enough? Could this be just the result of chance, or is this vaccine really effective ? It is in these cases that the hypothesis testing comes in and has an very important role to play.</p><h3>Statistical Inference</h3><p>Statistical inference is the process of drawing conclusions about the population based on a sample from that population. This technique really comes in handy when it becomes physically impossible to acquire stats and information about the entire population. We can ask numerous questions about the population and might be able to draw some definitive conclusions based on single randomly drawn sample from that population.</p><ul><li>Suppose, we survey a total of 50 different higher education institutions in India. We found that out of 950 professors in those institutions, 640 are male and 310 are female.</li><li>Based on this statistic can we come to a make a claim that there are less than 30% preference for female professors in Indian institutions ? Does the data provide enough evidence to infer a gender bias based on this statistic ?</li></ul><p><strong>Steps in Hypothesis testing :</strong></p><ul><li>Given a claim, identify the null hypothesis and the alternative<br>hypothesis, and express them both in symbolic form.</li><li>Given a claim and sample data, calculate the value of the test statistic.</li><li>Given a significance level, identify the critical value(s).</li><li>Given a value of the test statistic, identify the P-value.</li><li>State the conclusion of a hypothesis test in simple, non-technical<br>terms.</li></ul><p><strong>Null hypothesis </strong>: The null hypothesis is a statement that the value of a<br>population parameter (such as proportion, mean, or standard deviation) is equal to some claimed value. This is the first assumption that you make about any event and is often quite mundane and doesn’t signify any progress or change.</p><p><strong>Alternative Hypothesis</strong> : The alternative hypothesis is the statement that the statistic has a value that somehow differs from the null hypothesis.This statement is often progressive in nature. The symbolic form of the alternative hypothesis must use one of these symbols: ≠, &lt;, &gt;.</p><p>Of the two symbolic expressions obtained so far, let the alternative<br>hypothesis be the one not containing equality so that it uses the symbol &lt; or &gt; or ≠. Let the null hypothesis be the symbolic expression that the statistic equals the fixed value being considered.</p><p><strong>Two salient features :</strong></p><ul><li><em>Rare event rule</em> : Under the assumption that null hypothesis is True, if probability of certain event is bleak, i.e. if the event is more likely to have occurred by chance, then our assumption is supposed to be incorrect and we reject null hypothesis in favor of alternate hypothesis.</li><li>In any case, we either reject or fail to reject the Null hypothesis. We never accept a null hypothesis.</li></ul><p>After formulating both the hypothesis, we conduct the hypothesis test under the assumption that the null hypothesis is true. Our goal is to collect enough evidence in favor of alternate hypothesis so as to be able to reject null hypothesis. However if our results are statistically insignificant, we fail to reject the null hypothesis. To be able to say if the results are statistically significant or not, we need to understand the concepts of <strong>test statistic </strong>and <strong>p value</strong>. But before discussing these terms in detail, lets learn about the concept of and <strong>significance level, critical region </strong>and <strong>types of test</strong> we run based on our hypotheses.</p><p><strong>Significance Level</strong></p><p>The significance level, also denoted as alpha or α, is a measure of the strength of the evidence that must be present in our sample before we will reject the null hypothesis and conclude that the effect is statistically significant. The researcher determines the significance level before conducting the experiment.</p><p>The significance level is the probability of rejecting the null hypothesis when it is true. For example, a significance level of 0.05 indicates a 5% risk of concluding that a difference exists when there is no actual difference. Lower significance levels indicate that we require stronger evidence before we will reject the null hypothesis.</p><p>In other words, the significance level is a statistical way of demonstrating how confident you are in your conclusion. If you set a high alpha (0.25), then you’ll have a better shot at supporting your alternative hypothesis, since you don’t need to find as big a difference between your test groups. However, you’ll also have a bigger chance at being wrong about your conclusion.</p><p><strong>Critical region</strong> is the region of values that corresponds to the rejection of the null hypothesis at some chosen significance level α. <strong>Critical Value</strong> is the permissible limit value beyond which results are statistically significant and Null hypothesis is rejected.</p><p><strong>Types of Test</strong></p><p>The types of test that we conduct is based on the alternate hypothesis (Ha)</p><p>If Ha : parameter &lt; value, then we conduct <strong>left-tailed test</strong>, where critical region lies on the left tail of the distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/0*Q5T2Zaqs3IhxpmOV.gif" /></figure><p>If Ha : parameter &gt;value, then we conduct <strong>right-tailed test</strong>, where critical region lies on the right tail of the distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/0*kb4nCWVa0voUz8Va.gif" /></figure><p>If Ha : parameter ≠ value, then we conduct a <strong>two-tailed test</strong>, where critical regions lie on both the left and right tails of distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/0*Rvuv6Rz0fP-C-W5h.gif" /></figure><h4><strong>Test Statistic</strong></h4><p>A Test statistic is a mathematical formula that allows researchers to determine the likelihood of obtaining sample outcomes if null hypothesis were true.</p><p>The value of test statistic is used to make a decision regarding the null hypothesis. The larger the test statistic, the further the distance, or the number of standard deviations, a sample mean is from the population mean stated in null hypothesis. Examples of test statistics that are used in hypothesis testing are :</p><p>Test statistic for proportions :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/157/0*KspTj56Itv_bpAKr.png" /></figure><p>Test statistic for mean :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/129/0*JKJbwpKBIJthX4-R.png" /></figure><p>If standard deviation σ of population is not known, but however the sample variance is known, we use a t-statistic with (n-1) degrees of freedom, instead of z-statistic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/170/0*OBBEhERPPHya42Hd.png" /></figure><p>When we want to test the measure deviation of sample variance (S²) from the population variance (σ²), we use χ² statistic with (n-1) degrees of freedom.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/0*ovLx-tAaqK2pWEXC.png" /></figure><h4><strong>P-value Approach</strong></h4><p>After we are done calculating the statistic of a parameter for a given sample, We need to calculate the P-value of the given statistic. P-value is nothing but the probability of observing a sample parameter that is as or more extreme than the observed and is given by the area under the tails with limits defined according to the type of test we conduct. Lets take the example of the z-statistic that is calculated assuming that our sample parameter follows a normal distribution, which also follows from the Central Limit Theorem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9BpF8kPCtkMACPCtVEqw2g.jpeg" /></figure><p>Now, we use significance levels during hypothesis testing to help us determine which hypothesis the data support. We compare your p-value to our significance level. If the p-value is less than our significance level, we can reject the null hypothesis and conclude that the effect is statistically significant. In other words, the evidence in our sample is strong enough to be able to reject the null hypothesis at the population level.</p><p><strong>Example 1:</strong></p><p>A principal at a certain school claims that the students in his school are above average intelligence. A random sample of thirty students IQ scores have a mean score of 112.5. Is there sufficient evidence to support the principal’s claim? The mean population IQ is 100 with a standard deviation of 15.</p><p><strong>Step 1</strong>: State the Null Hypothesis. The accepted fact is that the population mean is 100, so: H0: μ=100.</p><p><strong>Step 2</strong>: State the Alternate Hypothesis. The claim is that the students have above average IQ scores, so: H1: μ &gt; 100. The fact that we are looking for scores “greater than” a certain point means that this is a right-tailed test.</p><p><strong>Step 3</strong>: State the α level. If you aren’t given an α level, use 5% (0.05).</p><p><strong>Step 4</strong>: Find the test statistic using this formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/120/0*NCej0jMLRJR1NqRw.jpg" /></figure><p>For this set of data: z= (112.5–100) / (15/√30) = 4.56.</p><p><strong>Step 5</strong>: Considering we are doing a right-tailed test, calculate the P-value for z statistic using the z table</p><p>P-value ∼ 0.00001.</p><p><strong>Step 6</strong>: Compare the P-value to significance level α. If p &lt; α, results are significant and null hypothesis is rejected. Else, we fail to reject the Null hypothesis.</p><p>Since p &lt; α = 0.05, we reject the null hypothesis, in favor of alternate hypothesis and effectively conclude that principal’s claim is True based on the statistical test conducted.</p><p><strong>Example 2</strong></p><p>The average height of students in a batch is 100 cm and the standard deviation is 15. However, the teacher believes that this has changed, so he decides to test the height of 75 random students in the batch. The average height of the sample comes out to be 105. Is there enough evidence to suggest that the average height has changed?</p><p><strong>Step 1</strong>: State the Null Hypothesis. In our case it will be the average height of students in the batch is 100.</p><p>H0 : μ = 100</p><p><strong>Step 2</strong>: State the Alternate Hypothesis. In our case, the teacher claims that the actual value has changed. He doesn’t know whether the average has gone up or down, but he believes that it has changed and is not 100 anymore.</p><p>Ha : μ ≠100</p><p>So if the alternate hypothesis is written with a ≠ sign that means that we are going to perform a 2-tailed test because chances are it could be more than 100 or less than 100 which makes it 2-tailed.</p><p><strong>Step 3</strong>: State the α level. If you aren’t given an α level, use 5% (0.05).</p><p><strong>Step 4</strong>: Find the test statistic using this formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/120/0*NCej0jMLRJR1NqRw.jpg" /></figure><p>For this set of data: z= (105–100)/(15/√7.5) = 2.89</p><p><strong>Step 5</strong>: Considering we are doing a two-tailed test, calculate the P-value for z statistic using the z table</p><p>P-value = 0.003852</p><p><strong>Step 6</strong>: Compare the P-value to significance level α. If p &lt; α, results are significant and null hypothesis is rejected. Else, we fail to reject the Null hypothesis.</p><p>Since p &lt; α = 0.05, we reject the null hypothesis, in favor of alternate hypothesis and effectively conclude that teacher’s claim is True that the average height of students in the batch has changed.</p><h4><strong>Statistical errors</strong></h4><p>We often come across terms like statistical errors as a result of conducting hypothesis tests. If the result of the test corresponds with reality, then a correct decision has been made. However, if the result of the test does not correspond with reality, then an error has occurred. There are two situations in which the decision is wrong. The null hypothesis may be true, whereas we reject H0. On the other hand, the alternative hypothesis Ha may be true, whereas we do not reject H0. Two types of error are distinguished: Type I error and type II error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/0*HOgRek3dK7HVAywm.jpg" /></figure><p><strong>Type I error</strong></p><p>The first kind of error is the rejection of a true null hypothesis as the result of a test procedure. This kind of error is called a type I error (false positive) and is sometimes called an error of the first kind.</p><p><strong>Type II error</strong></p><p>The second kind of error is the failure to reject a false null hypothesis as the result of a test procedure. This sort of error is called a type II error (false negative) and is also referred to as an error of the second kind.</p><p><strong>Power of Hypothesis Test</strong></p><p>The power of a hypothesis test is the probability that the test rejects the null hypothesis (H0) when a specific alternate hypothesis (Ha) is true i.e., it indicates the probability of avoiding a Type-II error. The statistical power ranges from 0 to 1, and as statistical power increases, the probability of making a type II error (wrongly failing to reject the null hypothesis) decreases. If probability of making Type II error is β, power of hypothesis test is given by 1-β.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B2tOD-FYX6nEnFbL.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=602fcb022a70" width="1" height="1" alt=""><hr><p><a href="https://medium.com/almabetter/hypothesis-testing-602fcb022a70">Hypothesis Testing</a> was originally published in <a href="https://medium.com/almabetter">AlmaBetter</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Game of Random Variables]]></title>
            <link>https://medium.com/almabetter/the-game-of-random-variables-4bfa3669b5a2?source=rss-12b8175d050b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bfa3669b5a2</guid>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[Smruti Ranjan Pradhan]]></dc:creator>
            <pubDate>Fri, 19 Mar 2021 13:36:45 GMT</pubDate>
            <atom:updated>2021-04-17T08:33:49.542Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LJmVD3zaPJvlEo__0j_PCQ.jpeg" /></figure><blockquote><strong><em>What is a Random Variable ?</em></strong></blockquote><p>As the name suggests, it is a term that associates itself to the concept of randomness and uncertainty. There are numerous such incidents that occur in our day-to-day life whose outcomes are difficult to predict with utmost certainty. For example, while playing a game of basket ball, the certainty with which you put the ball in the basket from the half line depends on your expertise in the game. Similarly, you can’t accurately guess the number of likes you might get in your next Instagram post. It has to depend on a wide range of factors such as visual appeal, message in the caption, and your brand/product outreach.</p><p>Here the phrase &#39;number of likes on next Instagram post&#39; can be coined as a random variable. The number of likes on a given post is a variable that can take any random integer value starting from 0 till infinity. Although the probability of you getting likes anything greater than 10000 might be bleak if you are a small brand. The probability of you having 5 billion likes is essentially 0 even if you are the largest brand in the world since the current population of the world is 7.9 billion and more than half of the world population is not on the internet and especially not on Instagram. Similarly, the total number of likes on a decent post not crossing 10 likes might be bleak as well, if your account has at least 100 followers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uwu-MQyYmnaWxrbJX4wS4Q.jpeg" /></figure><blockquote><strong>Probability Distributions</strong></blockquote><p>We can clearly infer from the above experiment that, the probabilities of number of likes taking certain value widely varies over the entire range of random variables. And this distribution of probabilities over the entire range of values for the random variable is known as Probability Distribution of the random variable.</p><ol><li><strong><em>Discrete Distributions</em></strong></li></ol><p>These kind of distributions describe the variation of probabilities with respect to discrete number of countable values for the random variable. For example, when we roll a die, we have only six outcomes : 1, 2, 3, 4, 5 and 6. If our random variable is the number appearing on a rolling die, we have only six discrete values for our random variable. And probability of each of those value is 1/6, given its an unbiased die. This type of discrete distribution where all probabilities are same is also known as uniform discrete distribution.</p><p><strong><em>(i) Uniform discrete distribution</em></strong></p><p>A uniform discrete distribution comprises of probabilities that are equal for all the values that a random variable can take. Probabilities for the outcomes of rolling an unbiased die is a classic example of uniform discrete distribution, where each of the outcomes 1, 2, 3, 4, 5 and 6 has a probability 1/6 to occur.</p><p>If we have k outcomes for a random variable X, probability of getting an outcome x is given by :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/0*TrIuvw4IfCQUN60t.png" /></figure><pre>import numpy as np<br>import matplotlib.pyplot as plt</pre><pre>y = np.full(6, 1/6)<br>plt.bar(range(1,len(y)+1), y)<br>plt.ylim(0,1.)<br>plt.ylabel(‘Probability’)<br>plt.xlabel(‘Outcomes of rolling an unbiased die’)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*1LnAIN-e2dvgJVHkMPZb5A.png" /><figcaption><strong>Uniform Distribution ( k = 6 )</strong></figcaption></figure><p><strong><em>(ii) Binomial Distribution</em></strong></p><p>This distribution is based on the concept of n independent and identical bernouli trials. A bernouli trial consists of two outcomes : ‘success’ and ‘failure’. In a given trial, let the probability of getting a a success in be p and probability of getting a failure is 1-p. We conduct n such trials that are independent of each other. We now want the probability of getting x number of successes in those n trials. The probability is given by :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/0*0Eq67qiupHxPfWvp.png" /></figure><pre>def factorial(n):<br> if n &gt; 0:<br> return n*factorial(n-1)<br> return 1</pre><pre>n,p = 100, 0.3<br>x = np.arange(0,n+1,1,dtype=int)<br>y = []<br>for x_ in x:<br> x_ = int(x_)<br> y.append( (factorial(n)/factorial(x_)/factorial(n-x_)) * ((1-p)**(n-x_)) * p**x_ )</pre><pre>plt.bar(x,y)<br>plt.xlim(10,50)<br>plt.show()</pre><p>A typical binomial distribution with n= 100 and p =0.3, looks like :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*iDgWajp4lXo-m_J5sraUjg.png" /><figcaption><strong>Binomial Distribution ( n = 100, p = 0.3 )</strong></figcaption></figure><p><strong><em>(iii) Geometric Distribution</em></strong></p><p>This distribution models the number of trials on which the first success occurs. If probability of success in a given trial is p, the probability distribution of x number of such trials is given by :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/0*Bu7omhllETscYOIM.png" /></figure><pre>n,p = 25, 0.2<br>x = np.arange(0,n+1,1,dtype=int)<br>y = (1-p)**x * p<br>plt.bar(x, y)<br>plt.show()</pre><p>A geometric distribution with p = 0.2 looks like :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*qHF3hud8tT9F1A88VxmfKg.png" /><figcaption><strong>Geometric Distribution ( p = 0.2 )</strong></figcaption></figure><p><strong><em>(iv) Poisson Distribution</em></strong></p><p>A Poisson distribution is defined as :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/0*jbhKW8tn4jB8c4I1.png" /></figure><p>where X is the random variable that determines the number of occurrences of certain event in a time interval, and λ is the average number of occurrences of certain invent in a time interval.</p><pre>lamda = 20<br>x = np.arange(0,40,1,dtype=int)<br>y = []<br>for x_ in x:<br> x_ = int(x_)<br> y.append(lamda**x_*np.exp(-lamda)/factorial(x_))<br>plt.bar(x,y)<br>plt.show()</pre><p>A poisson distribution with λ = 20 looks like :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*aernZ79oz413QgfVTdF62Q.png" /><figcaption><strong>Poisson Distribution ( λ = 20 )</strong></figcaption></figure><p><strong><em>2. Continuous Distributions</em></strong></p><p>A continuous distribution is a probability distribution function for a continuous random variable i.e. a random variable with infinitely many possible values between any two random variable values. For example the height or weight of a person can be considered as a continuous random variable, whereas the probability of a person having certain height/weight gives rise to the concept of continuous probability distribution.</p><p><strong><em>(i) Normal Distribution</em></strong></p><p>This distribution has lot of applications in statistics. It has two important parameter μ and σ, μ represents mean of the distribution, while σ represents the standard deviation of the distribution. Now the normal distribution is defined as :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/0*Xbe98TNZYsFuDjCG.png" /></figure><pre>mu, sig = 10, 5<br>x = np.arange(0,20,.1)<br>y = 1/(sig*np.sqrt(2*np.pi)) * np.exp(-(x-mu)**2/(2*sig**2))<br>plt.plot(x,y,linewidth=3)<br>plt.show()</pre><p>A normal distribution with μ = 10 and σ = 5, looks like :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*HXuUA-KEtZifQC1ApUFJNw.png" /><figcaption><strong>Normal distribution ( μ = 10.0, σ = 5 )</strong></figcaption></figure><p>(ii) Exponential distribution</p><p>Exponential distribution is nothing but the continuous version of geometric distribution. It’s mathematical formulation is given by :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/0*b32cWUtB1awnD96N.png" /></figure><pre>lamda = 2.<br>x = np.arange(0,3.,.05)<br>y = lamda*np.exp(-lamda*x)<br>plt.plot(x,y,linewidth=3)<br>plt.show()</pre><p>Exponential distribution with λ = 2, looks like :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*MDTSx5mXfNwmOWiD0JUkKg.png" /><figcaption><strong>Exponential Distribution ( λ = 2 )</strong></figcaption></figure><p>Now that we have learnt about different kind of distributions, lets try to create a possible probability distribution for the total number of likes for next Instagram post based on our earlier discussion. Suppose you are an average Instagram user with a decent 500 follower base. And you have prepared a quite engaging picture for your next Instagram post. The probability distribution for the number of likes is most likely going to be a right skewed distribution. A <strong>right skewed distribution</strong> is a distribution with most number of observations in the lower end of values for the random variable compared to those on the higher end. Similarly, a <strong>left skewed distribution</strong> is a distribution with most number of observations in the higher end of values for the random variable compared to those on the lower end.</p><pre>from scipy.stats import skewnorm</pre><pre>a = 3<br>mean, std = 70, 140<br>fig, ax = plt.subplots(1, 1)</pre><pre>x = np.linspace(0,600, 200)<br>ax.plot(x, skewnorm.pdf(x, a, mean, std),&#39;r-&#39;, lw=5)<br><br>r = skewnorm.rvs(a, mean, std, size=5000)<br>ax.hist(r, density=True, histtype=&#39;stepfilled&#39;, alpha=0.2, bins=50)<br>ax.legend(loc=&#39;best&#39;, frameon=False)<br>plt.ylabel(&#39;Probability&#39;)<br>plt.xlabel(&#39;Number of likes in post&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*uKe3jMOfbioxTjJZ076UKw.png" /><figcaption><strong>Right skewed distribution for the total number of likes on an Instagram Post</strong></figcaption></figure><blockquote><strong>Cumulative Distribution function</strong></blockquote><p>Cumulative distribution function of a random variable X is defined as the sum of all the probabilities of values of X that are less than a certain value x. In mathematical terms, this can be written as:</p><p>For discrete distributions, CDF is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/0*07HElgo1GEzMWHlp.png" /></figure><p>If f(x) is the continuous probability density function, CDF is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/0*V64Q2ePpVpQAhfNR.png" /></figure><p>As x → ∞ , the cumulative distribution function P( X ≤ ∞) →1, which shows the sum of all the probabilities in a probability density function is 1.</p><blockquote><strong>Joint Distributions</strong></blockquote><p>Sometimes the probability density function is not only a function of a single variable but multiple different random variables. For example, P(X=x,Y=y) = f(x,y) is a function of two different random variables. Here f(x,y) is nothing but the Joint distribution function of both variables X and Y.</p><p>Similar to what we observed in single random variable, sum of all the probability of a joint distribution also equals 1 i.e.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/0*EydPtmYNk2g9-QVB.png" /></figure><p><strong>Marginal Distribution</strong></p><p>Marginal probability distribution of a variable X is defined as the probability density function with respect to X while summing the probabilities over all other variables (Y).</p><p>In case of a discrete joint distribution, marginal probability distribution is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/0*3cvg9kWezELx5tyQ.png" /></figure><p>While in case of a continuous joint distribution, marginal probability distribution is given by :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/0*hc0PPvUHP0gkPF0s.png" /></figure><p>If two random variables are independent, Joint probability distribution of X and Y can be written as :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/0*AUgC20mJRuApJ4Zp.png" /></figure><blockquote><strong><em>Inferential Statistics</em></strong></blockquote><p>Inferential statistics if that domain of statistics which is very useful to determine the population statistic based on a sample statistic. This technique is often used since in most real world cases, the sample size is quite smaller than the actual population and we need to determine the statistics of the population. Lets take an example to better understand the theory behind inferential statistics.</p><p>Let X be a random variable. We randomly select a sample of size n from the population. A <strong>statistic </strong>is something that is a function of n-sized sample. For example the mean and variance of the sample can be called as statistics. Again, a statistic is nothing but a random variable as well. We can randomly select a large number of such n-sized samples from the population, take mean and variances of those samples and try to see their distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/164/0*j_wIgAijJSMHrnXR.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/0*76usR36Wi2chAnO0.png" /></figure><p><strong><em>Sample Mean and Central Limit Theorem</em></strong></p><p>Lets suppose we take large number of samples with n observations from a population having some arbitrary underlying distribution with mean μ and variance σ².</p><p>For large enough n, the sampling distribution of the sample mean resembles the normal distribution with mean μ and variance σ²/n, irrespective of underlying distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/172/0*-fc8QziRk2VwS_03.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/0*urW2I0K2mrkLSXCx.png" /></figure><p>This is known as <strong>Central Limit Theorem</strong></p><p>In most cases, σ² in unknown. In those cases we can use t-distribution to approximate the distribution of sample mean. The t-distribution makes use of sample variance S² instead of population variance σ², i.e.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/167/0*thOsupcEEdwkqh2j.png" /></figure><p><strong>Sample Variance Distribution</strong></p><p>When we try to look at the sampling distribution of sample variances, we can say that the mean of the sample variance distribution will be equal to μ. But the variance of the sampling distribution of sample variance depends on the underlying distribution of the population. However, if the underlying distribution is a normal distribution, the sampling distribution of the sample variance resembles a χ² distribution as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/215/0*W5D3zD_hBv9NzQUr.png" /></figure><p><strong>Confidence Intervals</strong></p><p>From the above discussed concepts of sampling distribution, we now will be able to estimate the parameters of the underlying distribution with certain confidence using confidence intervals. A 100(1-α) % confidence interval of the population mean is given by :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/0*odi7sCH2NO5aRbqV.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/0*MSJoXH3aCjglfmfR.png" /></figure><p>However if the standard deviation σ of underlying distribution is unknown, we can use t-statistic to come up with a confidence interval for the population mean μ, which is given by :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/0*fIoHYekiBfyKOTYP.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bfa3669b5a2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/almabetter/the-game-of-random-variables-4bfa3669b5a2">The Game of Random Variables</a> was originally published in <a href="https://medium.com/almabetter">AlmaBetter</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>