Full text
Bachelor’s Degree Final Project Machine Learning Techniques for Natural Language Processing Faculty of Mathematics Statistics and Operational Research Department Presented by: Amparo Jare˜no Garc´ıa Supervised by: Dr. Rafael Pino Mej´ ıas Dual Degree Mathematics and Statistics Academic year 2022-23 Seville, July 2023
Abstract Language is such a powerful tool that enables communication between humans. However, there have been some barriers, historically, which arose the need for automatisation of linguistic tasks. After overcoming setbacks, a balance between linguistics and computer science was achieved, which was based mainly on artificial intelligence. The objective of this work is to understand the text preprocessing so that machine learning algorithms can be applied to draw insights. For this purpose, we will dive into supervised learning theory together with discriminative and generative algorithms that will be perform text classification tasks: a fake news classifier and a film reviews sentiment analysis. Furthermore, we will explore the variety of purposes and the industrial applications that Natural Language Processing has.
Resumen El lenguaje es una herramienta tan poderosa que permite la comunicaci´on entre los seres humanos. Sin embargo, hist´oricamente han existido algunas barreras que fomentaron la necesidad de automatizar las tareas ling¨u´ısticas. Tras superar los contratiempos, se logr´o un equilibrio entre la ling¨u´ıstica y la inform´atica, el cual se fundament´o principalmente en la inteligencia artificial. El objetivo de este trabajo es comprender el preprocesamiento de textos para poder aplicar algoritmos de aprendizaje autom´atico que permitan extraer conclusiones. Para ello, nos sumergiremos en la teor´ıa del aprendizaje supervisado junto con algoritmos discriminativos y generativos que realizar´an tareas de clasificaci´on de textos: un clasificador de noticias falsas y un an´alisis de sentimientos de cr´ıticas de pel´ıculas. Adem´as, exploraremos la variedad de prop´ositos y de aplicaciones industriales que tiene el Procesamiento del Lenguaje Natural.
Contents 1 Text Basics 1 1.1 Introduction................................ 1 1.2 History................................... 2 2 Language Normalisation 4 2.1 Morphological Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . 5 2.1.1 Stemming ............................. 6 2.1.2 Lemmatisation .......................... 8 2.1.2.1 WordNet ........................ 10 2.2 Lexical Representations . . . . . . . . . . . . . . . . . . . . . . . . . . 14 2.2.1 Tokenisation............................ 14 2.2.2 StopWords ............................ 15 2.2.3 Documents representation . . . . . . . . . . . . . . . . . . . . 18 2.2.3.1 Bag-of-Words . . . . . . . . . . . . . . . . . . . . . . 19 2.2.3.2 TF-IDF......................... 19 2.2.4 N-Grams.............................. 20 3 Machine Learning 22 3.1 Introduction................................ 22 3.2 Supervised Learning . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 3.2.1 Statistical Learning Theory . . . . . . . . . . . . . . . . . . . 25 3.2.2 Generalisation-Approximation Trade-off via the Bias-Variance Analysis.............................. 29 3.2.3 Model Performance . . . . . . . . . . . . . . . . . . . . . . . . 30 3.2.3.1 Classification Metrics . . . . . . . . . . . . . . . . . . 30 3.2.3.2 Regression Metrics . . . . . . . . . . . . . . . . . . . 33 3.2.4 ModelValidation ......................... 35 3.3 Discriminative Classifiers . . . . . . . . . . . . . . . . . . . . . . . . . 37 3.3.1 Logistic Regression . . . . . . . . . . . . . . . . . . . . . . . . 37 3.3.2 Support Vector Machines . . . . . . . . . . . . . . . . . . . . . 39 3.3.3 DecisionTree ........................... 44 3.3.4 Gradient Descent . . . . . . . . . . . . . . . . . . . . . . . . . 45 3.3.4.1 Stochastic Gradient Descent . . . . . . . . . . . . . . 46 3.3.5 Boosting.............................. 48 3.3.5.1 Gradient Boosting . . . . . . . . . . . . . . . . . . . 50 3.3.5.1.1 XGBoost . . . . . . . . . . . . . . . . . . . 53 3.4 Generative Classifier . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 I
3.4.1 NaiveBayes............................ 54 3.4.2 Linear Discriminant Analysis . . . . . . . . . . . . . . . . . . 55 4 Applications 59 4.1 TextClassification ............................ 60 4.1.1 Sentiment Analysis . . . . . . . . . . . . . . . . . . . . . . . . 62 4.2 TextClustering .............................. 63 4.2.1 TopicModelling.......................... 64 4.3 Machine Translation . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 4.3.1 Rule-based Machine Translation . . . . . . . . . . . . . . . . . 65 4.3.2 Statistical Machine Translation . . . . . . . . . . . . . . . . . 66 4.3.3 Neural Machine Translation . . . . . . . . . . . . . . . . . . . 67 4.4 QuestionAnswering............................ 69 4.4.1 Information Retrieval Based . . . . . . . . . . . . . . . . . . . 70 4.4.2 Knowledge-Based QA . . . . . . . . . . . . . . . . . . . . . . . 70 4.4.3 Automated Reasoning . . . . . . . . . . . . . . . . . . . . . . 70 4.5 Summarisation .............................. 71 4.5.1 Extraction Based . . . . . . . . . . . . . . . . . . . . . . . . . 71 4.5.2 Abstraction Based . . . . . . . . . . . . . . . . . . . . . . . . 71 4.6 Industrial applications . . . . . . . . . . . . . . . . . . . . . . . . . . 72 4.6.1 Finance .............................. 72 4.6.2 Business.............................. 72 4.6.3 Healthcare............................. 73 4.6.4 Legal and Compliance . . . . . . . . . . . . . . . . . . . . . . 74 4.6.5 Education............................. 74 4.7 Ethical Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . 75 5 Python 76 5.1 Natural Language Toolkit . . . . . . . . . . . . . . . . . . . . . . . . 78 5.2 SpaCy ................................... 79 5.3 Scikit-learn ................................ 81 6 Results 83 7 Appendix 139 Bibliography 159 II
List of Figures 2.1 The WordNet example representation as a rooted DAG. Source: [16] . 11 2.2 The “is a” relationship. Source: [17] . . . . . . . . . . . . . . . . . . . 12 2.3 Example of shortest ancestral path. Source: [18] . . . . . . . . . . . . 13 2.4 Barplot of the 30 most frequent words in the Brown Corpus. Source: Own elaboration (section (7)). . . . . . . . . . . . . . . . . . . . . . . 17 2.5 Log-log scale plot of the 20000 most frequent words in the Brown Corpus, regarding their rank. Source: Own elaboration. . . . . . . . . 18 3.1 Machine Learning as a subset of Artificial Intelligence. Source: [1] . . 23 3.2 Overfitting and underfitting in regression and classification models. Source:[25] ................................ 27 3.3 Model training and validation process. Source: [30] . . . . . . . . . . 35 3.4 Illustration of 5-fold cross-validation. Source: Scikit-learn [83]. . . . . 36 3.5 Sigmoid function. Source: [32]. . . . . . . . . . . . . . . . . . . . . . 37 3.6 SVM finding the maximum margin separation between labelled data. Source:Wikipedia[33]........................... 39 3.7 Non-linear transformation and finding of a separating hyperplane in the transformed space. Source: [36] . . . . . . . . . . . . . . . . . . . 43 3.8 Decision Tree parts. Source: [39] . . . . . . . . . . . . . . . . . . . . 44 3.9 Gradient descent on a series of level sets. Source: [41] . . . . . . . . . 45 3.10 Gradient Descent and Stochastic Gradient Descent on a series of level sets comparison. Source: [47] . . . . . . . . . . . . . . . . . . . . . . 47 3.11 Boosting algorithm classifiers. Source: [50] . . . . . . . . . . . . . . . 48 3.12 Boosting algorithm final classifier. Source: [50] . . . . . . . . . . . . . 49 3.13 Classifier weight as a function of error. Source: Own elaboration extractedfrom[48] ............................ 50 3.14 LDA maximising the component axes for class-separation. Source: [56] 56 4.1 NLP taks and applications. Source: [57]. . . . . . . . . . . . . . . . . 59 4.2 Identification of spam emails by text classification. Source: [60]. . . . 61 4.3 Plutchik’s wheel of emotions. Source: [62] . . . . . . . . . . . . . . . 63 4.4 Human raters assess the quality of translations for a given source sentence by comparing them. The raters assign scores ranging from 0 (nonsense) to 6 (perfect translation). Source: [66] . . . . . . . . . . 67 4.5 An overview of the NMT architecture (encoder-decoder framework). Source:[67] ................................ 68 III
Chapter 2 Language Normalisation It is crucial to understand the basic concept of natural language, which refers to any language that has evolved naturally in humans through use and repetition without conscious planning or forethought. Natural languages can take different forms, such as speech, written or signing. Estimates of the number of human languages in the world vary between 5,000 and 7,000, depending on distinction between languages and dialects, respectively. Despite the variety of vocabulary in our mother language, we only use at most 10% of words in a day-to-day setting. This ambiguity makes it inherently hard for computers to process and understand natural language. This difficulty increases when sentiments influence human language with sarcasm, irony, metaphors and humour. Moreover, social networks are changing human language with the introduction of emojis and new terminology resulting from current trends. To analyse a natural language, it has to be distinguished the different linguistic characteristics for text and speech analysis. These categories found in table 2.1 are useful to provide a rich set of representations for machine learning algorithms. Text analysis Morphology Word structure Lexical Segmenting words Syntax Sentence structure Semantics Linguistic meaning Discourse Meaning among sentences Pragmatics Meaning through speaker intent Speech analysis Acoustics Representations of sound Phonetics Speech sounds Phonemics Sound patterns and changes Prosodics Intonation, stress, and rhythm Table 2.1: Summary of language analysis categories. Source: [1] Natural language processing is the mapping of language to representations which capture the characteristics of morphology, dictionaries, syntax, semantics or discourse. The choice of the representation can have a major impact on subsequent tasks and will depend on the selected machine learning algorithms. 4
Chapter 2. Language Normalisation 2.1. Morphological Analysis In the following sections of this chapter, we will dive into these representations to better understand their role in linguistics and purpose in natural language processing. In this work, we will focus on the most common text-based representations and the preprocess methodology to follow. 2.1 Morphological Analysis Within the discipline of linguistics, morphology is the study of the structure and formation of words. This refers to the rules and conventions used to shape words depending on their contexts, such as plural, gender, contraction and conjugation. Words are composed of subcomponents called morphemes, which are the smallest unit of meaning in a language. Morphemes can be classified into free or bound morphemes: Free morpheme: a morpheme which is a word by themself, such as “run”, “dog” or “book”. They can also appear within lexemes such as “bookstore”, which is the compound of two free morphemes: “book” and “store”. Bound morpheme: a morpheme that cannot stand alone as a word but must be attached to a free morpheme to create a word. Here, it is important to make a distinction between two classes: inflectional and derivational. – Inflectional bound morphemes: they add information about grammatical number, gender or verbal tense. Some examples are “dogs”, “prince” to “princess” or “booked”. – Derivational bound morphemes: create new words by adding affixes, which are prefixes when added to the front of a word and suffixes when added to the back. Another less common types are infixes, when added in the middle of a word, and circumfixes, which consists of two parts, one attached to the beginning and the other to the end of the word. They directly change the meaning of words as well as the part of speech. For instance, adding the suffix -er to the root run creates the word “runner”, which has been tranformmed from a verb to a noun. Despite the diversity of possible morpheme combinations, English has simple morphologic rules in comparison to other languages like Arabic [6]. For this reason, computers have to consider morphological analysis, whose main normalisation approaches are stemming and lemmatisation. Both truncating techniques aim to simplify text processing by reducing words to their root or base form and are widely used in different applications such as information retrieval, machine translation, text classification and tagging systems. These and even more applications will be discussed in section (4). 5
Chapter 2. Language Normalisation 2.1. Morphological Analysis 2.1.1 Stemming Researcher J.B. Lovins defines stemming in his publication Development of a Stemming Algorithm [7] as: “A stemming algorithm is a computational procedure which reduces all words with the same root (or, if prefixes are left untouched, the same stem) to a common form, usually by stripping each word of its derivational and inflectional suffixes.” Stemming can be useful for standardising vocabulary since the stem and their inflected words have related meaning, which allows to build relationships between them. However, due to the cut of the end beginning of a word, this process can result in stems that are not real words. In addition to this, stemming can introduce ambiguity, as it is shown in the following example: photographs →photograph photographed →photograph photographers →photograph Although humans can easily identify differences in meaning, it is still difficult for computers to do so through stemming. It is relevant to notice that words with different meanings have the same stem: “photographers” and “photographs” (people versus items). On the contrary, this shows that stemming is robust to spelling errors, as the correct root may still be inferred correctly. From 1960s, several stemming algorithms, which are known as stemmers, have been developed. The most popular algorithm is the Porter stemmer, which was published in 1980 by Martin F. Porter, in the paper An algorithm for suffix stripping [8]. It consists of five steps to remove suffixes, within each step, rules are tested until a condition is satisfied. For this particular rule, the suffix is removed, and the algorithm goes to the next step. The rules have the following structure: (condition) suffix −→ new suffix For instance, the rule (2.1.1) means that the words whose stem contains a vowel should be removed the ing suffix. So, “motoring” becomes “motor”, while “sing” remains unchanged. The algorithm consists of 60 rules approximately, which can be found in [9]. (*v*) ING −→ (2.1.1) A few years later, Martin Porter implemented some corrections in a new algorithm known as Snowball Stemmer, as a tribute to SNOBOL1. While Porter 1SNOBOL (”StriNg Oriented and symBOlic Language”) is a programming language developed in the 1960s for text and string manipulation. It has built-in support for pattern-matching and search capabilities, and is designed to handle complex pattern matching and text processing tasks that are difficult or impossible to express in other programming languages. 6
Chapter 2. Language Normalisation 2.1. Morphological Analysis Stemmer can only be used in English, Snowball Stemmer supports 13 languages, incluiding French, German and Spanish. Snowball is characterised to be more aggressive but also more accurate than Porter stemmer. Another relevant algorithm is Lancaster stemmer, which was developed by C.D. Paice at Lancaster University in 1990. This is an iterative algorithm containing 120 rules, which are only applicable to English. Compared with the previous stemmers, Lancaster is the most aggressive. Python: With the aim of implementing these stemmer algorithms in Python, NLTK (Natural Language Toolkit) is used. This is a Python library used for natural language processing into we will dive in the subsection (5.1). Therefore, the first step is to download and import this library. To use stemmers, import the corresponding algorithm from the module nltk.stem. For instance, Martin Porter algorithm corresponds with the PorterStemmer class, from which we have to create an instance. Then, use the stem() method for each word by passing it through a for loop to evaluate different examples. An analogous implementation can be made for the rest of stemmers. Word Porter Snowball Lancaster program program program program programming program program program programer program program program programs program program program programmed program program program people peopl peopl peopl procedure procedur procedur proc successful success success success photographers photograph photograph photograph photographs photograph photograph photograph protographed protograph protograph protograph unacceptable unaccept unaccept unacceiv fairly fairli fair fair sportingly sportingli sport sport universal univers univers univers university univers univers univers data data data dat datum datum datum dat Table 2.2: Porter, Snowball and Lancaster algorithms results for a list of words. Source: Own elaboration (see section (7)). As it is displayed in table 2.2, the stemmers were able to correctly reduce each word to its base form, but some are not perfect and can sometimes result in stem words that are not actual words or might be too aggressive in their stemming, as it is the case of Lancaster algorithm. 7
Chapter 2. Language Normalisation 2.1. Morphological Analysis Regarding incorrect stemmisation, there are two types of errors: Over-stemming: is when two words with different stems are stemmed to the same root. Statistically, this definition matches what is known as a false positive. In the table 2.2, “universal” and “university” are a clear overstemming example. This would imply that both words have a similar meaning, which is not correct. Under-stemming: is when two words that should be stemmed to the same root are not. This corresponds to a false negative. If we consider the stemming of “data” and “datum” shown in table 2.2, we can see that only the Lancaster algorithm does in the correct way since both words have the same stem and meaning. However, this occurs mainly because Lancaster is the most straightforward stemmer. On general, stemmers which reduce over-stemming errors, increase under-stemming, and viceversa. A good stemmer algorithm would be one that finds the balance between these two extremes. 2.1.2 Lemmatisation In the chapter Lemmatisation as a Tagging Task [13], lemmatisation is defined as the following: “Lemmatisation is the task of grouping together word forms that belong to the same inflectional morphological paradigm and assigning to each paradigm its corresponding canonical form called lemma.” Lemma refers to a word form that exists and has meaning by itself, being found in the dictionary. For this purpose, lemmatisation relies more on morphological analysis of words, using a sophisticated approach that takes into account the part of speech and the word context in the sentence. This requires the existence of dictionaries for each language to provide this type of analysis. However, such dictionaries are created manually and cannot be developed quickly in many languages. To understand the differences with stemming, we can analyse the previous example: photographs →photograph photographed →photograph photographers →photographer Now, we can see that the meaning of each word is considered and remains. The results are similar to those of stemming, but they are actually words. In contrast to stemming, meaning and context are considered. On the other hand, lemmatisation is sensitive to spelling errors, which requires a preprocessing task for spell correction 8
Chapter 2. Language Normalisation 2.1. Morphological Analysis and it is slower because of looking up in a dictionary. Python: We consider the implementation in Python with NLTK package, from which we download WordNet (see section (2.1.2.1)) lemmatiser. Firstly, we create an instance of the lemmatiser and use its lemmatize() method to lemmatise a word. For this, we have to indicate in the argument pos the grammatical category, or also known as part of speech (POS) tags of each word. These grammatical categories are vfor verbs, afor adjectives, rfor adverbs and nfor nouns, which is the default option. With this information, the words are lemmatised accordingly and the result are actual words. The results are shown in table 2.3, which can be compared with the stemming methods in in table 2.2. Word POS Lemmatisation program n program programming v program programer n programer programs v program programmed v program people n people procedure n procedure successful a successful photographers n photographer photographs n photograph photographed v photograph unacceptable a unacceptable fairly r fairly sportingly r sportingly universal a universal university n university data n data datum n datum Table 2.3: Lemmatisation results indicating the corresponding POS tag. Source: Own elaboration (see section (7)). Words are reduced to their canonical form, lemma, which has meaning by itself. The main problem is that words that cannot be found in WordNet will remain unchanged and that the POS tag has to be included in this method to obtain better results. To summarise, here you can find a table 2.4, which compares the benefits and drawbacks between stemming and lemmatisation. 9
Chapter 2. Language Normalisation 2.1. Morphological Analysis Advantages Disadvantages Stemming Model performance Overstemming Grouping similar words Understemming Easier to analyse and understand Language difficulties Robust to spelling errors Not actual words Lemmatisation Accuracy Time-consuming Actual words Sensitive to spelling errors Table 2.4: Advantages and disadvantages of stemming and lemmatisation. Source: Own elaboration. 2.1.2.1 WordNet Since there are words that can have multiple different lemmas, lemmatisation algorithms or lemmatisers need the part of speech tag in that specific context. For this purpose, WordNet [15] is used as an English dictionary for lemmatisation. WordNet was released in 1986 at Princeton University by Christiane Fellbaum. It consists of a large semantic network or graph in which words are interconnected by means of labelled arcs that represent meaning relations. This database is organised in synsets, which each refers to a set of words which are semantically equivalent (or, also known as synonyms). This can be seen as a many-to-one mapping of word forms and concepts. Synsets can be seen as the nodes of WordNet and edges as meaningbased relations. Nowadays, there are 117000 synsets, each one corresponding to one category: nouns, verbs, adjectives and adverbs. Regarding another semantic representation present in table 2.5, polysemy can be captured when the same word appears in different synsets, each with their own synonyms, since this would imply that it has distinct meanings. In contrast, antonyms are linked by an “antonym” pointer between words. Synonymy Words having the same meaning Antonymy Words having the opposite meaning Polysemy Word with two or more distinct meanings Hypernymy Generic word whose meaning includes other words (hyponyms) Hyponymy Specific word whose meaning is included in a broad category (hypernym) Table 2.5: Semantic relations between words. Source: [1] Considering that WordNet is a graph, there is an important semantic relation which can be represented through directed edges: hypernymy and hyponymy. In this way, we link specific concepts to more general ones, but it could also be seen the other way around, as a bi-directional relation, from a global category to a particular case. However, with the aim of representing it as a directed graph, we will consider that each directed edge v→wmeans that wis a hypernym of v, or equivalently, vis a hyponym of w. For example, the synset gym shoe, sneaker, tennis shoe is a hyponym of shoe, which in turn is a hyponym of footwear, footgear, etc. And gym shoe, sneaker, tennis shoe is a hypernym of plimsoll, which denotes a specific type of sneaker ([15] pp. 233). This is how this hierarchical relation is constructed, 10
Chapter 2. Language Normalisation 2.1. Morphological Analysis entity abstraction relation part substance medium solvent remover protoplasm platelet activator catalyst enzyme complement superoxide_dismutase protease angiotensin_converting_enzyme essence mixture alloy steel copper-base_alloy bronze brass pewter composition soup compost paste colloid sol emulsion gel suspension vapor steam water_vapor spray slurry mash matte plaster grout spackle stucco solution sap injection gargle infusion dilution electrolyte solid_solution double_salt alum alum toner atom isotope radioisotope label chemistry fluid liquid alcohol methanol sterol cholesterol glycerol ethyl_alcohol liquor distillate ammonia_water ink antifreeze medium coolant element water earth fire air quintessence material aggregate chemical softener phytochemical carotenoid carotene flux compound buffer incense fixing_agent hypo formulation polish starch nebula complex hydrochloride binary_compound ammonia ammonium water slush seawater dishwater fresh_water condensate rain chloride siloxane silicone salt phosphate halide chloride fluoride cyanide sodium_carbonate sulfate calcium_sulphate gypsum alabaster plaster_of_paris carbonate bicarbonate synthetic rubber acid carboxylic_acid acetic_acid vinegar preservative spice polymer polyamide nylon synthetic_resin polyester polyethylene vinyl_polymer styrene polystyrene caustic lye oxide silica peroxide calcium_oxide trioxide arsenic dioxide monoxide ferric_oxide rust sulfide hydroxide hydroxide calcium_hydroxide repellent repellent derivative nitrate nitroglycerin base menthol stripper enamel organic_compound ester glyceryl_ester glyceride triglyceride polyester urethane nucleotide adenosine_monophosphate neurochemical neurotransmitter endorphin amide peptide macromolecule lipid fat animal_fat butterfat myelin oil essential_oil turpentine grease animal_oil blubber petroleum lemongrass wax cerumen beeswax protein antibody antitoxin simple_protein scleroprotein keratin gelatin conjugated_protein hemoprotein hemoglobin carbohydrate monosaccharide aldose aldohexose glucose ketose ketohexose fructose hexose oligosaccharide disaccharide lactose polysaccharide cellulose pulp starch cornstarch ether nitrile hydrocarbon octane kerosene bitumen pitch gasoline provitamin provitamin_a aromatic_hydrocarbon benzene resin natural_resin amber anime copal zanzibar_copal oleoresin turpentine balsam balm aliphatic_compound methane_series amine monoamine monoamine_neurotransmitter serotonin dopamine methane butane acetylene aldehyde formaldehyde steroid ketosteroid ketone acetone alkaloid nicotine caffeine ephedrine tenderizer stabilizer fertilizer organic manure restrainer fraction explosive gunpowder product pesticide spray insecticide carrier fumigant particulate dust fallout fiber fibril string lint man-made_fiber natural_fiber plant_fiber hemp straw cotton staple animal_fiber wool fleece cashmere alpaca silk horsehair filling cement discharge exudate gum frankincense lacquer latex rubber humate lignite jet waste sewage rubbish debris slack litter exhaust garbage pollutant impurity filth slop body_waste fecal_matter crap droppings urine earth soil mold clay adobe subsoil mud slop topsoil sand gumbo silt foam hazmat plant_material plant_product wood matchwood matchwood brushwood driftwood log sawdust knot wicker hardwood softwood chaff bran cork sorbent absorbent_material absorber sponge packing_material cardboard card coloring_material indicator acid-base_indicator litmus stain pigment dye bluing hair_dye henna pigment sepia watercolor lake lake animal_pigment melanin rock gravel ballast shingle marble sedimentary_rock slate arenaceous_rock sandstone brownstone grit shale limestone magma pudding_stone igneous_rock batholith granite volcanic_rock lava volcanic_glass obsidian pumice matrix impregnation precursor builder toner conductor copper semiconductor silicon silver animal_material shell horn whalebone tortoiseshell animal_product animal_skin fur mink beaver bearskin chinchilla raccoon seal leopard squirrel lapin otter muskrat lambskin hide goatskin cowhide parchment leather grain pigskin suede crushed_leather horsehide calf alligator sheepskin kid cowhide buckskin buff mocha lac shellac dentine ivory bone mineral opal ore fluorite corundom sapphire zircon jargoon hyacinth turquoise asphalt talc spar calcite chalk alabaster quartz rock_crystal rhinestone amethyst chalcedony onyx sard plasma topaz garnet borax amphibole asbestos beryl emerald topaz atom dust sealing_material filler putty size sealant adhesive_material paste wafer cement glue birdlime binder fluff ammunition abrasive emery_paper thickening insulator raw_material wad paper blotting_paper wallpaper chad dimpled_chad newspaper tissue flypaper pad notepad crepe papyrus manifold_paper carbon_paper oilpaper linen parchment contaminant medium body_substance liquid_body_substance serum whey secretion hormone steroid_hormone corticosteroid hydrocortisone cortisone estrogen androgen testosterone pheromone nectar musk chemical_element noble_gas argon neon helium radon iodine arsenic sulfur brimstone phosphorus oxygen plutonium carbon diamond charcoal graphite pencil radiocarbon carbon_black metallic_element noble_metal gold platinum iron aluminum nickel zirconium sodium radium tungsten cobalt magnesium uranium lithium zinc titanium potassium tin chromium chrome cadmium calcium nitrogen hydrogen chlorine group halogen attribute shape amorphous_shape space opening hole knothole physical_entity thing unit molecule group vinyl alkyl ethyl nitrite amino object whole artifact paving asphalt blacktop tarmacadam building_material shingle flooring fencing_material staff lumber board deal planking roofing_material slate tile covering_material fiberglass linoleum puddle cement concrete cement mortar insulating_material corkboard instrumentality device instrument weapon weapon_of_mass_destruction chemical_weapon tear_gas natural_object covering bark phellem plant_part plant_organ reproductive_structure fruit seed oilseed linseed location region layer snow crud causal_agent agent vasoconstrictor agent bleaching_agent coagulant chemical_agent oxidant hydrogen_peroxide scavenger wetting_agent detergent antacid inducer drug dilator vasodilator medicine bronchodilator matter antimatter residue ash emanationectoplasm solid glass lead_glass paste natural_glass quartz_glass precipitate sludge powder crystal ice hailstone icicle gem transparent_gem opaque_gem jade coral twins plastic vinyl thermoplastic celluloid sludge fluid gas ozone propane air breath halitus halitosis liquid elixir vegetable_matter coal glop system substance poison toxin plant_toxin hemlock neurotoxin animal_toxin venom metabolite food culture_medium nutriment vitamin water-soluble_vitamin b-complex_vitamin vitamin_b1 vitamin_b2 niacin leaven sourdough yeast mother carcinogen vehicle lubricant philosopher's_stone jelly refrigerant inhibitor moderator antioxidant fuel fire coke fossil_fuel natural_gas firewood backlog brand igniter kindling punk allergen propellant process phenomenon natural_phenomenon physical_phenomenon atmospheric_phenomenon condensation dew substance Save as Image http://localhost:8000/force/tree.html 1 of 1 21/07/2014 22:04 Figure 2.1: The WordNet example representation as a rooted DAG. Source: [16] where scaling through all noun synsets, we can reach to a common node. This root corresponds to the concept entity, which encompassess all things that exist in the world, incluiding physical entity,abstract entity and thing. For these reasons, WordNet can be seen as a directed acyclic graph (DAG), though not a tree since each synset can have several hypernyms. In figure 2.2, there is a graphical example of the is-a relationship, which joins a hyponym to a hypernym [17]. As before, for this particular case, a birdcage is a hyponym to cage, and cage is a hyponym to enclosure. These mathematical concepts are explained below, and are useful because it provide researchers with DAG properties and tools, which can be very useful to implement in NLP. Definition 2.1.1. Adirected graph G is a pair G=(V, E) comprising: V: a set of vertices (nodes). E: a set of directed edges, which are ordered pairs of distinct vertices. E⊆ {(x, y)|(x, y)∈V2, x =y} Definition 2.1.2. Acycle in a graph G = (V, E) is a sequence of distinct vertices v1, v2, . . . , vk∈Vsuch that vivi+1 ∈E(G)∀i= 1, . . . , k −1and v1vk∈E(G). 11
Chapter 2. Language Normalisation 2.1. Morphological Analysis Cage, coop Entity Entity, physical thing Object, physical object Natural object Artefact, artifact Plant part Plant organ Plant root Carrot Radish Enclosure Cage, coop Birdcage Squirrel cage Hutch Figure 2.2: The “is a” relationship. Source: [17] Definition 2.1.3. Adirected acyclic graph (DAG) is a directed graph, with no directed cycles. Definition 2.1.4. A vertex vis an ancestor of win graph G if v=wor there is a directed path in G from wto v. Definition 2.1.5. Aroot in a graph is a vertex which is an ancestor of every other vertex. Regarding the NLP problem of establishing similarity relationships between words, WordNet DAG plays a vital role since it allows to find the shortest path which connects two words. For this, new concepts are introduced: Definition 2.1.6. An ancestral path between two vertices vand win a digraph (directed graph) is a directed path from vto a common ancestor x, together with a directed path from wto the same ancestor x. Definition 2.1.7. Ashortest ancestral path between two vertices vand wis an ancestral path of minimum total length. In other words, it is the shortest path between these two vertices that leads to their closest common ancestor. Note that the length of the shortest path between vand wis the combination of the lengths from both vand wto their nearest common ancestor. In relation to NLP, if uis an ancestor of v, this means that uis a hypernym of v, or the other way around, vis an hyponym of u. 12
Chapter 2. Language Normalisation 2.2. Lexical Representations A document-term matrix is a matrix that describes the frequency of terms that occur in a collection of documents. In this case, rows correspond to documents and columns correspond to terms. However, it is also common to use the transpose, which is known as term-document matrix. The entries of the matrix can be computed with different methods, which are explained below. These matrices are often stored as a sparse matrix object, which can be treated as though they were matrices, but are stored in a more efficient format. 2.2.3.1 Bag-of-Words The bag-of-words (BoW) set each entry of the document-term matrix equal to the frequency of word occurrence within each document. This process is also known as count vectorisation. Therefore, each document (row) can be represented by a high dimensional sparse vector, where each component corresponds to the term frequency of a unique word within a dictionary. In other words, the bag-of-words is basically the absolute frequency fij of word jin the document i. As mentioned in section (2.2.2), the most frequent words tend to be the less relevant regarding semantics. To solve this issue, it is enough to remove stop words in a preprocessing step. This also allows to reduce the dimension of the matrix and save memory, but still the matrix would contain many 0s (sparse matrix), which can be computationally challenging. This is why lowercasing, stemming or lemmatisation are also carried out before constructing the BoW to reduce the dimension of the vocabulary. Another drawback is that it only takes into account the spelling. Therefore, a word appearing with different meanings (polysemic) in the same document will not be distinguised. Alternative method: Since absolute frequencies can be influenced by the length of each document, normalisation could also be applied using relative frequencies. These are some possible implementations: Respect the maximum frequency per document, denotaded by max j∈Jfij :fij maxj∈Jfij . Respect the total number of occurrences per document: fij Pw∈Wfiw . 2.2.3.2 TF-IDF Term Frequency (TF) - Inverse Document Frequency (IDF) is a numerical statistic whose aim is to reflect the importance a word has in a document within a corpus. It is a document representation where a penalty coefficient is applied to common words in different documents. It is based on the following ideas: 1. The most frequent terms in a given document should have a higher relevance than the rest of the words. This is implemented through the Term Frequency 19
Chapter 2. Language Normalisation 2.2. Lexical Representations (TF) as the relative frequency explained before TFij =fij Pw∈Wfiw (2.2.2) where fij denotes the number of ocurrences of term jin the document i. This can also be defined using the logarithmically scaled frequency as: 1 + log (TFij) (2.2.3) 2. The terms occurring multiple times in different documents of the corpus do not help to determine the unambiguous content of a text and should therefore be penalised. To consider this, the Inverse Document Frequency (IDF) is calculated IDFj= log N nj(2.2.4) where Ndenotes the total number of documents and njis the number of documents containing the term j. Therefore, the result TF-IDF is the combination of both criteria so that the associated weights are directly proportional to the occurrences of the term in a document and at the same time, it reduces the TF-IDF value for the term based on the frequency across all documents. Combining the previous equations 2.2.2, 2.2.3 and 2.2.4, assuming a logarithmic scale, TF-IDF is obtained: TF-IDFij = (1 + log (TFij)) ×IDFj=1 + log fij Pw∈Wfiw ×log N nj (2.2.5) Suppose there is a term that is present in all the documents of the corpus, that is to say, nj=N. This would imply that IDFjwould be 0 since the fraction of the logarithm would be 1, and therefore, the value of TF-IDF is 0 too. This is how terms which do not add useful information are completely penalised. Currently, TF-IDF is one of the most popular weighting method, with wellknown libraries using it. Some practical examples are explained in section (7) for better understanding of these methods. 2.2.4 N-Grams Word level representations have limitations in capturing the relationship with adjacent words, hindering the ability to incorporate grammar and context. The bag-of- words model, based on a Markov assumption, disregards word order and focuses solely on token presence and frequency. This model predicts a phrase containing L tokens with probability [1]: P(w1, w2. . . wL) = L Y i=1 P(wi) (2.2.6) 20
Chapter 2. Language Normalisation 2.2. Lexical Representations However, there are many situations where sequences of words are relevant. For this reason, another approach known as n-gram is very useful in NLP. An n-gram is a sequence of nconsecutive words or tokens in a text. In this case, the probability would be predicted as: P(w1, w2. . . wL) = L Y i=n P(wi|wi−1wi−2wi−n) (2.2.7) Note that equation (2.2.6) is a particular case for n= 1 in equation (2.2.7). This is also known as unigram. Another particular case are bigrams, which considers two consecutive words. They distinguish between “lion king” and “king lion” [1]. Then, a sentence of Ltokens would yield L−1 bigrams: P(w1, w2. . . wL) = L Y i=2 P(wi|wi−1) (2.2.8) This can be useful to solve the problem of tokens, where United States was considered as two separate tokens and using a bigram we would be able to capture this relationship in a unique token. 21
Chapter 3 Machine Learning Machine Learning (ML) has emerged as a powerful discipline that enables computers to learn from data and make predictions or decisions. In this chapter, we dive into the fundamentals of ML, with a primary focus on supervised learning. We will explore the statistical learning theory, the trade-off between bias and variance, model performance evaluation and model validation techniques. Moving further, we distinguish between discriminative and generative classifiers. Discriminative classifiers focus on learning the decision boundary between different classes, while generative classifiers model the underlying distribution of each class. We provide a comprehensive explanation of logistic regression, support vector machines (SVM), decision trees, gradient descent (GD), stochastic gradient descent (SGD), boosting, gradient boosting, and XGBoost as prominent examples of discriminative classifiers. Additionally, we explore Naive Bayes and Linear Discriminant Analysis (LDA) as examples of generative classifiers. 3.1 Introduction Learning is the process of converting information and experience into knowledge and understanding, which is measured by the ability to perform certain tasks independently [23]. Machine learning is therefore a field dedicated to building methods that let machines learn (learning process) so that they could carry out tasks without assistance. Machine Learning is a subcategory of Artificial Intelligence (see figure 3.1), which refers to the simulation of human intelligence in machines, programmed to execute tasks that would typically require human intelligence. The key difference is that while AI is about creating machines that can reason and make decisions like humans, Machine Learning is about developing algorithms that enable machines to learn from data and improve their performance over time. Mathematically, Machine Learning encompasses approximation theory, probability and optimization theory. The goal is to learn, which implies finding a function that models the outputs appropiately according to the inputs. h:X → Y 22
Chapter 3. Machine Learning 3.1. Introduction Artificial Intelligence Machine Learning Deep Learning Neural Networks Unsupervised Learning Supervised Learning Reinforcement Learning Figure 3.1: Machine Learning as a subset of Artificial Intelligence. Source: [1] This function hmaps the space of inputs or characteristics Xto the space of outputs or responses Y. Such a function is called a hypothesis, a predictor or a classifier. Another common name is binary classifier when dealing with problems with two categories, which can be coded as 0 and 1, or −1 and 1. Machine Learning can be divided into the following areas, which are also shown in figure 3.1: Supervised Learning: it consists of learning from answers (labels) belonging to a collection of data {xi, yi}n i=1 ⊂ X×Y. This input data allows the model to adjust its weights until it has been fitted appropriately, considering a balance between overfitting and underfitting. Depending on the type of output, there are two types of supervised learning: – Classification: labels correspond to a fixed set of categories. For instance, classifying a new as either fake or true. – Regression: the output would be a real number. For instance, predicting the cost of buying a house in the future. Neural networks, Na¨ıve Bayes, linear regression, logistic regression, random forest and support vector machine (SVM) are common algorithms used in these tasks. Unsupervised Learning: it determines clusters from data where there are no labels present. These algorithms discovers hidden patterns of similarities and differences. Not only is unsupervised learning used for grouping, but it is also used to reduce the number of features in a model through the process of dimensionality reduction. 23
Chapter 3. Machine Learning 3.2. Supervised Learning Principal component analysis (PCA), singular value decomposition (SVD) and k-means clustering are methods used in unsupervised learning. Semi-Supervised Learning: it is a combination of the previous ones, that is to say, the entire set is not labelled or it is expensive to label all the data. Reinforcement Learning: it focuses on maximising a reward or penalty associated with an action or environment provided as input. The algorithms are trained to encourage certain sucessive actions or behaviours. It is common to use these techniques for games, where the reward may be winning the game and a number of actions must to be taken before. Regarding figure 3.1, Deep Learning is a subset of Machine Learning that involves the development of neural networks with multiple layers that can learn and make decisions based on complex data inputs. In essence, it is a type of machine learning algorithm that uses artificial neural networks to simulate the function of the human brain, allowing machines to learn from large amounts of data and improve their performance over time. 3.2 Supervised Learning As previously stated, supervised machine learning consists of learning from answers (labels). Then, some concepts are introduced to build the basic framework. Let Xbe the population of all possible data for a particular learning problem (e.g., distinguish between fake and true news). From X, samples can be obtained independently with an unknown probability distribution P(X). Therefore, a sample X of nelements or also known as instances can be represented as X=x1,x2,...,xn. It is clear that X⊆ X. The input space Xis modelled as a metric space Rd, in which the dimension drefers to the attributes or features. These features can be: Categorical or qualitative variables represent characteristics or attributes that can be observed and categorised but not measured numerically. They can also be distinguised between: – Ordinal: when there are a discrete categories or levels. For example, quality ={poor, fair, good, excellent}. – Nominal: describe categories that do not have a specific order to them. For instance, gender ={male, female}. Numeric or quantitative variables represent numerical quantities that can be measured or counted. These variables have meaningful numerical values and allow for mathematical operations such as addition, subtraction, multiplication and division. A further distinction could be made: – Discrete: takes a finite number of values. Examples of discrete variables include the number of siblings a person has, the number of cars in a parking lot and the number of customers in a store at a given time. 24
Chapter 3. Machine Learning 3.2. Supervised Learning – Continuous: can be a scalar in Rand can be measured on a continuous scale. Examples of continuous variables include length, weight, speed and income. This is a general classification of variables, which also includes the output (labels). As mentioned in the introduction (3.1), when the output is categorial, the problem is to classify, whereas a numerical output involves a regression problem. Therefore, each instance can be seen as a d-dimensional vector, which together with the whole sample Xof nelements, a n×dmatrix can be obtained. Each row would be the vector xicorresponding to the i-th instance of the sample, and its label yicould be stored in a vector Y. X= x1 x2 . . . xn = x11 x12 ··· x1d x21 x22 ··· x2d . . .. . ..... . . xn1xn2··· xnd ,Y= y1 y2 . . . yn (3.2.1) We can also represent the sample as a labelled dataset D: D={(x1, y1),(x2, y2), . . . (xn, yn)}(3.2.2) 3.2.1 Statistical Learning Theory In addition to the probability distribution P(X), there is another unknown element referred to as the target function. This function f:X → Y maps the input space Xto the desired output space Y. The goal in machine learning is to approximate the function fwith a function hfrom a large hypothesis space H, based only on the knowledge of a finite sample as Din (3.2.2). The evaluation of the best fit is measured by a loss function or also known as cost function. Definition 3.2.1. Aloss function L:Y ×Y → R+is a function that measures the mismatch between a prediction on a given input x∈ X and its label y∈ Y, and associate a cost. There are different loss functions, but we will focused on two approaches depending on the type of problem. For classification problems, an indicator loss function is commonly used: L(h(xi), yi) = 1{h(xi)=yi}=(1 if h(xi)=yi 0 if h(xi) = yi(3.2.3) Notation: 1A(x) denotes the indicator function. Then, if x∈A,1A(x) = 1, and 1A(x) = 0 otherwise. For regression problems, where the output is a real number, the square error is used as a loss function: L(h(xi), yi)=(h(xi)−yi)2(3.2.4) 25
Chapter 3. Machine Learning 3.2. Supervised Learning Definition 3.2.2. The empirical or training error of a function h:X → Y is the average loss L(h(xi), yi)over the training data. ˆ R(h) := 1 n n X i=1 L(h(xi), yi) (3.2.5) Therefore, substituting the loss function expression in (3.2.5) with the corresponding forms used for classification and regression problems in equations (3.2.3) and (3.2.4), respectively, it is obtained: ˆ R(h) = 1 n n X i=1 L(h(xi), yi) = 1 n n X i=1 1{h(xi)=yi}(3.2.6a) ˆ R(h) = 1 n n X i=1 L(h(xi), yi) = 1 n n X i=1 (h(xi)−yi)2(3.2.6b) The equation (3.2.6a) is the final expression of the empirical error for classification problems, while (3.2.6b) is used in the regression case. All things considered, the main objective was to find an approximation function hamong a set Hclose to the target function. Using the previous concept introduced, we can formulate an optimisation problem whose aim is to minimise the empirical error: min h∈H ˆ R(h) (3.2.7) However, if this was the only objective, the result would lead to overfitting because the optimal solution would be any function hthat satisfies h(xi) = yi∀i={1, . . . , n}(3.2.8) This is known as memorisation and it occurs when the function adapts too closely to the seen data. As a result, there is no empirical risk, but the function will perform poorly on unseen data. ˆ R(h) = 1 n n X i=1 L(h(xi), yi) = 1 n n X i=1 L(yi, yi)=0 Therefore, it is vital to consider how the classifier generalise the learning process instead of memorising to be able to forecast unseen data. When a model generalises well, it is able to capture underlying patterns and relationships from the training data and apply them to make accurate predictions or classifications on new instances. Nonetheless, generalisation could lead to the opposite side, underfitting, when the model has not been trained enough on the data. This also lead to a poor classifier or prediction function since it would not predict accurately neither training nor new data and it would only capture a general trend, which is not enough to fit appropiately. These are the reasons why it is important to find a balance between memorisation and generalisation, or, in other words, between overfitting and underfitting. 26
Chapter 3. Machine Learning 3.2. Supervised Learning Figure 3.2: Overfitting and underfitting in regression and classification models. Source: [25] To introduce the concept of generalisation risk, we assume that the training data is considered as samples from a pair of random variables (X, Y ) with an unknown probability distribution X×Y. Definition 3.2.3. The generalisation risk explains how a classifier h∈ H performs on average on unseen data given a loss function L. R(h) := E[L(h(X), Y )] (3.2.9) Note that if we consider the unit loss function, the generalisation risk is the probability of misclassifying a random instance of the distribution X×Y. R(h) := E[L(h(X), Y )] = 1·P({h(X)=Y}) + 0·P({h(X) = Y}) = P({h(X)=Y}) Instead of considering training data to be ninstances {xi, yi}n i=1, the data can be also modelled as sampling from npairs of random variables (Xi, Yi), which are identically distributed and independent copies of (X, Y ). Proposition 3.2.1. The empirical risk ˆ R(h)is an unbiased estimator of the generalisation risk R(h). Proof. For this framework and a given classifier h, the empirical risk is now a random variable, to which the expected value can be applied: E[ˆ R(h)] = E"1 n n X i=1 L(h(Xi), Yi)#lin =1 n n X i=1 E[L(h(Xi), Yi)] iid =n nE[L(h(X), Y )] = E[L(h(X), Y )] = R(h) The linearity property of expectation and the independence and identically distribution of (Xi, Yi) to (X, Y )∀i∈ {1, . . . , n}help to conclude the proof. 27
Chapter 3. Machine Learning 3.2. Supervised Learning Definition 3.2.4. The Bayes classifier is a function that achieves the minimal risk among all possible functions. Mathematically, the Bayes classifier can be expressed as a maximum a posteriori (MAP) estimador as: h∗(x) = arg max yP(Y=y|X=x) (3.2.10) Definition 3.2.5. The excess risk of a classifier h∈ H compares the generalisation risk of this classifier to the Bayes classifier. E(h) = R(h)−R(h∗) (3.2.11) Note that the excess risk satisfies E(h)≥0 by definition. We can decompose the generalisation risk of a given classifier ˆ h∈ H into three quantities: R(ˆ h) = R(ˆ h)−inf h∈H R(h) | {z } Estimation error + inf h∈H R(h)−R(h∗) | {z } Approximation error +R(h∗) |{z} Irreducible error (3.2.12) Estimation error: it is the difference in performance between the classifier ˆ hand the best possible classifier within the class H. Approximation error: it measures how close the best generalisation error in the space His to the one associated with the Bayes classifier (the best among all). Irreducible error: it is the generalisation error associated to the Bayes classifier, and therefore, it cannot be reduced. There is a trade-off between estimation and approximation errors: they are inversely related, that is to say, when one increases, the other decreases. Here, there are the two possible extreme situations: 1. The estimation error is reduced when the classifier ˆ h∈ H is close to the best among the space H. This can be achieved by making Hsmaller, but this would lead to an increase in the approximation error since the space Hwould be too restrictive and it would be more difficult that the Bayes classifier or a closed approximation could be contained in H. 2. On the contrary, the approximation error is reduced by increasing the size of the space Hso that the best within the class could be closer or even equal to the Bayes classifier. This would imply an increase in the estimation error since it would be complex in some situations to find the minimum within a large space H. This is the reason why it is vital to find a balance between them. 28
Chapter 3. Machine Learning 3.2. Supervised Learning 3.2.4 Model Validation In the context of machine learning, model validation refers to the procedure of evaluating and assessing the performance as well as the generalisation capability of a trained model using validation data. It helps to determine the model’s performance on unseen data, offering valuable insights into its effectiveness and reliability. Validation requires selecting a model with the right hyperparameter values. For this, it is crucial that performance should not be measured using the same data that was used for training. Therefore, the first step is to split the data into a training set Dtrain and a validation set Dval. This can be done using the function model selection.train test split from the library sklearn (section (5.3)). The process consists of training the model and then, evaluating this model in the validation set for further improvement, as shown in Figure 3.3. Figure 3.3: Model training and validation process. Source: [30] The main drawback with this methodology is the requisite to have a large dataset for splitting, which sometimes can be a difficult or expensive task. For this reason, an alternative is k-fold cross-validation, in which the dataset is divided into k folds of approximately equal size. The model is trained ktimes, each time using k−1 folds for training and one fold for validation to measure the error Ei V al for a fold i∈ {1, ..k}. These metrics are then averaged across all the iterations to obtain a single estimte of the validation error EV al. EV al =1 k k X i=1 Ei V al This technique provides a more robust estimation of model performance and is less dependent on a single data split. For the smallest datasets, a special case of k-fold cross-validation is used: the leave-one-out cross validation, where only one observation is omitted. The process is illustrated in figure 3.7, which can be used to retrieve information about model performance and also for hyper-parameters search. 35
Chapter 3. Machine Learning 3.2. Supervised Learning Figure 3.4: Illustration of 5-fold cross-validation. Source: Scikit-learn [83]. As mentioned in the previous section (3.2.3), it is important to have a balanced set. In some cases, we may want also want labels to be equally distributed in the training and testing sets. This is called stratification, which can be easily implemented by sklearn.model selection.StratifiedShuffleSplit() or StratifiedKFold method for stratified k-fold cross-validation. 36
Chapter 3. Machine Learning 3.3. Discriminative Classifiers 3.3 Discriminative Classifiers In this section, we are introducing discriminative classifiers that are used in the final section (7). Discriminative classifiers focuses on modelling the decision boundary or the posterior probability of the class labels given the input features P(Y|X). Rather than explicitly modelling the joint probability distribution of the features and class labels, discriminative classifiers directly learn the mapping function from input features to class labels. Discriminative classifiers require labelled training data to learn the mapping function that directly predicts the labels from the input features. This learning should consider unseen data when deciding the best parameters for the model. In classification, a decision rule is required to assign instances to classes. 3.3.1 Logistic Regression Logistic regression extends the ideas of linear regression since it can be seen as a transformation on the linear combination β⊺x, which returns a probability in case of classification. Figure 3.5: Sigmoid function. Source: [32]. This transformation is mainly based in the logit or sigmoid function: σ(x) = 1 1 + e−x=ex ex+ 1 Properties of the sigmoid function: Bounded in (0,1). lim x→∞ σ(x)=1 lim x→−∞ σ(x) = 0 σ(x)′=σ(x) (1 −σ(x)) For a binary classification, then we assume the following framework yi∈ {0,1} and explanatory variables xi1, . . . , xip ,xi∈Rp∀i∈ {1, . . . , n}. In this case, we want to model P(yi= 1|xi) . Since it is a probability, we cannot model it as a linear function as this would return values outside of (0,1). This is the reason why the logit function was used as well as odds ratio to end up modelling their log-odds as a linear function: P(yi= 1|xi) P(yi= 0|xi)=pi 1−pi (3.3.1) Taking the logarithm, it can now take any real value, which can be modelled as an instance of a generalised linear model (GLM). log P(yi= 1|xi) P(yi= 0|xi)= log pi 1−pi=β0+β⊺xi(3.3.2) 37
Chapter 3. Machine Learning 3.3. Discriminative Classifiers where β∈Rp. It sufficies to solve for pito obtain the value modelled by the logit or sigmoid function as: pi=P(yi= 1|xi) = eβ0+β⊺xi 1 + eβ0+β⊺xi=1 1 + e−(β0+β⊺xi)=σ(β0+β⊺xi) (3.3.3) Now, we can know the value of the odds ratio in equation (3.3.1) : P(yi= 1|xi) P(yi= 0|xi)=pi 1−pi =eβ0+β⊺xi The resulting classifier is ˆyi= 1 if pi> c and ˆyi= 0 if pi< c for a threshold c fixed according to classification metrics (section (3.2.3.1)), which is usually 1 2. The problem has been reduced to estimating the parameters β0and βgiven a dataset. Some advantages of logistic regression are that it can detect irrelevant variables (βj= 0) and it also allows for non-linear terms by substituting with a new variable (zk=x2 k). The likelihood given a dataset can be written as: L(x) = n Y i=1 P(yi|xi) Taking the logarithm, we obtain the log-likelihood: log L(x) = n X i=1 log (P(yi|xi)) = n X i=1 (log P(yi= 1|xi) = log(pi) if yi= 1 log P(yi= 0|xi) = log(1 −pi) if yi= 0 log L(x) = n X i=1 (log (σ(β0+β⊺xi)) if yi= 1 log (1 −σ(β0+β⊺xi)) if yi= 0 (3.3.4) This expression (3.3.4) can be rewritten as: log L(σ(x)) = n X i=1 (yilog (σ(β0+β⊺xi)) + (1 −yi) log (1 −σ(β0+β⊺xi))) (3.3.5) As mentioned in section (3.2.1), the loss or cost function can be used to measure how a model performs. In the case of logistic regression, we use the logarithmic cost or cross-entropy function (3.3.5). This loss function can be used to optimise the solution through iterative algorithms as gradient descent (see section (3.3.4)). 38
Chapter 3. Machine Learning 3.3. Discriminative Classifiers 3.3.2 Support Vector Machines Figure 3.6: SVM finding the maximum margin separation between labelled data. Source: Wikipedia [33]. Support Vector Machines (SVM) is considered to be one of the most relevant machine learning algorithm based on statistical learning theory. This model was developed by Vladimir Vapnik and his colleagues (Boser, Guyon and Cortes). SVM is designed to map training examples to points in space with the objective of maximising the margin or width of separation between different categories. This margin represents the gap between the decision boundary of the SVM and the closest data points from each category. Once the mapping is established, new examples can be projected onto the same space and predicted to belong to a specific category based on which side of the margin they fall on. In other words, the SVM classifies new examples by determining which side of the gap they lie on. In the simplest case, given a binary labelled dataset Dlabelled, which corresponds to {(xi, yi)}N i=1, with xi∈ X ⊂ Rand yi∈ {−1,1}, being linearly separable. The goal is to find a hyperplane that separates one class from the other so that we can determine the maximum separation between labels. This problem can be formulated as a linear programming problem: Find the weights w∈Rdand a bias term b∈Rsuch that w⊺x−b≥1 if yi= 1,w⊺x−b≤ −1 if yi=−1 (3.3.6) By convention, the quantities 1 and −1 are used, but any other quantity could be accepted by rescaling wand b. In addition to this, the problem (3.3.6) is equivalent to: yi(w⊺x−b)−1≥0∀i∈ {1, . . . , n}(3.3.7) When the equality of these inequations is reached, that is to say, a point xthat satisfies w⊺x−bequal to 1 or −1 is known as support vector since it is closest to the maximum-margin hyperplane. This hyperplane satisfies w⊺x−b= 0. Denote the distance from the maximum-margin hyperplane to the closest positive and closest negative point by δ+and δ−, respectively. Then, the margin of a classifier is the sum of these two distances δ=δ++δ−. Assume xto be the closset positive point to H={x:h(x) = 0}. Then, w⊺x−b= 1 and δ2 += min z∥x−z∥2such that h(z) = 0 39
Chapter 3. Machine Learning 3.3. Discriminative Classifiers The latter can be formulated using Lagrange multipliers: L(z, λ) = ∥x−z∥2+λh(z) = ∥x−z∥2+λ(w⊺z−b) To solve the optimisation problem, differenciate as follows: ∇zL(z, λ) = 2(x−z) + λw= 0 (3.3.8) ∂ ∂λL(z, λ) = w⊺z−b= 0 ⇒w⊺z=b By multiplying the first equation (3.3.8) by w⊺and substituting then: 2(w⊺x−w⊺z |{z} =b ) + λ∥w∥2= 0 ⇒2(w⊺x−b | {z } =h(x)=1 ) + λ∥w∥2= 0 ⇒λ=−2 ∥w∥2 Once we have λvalue, we can substitue it in equation (3.3.8): x−z=−λw 2=w ∥w∥2 Then, we have found the minimum distance to the closest positive label by applying the norm to the previous equation: δ+=∥x−z∥=1 ∥w∥ The same argument can be applied to the distance closest to the negative label δ− and then, the margin of this particular hyperplane is: δ=δ++δ−=2 ∥w∥ To find the hyperplane with largest margin, we thus have to solve a quadratic optimisation problem: (P) min w,b ∥w∥2 2subject to yi(w⊺x−b)−1≥0∀i∈ {1, ..n}(3.3.9) The Lagrangian of this problem is L(w, b, λ) = 1 2∥w∥2− n X i=1 (λiyiw⊺x−λiyib−λi) = 1 2w⊺w−λ⊺Xw +bλ⊺y+ n X i=1 λi where Xdenotes the matrix with the yixi⊺as rows. Now, we can derive the conditions on the gradient with respect to wand bof the Lagrangian as ∇wL(w, b, λ) = w−X⊺λ= 0 (3.3.10) ∂ ∂bL(w, b, λ) = y⊺λ= 0 (3.3.11) If (3.3.11) is not satisfied, the problem is unbounded and cannot be solved. 40
Chapter 3. Machine Learning 3.3. Discriminative Classifiers If y⊺λ= 0, (3.3.10) is a necessary and sufficient condition for a minimiser. To obtain the Lagrange dual g(λ), we use the conditions (3.3.10) and (3.3.11): g(λ) = (−1 2λ⊺XX⊺λ+Pn i=1 λiif y⊺λ= 0 −∞ else Since, it sufficies to maximise the Lagrange dual problem: max λ≥0g(λ)⇔min λ≥0−g(λ) Then, the dual optimisation problem to solve is: (D) min λ 1 2λ⊺XX⊺λ−λ⊺esubject to λ≥0(3.3.12) where eis the vector whose components are equal to 1. Karush-Kuhn-Tucker conditions are introduced to determine b, since the solution of the dual problem only gives the weights wobtained from w=X⊺λ(equation (3.3.10)). Theorem 3.3.1 (Karush-Kuhn-Tucker conditions).Given a primal problem min x∈Rnf(x) subject to h(x)≤0 l(x) = 0 Assume x∗and (λ∗,µ∗)are the primal and dual solutions to the previous problem, respectively. Then, the following conditions are satisfied: h(x∗)≤0 l(x∗) = 0 λ∗≥0 λ∗ ihi(x∗) = 0,1≤i≤n ∇xf(x∗) + ∇xh(x∗)⊺λ∗+∇xl(x∗)⊺µ∗=0 (3.3.14) Then, combinaning the KKT conditions of the primal problem (3.3.9) with the conditions of the Lagrangian, we obtain the following: Xw −by−e≥0 λ≥0 λi(1 −yi(w⊺x−b)) = 0 ∀i∈ {1, . . . , n} w−X⊺λ= 0 y⊺λ= 0 (3.3.15) We can know bfrom the third equation when λi= 0. Now, we can find the maximum margin hyperplane solving the previous equations since it provides the weights wand the bias term b. 41
Chapter 3. Machine Learning 3.3. Discriminative Classifiers Nevertheless, this method is not applicable when labels are not linearly separable (our main assumption). To solve this problem, we introduce slack variables sito allow some observations to be misclassified. The resulting problem would be: (P) min w,b ∥w∥2 2+µ n X i=1 si subject to yi(w⊺x−b)−1 + si≥0∀i∈ {1, ..n} si≥0∀i={1, . . . , n} where the parameter µdetermines how much weight is given to misclassification, that is to say, if µis large, then siwill be close to 0 and less observations would be misclassified. The restrictions also allow for the i-th point to land on the wrong side if si>1. Following a similar procedure as before, the Lagrangian of this problem can also be retrieved. Despite this new methodology, which can solve non-linearity issues in some cases, it can also not be enough. For this reason, non-linear transformations can be performed through the kernel trick. Note that the dual problem (3.3.12) depends only on the dot product of the data points, the entries of the matrix XX⊺. The trick is to perform non-linear separation by embedding data in higher-dimensional space H: Φ : Rp→ H This function Φ is known as feature map. Definition 3.3.1. A function k(·,·) : Rp×Rp→R is a kernel function if ∀m≥1and x1,...,xm∈Rp, the m×mmatrix Kwith (K)ij := k(xi,xj)is symmetric and positive semi-definite. Proposition 3.3.1. If k(·,·) : Rp×Rpdefined as k(x,y) = ⟨Φ(x),Φ(y)⟩H is a kernel function. Proof. For the proof, we use the definition of a kernel function (3.3.1) to prove that the matrix K defined by Kij =k(xi,xj) is: Symmetric: use the commutative property of the dot product. Kij =k(xi,xj) = ⟨Φ(xi),Φ(xj)⟩H=⟨Φ(xj),Φ(xi)⟩H=k(xj,xi) = Kji Positive semi-definite: for any v∈Rm v⊺Kv= m X i,j=1 viKijvj= m X i,j=1 vik(xi,xj)vj= m X i,j=1 vi⟨Φ(xi),Φ(xj)⟩Hvj =⟨ m X i=1 viΦ(xi), m X j=1 vjΦ(xj)⟩H=∥ m X i=1 viΦ(xi)∥2 H≥0 42
Chapter 3. Machine Learning 3.3. Discriminative Classifiers Theorem 3.3.2 (Moore-Aronszajn theorem: Every kernel has an associated feature map).If k(·,·)is a kernel function, then there exists a Hilbert space Hwith dot product ⟨·,·⟩Hsuch that k(x,y) = ⟨Φ(x),Φ(y)⟩H∀x,y∈Rp By theorem (3.3.2), we can know work with a kernel instead of using the feature map. Some useful kernel functions are: Radial basis function or also known as Gaussian kernel: k(x,y) = e−∥x−y∥2 2σ2 Polynomial kernel of degree p: k(x,y) = (1 + xx⊺)p Now, it sufficies to implement this idea into the (3.3.12) formulation: (D) min λ 1 2 n X i=1 n X j=1 (λiyik(xi,xj)yjλj) + n X i=1 λisubject to λ≥0(3.3.17) Figure 3.7: Non-linear transformation and finding of a separating hyperplane in the transformed space. Source: [36] In summary, the key is to transform the data to a higher dimensional space so that linearity separation could be achieved to classify. 43
Chapter 3. Machine Learning 3.3. Discriminative Classifiers 3.3.3 Decision Tree Decision tree is a hierarchical data structure that represents data through a divide and conquer strategy ([37] pp 2) and it is used for both classification and regression tasks. Figure 3.8: Decision Tree parts. Source: [39] As depicted in table 3.8, the structure of a decision tree begins with a root node that lacks incoming branches. From the root node, branches extend to internal nodes, also referred to as decision nodes. These nodes evaluate the available features to create subsets of data that exhibit homogeneity, which are represented by leaf nodes or terminal nodes. Each leaf node corresponds to a distinct outcome within the dataset, encompassing all the possible results. The maximum depth is the maximum number of nodes between the root note and the lower end. The tree structure is constructed in a recursive manner, where each node splits the data into subsets based on a selected feature. This process continues until a stopping criterion is met, such as reaching a maximum depth or when all the instances in a subset belong to the same class. Once the decision tree is constructed, it can be used for classification or regression tasks. For classification, each instance follows the decision path from the root to a leaf node, and the class associated with that leaf node is assigned as the predicted class for the instance. For regression, the predicted value is determined by averaging the target values of the instances in the leaf node. Decision trees have several advantages. They are easy to interpret and visualise, providing insights into the decision-making process. Decision trees can handle both numerical and categorical features and can capture non-linear relationships in the data. They can also handle missing values and outliers effectively. However, decision trees are prone to overfitting, especially when the tree grows too deep. Techniques like pruning, setting a maximum depth, or using ensemble methods like random forests can help mitigate overfitting. 44
Chapter 3. Machine Learning 3.3. Discriminative Classifiers F∗= arg min FE[L(y, F(x))] (3.3.19) Gradient Boosting searchs for an approximation of (3.3.19) as: ˆ F(x) = M X i=1 αihi(x) (3.3.20) where hi(x) are functions belonging to the class H, which are usually trees. To determine ˆ F, a training sample {(x1, y1),...,(xn, yn)}is used. A recursive greedy2procedure is used, starting from a constant function F0: F0(x) = arg min α n X i=1 L(yi, α) Fm(x) = Fm−1(x) + arg min h∈H n X i=1 L(yi, Fm−1(xi) + h(xi)) To solve the previous problem, a maximum descent algorithm is used (see section (3.3.4)), which moves in the direction of the gradient vector of the loss function Lbut in the opposite sense. Fm(x) = Fm−1(x)−αm n X i=1 ∇hL(yi, Fm−1(xi)) αm= arg min α n X i=1 L yi, Fm−1(xi)−α∂L(yi, F(xi)) ∂F(xi)Fm(x)=Fm−1(x)! This procedure is summarised in Algorithm 4. Gradient boosting can be prone to overfitting because of the model capacity, learning rate or the weak learner complexity. To mitigate overfitting, regularisation can be employed. Modify the model update rule.: Fm(x) = Fm−1(x) + ν αmhm(x) where νis an adjustable parameter known as learning rate. 2A greedy algorithm makes locally optimal choices at each step with the aim of finding a global optimum. It makes the best choice at each stage without considering the larger context or potential consequences of that decision. The algorithm greedily selects the option that appears to be the most advantageous at the current moment, without reconsidering or revising previous choices. While this approach can often yield efficient solutions, it does not guarantee finding the optimal solution in all cases. 51
Chapter 3. Machine Learning 3.3. Discriminative Classifiers Data: Data {(xi, yi)}n i=1,xi∈Rd,yi∈R,Mbe the number of iterations Result: A final model F(x) begin Initialise the model: F0(x) = arg min α n X i=1 L(yi, α); for m= 1 to Mdo Calculate the pseudo-residual: wi=−∂L(yi, F(xi)) ∂F(xi)Fm(x)=Fm−1(x)∀i= 1, . . . , n Train a base classifier hm(x) to the pseudo-residuals by using as training sample {(xi, wi)}n i=1.; Calculate the search step αby solving the following one-dimensional optimization problem: αm= arg min α n X i=1 L(yi, Fm−1(xi) + αhm(xi)) Update the model: Fm(x) = Fm−1(x) + αmhm(x) end end Algorithm 4: Gradient Boosting Algorithm. Source: [48] 52
Chapter 3. Machine Learning 3.3. Discriminative Classifiers The model’s ability to generalise is greatly enhanced by using small values of ν(ν < 0.1), despite the significant increase in computational effort associated with them. Stochastic Gradient Boosting introduces randomness into the algorithm to improve its performance and reduce overfitting. Unlike traditional gradient boosting, which uses the full training set to grow each weak learner, stochastic gradient boosting samples a subset of the training data at each iteration as it is mainly based on SGD (see section (3.3.4.1)). This reduces the computational cost as well as decreases overfitting. A specific fraction fof the learning sample is chosen, where values of franging from 0.5 to 0.8 yield satisfactory outcomes. Generally, a value of f= 0.5 is commonly employed. 3.3.5.1.1 XGBoost XGBoost (eXtreme Gradient Boosting) is a high-performance, adaptable and portable distributed gradient boosting library that has been optimised for efficiency. It implements machine learning algorithms within the Gradient Boosting framework [51]. XGBoost is is an open-source software library for C++, Java, Python, R, Julia, Perl and Scala. Therefore, it has a large and active community, which has contributed to its continuous development and improvement. XGBoost incorporates regularisation techniques to control overfitting and improve generalisation. It includes L1and L2regularisation terms which penalise the complexity of the model. Regularisation can be defined as an application of Occam’s Razor (also known as the principle of parsimony) in that the goal is to choose a simpler hypothesis [1]. Lasso Regularisation (L1Norm): adds a penalty term to the loss function that is proportional to the absolute value of the model’s coefficients. It encourages some of the coefficients to become exactly zero, effectively performing feature selection. Due to this, the resulting models tend to be more interpretable, indicating the most important features in the model. wopt = arg min w∈Rd+1(Ltrain(h) + λ|w|) (3.3.21) Ridge Regularisation (L2Norm): adds a penalty term proportional to the squared value of the coefficients. By contrary, the coefficients tend to 0 , but they are not equal to 0. This can be advantageous when dealing with highly correlated features. wopt = arg min w∈Rd+1(Ltrain(h) + λw⊺w) (3.3.22) λis known as the regularisation constant, which is normally selected using the validation technique. 53
Chapter 3. Machine Learning 3.4. Generative Classifier What made XGboost so popular was the remarkable success in various machine learning competitions [52] and real-world applications. Its excellent performance, scalability and feature-rich nature make it a popular choice for data scientists and practitioners working on predictive modelling tasks. 3.4 Generative Classifier Generative Classifier learn a model of the join probability distribution P(X, Y ) on given input data Xand their labels Y. Then, algorithms such as naive Bayes or Linear Discriminant Analysis are used to calculate conditional probability P(Y|X) and predict the most likely label. Generative classifiers offer more than just predicting class labels: they also have the capability to generate new samples based on the learned data distribution. This feature makes generative classifiers valuable for tasks such as data synthesis or generating new instances that exhibit similarities to the original data. 3.4.1 Naive Bayes Naive Bayes classifier is a simple probabilistic classifier based on Bayes’s rule and an assumption of independence between the features or attributes. Theorem 3.4.1 (Baye’s rule). P(A|B) = P(B|A)P(A) P(B) where Aand Bare events with P(B)= 0. P(A|B)is the posterior probability. P(B|A)is known as the likelihood. P(A)and P(B)are prior probabilities. The aim is to model P(Y=y|X=x), which using Bayes’ rule (3.4.1): P(Y=y|X=x) = P(X=x|Y=y)P(Y=y) P(X=x) which under Naive Bayes assumption, =Qm j=1 P(Xj=xj|Y=y)P(Y=y) P(X=x)∝ m Y j=1 P(Xj=xj|Y=y)P(Y=y) We want the maximum a-posteori to know how to classify, that is to say: hBayes(x) = arg max y∈{0,1}P(Y=y) m Y j=1 P(Xj=xj|Y=y) (3.4.1) The key is estimating the parameters of Naive Bayes: the prior class P(Y=y) and the likelihood of each feature given the class P(Xj=xj|Y=y). 54
Chapter 3. Machine Learning 3.4. Generative Classifier The maximum likelihood of these estimates are: P(Y=yi) = count(yi) n P(Xj=k|Y=yi) = count(Xji =k) count(yi) where count(Xji =k) refers to the number of instances that the attribute Xjtakes the value kand belong to the class yi. The problem is that this goes to 0 if it does not exist such an instance. In this case, it would assign a probability 0, ignoring the other attributes. To solve this issue, Laplace smoothing adds a pseudocount parameter α > 0: P(Xj=k|Y=yi) = count(Xji =k) + α count(yi) + α values(Xj) where values(Xj) is the number of categories the attribute Xjhas. An alternative is to assume that continues values are distributed according to a Gaussian distribution, and therefore, the probability can be computed plugging k into normal density function: P(Xj=k|Y=yi) = 1 √2πσji e (k−µji)2 2σ2 ji (3.4.2) where µji is the mean of the values in class iof attribute Xjand σji refers to the variance. 3.4.2 Linear Discriminant Analysis Linear Discriminant Analysis (LDA) was developed by Ronald Fisher to classify data. The key idea is to project data such that separation between classes is achieved. Assume binary classification with labels 1 and 2 and that there are ppredictor variables for each group: xji ∈Rpi∈ {1, . . . , nj}, j ∈ {1,2} Then, the aim is to find a linear combination which maximises the ratio of variability between groups relative to the total variability. Let v∈Rp. Note that v⊺xji is the projection of xji into a one dimensional subspace, a line in direction v. Now, we define some measure to proceed with the reasoning. Let xjbe the mean of class jand zjbe the projected mean of class j. The relationship between them is: zj=1 nj nj X i=1 v⊺xji =v⊺ 1 nj nj X i=1 xji!=v⊺xj 55
Chapter 3. Machine Learning 3.4. Generative Classifier Figure 3.14: LDA maximising the component axes for class-separation. Source: [56] One could think that |z1−z2|is a good measure of separation, but the problem relies that it does not consider the variance of the classes. This is the reason why we consider the maximisation relative to the total variability. To measure the spread around the mean, we consider the scatter or pooled covariance matrix. The scatter for projected samples of group jis: s2 zj= nj X i=1 (zji −zj)2 Small s2 zjmeans that projections of group jare closed to their projected mean of the group. In the same way, we can also define the scatter matrices Sjfor group jbefore the projection and find the relationship with the projected one: S2 j= nj X i=1 (xji −xj)(xji −xj)⊺ s2 zj= nj X i=1 (zji −zj)2= nj X i=1 (v⊺(xji −xj))⊺(v⊺(xji −xj)) = nj X i=1 ((xji −xj)⊺v)(v⊺(xji −xj)) = nj X i=1 v⊺(xji −xj)(xji −xj)⊺)v=v⊺S2 jv The within-class scatter matrix is defined as: S2 W=1 N−K K X j=1 S2 j 56
Chapter 3. Machine Learning 3.4. Generative Classifier where N=PK j=1 njand Kis the total number of groups that exists. For binary classification, it would be: S2 W=1 n1+n2−2(S2 1+S2 2) Then, the relationship with projection is: s2 z=1 N−K K X j=1 s2 zj=1 N−K K X j=1 v⊺S2 jv=v⊺S2 Wv In the same way, the between-class scatter matrix is: S2 B= (x1−x2)(x1−x2)⊺ which measures the separation bwteen the means of two classes before projection. The separation between the projected means can be rewritten as: (z1−z2)2= (v⊺x1−v⊺x2)2=v⊺(x1−x2)(x1−x2)⊺v=v⊺S2 Bv Thus, our objective is to find v∈Rpsuch that zji =v⊺xji ∈Rmaximises the separation between projected classes relative to the the variance within each projected class: max v∈Rp (z1−z2)2 s2 z = max v∈Rp (v⊺(x1−x2))2 v⊺S2 Wv= max v∈Rp v⊺S2 Bv v⊺S2 Wv(3.4.3) Note that we need to assume that S2 Wis symmetric positive definite or we cannot apply LDA. This also implies that we need to have enough data points. The rule for classification consists of assigning a new observation x∗to class 1 when its projection is closer to the projected mean of class 1 z1than to z2: (v⊺x∗−z1)2<(v⊺x∗−z2)2 ⇔z2 1−2z1v⊺x∗< z2 2−2z2v⊺x∗ ⇔z2 1−z2 2<2(z1−z2)v⊺x∗ (3.4.4) Proposition 3.4.1. For any symmetric positive definite p×pmatrix Sand non-zero u∈Rp. Then, for any non-zero v∈Rp max v=0 (v⊺u)2 v⊺Sv=u⊺S−1u and the maximum is achieved for v=S−1u Proof. (v⊺u)2= (v⊺S1 2S−1 2u)2= ((S1 2v)⊺(S−1 2u))2C-S ≤(v⊺Sv)(u⊺S−1u) By Cauchy-Schwartz (C-S), we also know that the equality is attained for v= S−1u. 57
Chapter 3. Machine Learning 3.4. Generative Classifier Theorem 3.4.2 (Fisher’s Linear Discriminant Analysis).Assuming x1=x2and S2 Wis symmetric positive definite. The maximiser of (3.4.3) is v:= S−1 W(x1−x2) Proof. The proof relies on applying the proposition (3.4.1) setting u=x1−x2so that the maximiser is v=S−1 W(x1−x2) Since SWis positive definite, we can simplify the classification rule (3.4.4): z1−z2=v⊺(x1−x2)=(x1−x2)⊺S−1 W(x1−x2)>0 Then, the classification rule is simplified to Assign to class 1 if 1 2(z1+z2)<v⊺x∗ 58
Chapter 4 Applications Communication is an essential aspect of human life, as it allows us to convey information, express emotions and ideas. Language serves as a fundamental tool for communication, providing a common ground for understanding between individuals. However, when it comes to interacting with computer systems, the challenge of language comprehension arises. Fortunately, Artificial Intelligence (AI) provides a solution, specifically in the form of Natural Language Processing (NLP), which empowers computer systems to understand and interpret this information. NLP enables systems to grasp not only the literal meaning of text but also to recognise sentiments, tones, opinions and other elements that contribute to meaningful conversations, reducing the gap between humans and machines. Figure 4.1: NLP taks and applications. Source: [57]. This chapter aims to provide a comprehensive overview of the applications of NLP. By leveraging NLP techniques, organizations can enhance communication, improve information retrieval, conduct sentiment analysis and augment decision- 59
Chapter 4. Applications 4.3. Machine Translation of the input sentence and the structure of the output sentence. This type of translation is used mostly in the creation of dictionaries and grammar programs To accomplish this, RBMT utilises several components, including a parser and analyser for the source language. These components analyse the grammatical structure of the input sentence, extracting relevant linguistic information. Additionally, a generator for the target language is employed to construct the desired output sentence based on the analysed structure. The transfer lexicon plays a crucial role in the translation process, serving as a resource that maps words and phrases from the source language to their appropriate translations in the target language. 4.3.2 Statistical Machine Translation Statistical Machine Translation (SMT) is characterised by its adoption of a probabilistic approach to facilitate the mapping from one language (source) to another (target). The underlying assumption in SMT is that each word in the target language corresponds to a translation of the source language words, with certain probabilities assigned to these mappings. By selecting the words with the highest probabilities, the system aims to generate the most optimal translation. Word alignment plays a crucial role in these statistical models and refers to the task of mapping words between a source language sentence and its corresponding translation in the target language. The model can be formulated as an optimisation problem [65] applying Bayes’s Rule (theorem (3.4.1)): ˆ Y= arg max YP(Y|X) = arg max YP(X|Y)P(Y) (4.3.1) where Xrefers to the source language and Yto the target language. This decomposition allows to split the problem into subproblems: P(X|Y) is the translation model (faithfulness), which defines a range of potential translations for a given target sentence. Additionally, the model assigns probabilities to these translations, reflecting their relative accuracy or correctness compared to each other. P(Y) is the language model (fluency), which reflects the model’s estimation of how well each sentence captures the characteristics and fluency of the target language. The argmax search process through the space of possible target translations is known as decoding. Decoding for SMT is NP-hard1. 1NP-hard (nondeterministic polynomial-time hard) is a classification used in computational complexity theory to describe problems that are at least as hard as the hardest problems in the complexity class NP (nondeterministic polynomial-time). A problem is considered NP-hard if any problem in NP can be reduced to it in polynomial time. 66
Chapter 4. Applications 4.3. Machine Translation Online translation tools as Google Translate was primarily driven by the statistical method, but now, it has transitioned to neural machine translation (see figure 4.4). Figure 4.4: Human raters assess the quality of translations for a given source sentence by comparing them. The raters assign scores ranging from 0 (nonsense) to 6 (perfect translation). Source: [66] 4.3.3 Neural Machine Translation Despite these challenges, machine translation has made significant progress in recent years, driven by advancements in deep learning and neural network encoderdecoder architectures. Thus, Neural Machine Translation (NMT) employs artificial neural networks to predict the probability of a sequence of words. Unlike traditional methods that focus on individual words or phrases, NMT models consider entire sentences as a whole in a unified framework. By utilising neural networks, NMT systems aim to capture the context, grammar and semantic information of the source language to generate accurate and fluent translations in the target language. This integrated modelling approach enables NMT to produce more coherent and contextually appropriate translations compared to previous machine translation techniques. Analysing sentence-level translation, NMT model can be viewed as a sequence- to-sequence model. Let x={x1, . . . , xS}be a source sentence and y={y1, . . . , yT} be a target sentence. By using the chain rule, the conditional distribution can be factorised as [67]: Pw(y=y|x=x) = T Y t=1 Pw(yt|y0, . . . , yt−1, x1, . . . , xS) (4.3.2) 67
Chapter 4. Applications 4.3. Machine Translation where each translated word ytdepends on previous translated words y1, . . . , yt−1 from the source sentence xas well as the parameters wof the model. As mentioned before, the encoder-decoder framework consits of four fundamental elements: Embedding layers: transform input data, such as words, into continuous vector representations called embeddings, which can be effectively processed by the neural networks. Encoder networks: takes the source embeddings and encodes it into hidden continuous representations or states. The encoder typically consists of recurrent neural network (RNN) layers: ht=RNNENC (xt,ht−1) which is iteratively applied until we obtain the final stage hS. Decoder networks: takes the encoded representation (final stage hS) from the encoder and generates the translated target language sentence. It operates in a sequential manner, generating one word at a time based on the previously generated words and the encoded source sentence. Classification layer: predicts the distribution of target tokens. It is usually a linear layer with softmax activation function to ensure that we obtain a probability. softmax(z) = ez PV i=1 zi where Vis the size of the vocabulary of the target language. Figure 4.5: An overview of the NMT architecture (encoder-decoder framework). Source: [67] An example of NMT is DeepL Translator, which is mainly based on Convolutional Neural Networks (CNN). 68
Chapter 4. Applications 4.4. Question Answering 4.4 Question Answering Question answering (QA) is the NLP task that focuses on developing systems capable of automatically answering questions posed by users in natural language. QA systems aim to understand the meaning and intent of the questions and provide accurate and relevant answers. Question answering is a complex procedure involving several steps. It begins with retrieving relevant documents, followed by extracting valuable information from these documents. Next, potential answers are suggested and evaluated based on supporting evidence. Finally, a concise text response in natural language is generated as the answer. Figure 4.6: A natural language question answering system takes questions in natural language and returns a concrete answer. Source: [69] There are different approaches to question answering: Closed-domain QA: focuses on answering questions within a specific topic. The system is designed to have in-depth knowledge about a limited set of topics. Open-domain QA: aims to answer questions across a wide range of topics and does not have a specific limitation to a predefined domain. These systems are designed to understand and generate answers based on general knowledge or information available on the web. Regarding QA methodology, the first step corresponds to question decomposition to form a query. This query formulation is a list of tokens or keywords that are send to an expert system to produce answers. Another approach is query reformulation, which consists of applying certain rules to rephrase the query so that it may look like a substring of possible answers. Here are some examples from [70]: Wh-word did A verb B−→ Averb+ed B Where is A −→ A is located in 69
Chapter 4. Applications 4.4. Question Answering 4.4.1 Information Retrieval Based The objective of question answering using information retrieval is to respond to a user’s question by locating brief text sections from the web or another large collection of documents. Web-based QA systems as Google Search use this methodology. After having formulated the query, it is mapped into a bag-of-words or TF-IDF to retrieve relevant documents and sections within them. Then, the system generates the final answer which can be the most relevant sentence or a combination between multiple passages. 4.4.2 Knowledge-Based QA Knowledge-Based QA is an approach that relies on structured knowledge bases to provide answers to user questions. Semantic parsing is employed to transform questions into relational queries that can be executed on a comprehensive database. These systems are known as semantic parsers and the database can be a full relational databse or knowledge base of RDF (Resource Description Framework) triples. A semantic triple or RDF triple is a set of three entities that codifies data into the form of subject-predicate-object. DBpedia is an example of a free semantic relation database that contains over 9.5 billion RDF in multiple languages. The extraction of this content is made from Wikipedia. 4.4.3 Automated Reasoning Automatic reasoning question answering (QA) is an approach that focuses on answering questions by performing logical inference and reasoning on structured knowledge or information. Automatic reasoning is a field of artificial intelligence that involves applying logical rules and inference mechanisms to derive answers based on the given question and the available knowledge. QA systems can improve their answer hypotheses by generating a collection of first-order logic clauses that augment semantic relations and the retrieved evidence. IBM Watson’s DeepQA is a QA system developed by IBM that incorporates all these three methodologies: IR-based, knowledge-based and automated reasoning. It gained significant attention when it competed and won against human contestants on the quiz show Jeopardy! in 2011. DeepQA continues to evolve, with ongoing research and development to enhance its capabilities in understanding complex questions, handling ambiguity, and providing accurate and insightful answers. Mean Reciprocal Rank (MRR) is a measure to evaluate question answering performance. The MRR is calculated as the average reciprocal rank (RR) of the first correct answer. The reciprocal rank of a query response is the multiplicative 70
Chapter 4. Applications 4.5. Summarisation inverse of the rank of the first correct answer [71]. MRR =1 N N X i=1 1 ranki (4.4.1) where rankirefers to the rank position of the first relevant document for the i-th query. If no correct answer was returned in the query, the reciprocal rank is 0. An outstanding performance is set at exceeding MRR = 0.83. 4.5 Summarisation Text Summarisation consists of identifying the most relevant information in a document or group of documents and generating a concise and coherent summary. Due to the exponential growth of textual content on the Internet and in various archives such as news articles, scientific papers, and legal documents, Automatic Text Summarisation (ATS) is gaining significant importance. The high volume of textual content makes manual text summarisation a time-consuming, labor-intensive and costly process. In fact, with such a vast amount of text, manual summarisation often becomes impractical. Therefore, the need for ATS arises as an efficient and effective solution to automatically summarise text, enabling users to extract key information without the need for extensive human effort [72]. 4.5.1 Extraction Based Extraction-based summarisation involves selecting and extracting the most important sentences or phrases from a document to create a summary. It relies on identifying key information and preserving the original wording of the source text. Sentences are selected based on their relevance to the overall meaning of the document. Various techniques can be used, such as ranking sentences based on their frequency, presence of keywords, or similarity to the document’s main topic. One approach to assessing significance is by quantifying informative words using lexical measures such as TF-IDF. Another approach is TextRank algorithm [73], which is a graph-based ranking model by considering lexical similarity between words. It is based on the concept of PageRank, which is used by Google to rank web pages. Once we get the scores, the sentences with the highest scores are reordered to form a coherent and concise final summary. 4.5.2 Abstraction Based Abstraction-based summarisation generates a summary by paraphrasing and rephrasing the content of the source text, rather than directly copying sentences as extraction-based. It takes a semantic approach to identify relations. It can be more challenging than extraction-based summarisation since it requires advanced NLP techniques and a deep understanding of the source text to accurately 71
Chapter 4. Applications 4.6. Industrial applications paraphrase the content while preserving its original meaning. It can also be computationally more demanding due to the need for sentence generation and linguistic analysis. 4.6 Industrial applications The progress in technology has brought a significant transformation to how humans communicate and interact with computers. This revolution has not only impacted individuals but also societies worldwide, providing them with communicative tools. Communication and interaction play a vital role in various aspects of daily life, including business, education, commerce, healthcare, politics, finance and socialising [76]. 4.6.1 Finance Data has become crucial in the field of finance, with valuable information residing in written documents and websites, among others. Finance professionals spend considerable time reviewing financial reports. To enhance financial decision-making, NLP and ML provide great solutions in the following areas: Risk assessment. It is based on assessing credit risk through credit scoring models, which estimates payment capacity based on previous spendings and history data. In addition to this, NLP can help fraud detection by identifying patterns or anomalies. Acounting and Auditing. NLP analyses financial statements and audit reports, extracting relevant information, identifying anomalies or errors, and facilitating data analysis. Stock market predictions. By extracting sentiment and combining it with other quantitative indicators, NLP can help investors and traders make more informed decisions and predict potential market movements. Furthermore, it can be really useful in constructing optimal investment portfolios that aim to maximise returns and minimise risk based on textual and numerical data. 4.6.2 Business Companies have the opportunity to expand their operations globally, leading to improved trade relations and ultimately boosting international commerce. There is a wide variety of NLP applications in this field, which can be summarised in the following keys with special focus on the latter: Cibersecurity. A clear example would be spam detection, which allow to mitigate risks and protect data. Recruiting and Hiring. Information extraction and named entity recognition are used to extract information about candidates, making resume screening easier and identifying the most suitable candidate for a position. Interview 72
Chapter 4. Applications 4.6. Industrial applications assessments and virtual interviews use NLP to summarise the information and make a candidate report. Moreover, employees’ job satisfaction can be measured through sentiment analysis techniques. Market Intelligence2(MI). Online assistants or chatbots can solve customers’ queries as well as to measure customer satisfaction and further areas of improvement. They can also be an interative way of communicating important information about the company to the customers such as new product release or delays. Competitors websites and industry news can provide useful insights so that NLP can identify new opportunities and strategies for the company to stay competitive. 4.6.3 Healthcare The applications of NLP in healthcare is one of the fastest growing and it is revolutionasing the way we process and analyse text in the medical field. This subsection explores these diverse applications: Clinical documentation. The vast amount of data collected in healthcare through electronic processes, particularly from Electronic Health Records (EHRs), is predominantly unstructured and of poor quality, making it largely unusable. Approximately 80% of healthcare data falls into this category. However, NLP offers a solution by extracting essential data elements from unstructured sources, restructuring it and making it more accessible and meaningful for analysis and decision-making purposes [76]. Clinical decision support. NLP techniques extract and analyse relevant information from diverse sources, aiding in identifying potential diagnoses, recommending appropriate treatment options and predicting patient outcomes. In addition to this, chatbots can provide immediate responses to patient inquiries, appointment scheduling, and basic healthcare information. Computer-Assisted Coding (CAC). NLP automates the process of assigning medical codes to medical records. Although it has significantly expedited the coding process, it has faced challenges in achieving optimal accuracy levels. Clinical trial matching. This is very similar to the HR process explained in section (4.6.2) since it basically consists of a selection of suitable candidates who meet the research criteria for the drug development process. Biological sequence analysis. This task aims to uncover patterns, relationships and functional insights within DNA, RNA and protein sequences. For instance, in the latter, n-grams can help identify functional domains, predict protein structures or classify proteins into families. 2Market intelligence refers to the process of gathering and analysing relevant information about market trends, customer behavior and competitor activities to make informed business decisions and gain a competitive edge. 73
Chapter 4. Applications 4.6. Industrial applications 4.6.4 Legal and Compliance NLP applications in the field of legal and compliance play a crucial role in various aspects: Criminal records. It becomes possible to extract key information from legal documents, such as court records or criminal databases. This increases efficiency search about individuals’ criminal histories, aiding in investigations and the administration of justice. Identification of patterns and trends. By analysing large volumes of legal texts, NLP can uncover patterns, anomalies and correlations that may go unnoticed by manual analysis. This allows to gain insights into emerging trends, potential risks and compliance violations. Extracting information from policy reports, which makes it easier to keep up to date and avoids potential risks or compliance violations. 4.6.5 Education NLP can enhance education by supporting the needs of students, teachers and researchers. Appart from information extraction, these are some useful applications in the field of education: Translation. NLP with machine translation help people to learn other languages together with a correct spelling and pronunciation. In addition to this, there are some specific tools that allow to improve academic writing since they provide immediate feedback. E-learning. It enables the development of intelligent virtual tutors and chatbots that can engage with learners providing personalised assistance, answering questions and offering real-time feedback. Some e-learning platforms include interactive games, making learning more enjoyable. Assessment. NLP can provide meaningful feedback to students and teachers assessing essays and answers, even with automate scoring system. Moreover, it is also able to generate quizzes to assess performance and identify areas of improvement. 74
Chapter 4. Applications 4.7. Ethical Considerations 4.7 Ethical Considerations The widespread adoption of NLP technologies has raised important ethical considerations that demand careful attention. One of the primary concerns is the privacy and security of user data. NLP systems often rely on collecting and analysing substantial amounts of personal information, such as text messages, emails and social media posts. It is essential to protect individuals’ privacy and handle their data responsibly and transparently. Organizations should establish robust data protection measures, employ anonymisation techniques and secure storage systems while adhering to relevant data protection regulations. Obtaining clear and informed consent from users regarding the collection and use of their personal data is crucial to build trust and uphold ethical standards. Another critical ethical consideration in NLP is the presence of bias and fairness issues in language processing systems. NLP algorithms are trained on vast amounts of textual data, which may contain societal biases and prejudices. If left unaddressed, these biases can perpetuate discrimination and inequalities in automated decision-making. It is crucial to mitigate bias in both the training data and the algorithms themselves to ensure fairness and equitable treatment. Ethical guidelines and practices should be implemented to promote diversity and inclusivity in NLP systems. Ongoing monitoring and evaluation should be conducted to identify and rectify biases that may emerge during the system’s usage. Furthermore, transparency in the decision-making process of NLP algorithms is essential, enabling users and stakeholders to understand how decisions are made and holding the technology accountable for any biases that may arise. In conclusion, as NLP technologies continue to advance, it is vital to address the ethical considerations associated with their use. Safeguarding privacy and data security, tackling bias and fairness concerns, and promoting transparency and accountability are crucial for responsible and ethical deployment of NLP systems. By proactively addressing these ethical considerations, we can maximise the benefits of NLP while protecting individuals’ rights and well-being and fostering trust in the technology. 75
Chapter 5. Python 5.3. Scikit-learn 5.3 Scikit-learn As stated in the paper Scikit-learn: Machine Learning in Python [83]: “Scikit-learn is a Python module integrating a wide range of state-of- the-art machine learning algorithms for medium-scale supervised and unsupervised problems. This package focuses on bringing machine learning to non-specialists using a general-purpose high-level language. Emphasis is put on ease of use, performance, documentation, and API consistency.” The history of scikit-learn traces back to the early 2000s. It originated as a Google Summer of Code project in 2007 and was initially developed by David Cournapeau. In 2010, contributors Fabian Pedregosa, Ga¨el Varoquaux, Alexandre Gramfort and Vincent Michel took leadership of the project and released the first public version of this library. Scikit-learn quickly gained traction within the Python community due to its simplicity, well-documented API and extensive set of features. This API took a vital role in this success since not only does it include an extensive documentation, but it also has examples, tutorials and some featuring real-word applications. In addition to this, they keep the balance between mathematical precision and easy-understanding of the concepts explained, which makes it accessible to a wider audience and foster a collaborative community. Scikit-learn uses mainly Numpy and Scipy Python libraries to build their algorithms, which some are written in Cython2to improve performance. Numpy is used for multi-dimensional arrays and matrices, together with functions for array operations. In scikit-learn, numpy is used for the data structure and model parameters. On the other hand, Scipy allows sickit-learn to implement efficient algorithms for linear algebra, sparse matrix representation, special functions and basic statistical functions. The scikit-learn library provides powerful tools for model selection, which is a crucial aspect of Machine Learning. Model selection involves choosing the best model or algorithm and its hyperparameters for a given task. For this purpose, scikit-learn offers several modules and functions which have been specifically designed. One of the primary tools for model selection is the model selection module. This module provides functions for evaluating and comparing different models using various techniques, such as cross-validation and grid search. For this, we use the train test split to obtain train and test subsets to validate our models. Cross-validation is a common technique for assessing the performance of a model on unseen data. Scikit-learn offers functions like cross val score and cross validate that facilitate cross-validation by splitting the data into multiple folds and evaluating the model on each fold. Grid search is another essential technique in model selection, which involves systematically searching through a specified hyperparameter grid to find the best combination of hyperparameters for a model. Scikit-learn provides the GridSearchCV 2Cython is a language for combining C in Python. 81
Chapter 5. Python 5.3. Scikit-learn Figure 5.5: Scikit-learn algorithm cheat-sheet. Source: Scikit-learn class, which automates the process of grid search and cross-validation, enabling users to efficiently explore different hyperparameter settings and identify the optimal configuration. In addition to grid search, scikit-learn also supports randomised search with the RandomizedSearchCV class. Randomised search is useful when the hyperparameter search space is large, as it allows for a more efficient exploration by sampling a subset of the parameter grid. Both the model and the hyperparameters are selected based on different evaluation metrics. The metrics module in scikit-learn offers more than 40 metrics available to analyse the results of the models. Some metrics used for regression models are mean square error (MSE), mean absolute error (MAE) or the coefficient of determination R2, which correspond to funtions mean squared error,mean absolute error and r2 score, respectively. Others like confusion matrix,accuracy score and classification report are used to evaluate and compare the results of classification models. Furthermore, scikit-learn pipeline is a powerful tool which makes it easier to organise the code since it allows to combine data normalisation and machine learning models into a single entity. Pipelines promote good coding practices, improve the reproducibility of results, and allow for efficient preprocessing, model training, crossvalidation and hyperparameter tuning. 82
Chapter 6 Results In this chapter, we will provide an overview of the Python code implemented for machine learning techniques that gather the concepts and procedures that have been explained along this work, together with a previous preprocessing step. To analyse the different machine learning algorithms explained (section (3)) and their performance, a binary text classification task is implemented. For this, a dataset [84] from Kaggle has been used, whose main aim is to find the best classifier (model) that distinguishes fake from real news. Kaggle is an online platform and community that hosts data science competitions, provides datasets for practice and offers a collaborative environment for data scientists, machine learning engineers and researchers. In addition to this, we are also going to perform a special case of text classification, sentiment analysis, which is based on distinguishing positive from negative film reviews. For this, another dataset from Kaggle about IMDb (Internet Movie Database) reviews has been used [85]. 83
Fake News Classifier Import Libraries [1]: import matplotlib.pyplot as plt import warnings warnings.filterwarnings( ' ignore ' ) import numpy as np import pandas as pd import seaborn as sns from nltk.corpus import stopwords from sklearn.model_selection import StratifiedKFold, cross_val_score, ,→ cross_val_predict from sklearn.metrics import confusion_matrix, classification_report, ,→ ConfusionMatrixDisplay from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import train_test_split, GridSearchCV, KFold Data Load [2]: true =pd.read_csv("C:/Users/Amparo/OneDrive/Desktop/data/true.csv") fake =pd.read_csv("C:/Users/Amparo/OneDrive/Desktop/data/fake.csv") Preprocessing and Exploratory Data Analysis (EDA) In this section, it is vital to deal with NA values and duplicates as a first step. Remove NA values and add a target column indicating whether the news is true or fake. [3]: true.dropna(inplace =True) fake.dropna(inplace =True) true[ ' Labels ' ]= 0 fake[ ' Labels ' ]= 1 Check for duplicated registers in the fake news dataset, and then, drop the occurrences except for the first one. [4]: fake.duplicated().sum() 84
Chapter 6. Results Fake News Classifier [4]: 3 [5]: fake.drop_duplicates(inplace=True) The same procedure is applied to the real news dataset. [6]: true.duplicated().sum() [6]: 206 [7]: true.drop_duplicates(inplace=True) Now, we can merge both datasets into a single labelled dataset to work with them. [8]: train_data =pd.concat([true, fake], ignore_index =True) [9]: print("We have a dataset with {} news".format(len(train_data))) We have a dataset with 44689 news Now, we count the number of documents per label to know if we have a balanced dataset. [10]: train_data["Labels"].value_counts() [10]: 1 23478 0 21211 Name: Labels, dtype: int64 [11]: train_data["subject"].value_counts() [11]: politicsNews 11220 worldnews 9991 News 9050 politics 6838 left-news 4459 Government News 1570 US_News 783 Middle-east 778 Name: subject, dtype: int64 [12]: train_data.groupby([ ' Labels ' ]).count() [12]: title text subject date Labels 0 21211 21211 21211 21211 1 23478 23478 23478 23478 [13]: np.sum(train_data.isnull())[2] [13]: 0 85
Chapter 6. Results Fake News Classifier [14]: ax, fig =plt.subplots() etiquetas =train_data.Labels.value_counts() etiquetas.plot(kind= ' bar ' , color=["red","green"]) plt.title( ' Bar chart ' ) plt.ylabel("Frequency of Labels") plt.xlabel("Labels") plt.show() [15]: import matplotlib.pyplot as plt # Count the frequency of each sentiment category etiquetas =train_data[ ' Labels ' ].value_counts() # Create a pie chart fig, ax =plt.subplots() ax.pie(etiquetas, labels=["Fake","True"], colors=["red","green"], autopct= ' %1. ,→ 1f%% ' ) ax.set_title( ' Pie Chart of Labels ' ) # Display the pie chart plt.show() 86
Chapter 6. Results Fake News Classifier Then, we can conclude that the dataset with 44689 documents is approximately balanced. Therefore, there are approximately the same number of fake and true news. To reduce the computational cost of this task, we are going to select 35000 news preserving this representation of labels. [16]: X=train_data[[ ' title ' , ' text ' , ' subject ' ]] y=train_data[ ' Labels ' ] # Use train_test_split for stratified sampling X_sampled, _, y_sampled, _ =train_test_split(X, y, train_size=35000, ,→ stratify=y, random_state=10) # Combine the sampled features and target into a dataframe data =pd.concat([X_sampled, y_sampled], axis=1) data.head() [16]: title \ 33440 DAY 2 RESULTS Of Wisconsin Recount Are In...And ... 32308 CNN ANCHOR Piles On Bill O'Reilly With Silly S... 9966 Leak of Senate encryption bill prompts swift b... 15770 German railway under fire for proposal to name... 22037 Here Are 12 Tweets Trump DEFINITELY Regrets S... text subject Labels 33440 The Wisconsin Election Commission posts recoun... politics 1 32308 The accusations surrounding Bill O Reilly have... politics 1 9966 WASHINGTON (Reuters) - Security researchers an... politicsNews 0 15770 BERLIN (Reuters) - German rail operator Deutsc... worldnews 0 22037 As you are probably aware, Donald Trump loves ... News 1 87
Chapter 6. Results Fake News Classifier [17]: import matplotlib.pyplot as plt # Count the frequency of each sentiment category etiquetas =data[ ' Labels ' ].value_counts() # Create a pie chart fig, ax =plt.subplots() ax.pie(etiquetas, labels=["Fake","True"], colors=["red","green"], autopct= ' %1. ,→ 1f%% ' ) ax.set_title( ' Pie Chart of Labels ' ) # Display the pie chart plt.show() Make an exploratory data analysis about the length of the characters for each class to know if this can be used as a determining feature. [18]: data["char_len"]=data["text"].apply(lambda x: len(x)) [19]: fig =plt.figure(figsize=(14,12)) sns.set_style("darkgrid") plt0 =sns.distplot(data[data.Labels==0].char_len, hist=True, label="True") plt1 =sns.distplot(data[data.Labels==1].char_len, hist=True, label="Fake") plt.legend(labels=["True","Fake"], loc = ' center right ' , fontsize ="x-large") # Axis labels plt.xlabel( ' Characters ' , fontsize=16) plt.ylabel( ' Density ' , fontsize=16) plt.show() 88
Chapter 6. Results Fake News Classifier We can see that true news have a lower length of characters, although they are really similar and this cannot be considered a determining factor to classify news. Now, we will define functions that will be used to preprocess the text as explained in this work. [20]: # Delete spaces def delete_spaces(text): return " ".join(text.split()) # To lower def texto_to_lower(text): return text.lower() # Tokenisation from nltk import word_tokenize def tokenisation(text): tokens =word_tokenize(text) return tokens 89
Chapter 6. Results Fake News Classifier precision recall f1-score support 0.0 0.9906 0.9895 0.9901 11630 1.0 0.9905 0.9915 0.9910 12870 accuracy 0.9906 24500 macro avg 0.9906 0.9905 0.9905 24500 weighted avg 0.9906 0.9906 0.9906 24500 XGBoost [[11596 34] [ 91 12779]] precision recall f1-score support 0.0 0.9922 0.9971 0.9946 11630 1.0 0.9973 0.9929 0.9951 12870 accuracy 0.9949 24500 macro avg 0.9948 0.9950 0.9949 24500 weighted avg 0.9949 0.9949 0.9949 24500 Gradient Boosting [[11592 38] [ 133 12737]] precision recall f1-score support 0.0 0.9887 0.9967 0.9927 11630 1.0 0.9970 0.9897 0.9933 12870 accuracy 0.9930 24500 macro avg 0.9928 0.9932 0.9930 24500 weighted avg 0.9931 0.9930 0.9930 24500 LDA [[10842 788] [ 512 12358]] precision recall f1-score support 0.0 0.9549 0.9322 0.9434 11630 1.0 0.9401 0.9602 0.9500 12870 accuracy 0.9469 24500 macro avg 0.9475 0.9462 0.9467 24500 weighted avg 0.9471 0.9469 0.9469 24500 SVC [[11534 96] [ 136 12734]] 96
Chapter 6. Results Fake News Classifier precision recall f1-score support 0.0 0.9883 0.9917 0.9900 11630 1.0 0.9925 0.9894 0.9910 12870 accuracy 0.9905 24500 macro avg 0.9904 0.9906 0.9905 24500 weighted avg 0.9905 0.9905 0.9905 24500 By definition, a confusion matrix Cis such that Ci,jis equal to the number of observations known to be in group iand predicted to be in group j. Thus, in binary classification, the count of true positives is C0,0, false positives is C1,0, true negatives is C1,1 and false negatives is C0,1. In this case, the positive class refers to true news and the negative class are the fake news. For a better understanding, we are going to check the classification report results to know how they have been calculated and put the theoretical concepts preivously explained into practice. Let select GaussianNB confussion matrix to perform these calculations. First, we calculate the precision or positive predictive value (PPV). Precision0=TP TP +FP =11071 11071 +1434 =0.885325 Since we are calculating precision for each class, we have to consider positive to be the class Python is calculating. This is equivalent to the negative predictive value (NPV). Precision1=TN TN +FN =11436 11436 +559 =0.9533972 Another important metric is the recall, which is also known as sensitivity or true positive rate (TPR). Recall0=TP TP +FN =11071 11071 +559 =0.95193465 The same reasoning as before is applied for the other class, where we would calculate the specificity or true negative rate (TNR). Recall1=TN TN +FP =11436 11436 +1434 =0.888578 Finally, F1score is a harmonic mean of precision and recall: F1=2Precision ×Recall Precision +Recall F0 1=2×0.8853 ×0.9519 0.8853 +0.9519 =0.9173928 97
Chapter 6. Results Fake News Classifier F1 1=2×0.9534 ×0.8886 0.9534 +0.8886 =0.9198 Support represents the number of instances in each class: 11630 true and 12870 fake news. The accuracy is proportion of the samples correctly classified. Accurary =TN +TP TP +FN +FP +TN =11071 +11436 24500 =0.918653 Macro average for a given metric is an arithmetic (unweighted) mean. Macro avg metric =1 N∑ i metrici where Nis the number of classes. For instance, we can calculate the macro average precision: Macro avg precision =precision0+precision1 2=0.8853 +0.9534 2=0.91935 On the other hand, weighted average for a given metric is a weighted mean with support as weights. Weighted avg metric =support0×metric0+···+supportN−1×metricN−1 support0+···+supportN−1 where the denominator is the number of total instances. For the precision, we would obtain: Weighted avg precision =11630 ×0.8853 +12870 ×0.9534 24500 =0.921073 For each model, we would obtain the mean and standard deviation of the 10 folds for each metric. In addition to this, the results would be visualised as a boxplot. [32]: def display_results(results, names, scores): # Create a DataFrame with mean and std for each score df_results =pd.DataFrame() df_results[ ' Model ' ]=names for score in scores: df_results[ ' Mean ' +score] =[result[score].mean() for result in ,→ results.values()] df_results[ ' Std ' +score] =[result[score].std() for result in results. ,→ values()] display(df_results) 98
Chapter 6. Results Fake News Classifier # Plot boxplot with means fig, axes =plt.subplots(len(scores), figsize=(10,8*len(scores))) for i, score in enumerate(scores): axes[i].set_title(score) axes[i].boxplot([result[score] for result in results.values()], ,→ labels=names, showmeans=True) plt.show() # Example usage display_results(results, names, [ ' accuracy ' , ' roc_auc ' ]) Model Mean accuracy Std accuracy Mean roc_auc Std roc_auc 0 Logistic 0.978082 0.003401 0.995008 0.001195 1 GaussianNB 0.918653 0.006893 0.973839 0.003292 2 Tree 0.991224 0.001186 0.990618 0.001406 3 XGBoost 0.994898 0.000899 0.998566 0.000335 4 Gradient Boosting 0.992939 0.001211 0.997783 0.001095 5 LDA 0.946939 0.004829 0.988385 0.001780 6 SVC 0.990531 0.001869 0.996192 0.001168 99
Chapter 6. Results Fake News Classifier 100
Chapter 6. Results Fake News Classifier From each fold, we obtain the accuracy, which is the percentage of well-classified news. Thus, we obtain the accuracy calculated 10 times and the accuracy associated with the model is the mean of these values, together with a measure of standard deviation. The latter allow us to know if the metric, accuracy in this case, has variability and relies on the sample. In general, all the models have a great performance in terms of accuracy (more than 90%). The “worst” performance is related with the generative classifiers: LDA and GaussianNB. As a winner in many Kaggle competitions, XGBoost has the best performance with almost 100% of accuracy, followed closely by Gradient Boosting. In addition to this, the accuracy across cross-validation has the lowest variance. It is true that XGBoost can be difficult to apply in real practice due to the high computational cost. This is why it can be better sometimes to consider other models that perform well, with less accuracy than XGBoost, but not so expensive computationally. Regarding the area under the characteristic curve, we still have very similar results to the accuracy with XGBoost and Gradient Boosting as best models. However, there are some differences in the ranking regarding Tree, SVC and Logistic Regression compared to accuracy. There are different explanations such as dealing with imbalanced dataset (not this case), predicting the majority class correctly, or model’s difficulty to separate labels. In this case, Tree has a higher accuracy but a lower ROC AUC than Logistic, which indicates that Tree performs better in terms of overall correctness or accuracy in predicting the class labels. However, when it comes to the ability to distinguish between the positive and negative classes, Logistic outperforms Tree. Hyperparameters search Once we have selected the best model, XGBoost, for our machine learning task, it becomes crucial to fine-tune its performance by optimising its hyperparameters. Performing a hyperparameter search involves systematically exploring different combinations of hyperparameters to find the optimal configuration that maximises the model’s performance on the given dataset. [33]: from sklearn.model_selection import KFold from sklearn.model_selection import GridSearchCV # define models and parameters model =XGBClassifier() lr =[0.1,0.01] md =[2,3,5] mcw =[1,5] g=[0.5,0.1,0.01] l=["reg:squarederror","reg:squaredlogerror"] Some XGBoost() hyperparameters we can tune are: • learning_rate: It controls the step size shrinkage during each boosting iteration. • max_depth: It specifies the maximum depth of a tree. 101
Chapter 6. Results Fake News Classifier • min_child_weight: It defines the minimum sum of instance weight needed in a child node. • gamma: It specifies the minimum loss reduction required to split a node further. • objective: It determines the loss function to be optimised during training. [34]: grid =dict(min_child_weight=mcw, max_depth =md, learning_rate=lr, gamma =g, ,→ objective =l) cv =KFold(n_splits=5) grid_search =GridSearchCV(estimator=model, param_grid=grid, n_jobs=-1, cv=cv, ,→ scoring= ' roc_auc ' ,error_score=0) [35]: grid_result =grid_search.fit(X_train, y_train) # summarise results print("Best ROC AUC: %f with parameters %s"%(grid_result.best_score_, ,→ grid_result.best_params_)) Best ROC AUC: 0.998508 with parameters { ' gamma ' : 0.1, ' learning_rate ' : 0.1, ' max_depth ' : 5, ' min_child_weight ' : 1, ' objective ' : ' reg:squaredlogerror ' } The probability that the model will assign a larger probability to a random true new than a random fake new is 0.998508, which is as an extraordinary value. [36]: model=XGBClassifier(min_child_weight= 1, max_depth = 5, learning_rate=0.1, gamma ,→ = 0.1, objective ="reg:squaredlogerror") model.fit(X_train,y_train) [36]: XGBClassifier(base_score=None, booster=None, callbacks=None, colsample_bylevel=None, colsample_bynode=None, colsample_bytree=None, early_stopping_rounds=None, enable_categorical=False, eval_metric=None, feature_types=None, gamma=0.1, gpu_id=None, grow_policy=None, importance_type=None, interaction_constraints=None, learning_rate=0.1, max_bin=None, max_cat_threshold=None, max_cat_to_onehot=None, max_delta_step=None, max_depth=5, max_leaves=None, min_child_weight=1, missing=nan, monotone_constraints=None, n_estimators=100, n_jobs=None, num_parallel_tree=None, objective= ' reg:squaredlogerror ' , predictor=None, ...) [37]: y_pred =model.predict(X_test) [38]: cm=confusion_matrix(y_test,y_pred) print(cm) print(classification_report(y_test,y_pred, digits=4)) [[4978 4] [ 52 5466]] precision recall f1-score support 0.0 0.9897 0.9992 0.9944 4982 102
Chapter 6. Results Fake News Classifier 1.0 0.9993 0.9906 0.9949 5518 accuracy 0.9947 10500 macro avg 0.9945 0.9949 0.9947 10500 weighted avg 0.9947 0.9947 0.9947 10500 Interpretation Precision refers to the proportion of correctly predicted positive instances among all the positive predictions. It can be seen as a normalisation of the confusion matrix by columns. • Out of all the news that the model predicted to be true, “only” 98.97% actually were. • Out of all the news that the model predicted to be fake, “only” 99.93% actually were. Recall refers to the proportion of correctly predicted positive instances among all the actual positive instances. It can be seen as a normalisation of the confusion matrix by rows. • Out of all the news that actually were true, the model predicted this outcome correctly for 99.92% of those news. • Out of all the news that actually were fake, the model predicted this outcome correctly for 99.06% of those news. Accuracy refers to the proportion of correct predictions compared to the total number of predictions. We can conclude that the model correctly predicted the outcome for approximately 99.47% of the instances. [39]: plt =ConfusionMatrixDisplay(cm) # Show the plot plt.plot() [39]: <sklearn.metrics._plot.confusion_matrix.ConfusionMatrixDisplay at 0x2187b0d18b0> 103
Chapter 6. Results Fake News Classifier We can visualise that 4978 were correctly classified as true out of 4982 actual true news and that 5466 were correctly classified as fake news out of 5518 actual fake news. Another insight is that 4978 were actual true news out of 5030 news classified as true and that 5466 were actual fake news out of 5470 reviews classified as fake. [40]: cmn =confusion_matrix(y_test, y_pred, normalize ="true") plt =ConfusionMatrixDisplay(cmn) # if ' true ' , the confusion matrix is normalized over the true conditions (e.g. ,→ rows); # Show the plot plt.plot() [40]: <sklearn.metrics._plot.confusion_matrix.ConfusionMatrixDisplay at 0x2181feaaaf0> This matrix shows the recall for each class since the confusion matrix has been normalised by rows (true). [41]: cmn =confusion_matrix(y_test, y_pred, normalize ="pred") plt =ConfusionMatrixDisplay(cmn) # if ' pred ' , the confusion matrix is normalized over the predicted conditions (e. ,→ g. columns); # Show the plot plt.plot() [41]: <sklearn.metrics._plot.confusion_matrix.ConfusionMatrixDisplay at 0x2181feaa0d0> 104
Chapter 6. Results Fake News Classifier This matrix shows the precision for each class since the confusion matrix has been normalised by columns (predictions). We obtained a classifier really accurate for both classes and thus, it can distinguish fake from real news. Alternative As mentioned previously, in practice, it can be difficult to use XGBoost due to the high computational cost. In this case, we could choose Logisitic Regression since the performance is really good and it is an easy algorithm to interpret the data. [42]: # define models and parameters model =LogisticRegression() solvers =[ ' newton-cg ' , ' liblinear ' ] penalty =[ ' l1 ' , ' l2 ' ] c_values =[100,10,1,0.1] Some LogisticRegression() hyperparameters we can tune are: • solver: The solver determines the optimisation algorithm to be used in fitting the logistic regression model. • penalty: This hyperparameter specifies the type of regularisation to be applied to the mode. • C: controls the amount of regularisation applied. [43]: grid =dict(solver=solvers,penalty=penalty,C=c_values) cv =KFold(n_splits=5) grid_search =GridSearchCV(estimator=model, param_grid=grid, n_jobs=-1, cv=cv, ,→ scoring= ' roc_auc ' ,error_score=0) [44]: grid_result =grid_search.fit(X_train, y_train) # summarize results 105
Chapter 6. Results IMDb Reviews: Sentiment Analysis [9]: import matplotlib.pyplot as plt # Count the frequency of each sentiment category etiquetas =dataO[ ' sentiment ' ].value_counts() # Create a pie chart fig, ax =plt.subplots() ax.pie(etiquetas, labels=etiquetas.index, colors=["green","red"], autopct= ' %1. ,→ 1f%% ' ) ax.set_title( ' Pie Chart of Sentiments ' ) # Display the pie chart plt.show() 112
Chapter 6. Results IMDb Reviews: Sentiment Analysis We are working with a balanced dataset since there are approximately the same number of positive and negative reviews. To reduce the computational cost of this task, we are going to select 40000 films reviews preserving this representation to work with a balanced dataset. [10]: X=dataO[ ' review ' ] y=dataO[ ' sentiment ' ] # Use train_test_split for stratified sampling X_sampled, _, y_sampled, _ =train_test_split(X, y, train_size=40000, ,→ stratify=y, random_state=42) # Combine the sampled features and target into a dataframe data =pd.DataFrame({ ' review ' : X_sampled, ' sentiment ' : y_sampled}) data.head() [10]: review sentiment 512 If I had known this movie was filmed in the ex... negative 2729 The cinema of the 60s was as much as time of r... positive 40138 Las Vegas is very funny and focuses on the sub... positive 6465 This musical has a deep meaning which is appre... positive 12190 Delightful Disney film with Angela Lansbury in... positive [11]: print(data["sentiment"].value_counts()) positive 20075 negative 19925 Name: sentiment, dtype: int64 [12]: import matplotlib.pyplot as plt # Count the frequency of each sentiment category etiquetas =data[ ' sentiment ' ].value_counts() # Create a pie chart fig, ax =plt.subplots() ax.pie(etiquetas, labels=etiquetas.index, colors=["green","red"], autopct= ' %1. ,→ 1f%% ' ) ax.set_title( ' Pie Chart of Sentiments ' ) # Display the pie chart plt.show() 113
Chapter 6. Results IMDb Reviews: Sentiment Analysis In this practical example, we are working with subjective opinions which have been extracted from IMDb website. This is the reason why it is vital to add some preprocessing step first. Here we have a list of abbreviatios that are commonly used in an informal text. [13]: # Thanks to https://www.kaggle.com/rftexas/text-only-kfold-bert abbreviations ={ "$" :" dollar ", " ¿ ":" euro ", "4ao" :"for adults only", "a.m" :"before midday", "a3" :"anytime anywhere anyplace", "aamof" :"as a matter of fact", "acct" :"account", "adih" :"another day in hell", "afaic" :"as far as i am concerned", "afaict" :"as far as i can tell", "afaik" :"as far as i know", "afair" :"as far as i remember", "afk" :"away from keyboard", "app" :"application", "approx" :"approximately", "apps" :"applications", "asap" :"as soon as possible", "asl" :"age, sex, location", "atk" :"at the keyboard", "ave." :"avenue", "aymm" :"are you my mother", "ayor" :"at your own risk", "b&b" :"bed and breakfast", "b+b" :"bed and breakfast", "b.c" :"before christ", 114
Chapter 6. Results IMDb Reviews: Sentiment Analysis "b2b" :"business to business", "b2c" :"business to customer", "b4" :"before", "b4n" :"bye for now", "b@u" :"back at you", "bae" :"before anyone else", "bak" :"back at keyboard", "bbbg" :"bye bye be good", "bbc" :"british broadcasting corporation", "bbias" :"be back in a second", "bbl" :"be back later", "bbs" :"be back soon", "be4" :"before", "bfn" :"bye for now", "blvd" :"boulevard", "bout" :"about", "brb" :"be right back", "bros" :"brothers", "brt" :"be right there", "bsaaw" :"big smile and a wink", "btw" :"by the way", "bwl" :"bursting with laughter", "c/o" :"care of", "cet" :"central european time", "cf" :"compare", "cia" :"central intelligence agency", "csl" :"can not stop laughing", "cu" :"see you", "cul8r" :"see you later", "cv" :"curriculum vitae", "cwot" :"complete waste of time", "cya" :"see you", "cyt" :"see you tomorrow", "dae" :"does anyone else", "dbmib" :"do not bother me i am busy", "diy" :"do it yourself", "dm" :"direct message", "dwh" :"during work hours", "e123" :"easy as one two three", "eet" :"eastern european time", "eg" :"example", "embm" :"early morning business meeting", "encl" :"enclosed", "encl." :"enclosed", "etc" :"and so on", "faq" :"frequently asked questions", "fawc" :"for anyone who cares", 115
Chapter 6. Results IMDb Reviews: Sentiment Analysis "fb" :"facebook", "fc" :"fingers crossed", "fig" :"figure", "fimh" :"forever in my heart", "ft." :"feet", "ft" :"featuring", "ftl" :"for the loss", "ftw" :"for the win", "fwiw" :"for what it is worth", "fyi" :"for your information", "g9" :"genius", "gahoy" :"get a hold of yourself", "gal" :"get a life", "gcse" :"general certificate of secondary education", "gfn" :"gone for now", "gg" :"good game", "gl" :"good luck", "glhf" :"good luck have fun", "gmt" :"greenwich mean time", "gmta" :"great minds think alike", "gn" :"good night", "g.o.a.t" :"greatest of all time", "goat" :"greatest of all time", "goi" :"get over it", "gps" :"global positioning system", "gr8" :"great", "gratz" :"congratulations", "gyal" :"girl", "h&c" :"hot and cold", "hp" :"horsepower", "hr" :"hour", "hrh" :"his royal highness", "ht" :"height", "ibrb" :"i will be right back", "ic" :"i see", "icq" :"i seek you", "icymi" :"in case you missed it", "idc" :"i do not care", "idgadf" :"i do not give a damn fuck", "idgaf" :"i do not give a fuck", "idk" :"i do not know", "ie" :"that is", "i.e" :"that is", "ifyp" :"i feel your pain", "IG" :"instagram", "iirc" :"if i remember correctly", "ilu" :"i love you", 116
Chapter 6. Results IMDb Reviews: Sentiment Analysis "ily" :"i love you", "imho" :"in my humble opinion", "imo" :"in my opinion", "imu" :"i miss you", "iow" :"in other words", "irl" :"in real life", "j4f" :"just for fun", "jic" :"just in case", "jk" :"just kidding", "jsyk" :"just so you know", "l8r" :"later", "lb" :"pound", "lbs" :"pounds", "ldr" :"long distance relationship", "lmao" :"laugh my ass off", "lmfao" :"laugh my fucking ass off", "lol" :"laughing out loud", "ltd" :"limited", "ltns" :"long time no see", "m8" :"mate", "mf" :"motherfucker", "mfs" :"motherfuckers", "mfw" :"my face when", "mofo" :"motherfucker", "mph" :"miles per hour", "mr" :"mister", "mrw" :"my reaction when", "ms" :"miss", "mte" :"my thoughts exactly", "nagi" :"not a good idea", "nbc" :"national broadcasting company", "nbd" :"not big deal", "nfs" :"not for sale", "ngl" :"not going to lie", "nhs" :"national health service", "nrn" :"no reply necessary", "nsfl" :"not safe for life", "nsfw" :"not safe for work", "nth" :"nice to have", "nvr" :"never", "nyc" :"new york city", "oc" :"original content", "og" :"original", "ohp" :"overhead projector", "oic" :"oh i see", "omdb" :"over my dead body", "omg" :"oh my god", 117
Chapter 6. Results IMDb Reviews: Sentiment Analysis "omw" :"on my way", "p.a" :"per annum", "p.m" :"after midday", "pm" :"prime minister", "poc" :"people of color", "pov" :"point of view", "pp" :"pages", "ppl" :"people", "prw" :"parents are watching", "ps" :"postscript", "pt" :"point", "ptb" :"please text back", "pto" :"please turn over", "qpsa" :"what happens", "ratchet" :"rude", "rbtl" :"read between the lines", "rlrt" :"real life retweet", "rofl" :"rolling on the floor laughing", "roflol" :"rolling on the floor laughing out loud", "rotflmao" :"rolling on the floor laughing my ass off", "rt" :"retweet", "ruok" :"are you ok", "sfw" :"safe for work", "sk8" :"skate", "smh" :"shake my head", "sq" :"square", "srsly" :"seriously", "ssdd" :"same stuff different day", "tbh" :"to be honest", "tbs" :"tablespooful", "tbsp" :"tablespooful", "tfw" :"that feeling when", "thks" :"thank you", "tho" :"though", "thx" :"thank you", "tia" :"thanks in advance", "til" :"today i learned", "tl;dr" :"too long i did not read", "tldr" :"too long i did not read", "tmb" :"tweet me back", "tntl" :"trying not to laugh", "ttyl" :"talk to you later", "u" :"you", "u2" :"you too", "u4e" :"yours for ever", "utc" :"coordinated universal time", "w/" :"with", 118
Chapter 6. Results IMDb Reviews: Sentiment Analysis "w/o" :"without", "w8" :"wait", "wassup" :"what is up", "wb" :"welcome back", "wtf" :"what the fuck", "wtg" :"way to go", "wtpa" :"where the party at", "wuf" :"where are you from", "wuzup" :"what is up", "wywh" :"wish you were here", "yd" :"yard", "ygtr" :"you got that right", "ynk" :"you never know", "zzz" :"sleeping bored and tired" } [14]: # Thanks to https://www.kaggle.com/rftexas/text-only-kfold-bert def convert_abbrev(word): return abbreviations[word.lower()] if word.lower() in abbreviations.keys() ,→ else word def convert_abbrev_in_text(text): tokens =word_tokenize(text) tokens =[convert_abbrev(word) for word in tokens] text = ' ' .join(tokens) return text # convert abbreviations data[ ' review ' ]=data[ ' review ' ].apply(lambda x: convert_abbrev_in_text(x)) In addition to this abbreviation conversion, we have noticed visualising the dataframe that there are html break tags since these reviews have been extracted from a website. Therefore, it is convenient to remove them. [15]: # remove html tags data[ ' review ' ]=data[ ' review ' ].apply(lambda x: x.replace( ' < br / > ' , '' )) We can calculate some extra features such as the number of words and number of characters per review to do some exploratory data analysis. [16]: data[ ' word_count ' ]=data[ ' review ' ].apply(lambda x: len(str(x).split())) data["char_len"]=data["review"].apply(lambda x: len(x)) [17]: fig =plt.figure(figsize=(14,12)) sns.set_style("darkgrid") plt0 =sns.distplot(data[data.sentiment=="positive"].char_len, hist=True, ,→ label="Positive") 119
Chapter 6. Results IMDb Reviews: Sentiment Analysis plt1 =sns.distplot(data[data.sentiment=="negative"].char_len, hist=True, ,→ label="Negative") plt.legend(labels=["Positive","Negative"], loc = ' center right ' , fontsize = ,→ "x-large") # Axis labels plt.xlabel( ' Characters ' , fontsize=16) plt.ylabel( ' Density ' , fontsize=16) plt.show() All the classes are right skewed around 1000 characters. Since they are very similar, we have to consider extra features. [18]: fig =plt.figure(figsize=(14,12)) sns.set_style("darkgrid") 120
Chapter 6. Results IMDb Reviews: Sentiment Analysis plt0 =sns.distplot(data[data.sentiment=="positive"].word_count, hist=True, ,→ label="Positive") plt1 =sns.distplot(data[data.sentiment=="negative"].word_count, hist=True, ,→ label="Negative") plt.legend(labels=["Positive","Negative"], loc = ' center right ' , fontsize = ,→ "x-large") # Axis labels plt.xlabel( ' Words ' , fontsize=16) plt.ylabel( ' Density ' , fontsize=16) plt.show() Both the number of words and the number of characters are distributed approximately equal across the positive and negative reviews. Therefore, these cannot be considered a determining feature. WordCloud provides a quick and intuitive way to identify the most frequent terms within a text. 121
Chapter 6. Results IMDb Reviews: Sentiment Analysis text_normalised sent_subjectivity \ 512 known movi film exasper dogm 95 style would ne... 0.241667 2729 cinema 60 much time revolut polit music filmma... 0.329634 40138 la vega funni focus substanc set amaz scene ou... 0.524286 6465 music deep mean appreci wise see wisdom contai... 0.563393 12190 delight disney film angela lansburi fine form ... 0.548512 sent_polarity embeddings 512 0.031250 [-0.23297037, 0.24585672, 0.090983965, -0.1447... 2729 0.030716 [-0.20859282, 0.171421, -0.007602942, -0.12960... 40138 0.161429 [-0.24537817, 0.21428183, 0.14903583, -0.08302... 6465 0.211445 [-0.14868726, 0.16624884, -0.1804222, 0.009106... 12190 0.189665 [-0.21085294, 0.12334834, -0.008020849, -0.081... [31]: vector_data =pd.concat([data.embeddings.apply(pd.Series), data[["sent_polarity","sent_subjectivity"]]], axis=1) We have transformed text to a numerical representation with 27 features, which corresponds to word embeddings and sentiment polarity and subjectivity, for the 40000 sampled reviews. [32]: vector_data.shape [32]: (40000, 27) [33]: vector_data.head() [33]: 0 1 2 3 4 5 6 \ 512 -0.232970 0.245857 0.090984 -0.144705 0.002647 0.000857 0.482371 2729 -0.208593 0.171421 -0.007603 -0.129600 0.110268 -0.023035 0.636843 40138 -0.245378 0.214282 0.149036 -0.083023 0.009157 -0.034927 0.397359 6465 -0.148687 0.166249 -0.180422 0.009106 0.051586 0.000221 0.664426 12190 -0.210853 0.123348 -0.008021 -0.081537 -0.124037 -0.165585 0.529820 7 8 9 ... 17 18 19 \ 512 -0.420550 0.034915 -0.096237 ... -0.147742 0.012249 -0.025490 2729 -0.443005 0.059925 -0.331034 ... -0.092161 0.067579 -0.143954 40138 -0.172392 0.002778 -0.344967 ... -0.335653 -0.066072 0.041860 6465 -0.308628 0.023470 -0.235530 ... -0.042695 0.336808 -0.323844 12190 -0.316194 0.119807 -0.311201 ... -0.039619 -0.059760 0.021153 20 21 22 23 24 sent_polarity \ 512 -0.152912 0.348241 0.240295 -0.099608 -0.409727 0.031250 2729 -0.150108 0.188386 -0.174485 -0.064974 -0.320691 0.030716 40138 0.200282 0.115927 0.072215 0.059028 -0.308877 0.161429 6465 -0.166169 0.004295 -0.113732 0.017440 -0.232162 0.211445 12190 -0.168560 0.223524 -0.462363 -0.261190 -0.234969 0.189665 128
Chapter 6. Results IMDb Reviews: Sentiment Analysis sent_subjectivity 512 0.241667 2729 0.329634 40138 0.524286 6465 0.563393 12190 0.548512 [5 rows x 27 columns] [34]: vector_data =vector_data.fillna(0) Now, we define a function to map the sentiments into numeric values. [35]: def map_sentiment(sentiment): if sentiment == "positive": return 0 elif sentiment == "negative": return 1 else: return None # Handle any other cases if necessary # Apply the function to create the numeric_sentiment column data[ ' numeric_sentiment ' ]=data[ ' sentiment ' ].apply(lambda x: map_sentiment(x)) [36]: X=sp.sparse.csc_matrix(vector_data) y=data["numeric_sentiment"] Machine Learning Split the dataset into a training and test sets (70%-30% respectively). [37]: X_train, X_test, y_train, y_test =train_test_split(X, y, random_state=27, ,→ test_size= 0.3) print(X_train.shape) print(X_test.shape) (28000, 27) (12000, 27) We have obtained a training sample of 28000 film reviews and a test set of 12000 film reviews. We define a function to perform cross validation with 10 folds across different models, which returns the final confusion matrix and the results for the given metrics. [38]: def model_evaluation(models, scores, X, y): global results global names results ={} names =[] 129
Chapter 6. Results IMDb Reviews: Sentiment Analysis # For each model for name, model in models: KF =KFold(n_splits=10, shuffle=True, random_state=98) model_results ={} # Cross-validation for score in scores: cv_results =cross_val_score(model, X, y, cv=KF, scoring=score, ,→ verbose=False) model_results[score] =cv_results y_pred =cross_val_predict(model, X, y, cv=KF) print(name) print(confusion_matrix(y, y_pred)) print(classification_report(y, y_pred, digits=4)) # Store results results[name] =model_results names.append(name) [39]: ## Define the models models =[ ("Logistic", LogisticRegression()), ("GaussianNB",GaussianNB()), ("Tree", DecisionTreeClassifier()), ("XGBoost", XGBClassifier()), ("Gradient Boosting", GradientBoostingClassifier()), ("LDA", LinearDiscriminantAnalysis()), ("SVC", SVC()) ] scores =["accuracy","roc_auc"] model_evaluation(models, scores, X_train.toarray(), y_train) Logistic [[10468 3542] [ 3608 10382]] precision recall f1-score support 0 0.7437 0.7472 0.7454 14010 1 0.7456 0.7421 0.7439 13990 accuracy 0.7446 28000 macro avg 0.7446 0.7446 0.7446 28000 weighted avg 0.7446 0.7446 0.7446 28000 130
Chapter 6. Results IMDb Reviews: Sentiment Analysis GaussianNB [[ 9595 4415] [ 3862 10128]] precision recall f1-score support 0 0.7130 0.6849 0.6987 14010 1 0.6964 0.7239 0.7099 13990 accuracy 0.7044 28000 macro avg 0.7047 0.7044 0.7043 28000 weighted avg 0.7047 0.7044 0.7043 28000 Tree [[8970 5040] [4978 9012]] precision recall f1-score support 0 0.6431 0.6403 0.6417 14010 1 0.6413 0.6442 0.6428 13990 accuracy 0.6422 28000 macro avg 0.6422 0.6422 0.6422 28000 weighted avg 0.6422 0.6422 0.6422 28000 XGBoost [[10398 3612] [ 3782 10208]] precision recall f1-score support 0 0.7333 0.7422 0.7377 14010 1 0.7386 0.7297 0.7341 13990 accuracy 0.7359 28000 macro avg 0.7360 0.7359 0.7359 28000 weighted avg 0.7360 0.7359 0.7359 28000 Gradient Boosting [[10556 3454] [ 3812 10178]] precision recall f1-score support 0 0.7347 0.7535 0.7440 14010 1 0.7466 0.7275 0.7369 13990 accuracy 0.7405 28000 macro avg 0.7407 0.7405 0.7405 28000 weighted avg 0.7407 0.7405 0.7405 28000 131
Chapter 6. Results IMDb Reviews: Sentiment Analysis LDA [[10498 3512] [ 3639 10351]] precision recall f1-score support 0 0.7426 0.7493 0.7459 14010 1 0.7467 0.7399 0.7433 13990 accuracy 0.7446 28000 macro avg 0.7446 0.7446 0.7446 28000 weighted avg 0.7446 0.7446 0.7446 28000 SVC [[10532 3478] [ 3632 10358]] precision recall f1-score support 0 0.7436 0.7517 0.7476 14010 1 0.7486 0.7404 0.7445 13990 accuracy 0.7461 28000 macro avg 0.7461 0.7461 0.7461 28000 weighted avg 0.7461 0.7461 0.7461 28000 [40]: def display_results(results, names, scores): # Create a DataFrame with mean and std for each score df_results =pd.DataFrame() df_results[ ' Model ' ]=names for score in scores: df_results[ ' Mean ' +score] =[result[score].mean() for result in ,→ results.values()] df_results[ ' Std ' +score] =[result[score].std() for result in results. ,→ values()] display(df_results) # Plot boxplot with means fig, axes =plt.subplots(len(scores), figsize=(10,8*len(scores))) for i, score in enumerate(scores): axes[i].set_title(score) axes[i].boxplot([result[score] for result in results.values()], ,→ labels=names, showmeans=True) plt.show() 132
Chapter 6. Results IMDb Reviews: Sentiment Analysis # Example usage display_results(results, names, [ ' accuracy ' , ' roc_auc ' ]) Model Mean accuracy Std accuracy Mean roc_auc Std roc_auc 0 Logistic 0.744643 0.009736 0.821323 0.009627 1 GaussianNB 0.704393 0.008310 0.775218 0.007537 2 Tree 0.642214 0.012242 0.642671 0.010289 3 XGBoost 0.735929 0.008710 0.810930 0.006704 4 Gradient Boosting 0.740500 0.009874 0.820305 0.008585 5 LDA 0.744607 0.010446 0.820955 0.009815 6 SVC 0.746071 0.009812 0.824763 0.009767 133
Chapter 6. Results IMDb Reviews: Sentiment Analysis 134
Chapter 6. Results IMDb Reviews: Sentiment Analysis For each model and from each fold, we obtain the accuracy and the roc auc, whose ditributions and means are visualised. In general, the majority of models (except GaussianNB and Tree) have good accuracy (around 75% on average) as well as good auc results (more than 0.8 over 1). The best models are Support Vector Machines (Classifier), Logistic Regression and LDA, which have a similar performance, although it is true that SVM has achieved a slightly better performance on average. Therefore, the best sentiment review analyser is SVC(). Hyperparameter search Once we have selected the best model, SVC, for our machine learning task, it becomes crucial to fine-tune its performance by optimising its hyperparameters. Performing a hyperparameter search involves systematically exploring different combinations of hyperparameters to find the optimal configuration that maximises the model’s performance (regarding roc auc) on the given dataset. Since we have a balanced dataset, we could have used accuracy as metric instead. Some SVC() hyperparameters we can tune are: • C: it is known as the regularisation parameter, which determines the trade-off between achieving a low training error and having a simpler decision boundary. It controls the penalty for misclassifying training examples. • gamma: defines the influence of each training example on the decision boundary. It controls the shape of the decision boundary and the flexibility of the model. • kernel: determines the type of decision boundary that the SVM algorithm will learn. It specifies the function used to transform the input features into higher-dimensional space, where a linear decision boundary can be more effectively found. [41]: model =SVC() grid ={ ' C ' :[1,10], ' gamma ' :[1,0.1], ' kernel ' :[ ' linear ' , ' rbf ' ]} cv =StratifiedKFold(n_splits=5) grid_search =GridSearchCV(estimator=model, param_grid=grid, n_jobs=-1, cv=cv, ,→ scoring= ' roc_auc ' ,error_score=0) [42]: grid_result =grid_search.fit(X_train, y_train) # summarise results print("Best ROC AUC: %f with parameters %s"%(grid_result.best_score_, ,→ grid_result.best_params_)) Best ROC AUC: 0.831763 with parameters { ' C ' : 1, ' gamma ' : 1, ' kernel ' : ' rbf ' } The probability that the model will assign a larger probability to a random positive review than a random negative review is 0.831763, which is as a good value. The kernel selected is the Gaussian Radial Basis Function (RBF). Mathematically: k(x,y) = e−||x−y||2 2σ2 135
Chapter 6. Results IMDb Reviews: Sentiment Analysis [43]: # define models and parameters model =SVC(C = 1, gamma = 1, kernel ="rbf") model.fit(X_train,y_train) [43]: SVC(C=1, gamma=1) [44]: y_pred =model.predict(X_test) cm =confusion_matrix(y_test, y_pred) print(cm) print(classification_report(y_test,y_pred, digits = 4)) [[4649 1416] [1525 4410]] precision recall f1-score support 0 0.7530 0.7665 0.7597 6065 1 0.7570 0.7430 0.7499 5935 accuracy 0.7549 12000 macro avg 0.7550 0.7548 0.7548 12000 weighted avg 0.7550 0.7549 0.7549 12000 Interpretations Precision + Out of all the reviews that the model predicted to be positive, “only” 75.3% actually were. • Out of all the reviews that the model predicted to be negative, “only” 75.7% actually were. Recall + Out of all the reviews that actually were positive, the model predicted this outcome correctly for 76.65% of those reviews. • Out of all the reviews that actually were negative, the model predicted this outcome correctly for 74.3% of those reviews. Accuracy • We can conclude that the model correctly predicted the outcome for approximately 75.49% of the reviews. [45]: plt =ConfusionMatrixDisplay(cm) # Show the plot plt.plot() [45]: <sklearn.metrics._plot.confusion_matrix.ConfusionMatrixDisplay at 0x1bbd4f9eac0> 136
Chapter 6. Results IMDb Reviews: Sentiment Analysis We can visualise that 4649 were correctly classified as true out of 6065 actual positive reviews and that 4410 were correctly classified as negative reviews out of 5935 actual negative reviews. Another insight is that 4649 were actual positive reviews out of 6174 reviews classified as positive and that 4410 were actual negative reviews out of 5826 reviews classified as negative. [46]: cmn =confusion_matrix(y_test, y_pred, normalize ="true") plt =ConfusionMatrixDisplay(cmn) # if ' true ' , the confusion matrix is normalized over the true conditions (e.g. ,→ rows); # Show the plot plt.plot() [46]: <sklearn.metrics._plot.confusion_matrix.ConfusionMatrixDisplay at 0x1bbd4f8ffd0> 137