code
stringlengths
2.5k
6.36M
kind
stringclasses
2 values
parsed_code
stringlengths
0
404k
quality_prob
float64
0
0.98
learning_prob
float64
0.03
1
# 1 Introducing 16S Microbiome Primary Analysis Amanda Birmingham, CCBB, UCSD ([email protected]) This document introduces a Standard Operating Procedure (SOP) that covers primary analysis of single-end, three-read, Golay-barcoded microbiome 16S sequencing data. <a name = "table-of-contents"></a> ## Table of Contents * [Background](#background) * [Basic Approach](#basic-approach) * [Required Inputs](#required-inputs) * [Standard Outputs](#standard-outputs) * [Required Time And Resources](#required-time-and-resources) Related Notebooks: * 2 Setting Up Starcluster for QIIME * 3 Validation, Demultiplexing, and Quality Control * 4 OTU Picking and Rarefaction Depth Selection * 5 Analyzing Core Diversity <a name = "background"></a> ## Background 16S rRNA is the small sub-unit (SSU) of bacteria’s ribosome. This gene is largely conserved across bacteria and archaea (providing conserved primer sites for amplification by polymerase chain reaction (PCR)) but also has hypervariable regions that can be used to separate different microbial “species”--more properly known as Operational Taxonomic Units or OTUs--and build phylogenetic trees. Usually, samples are taken from mixed microbial communities and a portion of the 16S gene is amplified by PCR (note that eukaryotic DNA is not widely amplified by primers to this gene as eukaryotes’ SSU is 18S rRNA). Amplicons are labeled with sample-specific indexes and sequenced in a highly multiplexed next-generation sequencing run. The Earth Microbiome Project standard 16S rRNA Amplification Protocol (see http://www.earthmicrobiome.org/emp-standard-protocols/16s/ ) recommends the use of a standard set of error-correcting Golay barcodes as the indices. In this case, a common sequencing approach produces three reads (read 1, read 2, and a barcode read, similar to the Illumina TruSeq approach) for each sample, with read lengths in the 100-150 base range, as shown here in this image from http://tucf-genomics.tufts.edu: <img src = "images/faq03_pic01.png" /> The resulting sequence data, once analyzed, provides information on the identity and abundance of the microbes in each sample. [Table of Contents](#table-of-contents) <a name = "basic-approach"></a> ## Basic Approach This SOP employs the QIIME (pronounced "chime") software developed by the Knight lab at UCSD to perform "primary analysis", the first stage of analysis of all 16S-based microbiome data. The major steps of this work are (i) read demultiplexing (if necessary) and basic quality control (QC), (ii) OTU picking, and (iii) core diversity analysis. Step iii comprises taxa summarization, alpha diversity calculations, and beta diversity calculations. Alpha diversity (i.e., within-sample) calculations are performed for three commonly used metrics: number of observed OTUs, whole-tree phylogenetic diversity, and the chao1 metric. The distributions of these metrics are visualized in boxplots for each selected category in the input data. Additionally, rarefaction curves are produced for each of these metrics for each category in the input data. Beta diversity (i.e., between-sample) calculations are performed for two commonly used metrics: unweighted and weighted UniFrac. The distributions of these two metrics are visualized in boxplots for each selected category in the input data. Additionally, for each metric, a principal coordinates analysis (PCoA) is performed and the top three dimensions of the result are visualized as an interactive 3-D graph. Primary analysis excludes tasks such as investigating the effect of alternate sequence depths on outcomes, recalculating diversity metrics on researcher-selected subsets of the full data set, and investigation of hypotheses generated from the primary analysis deliverables. The pipeline is executed by the validate_mapping_file.py, split_libraries_fastq.py, pick_open_reference_otus.py, and core_diversity_analyses.py workflow scripts of the QIIME open-source microbial ecology package. This software is built in Python 2.7.3 and deployed on Ubuntu linux. 3-D graphs are visualized with Emperor, a browser-based open-source visualization tool. Analysis currently runs on Amazon Web Services using Python-based StarCluster 0.95.6, an open-source cluster-computing toolkit, although it is anticipated that future versions of the cluster will transition to cfncluster for greater flexibility in dynamic cluster sizing. [Table of Contents](#table-of-contents) <a name = "required-inputs"></a> ## Required Inputs Researchers requesting primary analysis should provide the following: 1. fastq file(s) of the 16S reads 2. A comma-separated-value mapping file with one row for each sample, containing (see http://qiime.org/documentation/file_formats.html , quoted below, for more details) * Sample name * Barcode sequence used for the sample * Linker/primer sequence used to amplify the sample * Sample description * “Any metadata that relates to the samples (for instance, health status or sampling site)” * “Any additional information relating to specific samples that may be useful to have at hand when considering outliers (for example, what medications a patient was taking at time of sampling)” 3. Experimental design information including * Sequencing instrument used * Expected read length * Expected read depth * Read type (single- or paired-end) * **Integrated analysis of paired-end reads is currently beyond the scope of this SOP**, but analysis of one of the two reads from a paired-end experiment is usually adequate. * Whether data have already been demultiplexed * If not * fastq file(s) of their barcodes for experiments with a separate index read * **Analysis of experiments not using a separate index read is currently beyond the scope of this SOP** * **Analysis of experiments using indexes other than those from the standard protocol is currently beyond the scope of this SOP** * Whether data contains positive or negative controls * If so, how to identify them in the mapping file * As many as four categories from mapping file that should be used to group data during primary analysis * (Optional) Preferences for * Minimum sequencing depth to use during rarefaction (essentially, preference for whether analyst should favor broader sample coverage or better-quality data per sample). * Default: Analyst’s choice based on data * OTU picking method (de novo, open reference, or closed reference) * Default: open reference * If open or closed, source of OTU reference sequences * Default: current greengenes 97% collection * Three or fewer alpha diversity metrics to employ * Default: number of observed OTUs, whole-tree phylogenetic diversity, and chao1 * Two or fewer beta diversity metrics to employ * Default: unweighted UniFrac, weighted UniFrac [Table of Contents](#table-of-contents) <a name = "standard-outputs"></a> ## Standard Outputs 1. If applicable, demultiplexed file(s) 2. If applicable, corrected mapping file that passes QIIME validation 3. Folder containing OTU picking outputs, including * OTU table file(s) in .biom format * Representative sequence set file in fasta format * Representative set taxonomy file in .tre format * Summary text file of counts per sample 4. Folder containing alpha diversity analysis outputs, including * Alpha rarefaction curves in .png format * Categorized alpha diversity metric box plots in .pdf format 5. Folder containing beta diversity outputs, including * Categorized beta diversity metric box plots in .pdf format * Interactive 3-D Emperor PCoA graphic, in .html format 6. Brief methods text suitable for publication, describing key method steps and choices such as that of sample depth, in .docx format 7. Summary report presentation describing findings, in .pptx format In the case of successful primary analysis, all of the above will be delivered. In the case of unsuccessful analysis due to low sequence quality, unsuccessful OTU picking, etc., deliverable 7 (summary report) will be delivered, as well as any other deliverables deemed meaningful by the analyst. [Table of Contents](#table-of-contents) <a name = "required-time-and-resources"></a> ## Required Time and Resources Typical microbiome datasets comprise a portion of a MiSeq run (which can contain up to ~15 million reads) split over a few hundred multiplexed samples, using ~1-5 gigabytes (GB) of storage. Although precise run times are, of course, a function of dataset size, sequence quality, categories chosen for analysis, and so forth, computation for primary analysis of a typical microbiome dataset can usually be completed in less than one working day. Only an hour or two of analyst time is required during this computation day, while another 2 to 8 hours of analyst effort is needed to assess the computed results, draw conclusions, and prepare deliverables; more time may of course be required for datasets that cause errors during primary analysis. For example, a primary analysis computation for dataset of ~6.5 million 100-base reads plus barcodes across 467 samples (~4 GB of sequence) took ~4 calendar hours on a 3-node StarCluster comprised of m3.2xlarge instances (each of which has 8 CPUs and 30 GB RAM) attached to a shared 30 GB EBS volume. [Table of Contents](#table-of-contents)
github_jupyter
# 1 Introducing 16S Microbiome Primary Analysis Amanda Birmingham, CCBB, UCSD ([email protected]) This document introduces a Standard Operating Procedure (SOP) that covers primary analysis of single-end, three-read, Golay-barcoded microbiome 16S sequencing data. <a name = "table-of-contents"></a> ## Table of Contents * [Background](#background) * [Basic Approach](#basic-approach) * [Required Inputs](#required-inputs) * [Standard Outputs](#standard-outputs) * [Required Time And Resources](#required-time-and-resources) Related Notebooks: * 2 Setting Up Starcluster for QIIME * 3 Validation, Demultiplexing, and Quality Control * 4 OTU Picking and Rarefaction Depth Selection * 5 Analyzing Core Diversity <a name = "background"></a> ## Background 16S rRNA is the small sub-unit (SSU) of bacteria’s ribosome. This gene is largely conserved across bacteria and archaea (providing conserved primer sites for amplification by polymerase chain reaction (PCR)) but also has hypervariable regions that can be used to separate different microbial “species”--more properly known as Operational Taxonomic Units or OTUs--and build phylogenetic trees. Usually, samples are taken from mixed microbial communities and a portion of the 16S gene is amplified by PCR (note that eukaryotic DNA is not widely amplified by primers to this gene as eukaryotes’ SSU is 18S rRNA). Amplicons are labeled with sample-specific indexes and sequenced in a highly multiplexed next-generation sequencing run. The Earth Microbiome Project standard 16S rRNA Amplification Protocol (see http://www.earthmicrobiome.org/emp-standard-protocols/16s/ ) recommends the use of a standard set of error-correcting Golay barcodes as the indices. In this case, a common sequencing approach produces three reads (read 1, read 2, and a barcode read, similar to the Illumina TruSeq approach) for each sample, with read lengths in the 100-150 base range, as shown here in this image from http://tucf-genomics.tufts.edu: <img src = "images/faq03_pic01.png" /> The resulting sequence data, once analyzed, provides information on the identity and abundance of the microbes in each sample. [Table of Contents](#table-of-contents) <a name = "basic-approach"></a> ## Basic Approach This SOP employs the QIIME (pronounced "chime") software developed by the Knight lab at UCSD to perform "primary analysis", the first stage of analysis of all 16S-based microbiome data. The major steps of this work are (i) read demultiplexing (if necessary) and basic quality control (QC), (ii) OTU picking, and (iii) core diversity analysis. Step iii comprises taxa summarization, alpha diversity calculations, and beta diversity calculations. Alpha diversity (i.e., within-sample) calculations are performed for three commonly used metrics: number of observed OTUs, whole-tree phylogenetic diversity, and the chao1 metric. The distributions of these metrics are visualized in boxplots for each selected category in the input data. Additionally, rarefaction curves are produced for each of these metrics for each category in the input data. Beta diversity (i.e., between-sample) calculations are performed for two commonly used metrics: unweighted and weighted UniFrac. The distributions of these two metrics are visualized in boxplots for each selected category in the input data. Additionally, for each metric, a principal coordinates analysis (PCoA) is performed and the top three dimensions of the result are visualized as an interactive 3-D graph. Primary analysis excludes tasks such as investigating the effect of alternate sequence depths on outcomes, recalculating diversity metrics on researcher-selected subsets of the full data set, and investigation of hypotheses generated from the primary analysis deliverables. The pipeline is executed by the validate_mapping_file.py, split_libraries_fastq.py, pick_open_reference_otus.py, and core_diversity_analyses.py workflow scripts of the QIIME open-source microbial ecology package. This software is built in Python 2.7.3 and deployed on Ubuntu linux. 3-D graphs are visualized with Emperor, a browser-based open-source visualization tool. Analysis currently runs on Amazon Web Services using Python-based StarCluster 0.95.6, an open-source cluster-computing toolkit, although it is anticipated that future versions of the cluster will transition to cfncluster for greater flexibility in dynamic cluster sizing. [Table of Contents](#table-of-contents) <a name = "required-inputs"></a> ## Required Inputs Researchers requesting primary analysis should provide the following: 1. fastq file(s) of the 16S reads 2. A comma-separated-value mapping file with one row for each sample, containing (see http://qiime.org/documentation/file_formats.html , quoted below, for more details) * Sample name * Barcode sequence used for the sample * Linker/primer sequence used to amplify the sample * Sample description * “Any metadata that relates to the samples (for instance, health status or sampling site)” * “Any additional information relating to specific samples that may be useful to have at hand when considering outliers (for example, what medications a patient was taking at time of sampling)” 3. Experimental design information including * Sequencing instrument used * Expected read length * Expected read depth * Read type (single- or paired-end) * **Integrated analysis of paired-end reads is currently beyond the scope of this SOP**, but analysis of one of the two reads from a paired-end experiment is usually adequate. * Whether data have already been demultiplexed * If not * fastq file(s) of their barcodes for experiments with a separate index read * **Analysis of experiments not using a separate index read is currently beyond the scope of this SOP** * **Analysis of experiments using indexes other than those from the standard protocol is currently beyond the scope of this SOP** * Whether data contains positive or negative controls * If so, how to identify them in the mapping file * As many as four categories from mapping file that should be used to group data during primary analysis * (Optional) Preferences for * Minimum sequencing depth to use during rarefaction (essentially, preference for whether analyst should favor broader sample coverage or better-quality data per sample). * Default: Analyst’s choice based on data * OTU picking method (de novo, open reference, or closed reference) * Default: open reference * If open or closed, source of OTU reference sequences * Default: current greengenes 97% collection * Three or fewer alpha diversity metrics to employ * Default: number of observed OTUs, whole-tree phylogenetic diversity, and chao1 * Two or fewer beta diversity metrics to employ * Default: unweighted UniFrac, weighted UniFrac [Table of Contents](#table-of-contents) <a name = "standard-outputs"></a> ## Standard Outputs 1. If applicable, demultiplexed file(s) 2. If applicable, corrected mapping file that passes QIIME validation 3. Folder containing OTU picking outputs, including * OTU table file(s) in .biom format * Representative sequence set file in fasta format * Representative set taxonomy file in .tre format * Summary text file of counts per sample 4. Folder containing alpha diversity analysis outputs, including * Alpha rarefaction curves in .png format * Categorized alpha diversity metric box plots in .pdf format 5. Folder containing beta diversity outputs, including * Categorized beta diversity metric box plots in .pdf format * Interactive 3-D Emperor PCoA graphic, in .html format 6. Brief methods text suitable for publication, describing key method steps and choices such as that of sample depth, in .docx format 7. Summary report presentation describing findings, in .pptx format In the case of successful primary analysis, all of the above will be delivered. In the case of unsuccessful analysis due to low sequence quality, unsuccessful OTU picking, etc., deliverable 7 (summary report) will be delivered, as well as any other deliverables deemed meaningful by the analyst. [Table of Contents](#table-of-contents) <a name = "required-time-and-resources"></a> ## Required Time and Resources Typical microbiome datasets comprise a portion of a MiSeq run (which can contain up to ~15 million reads) split over a few hundred multiplexed samples, using ~1-5 gigabytes (GB) of storage. Although precise run times are, of course, a function of dataset size, sequence quality, categories chosen for analysis, and so forth, computation for primary analysis of a typical microbiome dataset can usually be completed in less than one working day. Only an hour or two of analyst time is required during this computation day, while another 2 to 8 hours of analyst effort is needed to assess the computed results, draw conclusions, and prepare deliverables; more time may of course be required for datasets that cause errors during primary analysis. For example, a primary analysis computation for dataset of ~6.5 million 100-base reads plus barcodes across 467 samples (~4 GB of sequence) took ~4 calendar hours on a 3-node StarCluster comprised of m3.2xlarge instances (each of which has 8 CPUs and 30 GB RAM) attached to a shared 30 GB EBS volume. [Table of Contents](#table-of-contents)
0.87851
0.8586
# Coding Paradigms for Device Control ``` %serialconnect ``` ## The Coding Challenge PD control for a Ball on beam device. The device is to sense the position of a ball on a 50cm beam, compare to a setpoint, and adjust beam position with servo motor. The setpoint and control constant is to be given by the device user. Display all relevant data. Use a button to start and stop operation. Devices: * Distance sensor - sense ball position * Analog actuator - change beam angle * Analog sensor - proportional gain * Analog sensor - derivative time * Analog sensor - setpoint * Display - display position, angle * Display - display control parameters * Button - Start/Stop Create code to: * Measure the ball position * Perform an action in response to the analog signal * Display state on LCD * Use on-board LED to show operational status ## Coding Paradigms * Single threaded, imperative coding * Python classes * further modularizes coding * data logging classes* Python classes * further modularizes coding * data logging classes * Python generators * separates event loop from device details * modularizes the device coding * each device can maintain a separate state * Asynchronous coding * further abstraction the event loop * non-blocking * multi-threading ## Single threaded, imperative coding ``` from machine import Pin, PWM import time class Servo(object): def __init__(self, gpio, freq=50): self.gpio = gpio self.pwm = PWM(Pin(gpio, Pin.IN)) self.pwm.freq(freq) self.pwm.duty_ns(0) def set_value(self, value): self.pulse_us = 500 + 20*max(0, min(100, value)) self.pwm.duty_ns(int(1000*self.pulse_us)) def off(self): self.pwm.duty_ns(0) servo = Servo(16) servo.set_value(0) time.sleep(2) servo.set_value(100) time.sleep(2) servo.off() from machine import Pin, I2C from lcd1602 import LCD1602 as LCD class Screen(object): def __init__(self, id, sda, scl): self.sda = Pin(sda, Pin.OUT) self.scl = Pin(scl, Pin.OUT) self.i2c = I2C(id, sda=self.sda, scl=self.scl) self.lcd = LCD(self.i2c, 2, 16) self.lcd.clear() def print(self, lines): for k, line in enumerate(lines): if line is not None: self.lcd.setCursor(0, k) self.lcd.print(line) screen0 = Screen(0, sda=8, scl=9) screen1 = Screen(1, sda=6, scl=7) screen0.print(("Hello World", "Go Irish!")) screen1.print(["", "Hello"]) from machine import Pin class PWM_motor(object): def __init__(self, gpio): self.pwm = PWM(Pin(gpio)) class Servo(PWM_motor): def __init__(self, gpio, freq=50): super(Y, self).__init__(gpio) self.pwm.freq(freq) def set_value(self, value): self.pulse_us = 500 + 20*max(0, min(100, value)) self.pwm.duty_ns(int(1000*self.pulse_us)) servo = Servo(16) servo.set_value(50) import machine import time class UltrasonicSensor(object): def __init__(self, gpio): self.pin = Pin(gpio) def get_distance_cm(self): # send pulse self.pin.init(Pin.OUT) self.pin.value(0) time.sleep_us(2) self.pin.value(1) time.sleep_us(10) self.pin.value(0) # listen for response self.pin.init(Pin.IN) # wait for on t0 = time.ticks_us() count = 0 while count < 10000: if self.pin.value(): break count += 1 # wait for off t1 = time.ticks_us() count = 0 while count < 10000: if not self.pin.value(): break count += 1 t2 = time.ticks_us() if t1 - t2 < 530: return (t2 - t1) / 29 / 2 else: return 0 sensor = UltrasonicSensor(20) print(sensor.get_distance_cm()) from machine import Pin, I2C, ADC, PWM import time from lcd1602 import LCD1602 as LCD from knob import Knob class Servo(object): def __init__(self, gpio, freq=50): self.gpio = gpio self.pwm = PWM(Pin(gpio)) self.pwm.freq(freq) self.pwm.duty_ns(0) def set_value(self, value): self.pulse_us = 500 + 20*max(0, min(100, value)) self.pwm.duty_ns(int(1000*self.pulse_us)) def off(self): self.pwm.duty_ns(0) class Screen(object): def __init__(self, id, sda, scl): self.sda = Pin(sda, Pin.OUT) self.scl = Pin(scl, Pin.OUT) self.i2c = I2C(id, sda=self.sda, scl=self.scl) self.lcd = LCD(self.i2c, 2, 16) self.lcd.clear() def print(self, lines): for k, line in enumerate(lines): if line is not None: self.lcd.setCursor(0, k) self.lcd.print(line) ## set up led led = Pin(25, Pin.OUT) ## set up lcd display 0 display0 = Screen(0, sda=8, scl=9) display1 = Screen(1, sda=6, scl=7) ## setup rotary angle sensors knob0 = Knob(26) knob1 = Knob(27) ## setup ultra-sonic distance sensor on Pin 20 sensor = UltrasonicSensor(20) ## set up servo motor servo = Servo(16) start = time.time() ball_position = 0 while time.time() - start < 20: ball_position = sensor.get_distance_cm() ball_setpoint = 50*knob0.get_value()/100 display0.print([f"SP = {ball_setpoint:0.2f} cm", f"PV = {ball_position:0.2f} cm"]) Kp = knob1.get_value() u = Kp*(ball_setpoint - ball_position) servo.set_value(u) display1.print([f"Kp = {Kp}", f"MV = {dt_us}"]) time.sleep(0.1) servo.off() ``` ## Discuss * Does this code provide a working prototype? * Is this code maintaina
github_jupyter
%serialconnect from machine import Pin, PWM import time class Servo(object): def __init__(self, gpio, freq=50): self.gpio = gpio self.pwm = PWM(Pin(gpio, Pin.IN)) self.pwm.freq(freq) self.pwm.duty_ns(0) def set_value(self, value): self.pulse_us = 500 + 20*max(0, min(100, value)) self.pwm.duty_ns(int(1000*self.pulse_us)) def off(self): self.pwm.duty_ns(0) servo = Servo(16) servo.set_value(0) time.sleep(2) servo.set_value(100) time.sleep(2) servo.off() from machine import Pin, I2C from lcd1602 import LCD1602 as LCD class Screen(object): def __init__(self, id, sda, scl): self.sda = Pin(sda, Pin.OUT) self.scl = Pin(scl, Pin.OUT) self.i2c = I2C(id, sda=self.sda, scl=self.scl) self.lcd = LCD(self.i2c, 2, 16) self.lcd.clear() def print(self, lines): for k, line in enumerate(lines): if line is not None: self.lcd.setCursor(0, k) self.lcd.print(line) screen0 = Screen(0, sda=8, scl=9) screen1 = Screen(1, sda=6, scl=7) screen0.print(("Hello World", "Go Irish!")) screen1.print(["", "Hello"]) from machine import Pin class PWM_motor(object): def __init__(self, gpio): self.pwm = PWM(Pin(gpio)) class Servo(PWM_motor): def __init__(self, gpio, freq=50): super(Y, self).__init__(gpio) self.pwm.freq(freq) def set_value(self, value): self.pulse_us = 500 + 20*max(0, min(100, value)) self.pwm.duty_ns(int(1000*self.pulse_us)) servo = Servo(16) servo.set_value(50) import machine import time class UltrasonicSensor(object): def __init__(self, gpio): self.pin = Pin(gpio) def get_distance_cm(self): # send pulse self.pin.init(Pin.OUT) self.pin.value(0) time.sleep_us(2) self.pin.value(1) time.sleep_us(10) self.pin.value(0) # listen for response self.pin.init(Pin.IN) # wait for on t0 = time.ticks_us() count = 0 while count < 10000: if self.pin.value(): break count += 1 # wait for off t1 = time.ticks_us() count = 0 while count < 10000: if not self.pin.value(): break count += 1 t2 = time.ticks_us() if t1 - t2 < 530: return (t2 - t1) / 29 / 2 else: return 0 sensor = UltrasonicSensor(20) print(sensor.get_distance_cm()) from machine import Pin, I2C, ADC, PWM import time from lcd1602 import LCD1602 as LCD from knob import Knob class Servo(object): def __init__(self, gpio, freq=50): self.gpio = gpio self.pwm = PWM(Pin(gpio)) self.pwm.freq(freq) self.pwm.duty_ns(0) def set_value(self, value): self.pulse_us = 500 + 20*max(0, min(100, value)) self.pwm.duty_ns(int(1000*self.pulse_us)) def off(self): self.pwm.duty_ns(0) class Screen(object): def __init__(self, id, sda, scl): self.sda = Pin(sda, Pin.OUT) self.scl = Pin(scl, Pin.OUT) self.i2c = I2C(id, sda=self.sda, scl=self.scl) self.lcd = LCD(self.i2c, 2, 16) self.lcd.clear() def print(self, lines): for k, line in enumerate(lines): if line is not None: self.lcd.setCursor(0, k) self.lcd.print(line) ## set up led led = Pin(25, Pin.OUT) ## set up lcd display 0 display0 = Screen(0, sda=8, scl=9) display1 = Screen(1, sda=6, scl=7) ## setup rotary angle sensors knob0 = Knob(26) knob1 = Knob(27) ## setup ultra-sonic distance sensor on Pin 20 sensor = UltrasonicSensor(20) ## set up servo motor servo = Servo(16) start = time.time() ball_position = 0 while time.time() - start < 20: ball_position = sensor.get_distance_cm() ball_setpoint = 50*knob0.get_value()/100 display0.print([f"SP = {ball_setpoint:0.2f} cm", f"PV = {ball_position:0.2f} cm"]) Kp = knob1.get_value() u = Kp*(ball_setpoint - ball_position) servo.set_value(u) display1.print([f"Kp = {Kp}", f"MV = {dt_us}"]) time.sleep(0.1) servo.off()
0.331552
0.75037
``` #default_exp suite ``` # Model Suite <br> ### Imports ``` #exports import yaml import numpy as np import pandas as pd from sklearn.ensemble import RandomForestRegressor from sklearn.model_selection import KFold, train_test_split from wpdhack import data, feature from tqdm import tqdm from random import randint from typing import Protocol from importlib import import_module import seaborn as sns import matplotlib.pyplot as plt from IPython.display import JSON #exports class ScikitModel(Protocol): def fit(self, X, y, sample_weight=None): ... def predict(self, X): ... def score(self, X, y, sample_weight=None): ... def set_params(self, **params): ... def create_train_test_indexes(X, **split_kwargs): if 'n_splits' not in split_kwargs.keys(): assert 'test_size' in split_kwargs.keys(), 'You must provide either `n_splits` or `test_size` within the `split_kwargs` parameters' size = X.shape[0] index_array = np.linspace(0, size-1, size).astype(int) train_test_indexes = [tuple(train_test_split(index_array, **split_kwargs))] else: kf = KFold(**split_kwargs) train_test_indexes = kf.split(X) return train_test_indexes def calculate_error_metrics(y1, y2, y1_pred, y2_pred, y_baseline): baseline_combined_rmse = np.sqrt(np.square(y_baseline - y1).sum() + np.square(y_baseline - y2).sum()) combined_rmse = np.sqrt(np.square(y1_pred - y1).sum() + np.square(y2_pred - y2).sum()) error_metrics = { 'y1_rmse': np.sqrt(np.square(y1_pred - y1).sum()), 'y2_rmse': np.sqrt(np.square(y2_pred - y2).sum()), 'combined_rmse': combined_rmse, 'skill_score': combined_rmse/baseline_combined_rmse } return error_metrics def calc_month_error_metrics( df_pred, df_target, month: str='2021-08' ): common_idxs = pd.DatetimeIndex(sorted(list(set(df_pred.index.intersection(df_target.index.tz_convert(None)))))) df_pred, df_target = df_pred.loc[common_idxs], df_target.loc[common_idxs.tz_localize('UTC')] df_pred, df_target = df_pred.drop_duplicates(), df_target.drop_duplicates() error_metrics = calculate_error_metrics( df_target.loc[month, 'value_max'].values, df_target.loc[month, 'value_min'].values, df_pred.loc[month, 'value_max'].values, df_pred.loc[month, 'value_min'].values, df_pred.loc[month, 'value_mean'].values ) return error_metrics def construct_prediction_df( y1_pred: np.ndarray, y2_pred: np.ndarray, index: pd.Index, df_features: pd.DataFrame ): df_pred = pd.DataFrame({'value_max': y1_pred, 'value_min': y2_pred}, index=index) df_pred.index.name = 'time' df_pred.index = index.tz_convert(None) # handling invalid values invalid_max_idxs = df_pred.index[~(df_features['value'].values < df_pred['value_max'].values)] invalid_min_idxs = df_pred.index[~(df_features['value'].values > df_pred['value_min'].values)] if len(invalid_max_idxs) > 0: df_pred.loc[invalid_max_idxs, 'value_max'] = df_features.loc[invalid_max_idxs.tz_localize('UTC'), 'value'].values if len(invalid_min_idxs) > 0: df_pred.loc[invalid_min_idxs, 'value_min'] = df_features.loc[invalid_min_idxs.tz_localize('UTC'), 'value'].values # final checks assert df_pred.isnull().sum().sum() == 0, 'There should be no NaN values in the predictions' return df_pred class ModelSuite: def __init__( self, model_1: ScikitModel=RandomForestRegressor(), model_2: ScikitModel=RandomForestRegressor(), ): self.set_models(model_1, model_2) return def set_models( self, model_1: ScikitModel=RandomForestRegressor(), model_2: ScikitModel=RandomForestRegressor(), trained: bool=False ): self.model_1 = model_1 self.model_2 = model_2 self.trained = trained return def fit_models( self, X: np.ndarray, y1: np.ndarray, y2: np.ndarray, shuffle=True, ): if shuffle == True: shuffler = np.random.permutation(X.shape[0]) X, y1, y2 = X[shuffler], y1[shuffler], y2[shuffler] if self.model_2 is not None: self.model_1.fit(X, y1) self.model_2.fit(X, y2) else: Y = np.column_stack([y1, y2]) self.model_1.fit(X, Y) self.trained = True return def predict_models( self, X: np.ndarray ): if self.model_2 is not None: y1_pred = self.model_1.predict(X) y2_pred = self.model_2.predict(X) else: Y_pred = self.model_1.predict(X) y1_pred, y2_pred = Y_pred[:, 0], Y_pred[:, 1] return y1_pred, y2_pred def run_test( self, df_target: pd.DataFrame, df_features: pd.DataFrame, y1_col: str='value_max', y2_col: str='value_min', split_kwargs: dict={ 'test_size': 0.1, 'shuffle': False }, use_target_delta: bool=False, fit_shuffle: bool=True ): X = df_features.values y1, y2 = df_target[y1_col].values, df_target[y2_col].values y_baseline = df_features['value'].values error_metrics = [] df_pred = pd.DataFrame() train_test_indexes = create_train_test_indexes(X, **split_kwargs) for train_index, test_index in train_test_indexes: X_train, X_test, y1_train, y1_test, y2_train, y2_test, y_baseline_train, y_baseline_test = X[train_index], X[test_index], y1[train_index], y1[test_index], y2[train_index], y2[test_index], y_baseline[train_index], y_baseline[test_index] self.fit_models(X_train, y1_train, y2_train, shuffle=fit_shuffle) y1_pred, y2_pred = self.predict_models(X_test) if use_target_delta == True: y1_pred, y2_pred, y1_test, y2_test = y1_pred+y_baseline_test, y2_pred+y_baseline_test, y1_test+y_baseline_test, y2_test+y_baseline_test df_pred = df_pred.append(construct_prediction_df(y1_pred, y2_pred, df_features.index[test_index], df_features.iloc[test_index]).assign(value_mean=y_baseline_test)) error_metrics += [calculate_error_metrics(y1_test, y2_test, y1_pred, y2_pred, y_baseline_test)] df_pred = df_pred.sort_index() avg_error_metrics = pd.DataFrame(error_metrics).mean().to_dict() return avg_error_metrics, df_pred def run_submission( self, df_train_target: pd.DataFrame, df_train_features: pd.DataFrame, df_submission_features: pd.DataFrame, submissions_dir: str='../data/submission', y1_col: str='value_max', y2_col: str='value_min', save_submission: bool=False, use_target_delta: bool=False, shuffle: bool=True ): X_train = df_train_features.values y1_train, y2_train = df_train_target[y1_col].values, df_train_target[y2_col].values X_submission = df_submission_features.values submission_index = df_submission_features.index # should shuffle indexes before doing this self.fit_models(X_train, y1_train, y2_train, shuffle=shuffle) y1_submission, y2_submission = self.predict_models(X_submission) df_pred = construct_prediction_df(y1_submission, y2_submission, submission_index, df_submission_features) if use_target_delta == True: assert 'value' in df_submission_features.columns df_pred = df_pred.add(df_submission_features['value'], axis=0) # saving if save_submission == True: df_pred.to_csv(f'{submissions_dir}/predictions.csv') df_pred.to_csv(f'{submissions_dir}/archive/predictions_{pd.Timestamp.now().strftime("%Y-%m-%d %H-%M-%S")}.csv') return df_pred data_dir = '../data' real_power_data_dir = '../data/real_power' sites = ['staplegrove'] grid_points = [1] df_features, df_target = data.construct_baseline_features_target_dfs(data_dir, weather_sites=sites, weather_grid_points=grid_points) df_features, df_target = feature.create_additional_features(df_features, df_target, sites=sites, grid_points=grid_points) df_target.index = df_target.index.tz_convert(None) df_features.head() # add example here of training and testing #exports def load_module_attr(module_attr_path: str): *module, attr = module_attr_path.split('.') assert len(module)>0, 'A module has not been passed, only an attribute' func = getattr(import_module('.'.join(module)), attr) return func def run_parameterised_model( data_dir: str='data', model_1: str='lightgbm.LGBMRegressor', # these can be any sklearn compatible model model_2: str='lightgbm.LGBMRegressor', model_1_kwargs: dict={}, model_2_kwargs: dict={}, data_kwargs: dict={ 'real_power_sub_dir': 'real_power', 'weather_sub_dir': 'weather', 'real_power_time_period': '_pre_august', 'real_power_site': 'Staplegrove_CB905', 'weather_sites': ['staplegrove'], 'weather_grid_points': [1], 'weather_interpolate_method': 'interpolate', 'use_target_delta': False }, y1_col: str='value_max', y2_col: str='value_min', split_kwargs: dict={ 'n_splits': 5, 'shuffle': False }, cols_subset: list=['value', 'temperature_staplegrove_1', 'solar_irradiance_staplegrove_1', 'windspeed_north_staplegrove_1', 'windspeed_east_staplegrove_1', 'pressure_staplegrove_1', 'spec_humidity_staplegrove_1', 'hour', 'doy', 'weekend', 'direction_staplegrove_1', 'speed_staplegrove_1', 'hcdh_staplegrove_1'], features_kwargs: dict={ 'features': ['temporal', 'dir_speed', 'hcdh'],#, 'lagged'], 'sites': ['staplegrove'], 'grid_points': [1] }, fit_shuffle: bool=True, weights_func=None, resampling_factor=None ): input_data = locals() if 'use_target_delta' not in data_kwargs.keys(): use_target_delta = False else: use_target_delta = data_kwargs['use_target_delta'] # data loading, generation, and processing df_features, df_target = data.construct_baseline_features_target_dfs(data_dir, **data_kwargs) df_features, df_target = feature.create_additional_features(df_features, df_target, **features_kwargs) df_features = feature.process_features(df_features, cols_subset=cols_subset) common_idxs = sorted(list(set(df_features.index.intersection(df_target.index)))) df_features, df_target = df_features.loc[common_idxs], df_target.loc[common_idxs] # resampling if weights_func is not None and resampling_factor is not None: resampling_weights = weights_func(df_features) n = int(df_features.shape[0]*resampling_factor) df_features = df_features.sample(n=n, replace=True, weights=resampling_weights) df_features = df_features.sort_index() df_target = df_target.loc[df_features.index] # model loading if isinstance(model_1, str): model_1 = load_module_attr(model_1) if isinstance(model_2, str): model_2 = load_module_attr(model_2) # model run if model_2 is not None: model_1_init, model_2_init = model_1(**model_1_kwargs), model_2(**model_2_kwargs) else: model_1_init, model_2_init = model_1(**model_1_kwargs), None model_suite = ModelSuite(model_1_init, model_2_init) error_metrics, df_pred = model_suite.run_test(df_target, df_features, y1_col=y1_col, y2_col=y2_col, split_kwargs=split_kwargs, use_target_delta=use_target_delta, fit_shuffle=fit_shuffle) return model_suite, error_metrics, df_pred, input_data %%time split_kwargs = {'n_splits': 3, 'shuffle': False} model_suite, error_metrics, df_pred, input_data = run_parameterised_model(data_dir=data_dir, split_kwargs=split_kwargs) error_metrics ``` <br> ### Prediction Analysis ``` df_pred.resample('7D').mean().plot() #exports def plot_obsv_v_pred( s_observed: pd.Series, s_prediction: pd.Series, dpi: int=150, s: float=0.4, linewidth: float=0, color: str='k', **scatter_kwargs ): min_, max_ = min(s_observed.min(), s_prediction.min()), max(s_observed.max(), s_prediction.max()) common_idxs = s_observed.index.intersection(s_prediction.index.tz_localize('UTC')) s_observed, s_prediction = s_observed.loc[common_idxs], s_prediction.loc[common_idxs.tz_localize(None)] # Plotting fig, ax = plt.subplots(dpi=dpi) ax.plot([min_, max_], [min_, max_], linewidth=1, color='r', zorder=0) ax.scatter(s_observed, s_prediction, s=s, linewidth=linewidth, color=color, **scatter_kwargs) ax.set_xlabel('Prediction') ax.set_ylabel('Observation') ax.set_xlim(min_, max_) ax.set_ylim(min_, max_) return plot_obsv_v_pred(df_target['value_max'], df_pred['value_max']) plot_obsv_v_pred(df_target['value_min'], df_pred['value_min']) #exports def create_residual_bin_avgs_s( s: pd.Series, bins=np.linspace(-2.5, 2.5, 51) ): bin_avg_values = np.mean(np.vstack((bins[1:], bins[:-1])), axis=0) s_residual_bin_avgs = s.groupby(pd.cut(s, bins=bins)).mean() - bin_avg_values s_residual_bin_avgs.index = bin_avg_values return s_residual_bin_avgs def plot_residual_bin_avgs(df_pred: pd.DataFrame): s_min_residual_bin_avgs = create_residual_bin_avgs_s(df_pred['value_min']).dropna() s_max_residual_bin_avgs = create_residual_bin_avgs_s(df_pred['value_max']).dropna() # Plotting fig, ax = plt.subplots(dpi=150) s_min_residual_bin_avgs.plot(label='min', ax=ax) s_max_residual_bin_avgs.plot(label='max', ax=ax) ax.plot([-2.5, 2.5], [0, 0], color='k', linestyle='--', linewidth=1) ax.legend(frameon=False) ax.set_xlabel('Demand (MW)') ax.set_ylabel('Residuals Average (MW)') ax.set_xlim( min(s_min_residual_bin_avgs.index.min(), s_max_residual_bin_avgs.index.min()), max(s_min_residual_bin_avgs.index.max(), s_max_residual_bin_avgs.index.max()) ) plot_residual_bin_avgs(df_pred) #exports flatten_list = lambda list_: [item for sublist in list_ for item in sublist] def plot_pred_sample( df_pred: pd.DataFrame, df_target: pd.DataFrame=None, n_obvs: int=48*5, subplot_kwargs: dict={'dpi': 150} ): common_idxs = df_pred.index.tz_localize('UTC').intersection(df_target.index) df_pred, df_target = df_pred.loc[common_idxs.tz_localize(None)], df_target.loc[common_idxs] # Plotting fig, axs = plt.subplots(**subplot_kwargs) if isinstance(axs, np.ndarray): dims = len(axs.shape) axs = list(axs) if dims > 1: axs = flatten_list(axs) else: axs = [axs] for ax in axs: rand_start_idx = randint(0, df_pred.shape[0]-1) rand_end_idx = rand_start_idx + n_obvs df_pred.iloc[rand_start_idx:rand_end_idx][['value_max', 'value_min']].plot(ax=ax, legend=False) if df_target is not None: df_target.iloc[rand_start_idx:rand_end_idx][['value_max', 'value_min']].plot(ax=ax, color='k', linestyle='--', linewidth=0.5, legend=False) ax.set_xlabel('') ax.set_ylabel('Net Demand (MW)') fig.tight_layout() plot_pred_sample(df_pred, df_target, subplot_kwargs={'figsize': (8, 6), 'dpi': 150, 'nrows': 2}) #exports def plot_residuals_dist( df_pred: pd.DataFrame, df_target: pd.DataFrame ): df_residuals = df_target.subtract(df_pred).dropna(axis=1) # Plotting fig, ax = plt.subplots(dpi=150) sns.histplot(df_residuals['value_max'], ax=ax, alpha=0.5, binwidth=0.025, linewidth=0, label='Max') sns.histplot(df_residuals['value_min'], ax=ax, alpha=0.5, binwidth=0.025, linewidth=0, label='Min', color='C1') ax.set_xlim(-2, 2) ax.set_yscale('log') ax.legend(frameon=False) ax.set_xlabel('Residuals (MW)') return plot_residuals_dist(df_pred, df_target) #exports def visualise_errors(df_pred: pd.DataFrame, df_target: pd.DataFrame): plot_obsv_v_pred(df_target['value_max'], df_pred['value_max']) plot_obsv_v_pred(df_target['value_min'], df_pred['value_min']) plot_residual_bin_avgs(df_pred) plot_residuals_dist(df_pred, df_target) return # visualise_errors(df_pred, df_target) ``` <br> ### Parameter Management ``` #exports def save_params(input_data, fp): with open(fp, 'w') as f: yaml.dump(input_data, f, sort_keys=False) return fp = '../data/params/test.yml' save = False if save == True: save_params(input_data, fp) #exports def load_params(fp): with open(fp, 'r') as f: input_data = yaml.load(f, Loader=yaml.FullLoader) return input_data input_data = load_params(fp) JSON(input_data) #hide from nbdev.export import notebook2script notebook2script() ```
github_jupyter
#default_exp suite #exports import yaml import numpy as np import pandas as pd from sklearn.ensemble import RandomForestRegressor from sklearn.model_selection import KFold, train_test_split from wpdhack import data, feature from tqdm import tqdm from random import randint from typing import Protocol from importlib import import_module import seaborn as sns import matplotlib.pyplot as plt from IPython.display import JSON #exports class ScikitModel(Protocol): def fit(self, X, y, sample_weight=None): ... def predict(self, X): ... def score(self, X, y, sample_weight=None): ... def set_params(self, **params): ... def create_train_test_indexes(X, **split_kwargs): if 'n_splits' not in split_kwargs.keys(): assert 'test_size' in split_kwargs.keys(), 'You must provide either `n_splits` or `test_size` within the `split_kwargs` parameters' size = X.shape[0] index_array = np.linspace(0, size-1, size).astype(int) train_test_indexes = [tuple(train_test_split(index_array, **split_kwargs))] else: kf = KFold(**split_kwargs) train_test_indexes = kf.split(X) return train_test_indexes def calculate_error_metrics(y1, y2, y1_pred, y2_pred, y_baseline): baseline_combined_rmse = np.sqrt(np.square(y_baseline - y1).sum() + np.square(y_baseline - y2).sum()) combined_rmse = np.sqrt(np.square(y1_pred - y1).sum() + np.square(y2_pred - y2).sum()) error_metrics = { 'y1_rmse': np.sqrt(np.square(y1_pred - y1).sum()), 'y2_rmse': np.sqrt(np.square(y2_pred - y2).sum()), 'combined_rmse': combined_rmse, 'skill_score': combined_rmse/baseline_combined_rmse } return error_metrics def calc_month_error_metrics( df_pred, df_target, month: str='2021-08' ): common_idxs = pd.DatetimeIndex(sorted(list(set(df_pred.index.intersection(df_target.index.tz_convert(None)))))) df_pred, df_target = df_pred.loc[common_idxs], df_target.loc[common_idxs.tz_localize('UTC')] df_pred, df_target = df_pred.drop_duplicates(), df_target.drop_duplicates() error_metrics = calculate_error_metrics( df_target.loc[month, 'value_max'].values, df_target.loc[month, 'value_min'].values, df_pred.loc[month, 'value_max'].values, df_pred.loc[month, 'value_min'].values, df_pred.loc[month, 'value_mean'].values ) return error_metrics def construct_prediction_df( y1_pred: np.ndarray, y2_pred: np.ndarray, index: pd.Index, df_features: pd.DataFrame ): df_pred = pd.DataFrame({'value_max': y1_pred, 'value_min': y2_pred}, index=index) df_pred.index.name = 'time' df_pred.index = index.tz_convert(None) # handling invalid values invalid_max_idxs = df_pred.index[~(df_features['value'].values < df_pred['value_max'].values)] invalid_min_idxs = df_pred.index[~(df_features['value'].values > df_pred['value_min'].values)] if len(invalid_max_idxs) > 0: df_pred.loc[invalid_max_idxs, 'value_max'] = df_features.loc[invalid_max_idxs.tz_localize('UTC'), 'value'].values if len(invalid_min_idxs) > 0: df_pred.loc[invalid_min_idxs, 'value_min'] = df_features.loc[invalid_min_idxs.tz_localize('UTC'), 'value'].values # final checks assert df_pred.isnull().sum().sum() == 0, 'There should be no NaN values in the predictions' return df_pred class ModelSuite: def __init__( self, model_1: ScikitModel=RandomForestRegressor(), model_2: ScikitModel=RandomForestRegressor(), ): self.set_models(model_1, model_2) return def set_models( self, model_1: ScikitModel=RandomForestRegressor(), model_2: ScikitModel=RandomForestRegressor(), trained: bool=False ): self.model_1 = model_1 self.model_2 = model_2 self.trained = trained return def fit_models( self, X: np.ndarray, y1: np.ndarray, y2: np.ndarray, shuffle=True, ): if shuffle == True: shuffler = np.random.permutation(X.shape[0]) X, y1, y2 = X[shuffler], y1[shuffler], y2[shuffler] if self.model_2 is not None: self.model_1.fit(X, y1) self.model_2.fit(X, y2) else: Y = np.column_stack([y1, y2]) self.model_1.fit(X, Y) self.trained = True return def predict_models( self, X: np.ndarray ): if self.model_2 is not None: y1_pred = self.model_1.predict(X) y2_pred = self.model_2.predict(X) else: Y_pred = self.model_1.predict(X) y1_pred, y2_pred = Y_pred[:, 0], Y_pred[:, 1] return y1_pred, y2_pred def run_test( self, df_target: pd.DataFrame, df_features: pd.DataFrame, y1_col: str='value_max', y2_col: str='value_min', split_kwargs: dict={ 'test_size': 0.1, 'shuffle': False }, use_target_delta: bool=False, fit_shuffle: bool=True ): X = df_features.values y1, y2 = df_target[y1_col].values, df_target[y2_col].values y_baseline = df_features['value'].values error_metrics = [] df_pred = pd.DataFrame() train_test_indexes = create_train_test_indexes(X, **split_kwargs) for train_index, test_index in train_test_indexes: X_train, X_test, y1_train, y1_test, y2_train, y2_test, y_baseline_train, y_baseline_test = X[train_index], X[test_index], y1[train_index], y1[test_index], y2[train_index], y2[test_index], y_baseline[train_index], y_baseline[test_index] self.fit_models(X_train, y1_train, y2_train, shuffle=fit_shuffle) y1_pred, y2_pred = self.predict_models(X_test) if use_target_delta == True: y1_pred, y2_pred, y1_test, y2_test = y1_pred+y_baseline_test, y2_pred+y_baseline_test, y1_test+y_baseline_test, y2_test+y_baseline_test df_pred = df_pred.append(construct_prediction_df(y1_pred, y2_pred, df_features.index[test_index], df_features.iloc[test_index]).assign(value_mean=y_baseline_test)) error_metrics += [calculate_error_metrics(y1_test, y2_test, y1_pred, y2_pred, y_baseline_test)] df_pred = df_pred.sort_index() avg_error_metrics = pd.DataFrame(error_metrics).mean().to_dict() return avg_error_metrics, df_pred def run_submission( self, df_train_target: pd.DataFrame, df_train_features: pd.DataFrame, df_submission_features: pd.DataFrame, submissions_dir: str='../data/submission', y1_col: str='value_max', y2_col: str='value_min', save_submission: bool=False, use_target_delta: bool=False, shuffle: bool=True ): X_train = df_train_features.values y1_train, y2_train = df_train_target[y1_col].values, df_train_target[y2_col].values X_submission = df_submission_features.values submission_index = df_submission_features.index # should shuffle indexes before doing this self.fit_models(X_train, y1_train, y2_train, shuffle=shuffle) y1_submission, y2_submission = self.predict_models(X_submission) df_pred = construct_prediction_df(y1_submission, y2_submission, submission_index, df_submission_features) if use_target_delta == True: assert 'value' in df_submission_features.columns df_pred = df_pred.add(df_submission_features['value'], axis=0) # saving if save_submission == True: df_pred.to_csv(f'{submissions_dir}/predictions.csv') df_pred.to_csv(f'{submissions_dir}/archive/predictions_{pd.Timestamp.now().strftime("%Y-%m-%d %H-%M-%S")}.csv') return df_pred data_dir = '../data' real_power_data_dir = '../data/real_power' sites = ['staplegrove'] grid_points = [1] df_features, df_target = data.construct_baseline_features_target_dfs(data_dir, weather_sites=sites, weather_grid_points=grid_points) df_features, df_target = feature.create_additional_features(df_features, df_target, sites=sites, grid_points=grid_points) df_target.index = df_target.index.tz_convert(None) df_features.head() # add example here of training and testing #exports def load_module_attr(module_attr_path: str): *module, attr = module_attr_path.split('.') assert len(module)>0, 'A module has not been passed, only an attribute' func = getattr(import_module('.'.join(module)), attr) return func def run_parameterised_model( data_dir: str='data', model_1: str='lightgbm.LGBMRegressor', # these can be any sklearn compatible model model_2: str='lightgbm.LGBMRegressor', model_1_kwargs: dict={}, model_2_kwargs: dict={}, data_kwargs: dict={ 'real_power_sub_dir': 'real_power', 'weather_sub_dir': 'weather', 'real_power_time_period': '_pre_august', 'real_power_site': 'Staplegrove_CB905', 'weather_sites': ['staplegrove'], 'weather_grid_points': [1], 'weather_interpolate_method': 'interpolate', 'use_target_delta': False }, y1_col: str='value_max', y2_col: str='value_min', split_kwargs: dict={ 'n_splits': 5, 'shuffle': False }, cols_subset: list=['value', 'temperature_staplegrove_1', 'solar_irradiance_staplegrove_1', 'windspeed_north_staplegrove_1', 'windspeed_east_staplegrove_1', 'pressure_staplegrove_1', 'spec_humidity_staplegrove_1', 'hour', 'doy', 'weekend', 'direction_staplegrove_1', 'speed_staplegrove_1', 'hcdh_staplegrove_1'], features_kwargs: dict={ 'features': ['temporal', 'dir_speed', 'hcdh'],#, 'lagged'], 'sites': ['staplegrove'], 'grid_points': [1] }, fit_shuffle: bool=True, weights_func=None, resampling_factor=None ): input_data = locals() if 'use_target_delta' not in data_kwargs.keys(): use_target_delta = False else: use_target_delta = data_kwargs['use_target_delta'] # data loading, generation, and processing df_features, df_target = data.construct_baseline_features_target_dfs(data_dir, **data_kwargs) df_features, df_target = feature.create_additional_features(df_features, df_target, **features_kwargs) df_features = feature.process_features(df_features, cols_subset=cols_subset) common_idxs = sorted(list(set(df_features.index.intersection(df_target.index)))) df_features, df_target = df_features.loc[common_idxs], df_target.loc[common_idxs] # resampling if weights_func is not None and resampling_factor is not None: resampling_weights = weights_func(df_features) n = int(df_features.shape[0]*resampling_factor) df_features = df_features.sample(n=n, replace=True, weights=resampling_weights) df_features = df_features.sort_index() df_target = df_target.loc[df_features.index] # model loading if isinstance(model_1, str): model_1 = load_module_attr(model_1) if isinstance(model_2, str): model_2 = load_module_attr(model_2) # model run if model_2 is not None: model_1_init, model_2_init = model_1(**model_1_kwargs), model_2(**model_2_kwargs) else: model_1_init, model_2_init = model_1(**model_1_kwargs), None model_suite = ModelSuite(model_1_init, model_2_init) error_metrics, df_pred = model_suite.run_test(df_target, df_features, y1_col=y1_col, y2_col=y2_col, split_kwargs=split_kwargs, use_target_delta=use_target_delta, fit_shuffle=fit_shuffle) return model_suite, error_metrics, df_pred, input_data %%time split_kwargs = {'n_splits': 3, 'shuffle': False} model_suite, error_metrics, df_pred, input_data = run_parameterised_model(data_dir=data_dir, split_kwargs=split_kwargs) error_metrics df_pred.resample('7D').mean().plot() #exports def plot_obsv_v_pred( s_observed: pd.Series, s_prediction: pd.Series, dpi: int=150, s: float=0.4, linewidth: float=0, color: str='k', **scatter_kwargs ): min_, max_ = min(s_observed.min(), s_prediction.min()), max(s_observed.max(), s_prediction.max()) common_idxs = s_observed.index.intersection(s_prediction.index.tz_localize('UTC')) s_observed, s_prediction = s_observed.loc[common_idxs], s_prediction.loc[common_idxs.tz_localize(None)] # Plotting fig, ax = plt.subplots(dpi=dpi) ax.plot([min_, max_], [min_, max_], linewidth=1, color='r', zorder=0) ax.scatter(s_observed, s_prediction, s=s, linewidth=linewidth, color=color, **scatter_kwargs) ax.set_xlabel('Prediction') ax.set_ylabel('Observation') ax.set_xlim(min_, max_) ax.set_ylim(min_, max_) return plot_obsv_v_pred(df_target['value_max'], df_pred['value_max']) plot_obsv_v_pred(df_target['value_min'], df_pred['value_min']) #exports def create_residual_bin_avgs_s( s: pd.Series, bins=np.linspace(-2.5, 2.5, 51) ): bin_avg_values = np.mean(np.vstack((bins[1:], bins[:-1])), axis=0) s_residual_bin_avgs = s.groupby(pd.cut(s, bins=bins)).mean() - bin_avg_values s_residual_bin_avgs.index = bin_avg_values return s_residual_bin_avgs def plot_residual_bin_avgs(df_pred: pd.DataFrame): s_min_residual_bin_avgs = create_residual_bin_avgs_s(df_pred['value_min']).dropna() s_max_residual_bin_avgs = create_residual_bin_avgs_s(df_pred['value_max']).dropna() # Plotting fig, ax = plt.subplots(dpi=150) s_min_residual_bin_avgs.plot(label='min', ax=ax) s_max_residual_bin_avgs.plot(label='max', ax=ax) ax.plot([-2.5, 2.5], [0, 0], color='k', linestyle='--', linewidth=1) ax.legend(frameon=False) ax.set_xlabel('Demand (MW)') ax.set_ylabel('Residuals Average (MW)') ax.set_xlim( min(s_min_residual_bin_avgs.index.min(), s_max_residual_bin_avgs.index.min()), max(s_min_residual_bin_avgs.index.max(), s_max_residual_bin_avgs.index.max()) ) plot_residual_bin_avgs(df_pred) #exports flatten_list = lambda list_: [item for sublist in list_ for item in sublist] def plot_pred_sample( df_pred: pd.DataFrame, df_target: pd.DataFrame=None, n_obvs: int=48*5, subplot_kwargs: dict={'dpi': 150} ): common_idxs = df_pred.index.tz_localize('UTC').intersection(df_target.index) df_pred, df_target = df_pred.loc[common_idxs.tz_localize(None)], df_target.loc[common_idxs] # Plotting fig, axs = plt.subplots(**subplot_kwargs) if isinstance(axs, np.ndarray): dims = len(axs.shape) axs = list(axs) if dims > 1: axs = flatten_list(axs) else: axs = [axs] for ax in axs: rand_start_idx = randint(0, df_pred.shape[0]-1) rand_end_idx = rand_start_idx + n_obvs df_pred.iloc[rand_start_idx:rand_end_idx][['value_max', 'value_min']].plot(ax=ax, legend=False) if df_target is not None: df_target.iloc[rand_start_idx:rand_end_idx][['value_max', 'value_min']].plot(ax=ax, color='k', linestyle='--', linewidth=0.5, legend=False) ax.set_xlabel('') ax.set_ylabel('Net Demand (MW)') fig.tight_layout() plot_pred_sample(df_pred, df_target, subplot_kwargs={'figsize': (8, 6), 'dpi': 150, 'nrows': 2}) #exports def plot_residuals_dist( df_pred: pd.DataFrame, df_target: pd.DataFrame ): df_residuals = df_target.subtract(df_pred).dropna(axis=1) # Plotting fig, ax = plt.subplots(dpi=150) sns.histplot(df_residuals['value_max'], ax=ax, alpha=0.5, binwidth=0.025, linewidth=0, label='Max') sns.histplot(df_residuals['value_min'], ax=ax, alpha=0.5, binwidth=0.025, linewidth=0, label='Min', color='C1') ax.set_xlim(-2, 2) ax.set_yscale('log') ax.legend(frameon=False) ax.set_xlabel('Residuals (MW)') return plot_residuals_dist(df_pred, df_target) #exports def visualise_errors(df_pred: pd.DataFrame, df_target: pd.DataFrame): plot_obsv_v_pred(df_target['value_max'], df_pred['value_max']) plot_obsv_v_pred(df_target['value_min'], df_pred['value_min']) plot_residual_bin_avgs(df_pred) plot_residuals_dist(df_pred, df_target) return # visualise_errors(df_pred, df_target) #exports def save_params(input_data, fp): with open(fp, 'w') as f: yaml.dump(input_data, f, sort_keys=False) return fp = '../data/params/test.yml' save = False if save == True: save_params(input_data, fp) #exports def load_params(fp): with open(fp, 'r') as f: input_data = yaml.load(f, Loader=yaml.FullLoader) return input_data input_data = load_params(fp) JSON(input_data) #hide from nbdev.export import notebook2script notebook2script()
0.643329
0.734242
# **Image Recognition**: Neural Nets Source: [https://github.com/d-insight/code-bank.git](https://github.com/d-insight/code-bank.git) License: [MIT License](https://opensource.org/licenses/MIT). See open source [license](LICENSE) in the Code Bank repository. ------------- ## Overview In this demo we will perform a common image classification task, using the MNIST dataset. We consider a dataset of hand-written images and we are going to predict the number associated with each image. Every image has a dimension of 28 * 28 pixels and is gray-scale. The input data includes the intensity associated with each pixel row by row, starting from top-left corner (784 pixels in total). The label field shows the number associated with each image. The state-of-the-art model achieves an error rate of only 0.23% (Ciresan et al. CVPR 2012). We will achieve an approximate error rate of 1.2% in this demo. <img src="https://3qeqpr26caki16dnhd19sv6by6v-wpengine.netdna-ssl.com/wp-content/uploads/2019/02/Plot-of-a-Subset-of-Images-from-the-MNIST-Dataset.png" width="700" height="500" align="center"/> Image source: https://3qeqpr26caki16dnhd19sv6by6v-wpengine.netdna-ssl.com/wp-content/uploads/2019/02/Plot-of-a-Subset-of-Images-from-the-MNIST-Dataset.png For an interactive hand-written image classification demo, visit: https://mnist-demo.herokuapp.com/ Dataset source: http://yann.lecun.com/exdb/mnist/ ## **Part 0**: Setup ``` # Put all import statements at the top of your notebook import warnings warnings.simplefilter('ignore') # Standard imports import pandas as pd import numpy as np import itertools # Data science packages from sklearn.model_selection import learning_curve, validation_curve, StratifiedShuffleSplit, train_test_split, StratifiedKFold from sklearn.metrics import confusion_matrix from sklearn.svm import SVC from sklearn.ensemble import RandomForestClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.dummy import DummyClassifier from sklearn.linear_model import LogisticRegression # Neural networks from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D from keras.utils.vis_utils import model_to_dot from keras.models import Sequential from keras.layers import Dense from keras.utils.np_utils import to_categorical from xgboost import XGBClassifier # Visualization packages import seaborn as sns import matplotlib.pyplot as plt from IPython.display import SVG %matplotlib inline # Set constants SCORE = 'accuracy' N_CORES = -1 SEED = 0 N_SPLITS = 3 # Define a helper function to facilitate drawing validation and learning curves def plot_validation_curve(train_scores, cv_scores, x_data, scale='lin', title='', y_label='', x_label=''): train_scores_mean = np.mean(train_scores, axis=1) train_scores_std = np.std(train_scores, axis=1) cv_scores_mean = np.mean(cv_scores, axis=1) cv_scores_std = np.std(cv_scores, axis=1) plt.title(title) plt.xlabel(x_label) plt.ylabel(y_label) plt.ylim(0.0, 1.1) lw = 2 plt.fill_between(x_data, train_scores_mean - train_scores_std,train_scores_mean + train_scores_std, alpha=0.2, color="r", lw=lw) plt.fill_between(x_data, cv_scores_mean - cv_scores_std, cv_scores_mean + cv_scores_std, alpha=0.2, color="g", lw=lw) if (scale == 'lin'): plt.plot(x_data, train_scores_mean, 'o-', color="r", label="Training score") plt.plot(x_data, cv_scores_mean, 'o-', color="g",label="Cross-validation score") elif (scale == 'log'): plt.semilogx(x_data, train_scores_mean, 'o-', color="r", label="Training score") plt.semilogx(x_data, cv_scores_mean, 'o-', color="g",label="Cross-validation score") plt.grid() plt.legend(loc="best") plt.show() # Helper function for plotting confusion matrix def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion Matrix', cmap=plt.cm.Reds): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, round (cm[i, j],2), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('Actual label') plt.xlabel('Predicted label') # Define a function to facilitate drawing learning curves def plot_learning_curve(train_scores,cv_scores,x_data,scale='lin',title='',y_label='',x_label=''): train_scores_mean = np.mean(train_scores, axis=1) train_scores_std = np.std(train_scores, axis=1) cv_scores_mean = np.mean(cv_scores, axis=1) cv_scores_std = np.std(cv_scores, axis=1) plt.title(title) plt.xlabel(x_label) plt.ylabel(y_label) plt.ylim(0.0, 1.1) lw = 2 plt.fill_between(x_data, train_scores_mean - train_scores_std,train_scores_mean + train_scores_std, alpha=0.2, color="r", lw=lw) plt.fill_between(x_data, cv_scores_mean - cv_scores_std, cv_scores_mean + cv_scores_std, alpha=0.2, color="g", lw=lw) if (scale == 'lin'): plt.plot(x_data, train_scores_mean, 'o-', color="r", label="Training score") plt.plot(x_data, cv_scores_mean, 'o-', color="g",label="Cross-validation score") elif (scale == 'log'): plt.semilogx(x_data, train_scores_mean, 'o-', color="r", label="Training score") plt.semilogx(x_data, cv_scores_mean, 'o-', color="g",label="Cross-validation score") plt.grid() plt.legend(loc="best") plt.show() ``` ## **Part 1**: Data Preprocessing and EDA ``` # Load data into a dataframe data = pd.read_csv('image_data.csv') data.head() # Dimensions of data data.shape # investigate basic statistics of data data.describe() # Drop missing value, if any data.dropna(inplace=True) data.shape # Separate features and target target = data['label'].values.ravel() features = data.iloc[:, 1:].values # Normalize features to be between 0 and 1 features = features / 255.0 # Check distribution of labels sns.countplot(target) # Visualize values of feature and its visual representation for an arbitrary data point # Define a subplot with two rows and one column fig, ax = plt.subplots(2, 1, figsize=(12,6)) dp_id = 100 # Plot features representation in 1D ax[0].plot(features[dp_id]) ax[0].set_title('784x1 data') # Plot features representation in 2D ax[1].imshow(features[dp_id].reshape(28,28), cmap='gray') ax[1].set_title('28x28 data') # Show the plot plt.show() ``` ## **Part 2**: Define Cross-Validation Schema and Dummy Classifier Baseline ``` # Divide data into training and testing sets X_train, X_test, y_train, y_test = train_test_split(features, target, test_size=0.2, random_state=SEED, stratify=target) # Define a baseline using dummy classifier # It enables you to define a basic classifier which apply simple strategies such as stratified # Stratified strategy predicts probability of belonging to positive class as percentage of positive cases dummy_clf = DummyClassifier(strategy='stratified', random_state = SEED) dummy_clf.fit(X_train, y_train) baseline_score = dummy_clf.score(X_test, y_test) print('Baseline accuracy: {}'.format(round(baseline_score, 4))) ``` ## **Part 3**: Prediction using Logistic Regression with Ridge regularization Note: For parameter `C` in `LogisticRegression`, smaller values specify stronger regularization. We follow the following steps to come up with a prediction model: 1. We tune our model parameter(s) using cross-validation on training set. 2. We fit the model with tuned parameter on training set. 3. We evaluate performance of our model using the test set. ``` # Define model model = LogisticRegression(penalty='l2', n_jobs = N_CORES, multi_class='multinomial', solver='saga', random_state=SEED) # Define cross-validation schema for tuning cv_schema = StratifiedKFold(n_splits = N_SPLITS, shuffle=True, random_state = SEED) # Tune model against a single hyper parameter C using validation_curve function tuning_param = 'C' tuning_param_range = np.logspace(-5, 5, 5) train_scores_val, cv_scores_val = validation_curve( model, X_train, y_train, param_name = tuning_param, param_range = tuning_param_range, cv = cv_schema, scoring = SCORE, n_jobs = N_CORES) # Plot validation curve plot_validation_curve(train_scores_val, cv_scores_val, tuning_param_range, scale='log', title='validation curve', y_label='accuracy', x_label='C') # Obtain the best value of the hyper parameter best_param_val = tuning_param_range[np.argmax(np.mean(cv_scores_val, axis=1))] %%time # Train model with best hyper parameter and assess its performance on the test data lr_clf = LogisticRegression(C = best_param_val, n_jobs = N_CORES, multi_class='multinomial', solver='saga', random_state=SEED) lr_clf.fit(X_train,y_train) lr_score = lr_clf.score(X_test, y_test) print('LR with Ridge accuracy: {}\n'.format(round(lr_score, 4))) ``` ## **Part 4**: Prediction using KNN Classifier ``` # Set parameters, model and cv schema model = KNeighborsClassifier(n_jobs = N_CORES) cv_schema = StratifiedKFold(n_splits = N_SPLITS, shuffle=True, random_state = SEED) %%time # Tune model against a single hyper parameter tuning_param = 'n_neighbors' tuning_param_range = np.array([int(i) for i in np.linspace(5.0, 45.0, 5)]) train_scores_val, cv_scores_val = validation_curve( model, X_train, y_train, param_name = tuning_param, param_range = tuning_param_range, cv = cv_schema, scoring = SCORE, n_jobs = N_CORES) # Plot validation curve plot_validation_curve(train_scores_val, cv_scores_val, tuning_param_range, scale='lin', title='validation curve', y_label='accuracy', x_label='n_nieghbors') # Obtain the best value of the hyper parameter best_param_val = tuning_param_range[np.argmax(np.mean(cv_scores_val, axis=1))] # Train model with best hyper parameter and assess its performance on test data knn_clf = KNeighborsClassifier(n_neighbors = best_param_val, n_jobs = N_CORES) knn_clf.fit(X_train,y_train) knn_score = knn_clf.score(X_test, y_test) print('KNN accuracy: {}'.format(round(knn_score, 4))) ``` ## **Part 5**: Prediction using Random Forest ``` # Set parameters, model and cv schema model = RandomForestClassifier(n_jobs = N_CORES) cv_schema = StratifiedKFold(n_splits = N_SPLITS, shuffle=True, random_state = SEED) %%time # Tune model against a single hyper parameter tuning_param = 'n_estimators' tuning_param_range = np.array([int(i) for i in np.linspace(10.0, 80.0, 5)]) train_scores_val, cv_scores_val = validation_curve( model, X_train, y_train, param_name = tuning_param, param_range = tuning_param_range, cv = cv_schema, scoring = SCORE, n_jobs = N_CORES) # Plot validation curve plot_validation_curve(train_scores_val, cv_scores_val, tuning_param_range, scale='lin', title='validation curve', y_label='accuracy', x_label='n_estimators') # Obtain the best value of the hyper parameter best_param_val = tuning_param_range[np.argmax(np.mean(cv_scores_val, axis=1))] print(best_param_val) # Train model with best hyper parameter and assess its performance on test data rf_clf = RandomForestClassifier(n_estimators = best_param_val, n_jobs = n_cores) rf_clf.fit(X_train,y_train) rf_score = rf_clf.score(X_test,y_test) print('RF accuracy: {}'.format(round(rf_score, 4))) ``` ## **Part 6**: Prediction using Gradient Boosted Trees ``` # XGboost library has a more performant implementation of gradient boosted trees model = XGBClassifier(n_jobs = N_CORES, random_state = SEED) cv_schema = StratifiedKFold(n_splits = N_SPLITS, random_state = SEED) %%time # Tune model against a single hyper parameter tuning_param = 'n_estimators' tuning_param_range = np.array([int(i) for i in np.linspace(10.0, 50.0, 5)]) train_scores_val, cv_scores_val = validation_curve( model, X_train, y_train, param_name = tuning_param, param_range = tuning_param_range, cv = cv_schema, scoring = SCORE, n_jobs = N_CORES) # Plot validation curve plot_validation_curve(train_scores_val, cv_scores_val, tuning_param_range, scale='lin', title='validation curve', y_label='accuracy', x_label='n_estimators') # Obtain the best value of the hyper parameter best_param_val = tuning_param_range[np.argmax(np.mean(cv_scores_val, axis=1))] # Train model with best hyper parameter and assess its perfrmance on test data gb_clf = XGBClassifier(n_estimators = best_param_val, n_jobs = N_CORES, random_state=SEED) gb_clf.fit(X_train, y_train) gb_score = gb_clf.score(X_test,y_test) print('Gradient boosted accuracy: {}'.format(round(gb_score, 4))) ``` ## **Part 7**: Prediction using SVC ``` # Set parameters, model and cv schema model = SVC(random_state = SEED) cv_schema = StratifiedKFold(n_splits = N_SPLITS, shuffle=True, random_state = SEED) %%time # Tune model against a single hyper parameter tuning_param = 'C' tuning_param_range = np.logspace(-5, 5, 5) train_scores_val, cv_scores_val = validation_curve( model, X_train, y_train, param_name = tuning_param, param_range = tuning_param_range, cv = cv_schema, scoring = SCORE, n_jobs = N_CORES) # Plot validation curve plot_validation_curve(train_scores_val, cv_scores_val, tuning_param_range, scale='log', title='validation curve', y_label='accuracy', x_label='C') # Obtain the best value of the hyper parameter best_param_val = tuning_param_range[np.argmax(np.mean(cv_scores_val, axis=1))] # Train model with increasing amount of training data svc_clf = SVC(C = best_param_val) svc_clf.fit(X_train, y_train) svc_score = svc_clf.score(X_test,y_test) print('SVC accuracy: {}'.format(round(svc_score, 4))) ``` ## **Part 8**: Prediction using Feed Forward Neural Network ``` # Encode target labels to one hot vectors (ex : 3 -> [0,0,0,1,0,0,0,0,0,0]) y_train_ohe = to_categorical(y_train, num_classes = 10) y_test_ohe = to_categorical(y_test, num_classes = 10) y_train_ohe[0] # Set parameters, model and cv schema epochs = 10 # Number of iterations over full training set batch_size = 200 # Number of observations to fit in every batch num_pixels = 28 * 28 num_classes = 10 # Create and compile a simple feed forward neural network def ffnn_model(): # Create a neural network with two dense layers model = Sequential() model.add(Dense(num_pixels, input_dim=num_pixels, kernel_initializer='normal', activation='relu')) model.add(Dense(num_classes, kernel_initializer='normal', activation='softmax')) # Compile model model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model model = ffnn_model() # Visualize keras model SVG(model_to_dot(model,show_shapes=True).create(prog='dot', format='svg')) # Fit the model to data model.fit(X_train, y_train_ohe, validation_data = (X_test, y_test_ohe), epochs = epochs, batch_size = batch_size) # Get model summary model.summary() # Evaluate trained model on test set ff_loss, ff_score = model.evaluate(X_test, y_test_ohe) print('Loss: {}'.format(round(ff_loss, 4))) print('Accuracy: {}'.format(round(ff_score, 4))) # Get predicted values predicted_classes = model.predict_classes(X_test) # Get index of correctly and incorrectly classified observations target_val_orig = np.argmax(y_test_ohe, 1) # Get index list of all correctly predicted values correct_indices = np.nonzero(np.equal(predicted_classes, target_val_orig))[0] # Get index list of all incorrectly predicted values incorrect_indices = np.nonzero(np.not_equal(predicted_classes, target_val_orig))[0] # Print number of correctly and incorrectly clasified observations print ('Correctly predicted: %i' % np.size(correct_indices)) print ('Incorrectly predicted: %i' % np.size(incorrect_indices)) # See a sample of incorrectly classified samples plt.figure(figsize=[20,8]) for i, incorrect in enumerate(incorrect_indices[:6]): plt.subplot(1,6,i+1) plt.imshow(X_test[incorrect].reshape(28,28), cmap='gray', interpolation='none') plt.title("Predicted {}, Class {}".format(predicted_classes[incorrect], target_val_orig[incorrect])) ``` ## **Part 9**: Prediction using Convolutional Neural Network ``` # Reshape image in 3 dimensions (height = 28px, width = 28px , canal = 1) X_train_reshaped = X_train.reshape(-1,28,28,1) X_test_reshaped = X_test.reshape(-1,28,28,1) # Access a single pixel value in reshaped arrays X_train_reshaped[2800][27][27][0] # Encode target labels to one hot vectors y_train_ohe = to_categorical(y_train, num_classes = 10) y_test_ohe = to_categorical(y_test, num_classes = 10) # Set parameters, model and cv schema epochs = 10 # number of iterations over full training set batch_size = 200 # number of observations to fit in every batch # Set the CNN architechture (architecture taken from: # https://machinelearningmastery.com/handwritten-digit-recognition-using-convolutional-neural-networks-python-keras/ def cnn_model(): model = Sequential() model.add(Conv2D(filters = 32, kernel_size = (5,5), padding = 'Same', activation ='relu', input_shape = (28,28,1))) model.add(Conv2D(filters = 32, kernel_size = (5,5), padding = 'Same', activation ='relu')) model.add(MaxPool2D(pool_size=(2,2))) model.add(Dropout(0.25)) model.add(Conv2D(filters = 64, kernel_size = (3,3), padding = 'Same', activation ='relu')) model.add(Conv2D(filters = 64, kernel_size = (3,3), padding = 'Same', activation ='relu')) model.add(MaxPool2D(pool_size=(2,2), strides=(2,2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(256, activation = "relu")) model.add(Dropout(0.5)) model.add(Dense(10, activation = "softmax")) # compile the model model.compile(optimizer = 'adam' , loss = "categorical_crossentropy", metrics=["accuracy"]) return (model) model = cnn_model() SVG(model_to_dot(model,show_shapes=True).create(prog='dot', format='svg')) # Fit the model to data model.fit(X_train_reshaped, y_train_ohe, validation_data=(X_test_reshaped, y_test_ohe), epochs=epochs, batch_size=batch_size) # Get model summary model.summary() # Evaluate trained model on test set cnn_loss, cnn_score = model.evaluate(X_test_reshaped, y_test_ohe) print('Loss: {}'.format(round(cnn_loss, 4))) print('Accuracy: {}'.format(round(cnn_score, 4))) # Get predicted values predicted_classes = model.predict_classes(X_test_reshaped) # Get index of correctly and incorrectly classified observations target_val_orig = np.argmax(y_test_ohe, 1) # Get index list of all correctly predicted values correct_indices = np.nonzero(np.equal(predicted_classes, target_val_orig))[0] # Get index list of all incorrectly predicted values incorrect_indices = np.nonzero(np.not_equal(predicted_classes, target_val_orig))[0] # Print number of correctly and incorrectly clasified observations print ('Correctly predicted: %i' % np.size(correct_indices)) print ('Incorrectly predicted: %i' % np.size(incorrect_indices)) # See a sample of incorrectly classified samples plt.figure(figsize=[20,8]) for i, incorrect in enumerate(incorrect_indices[:6]): plt.subplot(1,6,i+1) plt.imshow(X_test[incorrect].reshape(28,28), cmap='gray', interpolation='none') plt.title("Predicted {}, Class {}".format(predicted_classes[incorrect], target_val_orig[incorrect])) # Look at confusion matrix y_pred_ohe = model.predict(X_test_reshaped) y_pred_classes = np.argmax(y_pred_ohe, axis = 1) y_true = np.argmax(y_test_ohe, axis = 1) confusion_mtx = confusion_matrix(y_true, y_pred_classes) plot_confusion_matrix(confusion_mtx, classes = range(10)) ``` ## **SUMMARY OF ACCURACY SCORES** ``` width = 35 models = ['Baseline', 'LR + Ridge', 'KNN', 'Random Forest', 'Boosted Trees', 'SVC', 'NN', 'CNN'] results = [baseline_score, lr_score, knn_score, rf_score, gb_score, svc_score, ff_score, cnn_score] print('', '=' * width, '\n', 'Summary of Accuracy Scores'.center(width), '\n', '=' * width) for i in range(len(models)): print(models[i].center(width-8), '{0:.4f}'.format(round(results[i], 4))) ``` ## **Part 10**: Investment into More Data ``` # Learning_curve function in sklearn.model_selection is used to assess performance of # a model with diferent training sizes, hence justifying possible investments # into gathering more data # Here we train random forest classifier with increasing amount of training data rf_clf = RandomForestClassifier(n_estimators = 50, n_jobs = N_CORES) cv_schema = StratifiedShuffleSplit(n_splits = N_SPLITS, test_size = 0.33, shuffle=True, random_state = SEED) train_sizes = np.linspace(.1, 1.0, 5) train_sizes, train_scores_learn, cv_scores_learn = learning_curve( rf_clf, features, target, cv = cv_schema, n_jobs = N_CORES, train_sizes = train_sizes, scoring = SCORE) # Plot learning curve plot_learning_curve(train_scores_learn, cv_scores_learn, train_sizes, scale='lin', title='learning curve of random forest classifier', y_label='accuracy', x_label='train set size') ``` ## **Part 11**: Discussion * How can one justify the investment on gathering additional data ? * How much an accuracy equal to 99.99 % is more significant than one equal to 99.90 % ? * What about 99.90 % compared to 99.00 % ?
github_jupyter
# Put all import statements at the top of your notebook import warnings warnings.simplefilter('ignore') # Standard imports import pandas as pd import numpy as np import itertools # Data science packages from sklearn.model_selection import learning_curve, validation_curve, StratifiedShuffleSplit, train_test_split, StratifiedKFold from sklearn.metrics import confusion_matrix from sklearn.svm import SVC from sklearn.ensemble import RandomForestClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.dummy import DummyClassifier from sklearn.linear_model import LogisticRegression # Neural networks from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D from keras.utils.vis_utils import model_to_dot from keras.models import Sequential from keras.layers import Dense from keras.utils.np_utils import to_categorical from xgboost import XGBClassifier # Visualization packages import seaborn as sns import matplotlib.pyplot as plt from IPython.display import SVG %matplotlib inline # Set constants SCORE = 'accuracy' N_CORES = -1 SEED = 0 N_SPLITS = 3 # Define a helper function to facilitate drawing validation and learning curves def plot_validation_curve(train_scores, cv_scores, x_data, scale='lin', title='', y_label='', x_label=''): train_scores_mean = np.mean(train_scores, axis=1) train_scores_std = np.std(train_scores, axis=1) cv_scores_mean = np.mean(cv_scores, axis=1) cv_scores_std = np.std(cv_scores, axis=1) plt.title(title) plt.xlabel(x_label) plt.ylabel(y_label) plt.ylim(0.0, 1.1) lw = 2 plt.fill_between(x_data, train_scores_mean - train_scores_std,train_scores_mean + train_scores_std, alpha=0.2, color="r", lw=lw) plt.fill_between(x_data, cv_scores_mean - cv_scores_std, cv_scores_mean + cv_scores_std, alpha=0.2, color="g", lw=lw) if (scale == 'lin'): plt.plot(x_data, train_scores_mean, 'o-', color="r", label="Training score") plt.plot(x_data, cv_scores_mean, 'o-', color="g",label="Cross-validation score") elif (scale == 'log'): plt.semilogx(x_data, train_scores_mean, 'o-', color="r", label="Training score") plt.semilogx(x_data, cv_scores_mean, 'o-', color="g",label="Cross-validation score") plt.grid() plt.legend(loc="best") plt.show() # Helper function for plotting confusion matrix def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion Matrix', cmap=plt.cm.Reds): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, round (cm[i, j],2), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('Actual label') plt.xlabel('Predicted label') # Define a function to facilitate drawing learning curves def plot_learning_curve(train_scores,cv_scores,x_data,scale='lin',title='',y_label='',x_label=''): train_scores_mean = np.mean(train_scores, axis=1) train_scores_std = np.std(train_scores, axis=1) cv_scores_mean = np.mean(cv_scores, axis=1) cv_scores_std = np.std(cv_scores, axis=1) plt.title(title) plt.xlabel(x_label) plt.ylabel(y_label) plt.ylim(0.0, 1.1) lw = 2 plt.fill_between(x_data, train_scores_mean - train_scores_std,train_scores_mean + train_scores_std, alpha=0.2, color="r", lw=lw) plt.fill_between(x_data, cv_scores_mean - cv_scores_std, cv_scores_mean + cv_scores_std, alpha=0.2, color="g", lw=lw) if (scale == 'lin'): plt.plot(x_data, train_scores_mean, 'o-', color="r", label="Training score") plt.plot(x_data, cv_scores_mean, 'o-', color="g",label="Cross-validation score") elif (scale == 'log'): plt.semilogx(x_data, train_scores_mean, 'o-', color="r", label="Training score") plt.semilogx(x_data, cv_scores_mean, 'o-', color="g",label="Cross-validation score") plt.grid() plt.legend(loc="best") plt.show() # Load data into a dataframe data = pd.read_csv('image_data.csv') data.head() # Dimensions of data data.shape # investigate basic statistics of data data.describe() # Drop missing value, if any data.dropna(inplace=True) data.shape # Separate features and target target = data['label'].values.ravel() features = data.iloc[:, 1:].values # Normalize features to be between 0 and 1 features = features / 255.0 # Check distribution of labels sns.countplot(target) # Visualize values of feature and its visual representation for an arbitrary data point # Define a subplot with two rows and one column fig, ax = plt.subplots(2, 1, figsize=(12,6)) dp_id = 100 # Plot features representation in 1D ax[0].plot(features[dp_id]) ax[0].set_title('784x1 data') # Plot features representation in 2D ax[1].imshow(features[dp_id].reshape(28,28), cmap='gray') ax[1].set_title('28x28 data') # Show the plot plt.show() # Divide data into training and testing sets X_train, X_test, y_train, y_test = train_test_split(features, target, test_size=0.2, random_state=SEED, stratify=target) # Define a baseline using dummy classifier # It enables you to define a basic classifier which apply simple strategies such as stratified # Stratified strategy predicts probability of belonging to positive class as percentage of positive cases dummy_clf = DummyClassifier(strategy='stratified', random_state = SEED) dummy_clf.fit(X_train, y_train) baseline_score = dummy_clf.score(X_test, y_test) print('Baseline accuracy: {}'.format(round(baseline_score, 4))) # Define model model = LogisticRegression(penalty='l2', n_jobs = N_CORES, multi_class='multinomial', solver='saga', random_state=SEED) # Define cross-validation schema for tuning cv_schema = StratifiedKFold(n_splits = N_SPLITS, shuffle=True, random_state = SEED) # Tune model against a single hyper parameter C using validation_curve function tuning_param = 'C' tuning_param_range = np.logspace(-5, 5, 5) train_scores_val, cv_scores_val = validation_curve( model, X_train, y_train, param_name = tuning_param, param_range = tuning_param_range, cv = cv_schema, scoring = SCORE, n_jobs = N_CORES) # Plot validation curve plot_validation_curve(train_scores_val, cv_scores_val, tuning_param_range, scale='log', title='validation curve', y_label='accuracy', x_label='C') # Obtain the best value of the hyper parameter best_param_val = tuning_param_range[np.argmax(np.mean(cv_scores_val, axis=1))] %%time # Train model with best hyper parameter and assess its performance on the test data lr_clf = LogisticRegression(C = best_param_val, n_jobs = N_CORES, multi_class='multinomial', solver='saga', random_state=SEED) lr_clf.fit(X_train,y_train) lr_score = lr_clf.score(X_test, y_test) print('LR with Ridge accuracy: {}\n'.format(round(lr_score, 4))) # Set parameters, model and cv schema model = KNeighborsClassifier(n_jobs = N_CORES) cv_schema = StratifiedKFold(n_splits = N_SPLITS, shuffle=True, random_state = SEED) %%time # Tune model against a single hyper parameter tuning_param = 'n_neighbors' tuning_param_range = np.array([int(i) for i in np.linspace(5.0, 45.0, 5)]) train_scores_val, cv_scores_val = validation_curve( model, X_train, y_train, param_name = tuning_param, param_range = tuning_param_range, cv = cv_schema, scoring = SCORE, n_jobs = N_CORES) # Plot validation curve plot_validation_curve(train_scores_val, cv_scores_val, tuning_param_range, scale='lin', title='validation curve', y_label='accuracy', x_label='n_nieghbors') # Obtain the best value of the hyper parameter best_param_val = tuning_param_range[np.argmax(np.mean(cv_scores_val, axis=1))] # Train model with best hyper parameter and assess its performance on test data knn_clf = KNeighborsClassifier(n_neighbors = best_param_val, n_jobs = N_CORES) knn_clf.fit(X_train,y_train) knn_score = knn_clf.score(X_test, y_test) print('KNN accuracy: {}'.format(round(knn_score, 4))) # Set parameters, model and cv schema model = RandomForestClassifier(n_jobs = N_CORES) cv_schema = StratifiedKFold(n_splits = N_SPLITS, shuffle=True, random_state = SEED) %%time # Tune model against a single hyper parameter tuning_param = 'n_estimators' tuning_param_range = np.array([int(i) for i in np.linspace(10.0, 80.0, 5)]) train_scores_val, cv_scores_val = validation_curve( model, X_train, y_train, param_name = tuning_param, param_range = tuning_param_range, cv = cv_schema, scoring = SCORE, n_jobs = N_CORES) # Plot validation curve plot_validation_curve(train_scores_val, cv_scores_val, tuning_param_range, scale='lin', title='validation curve', y_label='accuracy', x_label='n_estimators') # Obtain the best value of the hyper parameter best_param_val = tuning_param_range[np.argmax(np.mean(cv_scores_val, axis=1))] print(best_param_val) # Train model with best hyper parameter and assess its performance on test data rf_clf = RandomForestClassifier(n_estimators = best_param_val, n_jobs = n_cores) rf_clf.fit(X_train,y_train) rf_score = rf_clf.score(X_test,y_test) print('RF accuracy: {}'.format(round(rf_score, 4))) # XGboost library has a more performant implementation of gradient boosted trees model = XGBClassifier(n_jobs = N_CORES, random_state = SEED) cv_schema = StratifiedKFold(n_splits = N_SPLITS, random_state = SEED) %%time # Tune model against a single hyper parameter tuning_param = 'n_estimators' tuning_param_range = np.array([int(i) for i in np.linspace(10.0, 50.0, 5)]) train_scores_val, cv_scores_val = validation_curve( model, X_train, y_train, param_name = tuning_param, param_range = tuning_param_range, cv = cv_schema, scoring = SCORE, n_jobs = N_CORES) # Plot validation curve plot_validation_curve(train_scores_val, cv_scores_val, tuning_param_range, scale='lin', title='validation curve', y_label='accuracy', x_label='n_estimators') # Obtain the best value of the hyper parameter best_param_val = tuning_param_range[np.argmax(np.mean(cv_scores_val, axis=1))] # Train model with best hyper parameter and assess its perfrmance on test data gb_clf = XGBClassifier(n_estimators = best_param_val, n_jobs = N_CORES, random_state=SEED) gb_clf.fit(X_train, y_train) gb_score = gb_clf.score(X_test,y_test) print('Gradient boosted accuracy: {}'.format(round(gb_score, 4))) # Set parameters, model and cv schema model = SVC(random_state = SEED) cv_schema = StratifiedKFold(n_splits = N_SPLITS, shuffle=True, random_state = SEED) %%time # Tune model against a single hyper parameter tuning_param = 'C' tuning_param_range = np.logspace(-5, 5, 5) train_scores_val, cv_scores_val = validation_curve( model, X_train, y_train, param_name = tuning_param, param_range = tuning_param_range, cv = cv_schema, scoring = SCORE, n_jobs = N_CORES) # Plot validation curve plot_validation_curve(train_scores_val, cv_scores_val, tuning_param_range, scale='log', title='validation curve', y_label='accuracy', x_label='C') # Obtain the best value of the hyper parameter best_param_val = tuning_param_range[np.argmax(np.mean(cv_scores_val, axis=1))] # Train model with increasing amount of training data svc_clf = SVC(C = best_param_val) svc_clf.fit(X_train, y_train) svc_score = svc_clf.score(X_test,y_test) print('SVC accuracy: {}'.format(round(svc_score, 4))) # Encode target labels to one hot vectors (ex : 3 -> [0,0,0,1,0,0,0,0,0,0]) y_train_ohe = to_categorical(y_train, num_classes = 10) y_test_ohe = to_categorical(y_test, num_classes = 10) y_train_ohe[0] # Set parameters, model and cv schema epochs = 10 # Number of iterations over full training set batch_size = 200 # Number of observations to fit in every batch num_pixels = 28 * 28 num_classes = 10 # Create and compile a simple feed forward neural network def ffnn_model(): # Create a neural network with two dense layers model = Sequential() model.add(Dense(num_pixels, input_dim=num_pixels, kernel_initializer='normal', activation='relu')) model.add(Dense(num_classes, kernel_initializer='normal', activation='softmax')) # Compile model model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model model = ffnn_model() # Visualize keras model SVG(model_to_dot(model,show_shapes=True).create(prog='dot', format='svg')) # Fit the model to data model.fit(X_train, y_train_ohe, validation_data = (X_test, y_test_ohe), epochs = epochs, batch_size = batch_size) # Get model summary model.summary() # Evaluate trained model on test set ff_loss, ff_score = model.evaluate(X_test, y_test_ohe) print('Loss: {}'.format(round(ff_loss, 4))) print('Accuracy: {}'.format(round(ff_score, 4))) # Get predicted values predicted_classes = model.predict_classes(X_test) # Get index of correctly and incorrectly classified observations target_val_orig = np.argmax(y_test_ohe, 1) # Get index list of all correctly predicted values correct_indices = np.nonzero(np.equal(predicted_classes, target_val_orig))[0] # Get index list of all incorrectly predicted values incorrect_indices = np.nonzero(np.not_equal(predicted_classes, target_val_orig))[0] # Print number of correctly and incorrectly clasified observations print ('Correctly predicted: %i' % np.size(correct_indices)) print ('Incorrectly predicted: %i' % np.size(incorrect_indices)) # See a sample of incorrectly classified samples plt.figure(figsize=[20,8]) for i, incorrect in enumerate(incorrect_indices[:6]): plt.subplot(1,6,i+1) plt.imshow(X_test[incorrect].reshape(28,28), cmap='gray', interpolation='none') plt.title("Predicted {}, Class {}".format(predicted_classes[incorrect], target_val_orig[incorrect])) # Reshape image in 3 dimensions (height = 28px, width = 28px , canal = 1) X_train_reshaped = X_train.reshape(-1,28,28,1) X_test_reshaped = X_test.reshape(-1,28,28,1) # Access a single pixel value in reshaped arrays X_train_reshaped[2800][27][27][0] # Encode target labels to one hot vectors y_train_ohe = to_categorical(y_train, num_classes = 10) y_test_ohe = to_categorical(y_test, num_classes = 10) # Set parameters, model and cv schema epochs = 10 # number of iterations over full training set batch_size = 200 # number of observations to fit in every batch # Set the CNN architechture (architecture taken from: # https://machinelearningmastery.com/handwritten-digit-recognition-using-convolutional-neural-networks-python-keras/ def cnn_model(): model = Sequential() model.add(Conv2D(filters = 32, kernel_size = (5,5), padding = 'Same', activation ='relu', input_shape = (28,28,1))) model.add(Conv2D(filters = 32, kernel_size = (5,5), padding = 'Same', activation ='relu')) model.add(MaxPool2D(pool_size=(2,2))) model.add(Dropout(0.25)) model.add(Conv2D(filters = 64, kernel_size = (3,3), padding = 'Same', activation ='relu')) model.add(Conv2D(filters = 64, kernel_size = (3,3), padding = 'Same', activation ='relu')) model.add(MaxPool2D(pool_size=(2,2), strides=(2,2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(256, activation = "relu")) model.add(Dropout(0.5)) model.add(Dense(10, activation = "softmax")) # compile the model model.compile(optimizer = 'adam' , loss = "categorical_crossentropy", metrics=["accuracy"]) return (model) model = cnn_model() SVG(model_to_dot(model,show_shapes=True).create(prog='dot', format='svg')) # Fit the model to data model.fit(X_train_reshaped, y_train_ohe, validation_data=(X_test_reshaped, y_test_ohe), epochs=epochs, batch_size=batch_size) # Get model summary model.summary() # Evaluate trained model on test set cnn_loss, cnn_score = model.evaluate(X_test_reshaped, y_test_ohe) print('Loss: {}'.format(round(cnn_loss, 4))) print('Accuracy: {}'.format(round(cnn_score, 4))) # Get predicted values predicted_classes = model.predict_classes(X_test_reshaped) # Get index of correctly and incorrectly classified observations target_val_orig = np.argmax(y_test_ohe, 1) # Get index list of all correctly predicted values correct_indices = np.nonzero(np.equal(predicted_classes, target_val_orig))[0] # Get index list of all incorrectly predicted values incorrect_indices = np.nonzero(np.not_equal(predicted_classes, target_val_orig))[0] # Print number of correctly and incorrectly clasified observations print ('Correctly predicted: %i' % np.size(correct_indices)) print ('Incorrectly predicted: %i' % np.size(incorrect_indices)) # See a sample of incorrectly classified samples plt.figure(figsize=[20,8]) for i, incorrect in enumerate(incorrect_indices[:6]): plt.subplot(1,6,i+1) plt.imshow(X_test[incorrect].reshape(28,28), cmap='gray', interpolation='none') plt.title("Predicted {}, Class {}".format(predicted_classes[incorrect], target_val_orig[incorrect])) # Look at confusion matrix y_pred_ohe = model.predict(X_test_reshaped) y_pred_classes = np.argmax(y_pred_ohe, axis = 1) y_true = np.argmax(y_test_ohe, axis = 1) confusion_mtx = confusion_matrix(y_true, y_pred_classes) plot_confusion_matrix(confusion_mtx, classes = range(10)) width = 35 models = ['Baseline', 'LR + Ridge', 'KNN', 'Random Forest', 'Boosted Trees', 'SVC', 'NN', 'CNN'] results = [baseline_score, lr_score, knn_score, rf_score, gb_score, svc_score, ff_score, cnn_score] print('', '=' * width, '\n', 'Summary of Accuracy Scores'.center(width), '\n', '=' * width) for i in range(len(models)): print(models[i].center(width-8), '{0:.4f}'.format(round(results[i], 4))) # Learning_curve function in sklearn.model_selection is used to assess performance of # a model with diferent training sizes, hence justifying possible investments # into gathering more data # Here we train random forest classifier with increasing amount of training data rf_clf = RandomForestClassifier(n_estimators = 50, n_jobs = N_CORES) cv_schema = StratifiedShuffleSplit(n_splits = N_SPLITS, test_size = 0.33, shuffle=True, random_state = SEED) train_sizes = np.linspace(.1, 1.0, 5) train_sizes, train_scores_learn, cv_scores_learn = learning_curve( rf_clf, features, target, cv = cv_schema, n_jobs = N_CORES, train_sizes = train_sizes, scoring = SCORE) # Plot learning curve plot_learning_curve(train_scores_learn, cv_scores_learn, train_sizes, scale='lin', title='learning curve of random forest classifier', y_label='accuracy', x_label='train set size')
0.839537
0.928991
# Gram-Schmidt process ## Instructions In this assignment you will write a function to perform the Gram-Schmidt procedure, which takes a list of vectors and forms an orthonormal basis from this set. As a corollary, the procedure allows us to determine the dimension of the space spanned by the basis vectors, which is equal to or less than the space which the vectors sit. You'll start by completing a function for 4 basis vectors, before generalising to when an arbitrary number of vectors are given. Again, a framework for the function has already been written. Look through the code, and you'll be instructed where to make changes. We'll do the first two rows, and you can use this as a guide to do the last two. ### Matrices in Python Remember the structure for matrices in *numpy* is, ```python A[0, 0] A[0, 1] A[0, 2] A[0, 3] A[1, 0] A[1, 1] A[1, 2] A[1, 3] A[2, 0] A[2, 1] A[2, 2] A[2, 3] A[3, 0] A[3, 1] A[3, 2] A[3, 3] ``` You can access the value of each element individually using, ```python A[n, m] ``` You can also access a whole row at a time using, ```python A[n] ``` Building on last assignment, in this exercise you will need to select whole columns at a time. This can be done with, ```python A[:, m] ``` which will select the m'th column (starting at zero). In this exercise, you will need to take the dot product between vectors. This can be done using the @ operator. To dot product vectors u and v, use the code, ```python u @ v ``` All the code you should complete will be at the same level of indentation as the instruction comment. ### How to submit Edit the code in the cell below to complete the assignment. Once you are finished and happy with it, press the *Submit Assignment* button at the top of this notebook. Please don't change any of the function names, as these will be checked by the grading script. If you have further questions about submissions or programming assignments, here is a [list](https://www.coursera.org/learn/linear-algebra-machine-learning/discussions/weeks/1/threads/jB4klkn5EeibtBIQyzFmQg) of Q&A. You can also raise an issue on the discussion forum. Good luck! ``` # GRADED FUNCTION import numpy as np import numpy.linalg as la verySmallNumber = 1e-14 # That's 1×10⁻¹⁴ = 0.00000000000001 # Our first function will perform the Gram-Schmidt procedure for 4 basis vectors. # We'll take this list of vectors as the columns of a matrix, A. # We'll then go through the vectors one at a time and set them to be orthogonal # to all the vectors that came before it. Before normalising. # Follow the instructions inside the function at each comment. # You will be told where to add code to complete the function. def gsBasis4(A) : B = np.array(A, dtype=np.float_) # Make B as a copy of A, since we're going to alter it's values. # The zeroth column is easy, since it has no other vectors to make it normal to. # All that needs to be done is to normalise it. I.e. divide by its modulus, or norm. B[:, 0] = B[:, 0] / la.norm(B[:, 0]) # For the first column, we need to subtract any overlap with our new zeroth vector. B[:, 1] = B[:, 1] - B[:, 1] @ B[:, 0] * B[:, 0] # If there's anything left after that subtraction, then B[:, 1] is linearly independant of B[:, 0] # If this is the case, we can normalise it. Otherwise we'll set that vector to zero. if la.norm(B[:, 1]) > verySmallNumber : B[:, 1] = B[:, 1] / la.norm(B[:, 1]) else : B[:, 1] = np.zeros_like(B[:, 1]) # Now we need to repeat the process for column 2. # Insert two lines of code, the first to subtract the overlap with the zeroth vector, # and the second to subtract the overlap with the first. B[:, 2] = B[:, 2] - B[:, 2] @ B[:, 0] * B[:, 0] B[:, 2] = B[:, 2] - B[:, 2] @ B[:, 1] * B[:, 1] # Again we'll need to normalise our new vector. # Copy and adapt the normalisation fragment from above to column 2. if la.norm(B[:, 2]) > verySmallNumber : B[:, 2] = B[:, 2] / la.norm(B[:, 2]) else : B[:, 2] = np.zeros_like(B[:, 2]) # Finally, column three: # Insert code to subtract the overlap with the first three vectors. B[:, 3] = B[:, 3] - B[:, 3] @ B[:, 0] * B[:, 0] B[:, 3] = B[:, 3] - B[:, 3] @ B[:, 1] * B[:, 1] B[:, 3] = B[:, 3] - B[:, 3] @ B[:, 2] * B[:, 2] # Now normalise if possible if la.norm(B[:, 3]) > verySmallNumber : B[:, 3] = B[:, 3] / la.norm(B[:, 3]) else : B[:, 3] = np.zeros_like(B[:, 3]) # Finally, we return the result: return B # The second part of this exercise will generalise the procedure. # Previously, we could only have four vectors, and there was a lot of repeating in the code. # We'll use a for-loop here to iterate the process for each vector. def gsBasis(A) : B = np.array(A, dtype=np.float_) # Make B as a copy of A, since we're going to alter it's values. # Loop over all vectors, starting with zero, label them with i for i in range(B.shape[1]) : # Inside that loop, loop over all previous vectors, j, to subtract. for j in range(i) : # Complete the code to subtract the overlap with previous vectors. # you'll need the current vector B[:, i] and a previous vector B[:, j] B[:, i] = B[:, i] - B[:, i] @ B[:, j] * B[:, j] # Next insert code to do the normalisation test for B[:, i] if la.norm(B[:, i]) > verySmallNumber : B[:, i] = B[:, i] / la.norm(B[:, i]) else : B[:, i] = np.zeros_like(B[:, i]) # Finally, we return the result: return B # This function uses the Gram-schmidt process to calculate the dimension # spanned by a list of vectors. # Since each vector is normalised to one, or is zero, # the sum of all the norms will be the dimension. def dimensions(A) : return np.sum(la.norm(gsBasis(A), axis=0)) ``` ## Test your code before submission To test the code you've written above, run the cell (select the cell above, then press the play button [ ▶| ] or press shift-enter). You can then use the code below to test out your function. You don't need to submit this cell; you can edit and run it as much as you like. Try out your code on tricky test cases! ``` V = np.array([[1,0,2,6], [0,1,8,2], [2,8,3,1], [1,-6,2,3]], dtype=np.float_) gsBasis4(V) # Once you've done Gram-Schmidt once, # doing it again should give you the same result. Test this: U = gsBasis4(V) gsBasis4(U) # Try the general function too. gsBasis(V) # See what happens for non-square matrices A = np.array([[3,2,3], [2,5,-1], [2,4,8], [12,2,1]], dtype=np.float_) gsBasis(A) dimensions(A) B = np.array([[6,2,1,7,5], [2,8,5,-4,1], [1,-6,3,2,8]], dtype=np.float_) gsBasis(B) dimensions(B) # Now let's see what happens when we have one vector that is a linear combination of the others. C = np.array([[1,0,2], [0,1,-3], [1,0,2]], dtype=np.float_) gsBasis(C) dimensions(C) ```
github_jupyter
A[0, 0] A[0, 1] A[0, 2] A[0, 3] A[1, 0] A[1, 1] A[1, 2] A[1, 3] A[2, 0] A[2, 1] A[2, 2] A[2, 3] A[3, 0] A[3, 1] A[3, 2] A[3, 3] A[n, m] A[n] A[:, m] u @ v # GRADED FUNCTION import numpy as np import numpy.linalg as la verySmallNumber = 1e-14 # That's 1×10⁻¹⁴ = 0.00000000000001 # Our first function will perform the Gram-Schmidt procedure for 4 basis vectors. # We'll take this list of vectors as the columns of a matrix, A. # We'll then go through the vectors one at a time and set them to be orthogonal # to all the vectors that came before it. Before normalising. # Follow the instructions inside the function at each comment. # You will be told where to add code to complete the function. def gsBasis4(A) : B = np.array(A, dtype=np.float_) # Make B as a copy of A, since we're going to alter it's values. # The zeroth column is easy, since it has no other vectors to make it normal to. # All that needs to be done is to normalise it. I.e. divide by its modulus, or norm. B[:, 0] = B[:, 0] / la.norm(B[:, 0]) # For the first column, we need to subtract any overlap with our new zeroth vector. B[:, 1] = B[:, 1] - B[:, 1] @ B[:, 0] * B[:, 0] # If there's anything left after that subtraction, then B[:, 1] is linearly independant of B[:, 0] # If this is the case, we can normalise it. Otherwise we'll set that vector to zero. if la.norm(B[:, 1]) > verySmallNumber : B[:, 1] = B[:, 1] / la.norm(B[:, 1]) else : B[:, 1] = np.zeros_like(B[:, 1]) # Now we need to repeat the process for column 2. # Insert two lines of code, the first to subtract the overlap with the zeroth vector, # and the second to subtract the overlap with the first. B[:, 2] = B[:, 2] - B[:, 2] @ B[:, 0] * B[:, 0] B[:, 2] = B[:, 2] - B[:, 2] @ B[:, 1] * B[:, 1] # Again we'll need to normalise our new vector. # Copy and adapt the normalisation fragment from above to column 2. if la.norm(B[:, 2]) > verySmallNumber : B[:, 2] = B[:, 2] / la.norm(B[:, 2]) else : B[:, 2] = np.zeros_like(B[:, 2]) # Finally, column three: # Insert code to subtract the overlap with the first three vectors. B[:, 3] = B[:, 3] - B[:, 3] @ B[:, 0] * B[:, 0] B[:, 3] = B[:, 3] - B[:, 3] @ B[:, 1] * B[:, 1] B[:, 3] = B[:, 3] - B[:, 3] @ B[:, 2] * B[:, 2] # Now normalise if possible if la.norm(B[:, 3]) > verySmallNumber : B[:, 3] = B[:, 3] / la.norm(B[:, 3]) else : B[:, 3] = np.zeros_like(B[:, 3]) # Finally, we return the result: return B # The second part of this exercise will generalise the procedure. # Previously, we could only have four vectors, and there was a lot of repeating in the code. # We'll use a for-loop here to iterate the process for each vector. def gsBasis(A) : B = np.array(A, dtype=np.float_) # Make B as a copy of A, since we're going to alter it's values. # Loop over all vectors, starting with zero, label them with i for i in range(B.shape[1]) : # Inside that loop, loop over all previous vectors, j, to subtract. for j in range(i) : # Complete the code to subtract the overlap with previous vectors. # you'll need the current vector B[:, i] and a previous vector B[:, j] B[:, i] = B[:, i] - B[:, i] @ B[:, j] * B[:, j] # Next insert code to do the normalisation test for B[:, i] if la.norm(B[:, i]) > verySmallNumber : B[:, i] = B[:, i] / la.norm(B[:, i]) else : B[:, i] = np.zeros_like(B[:, i]) # Finally, we return the result: return B # This function uses the Gram-schmidt process to calculate the dimension # spanned by a list of vectors. # Since each vector is normalised to one, or is zero, # the sum of all the norms will be the dimension. def dimensions(A) : return np.sum(la.norm(gsBasis(A), axis=0)) V = np.array([[1,0,2,6], [0,1,8,2], [2,8,3,1], [1,-6,2,3]], dtype=np.float_) gsBasis4(V) # Once you've done Gram-Schmidt once, # doing it again should give you the same result. Test this: U = gsBasis4(V) gsBasis4(U) # Try the general function too. gsBasis(V) # See what happens for non-square matrices A = np.array([[3,2,3], [2,5,-1], [2,4,8], [12,2,1]], dtype=np.float_) gsBasis(A) dimensions(A) B = np.array([[6,2,1,7,5], [2,8,5,-4,1], [1,-6,3,2,8]], dtype=np.float_) gsBasis(B) dimensions(B) # Now let's see what happens when we have one vector that is a linear combination of the others. C = np.array([[1,0,2], [0,1,-3], [1,0,2]], dtype=np.float_) gsBasis(C) dimensions(C)
0.579043
0.986455
# Contribute Before we can accept contributions, you need to become a CLAed contributor. E-mail a signed copy of the [CLAI](https://github.com/openpifpaf/openpifpaf/blob/main/docs/CLAI.txt) (and if applicable the [CLAC](https://github.com/openpifpaf/openpifpaf/blob/main/docs/CLAC.txt)) as PDF file to [email protected]. (modify-code)= ## Modify Code For development of the openpifpaf source code itself, you need to clone this repository and then: ```sh pip3 install numpy cython pip3 install --editable '.[dev,train,test]' ``` The last command installs the Python package in the current directory (signified by the dot) with the optional dependencies needed for training and testing. If you modify `functional.pyx`, run this last command again which recompiles the static code. Develop your features in separate feature branches. Create a pull request with your suggested changes. Make sure your code passes `pytest`, `pylint` and `pycodestyle` checks: ```sh pylint openpifpaf pycodestyle openpifpaf pytest cd guide python download_data.py pytest --nbval-lax --current-env *.ipynb ``` ## Things to Contribute This is a research project and changing fast. Contributions can be in many areas: * Add a new dataset? * Add a new base network? * Try a different loss? * Try a better multi-task strategy? * Try a different head architecture? * Add a new task? * Run on new hardware (mobile phones, embedded devices, ...)? * Improve training schedule/procedure? * Use it to build an app? * Improve documentation (!!) * ... ## Missing Dependencies OpenPifPaf has few core requirements so that you can run it efficiently on servers without graphical interface. Sometimes, you just want to install all possible dependencies. Those are provided as "extra" requirements. Use the following `pip3` command to install all extras. ``` import sys if sys.version_info >= (3, 8): import importlib.metadata extras = importlib.metadata.metadata('openpifpaf').get_all('Provides-Extra') print(f'pip3 install "openpifpaf[{",".join(extras)}]"') ``` ## Your Project and OpenPifPaf Let us know about your open source projects. We would like to feature them in our "related projects" section. The simplest way to integrate with OpenPifPaf is to write a plugin. If some functionality is not possible through our plugin architecture, open an issue to discuss and if necessary send us a pull request that enables the missing feature you need. If you do need to make a copy of OpenPifPaf, you must respect our license. ## Build Guide ```sh cd guide jb build . ``` If you encounter issues with the kernel spec in a notebook, open the notebook with a text editor and find `metadata.kernelspec.name` and set it to `python3`. Alternatively, you can patch your local package yourself. Open `venv/lib/python3.9/site-packages/jupyter_cache/executors/utils.py` in your editor and add `kernel_name='python3'` to the arguments of `nbexecute()` [here](https://github.com/executablebooks/jupyter-cache/blob/1431ed72961fabc2f09a13553b0aa45f4c8a7c23/jupyter_cache/executors/utils.py#L56). Alternatively, for continuous integration, the `kernel_name` is replace in the json of the Jupyter Notebook before executing jupyter-book [here](https://github.com/openpifpaf/openpifpaf/blob/6db797205cd082bf7a80e967372957e56c9835fb/.github/workflows/deploy-guide.yml#L47). Only use this operation on a discardable copy as `jq` changes all formatting. ## Build Environment ``` %%bash pip freeze %%bash python -m openpifpaf.predict --version ```
github_jupyter
pip3 install numpy cython pip3 install --editable '.[dev,train,test]' pylint openpifpaf pycodestyle openpifpaf pytest cd guide python download_data.py pytest --nbval-lax --current-env *.ipynb import sys if sys.version_info >= (3, 8): import importlib.metadata extras = importlib.metadata.metadata('openpifpaf').get_all('Provides-Extra') print(f'pip3 install "openpifpaf[{",".join(extras)}]"') cd guide jb build . %%bash pip freeze %%bash python -m openpifpaf.predict --version
0.274449
0.779532
# Lecture 7: Vectorized Programming CSCI 1360E: Foundations for Informatics and Analytics ## Overview and Objectives We've covered loops and lists, and how to use them to perform some basic arithmetic calculations. In this lecture, we'll see how we can use an external library to make these computations much easier and much faster. - Understand how to use `import` to add functionality beyond base Python - Compare and contrast NumPy arrays to built-in Python lists - Define "broadcasting" in the context of vectorized programming - Use NumPy arrays in place of explicit loops for basic arithmetic operations ## Part 1: Importing modules With all the data structures we've discussed so far--lists, sets, tuples, dictionaries, comprehensions, generators--it's hard to believe there's anything else. But oh *man*, is there a big huge world of Python extensions out there. These extensions are known as *modules*. You've seen at least one in play in your assignments so far: ``` import random ``` Anytime you see a statement that starts with `import`, you'll recognize that the programmer is pulling in some sort of external functionality not previously available to Python by default. In this case, the `random` package provides some basic functionality for computing random numbers. That's just one of **countless** examples...an infinite number that continues to nonetheless increase daily. Python has a bunch of functionality that comes by default--no `import` required. Remember writing functions to compute the maximum and minimum of a list? Turns out, those already exist by default (sorry everyone): ``` x = [3, 7, 2, 9, 4] print("Maximum: {}".format(max(x))) print("Minimum: {}".format(min(x))) ``` Quite a bit of other functionality--still built-in to the default Python environment!--requires explicit `import` statements to unlock. Here are just a couple of examples: ``` import random # For generating random numbers, as we've seen. import os # For interacting with the filesystem of your computer. import re # For regular expressions. Unrelated: https://xkcd.com/1171/ import datetime # Helps immensely with determining the date and formatting it. import math # Gives some basic math functions: trig, factorial, exponential, logarithms, etc. import xml # Abandon all hope, ye who enter. ``` If you are so inclined, you can see the full Python default module index here: [https://docs.python.org/3/py-modindex.html](https://docs.python.org/3/py-modindex.html). It's quite a bit! Made all the more mind-blowing to consider the default Python module index is bit a *tiny, miniscule drop in the bucket* compared to the myriad 3rd-party module ecosystem. These packages provides methods and functions wrapped inside, which you can access via the "dot-notation": ``` import random random.randint(0, 1) ``` Dot-notation works by 1. specifying `package_name` (in this case, `random`) 2. dot: `.` 3. followed by `function_name` (in this case, `randint`, which returns a random integer between two numbers) As a small tidbit--you can treat imported packages almost like variables, in that you can name them whatever you like, using the `as` keyword in the import statement. Instead of ``` import random random.randint(0, 1) ``` We can tweak it ``` import random as r r.randint(0, 1) ``` You can put whatever you want after the `as`, and anytime you call methods from that module, you'll use the name you gave it. Don't worry about trying to memorize all the available modules in core Python; in looking through them just now, I was amazed how many I'd never even heard of. Suffice to say, you can get by. Especially since, once you get beyond the core modules, there's an ever-expanding universe of 3rd-party modules you can install and use. [Anaconda comes prepackaged with quite a few](https://docs.continuum.io/anaconda/pkg-docs) (see the column "In Installer") and the option to manually install quite a few more. Again, **don't worry about trying to learn all these**. There are simply too many. You'll come across packages as you need them. For now, we're going to focus on one specific package that is central to most modern data science: **NumPy**, short for **Num**erical **Py**thon. ## Part 2: Introduction to NumPy NumPy, or Numerical Python, is an incredible library of basic functions and data structures that provide a robust foundation for computational scientists. Put another way: if you're using Python and doing any kind of math, you'll probably use NumPy. At this point, NumPy is so deeply embedded in so many *other* 3rd-party modules related to scientific computing that even if you're not making *explicit* use of it, at least one of the other modules you're using probably is. ### NumPy's core: the `ndarray` In core Python, if we wanted to represent a matrix, we would more or less have to build a "list of lists", a monstrosity along these lines: ``` matrix = [[ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9] ] print(matrix) ``` Indexing would still work as you would expect, but looping through a matrix--say, to do matrix multiplication--would be laborious and highly inefficient. We'll demonstrate this experimentally later, but suffice to say Python lists embody the drawbacks of using an *interpreted* language such as Python: they're easy to use, but oh so slow. By contrast, in NumPy, we have the `ndarray` structure (short for "n-dimensional array") that is a highly optimized version of Python lists, perfect for fast and efficient computations. To make use of NumPy arrays, import NumPy (it's installed by default in Anaconda, and on JupyterHub): ``` import numpy ``` Now just call the `array` method using our list from before! ``` arr = numpy.array(matrix) print(arr) ``` To reference an element in the array, just use the same notation we did for lists: ``` arr[0] arr[2][2] ``` You can also separate dimensions by commas: ``` arr[2, 2] ``` Remember, with indexing matrices: the first index is the *row*, the second index is the *column*. ### NumPy's submodules NumPy has an impressive array of utility modules that come along with it, optimized to use its `ndarray` data structure. I highly encourage you to use them, even if you're not using NumPy arrays. **1: Basic mathematical routines** All the core functions you could want; for example, all the built-in Python math routines (trig, logs, exponents, etc) all have NumPy versions. (`numpy.sin`, `numpy.cos`, `numpy.log`, `numpy.exp`, `numpy.max`, `numpy.min`) **2: Fourier transforms** If you do any signal processing using Fourier transforms (which we might, later!), NumPy has an entire sub-module full of tools for this type of analysis in `numpy.fft` **3: Linear algebra** We'll definitely be using this submodule later in the course. This is most of your vector and matrix linear algebra operations, from vector norms (`numpy.linalg.norm`) to singular value decomposition (`numpy.linalg.svd`) to matrix determinants (`numpy.linalg.det`). **4: Random numbers** NumPy has a phenomenal random number library in `numpy.random`. In addition to generating uniform random numbers in a certain range, you can also sample from any known parametric distribution. ## Part 3: Vectorized Arithmetic "Vectorized arithmetic" refers to how NumPy allows you to efficiently perform arithmetic operations on entire NumPy arrays at once, as you would with "regular" Python variables. For example: let's say you have a vector and you want to normalize it to be unit length; that involves dividing every element in the vector by a constant (the magnitude of the vector). With lists, you'd have to loop through them manually. ``` vector = [4.0, 15.0, 6.0, 2.0] # To normalize this to unit length, we need to divide each element by the vector's magnitude. # To learn it's magnitude, we need to loop through the whole vector. # So. We need two loops! magnitude = 0.0 for element in vector: magnitude += element ** 2 magnitude = (magnitude ** 0.5) # square root print("Original magnitude: {:.2f}".format(magnitude)) new_magnitude = 0.0 for index, element in enumerate(vector): vector[index] = element / magnitude new_magnitude += vector[index] ** 2 new_magnitude = (new_magnitude ** 0.5) print("Normalized magnitude: {:.2f}".format(new_magnitude)) ``` Now, let's see the same operation, this time with NumPy arrays. ``` import numpy as np # This tends to be the "standard" convention when importing NumPy. import numpy.linalg as nla vector = [4.0, 15.0, 6.0, 2.0] np_vector = np.array(vector) # Convert to NumPy array. magnitude = nla.norm(np_vector) # Computing the magnitude: one-liner. print("Original magnitude: {:.2f}".format(magnitude)) np_vector /= magnitude # Vectorized division!!! No loop needed! new_magnitude = nla.norm(np_vector) print("Normalized magnitude: {:.2f}".format(new_magnitude)) ``` No loops needed, far fewer lines of code, and a simple intuitive operation. Operations involving arrays on both sides of the sign will also work (though the two arrays need to be the same length). For example, adding two vectors together: ``` x = np.array([1, 2, 3]) y = np.array([4, 5, 6]) z = x + y print(z) ``` Works exactly as you'd expect, but no [explicit] loop needed. This becomes particularly compelling with matrix multiplication. Say you have two matrices, $A$ and $B$: ``` A = np.array([ [1, 2], [3, 4] ]) B = np.array([ [5, 6], [7, 8] ]) ``` If you recall from algebra, matrix multiplication $A \times B$ involves multipliying each *row* of $A$ by each *column* of $B$. But rather than write that code yourself, Python (as of version 3.5) gives us a dedicated matrix multiplication operator: the `@` symbol! ``` A @ B ``` ### In summary - NumPy arrays have all the abilities of lists (indexing, mutability, slicing) plus a whole lot of additional benefits, such as *vectorized computations*. - About the only limitation of NumPy arrays relative to Python lists is constructing them: with lists, you can build them through generators or the `append()` method, but you can't do this with NumPy arrays. Therefore, if you're building an array from scratch, the best option would be to build the list and then pass that to `numpy.array()` to convert it. Adjusting the length of the NumPy array *after* it's constructed is more difficult. - The Python ecosystem is *huge*. There is some functionality that comes with Python by default, and some of this default functionality is available immediately; the other default functionality is accessible using `import` statements. There is even more functionality from 3rd-party vendors, but it needs to be installed before it can be `import`ed. NumPy falls in this lattermost category. - Vectorized operations are always, always preferred to loops. They're easier to write, easier to understand, and in almost all cases, much more efficient. ## Review Questions Some questions to discuss and consider: 1: NumPy arrays have an attribute called `.shape` that will return the dimensions of the array in the form of a tuple. If the array is just a vector, the tuple will only have 1 element: the length of the array. If the array is a matrix, the tuple will have 2 elements: the number of rows and the number of columns. What will the `shape` tuple be for the following array: `tensor = np.array([ [ [1, 2], [3, 4] ], [ [5, 6], [7, 8] ], [ [9, 10], [11, 12] ] ])` 2: Vectorized computations may seem almost like magic, and indeed they are, but at the end of the day there has to be a loop *somewhere* that performs the operations. Given what we've discussed about interpreted languages, compiled languages, and in particular how the delineations between the two are blurring, what would your best educated guess be (ideally without Google's help) as to where these loops actually happen that implemented the vectorized computations? 3: Using your knowledge of slicing from a few lecture ago, and your knowledge from this lecture that NumPy arrays also support slicing, let's take an example of selecting a sub-range of rows from a two-dimensional matrix. Write the notation you would use for slicing out / selecting all the rows *except* for the first one, while retaining all the columns (hint: by just using `:` as your slicing operator, with no numbers, this means "everything"). ## Course Administrivia **If you're having trouble with the assignments, please contact me!** You can also post about it in Slack; that's specifically what I created the `#csci1360e-discussions` channel for: to collaborate and discuss any concepts you want with your classmates. I'll jump in wherever and whenever I can, but if you're having an issue chances are someone else is, too. All I want to avoid is straight copy-paste of code, but collaboration is perfectly fine and strongly encouraged! ## Additional Resources 1. Grus, Joel. *Data Science from Scratch*. 2015. ISBN-13: 978-1491901427 2. McKinney, Wes. *Python for Data Analysis*. 2012. ISBN-13: 860-1400898857 3. NumPy Quickstart Tutorial: [https://docs.scipy.org/doc/numpy-dev/user/quickstart.html](https://docs.scipy.org/doc/numpy-dev/user/quickstart.html)
github_jupyter
import random x = [3, 7, 2, 9, 4] print("Maximum: {}".format(max(x))) print("Minimum: {}".format(min(x))) import random # For generating random numbers, as we've seen. import os # For interacting with the filesystem of your computer. import re # For regular expressions. Unrelated: https://xkcd.com/1171/ import datetime # Helps immensely with determining the date and formatting it. import math # Gives some basic math functions: trig, factorial, exponential, logarithms, etc. import xml # Abandon all hope, ye who enter. import random random.randint(0, 1) import random random.randint(0, 1) import random as r r.randint(0, 1) matrix = [[ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9] ] print(matrix) import numpy arr = numpy.array(matrix) print(arr) arr[0] arr[2][2] arr[2, 2] vector = [4.0, 15.0, 6.0, 2.0] # To normalize this to unit length, we need to divide each element by the vector's magnitude. # To learn it's magnitude, we need to loop through the whole vector. # So. We need two loops! magnitude = 0.0 for element in vector: magnitude += element ** 2 magnitude = (magnitude ** 0.5) # square root print("Original magnitude: {:.2f}".format(magnitude)) new_magnitude = 0.0 for index, element in enumerate(vector): vector[index] = element / magnitude new_magnitude += vector[index] ** 2 new_magnitude = (new_magnitude ** 0.5) print("Normalized magnitude: {:.2f}".format(new_magnitude)) import numpy as np # This tends to be the "standard" convention when importing NumPy. import numpy.linalg as nla vector = [4.0, 15.0, 6.0, 2.0] np_vector = np.array(vector) # Convert to NumPy array. magnitude = nla.norm(np_vector) # Computing the magnitude: one-liner. print("Original magnitude: {:.2f}".format(magnitude)) np_vector /= magnitude # Vectorized division!!! No loop needed! new_magnitude = nla.norm(np_vector) print("Normalized magnitude: {:.2f}".format(new_magnitude)) x = np.array([1, 2, 3]) y = np.array([4, 5, 6]) z = x + y print(z) A = np.array([ [1, 2], [3, 4] ]) B = np.array([ [5, 6], [7, 8] ]) A @ B
0.45641
0.986165
# Quick Start Below is a sample demo of interaction with the environment. ``` from maro.simulator import Env from maro.simulator.scenarios.cim.common import Action, DecisionEvent env = Env(scenario="cim", topology="toy.5p_ssddd_l0.0", start_tick=0, durations=100) metrics: object = None decision_event: DecisionEvent = None is_done: bool = False while not is_done: action: Action = None metrics, decision_event, is_done = env.step(action) print(metrics) ``` # Environment of Container Inventory Management (CIM) To initialize an environment, you need to specify the values of several parameters: - **scenario**: The target scenario of this Env. - `cim` denotes for the Container Inventory Management (CIM). - **topology**: The target topology of this Env. As shown below, you can get the predefined topology list by calling `get_topologies(scenario='cim')`. - **start_tick**: The start tick of this Env, 1 tick corresponds to 1 day in cim. - In the demo above, `start_tick=0` indicates a simulation start from the beginning of the given topology. - **durations**: The duration of this Env, in the unit of tick/day. - In the demo above, `durations=100` indicates a simulation length of 100 days. You can get all available scenarios and topologies by calling: ``` from maro.simulator.utils import get_scenarios, get_topologies from pprint import pprint from typing import List scenarios: List[str] = get_scenarios() topologies: List[str] = get_topologies(scenario='cim') pprint(f'The available scenarios in MARO:') pprint(scenarios) print() pprint(f'The predefined topologies in CIM:') pprint(topologies) ``` Once you created an instance of the environment, you can easily access the real-time information of this environment, like: ``` from maro.backends.frame import SnapshotList from maro.simulator import Env from pprint import pprint from typing import List # Initialize an Env for CIM scenario env = Env(scenario="cim", topology="toy.5p_ssddd_l0.0", start_tick=0, durations=100) # The current tick tick: int = env.tick print(f"The current tick: {tick}.") # The current frame index, which indicates the index of current frame in the snapshot-list frame_index: int = env.frame_index print(f"The current frame index: {frame_index}.") # The agent index list in the environment agent_idx_list: List[int] = env.agent_idx_list print(f"There are {len(agent_idx_list)} agents in this Env.") # The whole snapshot-list of the environment, snapshots are taken in the granularity of the given snapshot_resolution # The example of how to use the snapshot will be shown later snapshot_list: SnapshotList = env.snapshot_list print(f"There will be {len(snapshot_list)} snapshots in total.") # The summary info of the environment summary: dict = env.summary print(f"\nEnv Summary:") pprint(summary) # The metrics of the environment metrics: dict = env.metrics print(f"\nEnv Metrics:") pprint(metrics) ``` # Interaction with the environment Before starting interaction with the environment, we need to know `DecisionEvent` and `Action` first. ## DecisionEvent Once the environment need the agent's response to promote the simulation, it will throw an `DecisionEvent`. In the scenario of CIM, the information of each `DecisionEvent` is listed as below: - **tick**: (int) The corresponding tick; - **port_idx**: (int) The id of the port/agent that needs to respond to the environment; - **vessel_idx**: (int) The id of the vessel/operation object of the port/agnet; - **action_scope**: (ActionScope) ActionScope has two attributes: - `load` indicates the maximum quantity that can be loaded from the port the vessel; - `discharge` indicates the maximum quantity that can be discharged from the vessel to the port; - **early_discharge**: (int) When the available capacity in the vessel is not enough to load the ladens, some of the empty containers in the vessel will be early discharged to free the space. The quantity of empty containers that have been early discharged due to the laden loading is recorded in this field. ## Action Once we get a `DecisionEvent` from the environment, we should respond with an `Action`. Valid `Action` could be: - `None`, which means do nothing. - A valid `Action` instance, including: - **vessel_idx**: (int) The id of the vessel/operation object of the port/agent; - **port_idx**: (int) The id of the port/agent that take this action; - **quantity**: (int) The sign of this value denotes different meanings: - Positive quantity means unloading empty containers from vessel to port; - Negative quantity means loading empty containers from port to vessel. ## Generate random actions based on the DecisionEvent The demo code in the Quick Start part has shown an interaction mode that doing nothing(responding with `None` action). Here we read the detailed information from the `DecisionEvent` and generate random `Action` based on it. ``` from maro.simulator import Env from maro.simulator.scenarios.cim.common import Action, DecisionEvent import random # Initialize an Env for cim scenario env = Env(scenario="cim", topology="toy.5p_ssddd_l0.0", start_tick=0, durations=100) metrics: object = None decision_event: DecisionEvent = None is_done: bool = False action: Action = None # Start the env with a None Action metrics, decision_event, is_done = env.step(None) while not is_done: # Generate a random Action according to the action_scope in DecisionEvent random_quantity = random.randint( -decision_event.action_scope.load, decision_event.action_scope.discharge ) action = Action( vessel_idx=decision_event.vessel_idx, port_idx=decision_event.port_idx, quantity=random_quantity ) # Randomly sample some records to show in the output if random.random() > 0.95: print(f"*************\n{decision_event}\n{action}") # Respond the environment with the generated Action metrics, decision_event, is_done = env.step(action) ``` ## Get the environment observation You can also implement other strategies or build models to take action. At this time, real-time information and historical records of the environment are very important for making good decisions. In this case, the the environment snapshot list is exactly what you need. The information in the snapshot list is indexed by 3 dimensions: - A tick index (list). (int / List[int]) Empty indicates for all time slides till now; - A port id (list). (int / List[int]) Empty indicates for all ports/agents; - An attribute name (list). (str / List[str]) You can get all available attributes in `env.summary` as shown before. The return value from the snapshot list is a numpy.ndarray with shape **(num_tick * num_port * num_attribute, )**. More detailed introduction to the snapshot list is [here](https://maro.readthedocs.io/en/latest/key_components/data_model.html#advanced-features). ``` from maro.simulator import Env from pprint import pprint env = Env(scenario="cim", topology="toy.5p_ssddd_l0.0", start_tick=0, durations=100) # To get the attribute list that can be accessed in snapshot_list pprint(env.summary['node_detail'], depth=2) print() # The attribute list of ports pprint(env.summary['node_detail']['ports']) from maro.backends.frame import SnapshotList from maro.simulator import Env from pprint import pprint from typing import List # Initialize an Env for CIM scenario env = Env(scenario="cim", topology="toy.5p_ssddd_l0.0", start_tick=0, durations=100) # Start the environment with None action _, decision_event, is_done = env.step(None) while not is_done: # Case of access snapshot after a certain number of ticks if env.tick >= 80: # The tick list of past 1 week past_week_ticks = [x for x in range(env.tick - 7, env.tick)] # The port index of the current decision_event decision_port_idx = decision_event.port_idx # The attribute list to access intr_port_infos = ["booking", "empty", "shortage"] # Query the snapshot list of this environment to get the information of # the booking, empty, shortage of the decision port in the past week past_week_info = env.snapshot_list["ports"][ past_week_ticks : decision_port_idx : intr_port_infos ] pprint(past_week_info) # This demo code is used to show how to access the information in snapshot, # so we terminate the env here for clear output break # Drive the environment with None action _, decision_event, is_done = env.step(None) ```
github_jupyter
from maro.simulator import Env from maro.simulator.scenarios.cim.common import Action, DecisionEvent env = Env(scenario="cim", topology="toy.5p_ssddd_l0.0", start_tick=0, durations=100) metrics: object = None decision_event: DecisionEvent = None is_done: bool = False while not is_done: action: Action = None metrics, decision_event, is_done = env.step(action) print(metrics) from maro.simulator.utils import get_scenarios, get_topologies from pprint import pprint from typing import List scenarios: List[str] = get_scenarios() topologies: List[str] = get_topologies(scenario='cim') pprint(f'The available scenarios in MARO:') pprint(scenarios) print() pprint(f'The predefined topologies in CIM:') pprint(topologies) from maro.backends.frame import SnapshotList from maro.simulator import Env from pprint import pprint from typing import List # Initialize an Env for CIM scenario env = Env(scenario="cim", topology="toy.5p_ssddd_l0.0", start_tick=0, durations=100) # The current tick tick: int = env.tick print(f"The current tick: {tick}.") # The current frame index, which indicates the index of current frame in the snapshot-list frame_index: int = env.frame_index print(f"The current frame index: {frame_index}.") # The agent index list in the environment agent_idx_list: List[int] = env.agent_idx_list print(f"There are {len(agent_idx_list)} agents in this Env.") # The whole snapshot-list of the environment, snapshots are taken in the granularity of the given snapshot_resolution # The example of how to use the snapshot will be shown later snapshot_list: SnapshotList = env.snapshot_list print(f"There will be {len(snapshot_list)} snapshots in total.") # The summary info of the environment summary: dict = env.summary print(f"\nEnv Summary:") pprint(summary) # The metrics of the environment metrics: dict = env.metrics print(f"\nEnv Metrics:") pprint(metrics) from maro.simulator import Env from maro.simulator.scenarios.cim.common import Action, DecisionEvent import random # Initialize an Env for cim scenario env = Env(scenario="cim", topology="toy.5p_ssddd_l0.0", start_tick=0, durations=100) metrics: object = None decision_event: DecisionEvent = None is_done: bool = False action: Action = None # Start the env with a None Action metrics, decision_event, is_done = env.step(None) while not is_done: # Generate a random Action according to the action_scope in DecisionEvent random_quantity = random.randint( -decision_event.action_scope.load, decision_event.action_scope.discharge ) action = Action( vessel_idx=decision_event.vessel_idx, port_idx=decision_event.port_idx, quantity=random_quantity ) # Randomly sample some records to show in the output if random.random() > 0.95: print(f"*************\n{decision_event}\n{action}") # Respond the environment with the generated Action metrics, decision_event, is_done = env.step(action) from maro.simulator import Env from pprint import pprint env = Env(scenario="cim", topology="toy.5p_ssddd_l0.0", start_tick=0, durations=100) # To get the attribute list that can be accessed in snapshot_list pprint(env.summary['node_detail'], depth=2) print() # The attribute list of ports pprint(env.summary['node_detail']['ports']) from maro.backends.frame import SnapshotList from maro.simulator import Env from pprint import pprint from typing import List # Initialize an Env for CIM scenario env = Env(scenario="cim", topology="toy.5p_ssddd_l0.0", start_tick=0, durations=100) # Start the environment with None action _, decision_event, is_done = env.step(None) while not is_done: # Case of access snapshot after a certain number of ticks if env.tick >= 80: # The tick list of past 1 week past_week_ticks = [x for x in range(env.tick - 7, env.tick)] # The port index of the current decision_event decision_port_idx = decision_event.port_idx # The attribute list to access intr_port_infos = ["booking", "empty", "shortage"] # Query the snapshot list of this environment to get the information of # the booking, empty, shortage of the decision port in the past week past_week_info = env.snapshot_list["ports"][ past_week_ticks : decision_port_idx : intr_port_infos ] pprint(past_week_info) # This demo code is used to show how to access the information in snapshot, # so we terminate the env here for clear output break # Drive the environment with None action _, decision_event, is_done = env.step(None)
0.725357
0.918553
<a id='header'></a> # Principal Component Analysis (PCA) In this notebook we present PCA-related functionalities from the ``reduction`` module. ### PCA functionalities - [**Section 1**](#global_local_pca): We present how *global and local PCA* can be performed using `PCA` class from the `reduction` module. - [**Section 2**](#plotting_pca): We present the plotting functionalities from the `reduction` module for viewing PCA results. *** **Should plots be saved?** ``` save_plots = False ``` *** <a id='global_local_pca'></a> ## Global vs. local PCA [**Go up**](#header) ``` from PCAfold import preprocess from PCAfold import reduction from PCAfold import PCA import matplotlib.pyplot as plt from matplotlib import gridspec import numpy as np # Set some initial parameters: global_color = '#6a6e7a' k1_color = '#0e7da7' k2_color = '#ceca70' PC_color = '#000000' data_point = 4 font_text = 20 line_width = 1 n_points = 1000 # Fonts: csfont = {'fontname':'Charter', 'fontweight':'regular'} hfont = {'fontname':'Charter', 'fontweight':'bold'} # Function for plotting: def plot_data_set(x, y, title_text=''): figure = plt.figure(figsize=(8, 5)) figureSubplot = plt.subplot(1,1,1) plt.scatter(x, y, color=global_color, marker='.', linewidth=data_point-2) plt.xticks([]), plt.yticks([]) plt.grid(alpha=0.2) plt.title(title_text, **csfont, fontsize=font_text, color=PC_color) ``` Create a function that will perform PCA transformation on local portions of the data set: ``` def local_pca(X, idx): n_clusters = len(np.unique(idx)) # Initialize the outputs: eigenvectors = [] eigenvalues = [] principal_components = [] for k in range(0, n_clusters): # Extract local cluster: X_k = X[idx==k,:] # Perform PCA in a local cluster: pca = PCA(X_k, scaling='none', n_components=2, use_eigendec=True) Z = pca.transform(X_k, nocenter=False) # Save the local eigenvectors, eigenvalues and PCs: eigenvectors.append(pca.A) eigenvalues.append(pca.L) principal_components.append(Z) return (eigenvectors, eigenvalues, principal_components) ``` *** ### Generate synthetic data set on which global PCA will be performed: This data set is composed of a single cloud: ``` mean_global = [0,1] covariance_global = [[3.4, 1.1], [1.1, 2.1]] x_noise, y_noise = np.random.multivariate_normal(mean_global, covariance_global, n_points).T y_global = np.linspace(0,4,n_points) x_global = -(y_global**2) + 7*y_global + 4 y_global = y_global + y_noise x_global = x_global + x_noise Dataset_global = np.hstack((x_global[:,np.newaxis], y_global[:,np.newaxis])) ``` Visualize the data set: ``` plot_data_set(x_global, y_global, 'Synthetic data set for global PCA') if save_plots==True: plt.savefig('../images/tutorial-pca-data-set-for-global-pca.png', dpi = 500, bbox_inches='tight') ``` Perform PCA transformation of the data set: ``` # Perform PCA: pca = PCA(Dataset_global, 'none', n_components=2) PC_scores_global = pca.transform(Dataset_global, nocenter=False) eigenvectors_global = pca.A eigenvalues_global = pca.L # Centered data set: Dataset_global_pp = pca.X_cs ``` *** ### Generate synthetic data set on which local PCA will be performed This data set is composed of two distinct clouds: ``` mean_local_1 = [0,1] mean_local_2 = [6,4] covariance_local_1 = [[2, 0.5], [0.5, 0.5]] covariance_local_2 = [[3, 0.3], [0.3, 0.5]] x_noise_1, y_noise_1 = np.random.multivariate_normal(mean_local_1, covariance_local_1, n_points).T x_noise_2, y_noise_2 = np.random.multivariate_normal(mean_local_2, covariance_local_2, n_points).T x_local = np.concatenate([x_noise_1, x_noise_2]) y_local = np.concatenate([y_noise_1, y_noise_2]) Dataset_local = np.hstack((x_local[:,np.newaxis], y_local[:,np.newaxis])) ``` Visualize the data set: ``` plot_data_set(x_local, y_local, 'Synthetic data set for local PCA') if save_plots==True: plt.savefig('../images/tutorial-pca-data-set-for-local-pca.png', dpi = 500, bbox_inches='tight') ``` Cluster the data set using two pre-defined bins: ``` idx = preprocess.predefined_variable_bins(Dataset_local[:,0], [2.5], verbose=False) centroids = preprocess.get_centroids(Dataset_local, idx) ``` Perform local PCA: ``` (eigenvectors_local, eigenvalues_local, _) = local_pca(Dataset_local, idx) ``` *** ### Plotting global vs. local PCA Plot the identified eigenvectors on the data set where global PCA was performed and on the data set where local PCA was performed: ``` figure = plt.figure(figsize=(13, 4)) gs = gridspec.GridSpec(1, 2, width_ratios=[1, 2]) # First subplot - global PCA: figureSubplot = plt.subplot(gs[0]) plt.scatter(Dataset_global_pp[:,0], Dataset_global_pp[:,1], s=data_point, color=global_color, marker='o', linewidth=line_width) # Plot global eigenvectors: plt.quiver(eigenvectors_global[0,0], eigenvectors_global[1,0], scale=30*(1-eigenvalues_global[0]), color=PC_color, width=0.014) plt.quiver(eigenvectors_global[0,1], eigenvectors_global[1,1], scale=10*(1-eigenvalues_global[1]), color=PC_color, width=0.014) plt.axis('equal') plt.yticks([]), plt.xticks([]) plt.title('Globally applied PCA', **csfont, fontsize=font_text, color=PC_color) # Plot global centroid: plt.scatter(0, 0, color=PC_color, marker='x', lineWidth=data_point, s=20); # Second subplot - local PCA: figureSubplot = plt.subplot(gs[1]) plt.scatter(Dataset_local[idx==0,0], Dataset_local[idx==0,1], s=data_point, c=k1_color, marker='o') plt.scatter(Dataset_local[idx==1,0], Dataset_local[idx==1,1], s=data_point, c=k2_color, marker='o') # Plot local eigenvectors: origin = [centroids[0][0]], [centroids[0][1]] plt.quiver(*origin, eigenvectors_local[0][0,0], eigenvectors_local[0][1,0], scale=30*(1-eigenvalues_local[0][0]), color=PC_color, width=0.007) plt.quiver(*origin, eigenvectors_local[0][0,1], eigenvectors_local[0][1,1], scale=20*(1-eigenvalues_local[0][1]), color=PC_color, width=0.007) origin = [centroids[1][0]], [centroids[1][1]] plt.quiver(*origin, eigenvectors_local[1][0,0], eigenvectors_local[1][1,0], scale=30*(1-eigenvalues_local[1][0]), color=PC_color, width=0.007) plt.quiver(*origin, eigenvectors_local[1][0,1], eigenvectors_local[1][1,1], scale=20*(1-eigenvalues_local[1][1]), color=PC_color, width=0.007) plt.axis('equal') plt.yticks([]), plt.xticks([]) plt.title('Locally applied PCA', **csfont, fontsize=font_text, color=PC_color) # Plot local centroids: plt.scatter(centroids[:, 0], centroids[:, 1], color=PC_color, marker='x', lineWidth=data_point, s=20); if save_plots==True: plt.savefig('../images/tutorial-pca-global-local-pca.png', dpi = 500, bbox_inches='tight') ``` *** <a id='plotting_pca'></a> ## Plotting PCA results [**Go up**](#header) Below we demonstrate plotting PCA results using the functions available in the ``reduction`` module. ``` # Set some initial parameters: title = None save_filename = None X_names = ['$T$', '$H_2$', '$O_2$', '$O$', '$OH$', '$H_2O$', '$H$', '$HO_2$', '$CO$', '$CO_2$', '$HCO$'] # Upload the sample data set: X = np.genfromtxt('data-state-space.csv', delimiter=',') ``` Create three PCA objects corresponding to different data scaling criteria: ``` pca_X_Auto = PCA(X, scaling='auto', n_components=2) pca_X_Range = PCA(X, scaling='range', n_components=2) pca_X_Vast = PCA(X, scaling='vast', n_components=2) pca_X_Pareto = PCA(X, scaling='pareto', n_components=2) ``` ### Eigenvectors Plot eigenvectors from one of the scaling options: ``` if save_plots == True: save_filename = 'plotting-pca' plt = reduction.plot_eigenvectors(pca_X_Auto.A[:,0], eigenvectors_indices=[], variable_names=X_names, plot_absolute=False, save_path='../images/', save_filename=save_filename) ``` Plot absolute values: ``` if save_plots == True: save_filename = 'plotting-pca-absolute' plt = reduction.plot_eigenvectors(pca_X_Auto.A[:,0], eigenvectors_indices=[], variable_names=X_names, plot_absolute=True, save_path='../images/', save_filename=save_filename) ``` Plot comparison of eigenvectors from all scaling options: ``` if save_plots == True: save_filename = '../images/plotting-pca-eigenvectors-comparison' plt = reduction.plot_eigenvectors_comparison((pca_X_Auto.A[:,0], pca_X_Range.A[:,0], pca_X_Vast.A[:,0]), legend_labels=['Auto', 'Range', 'Vast'], variable_names=X_names, plot_absolute=False, color_map='coolwarm', save_filename=save_filename) ``` Plot absolute values: ``` if save_plots == True: save_filename = '../images/plotting-pca-eigenvectors-comparison-absolute' plt = reduction.plot_eigenvectors_comparison((pca_X_Auto.A[:,0], pca_X_Range.A[:,0], pca_X_Vast.A[:,0]), legend_labels=['Auto', 'Range', 'Vast'], variable_names=X_names, plot_absolute=True, color_map='coolwarm', save_filename=save_filename) ``` ### Eigenvalues Plot eigenvalue distribution: ``` if save_plots == True: save_filename = '../images/plotting-pca-eigenvalue-distribution' plt = reduction.plot_eigenvalue_distribution(pca_X_Auto.L, normalized=False, save_filename=save_filename) ``` Plot normalized eigenvalue distribution: ``` if save_plots == True: save_filename = '../images/plotting-pca-eigenvalue-distribution-normalized' plt = reduction.plot_eigenvalue_distribution(pca_X_Auto.L, normalized=True, save_filename=save_filename) ``` Plot comparison of eigenvalues from all scaling options: ``` if save_plots == True: save_filename = '../images/plotting-pca-eigenvalue-distribution-comparison' plt = reduction.plot_eigenvalue_distribution_comparison((pca_X_Auto.L, pca_X_Range.L, pca_X_Vast.L), legend_labels=['Auto', 'Range', 'Vast'], normalized=False, color_map='coolwarm', save_filename=save_filename) ``` Plot absolute values: ``` if save_plots == True: save_filename = '../images/plotting-pca-eigenvalue-distribution-comparison-normalized' plt = reduction.plot_eigenvalue_distribution_comparison((pca_X_Auto.L, pca_X_Range.L, pca_X_Vast.L), legend_labels=['Auto', 'Range', 'Vast'], normalized=True, color_map='coolwarm', save_filename=save_filename) ``` ### Cumulative variance Plot cumulative variance: ``` if save_plots: save_filename = '../images/cumulative-variance' plt = reduction.plot_cumulative_variance(pca_X_Auto.L, n_components=0, save_filename=save_filename) ``` You can also truncate the number of eigenvalues: ``` if save_plots: save_filename = '../images/cumulative-variance-truncated' plt = reduction.plot_cumulative_variance(pca_X_Auto.L, n_components=5, save_filename=save_filename) ``` ### Two-dimensional manifold Finally, we transform the original data set to the new basis: ``` principal_components = pca_X_Vast.transform(X) ``` and we plot the two-dimensional manifold: ``` if save_plots: save_filename = '../images/plotting-pca-2d-manifold-black' plt = reduction.plot_2d_manifold(principal_components[:,0], principal_components[:,1], color_variable='k', x_label='$Z_1$', y_label='$Z_2$', colorbar_label=None, save_filename=save_filename) ``` two-dimensional manifold colored by temperature variable: ``` if save_plots: save_filename = '../images/plotting-pca-2d-manifold' plt = reduction.plot_2d_manifold(principal_components[:,0], principal_components[:,1], color_variable=X[:,0], x_label='$Z_1$', y_label='$Z_2$', colorbar_label='$T$ [-]', save_filename=save_filename) ``` ### Parity plots Parity plots of reconstructed variables can be visualized using `reduction.plot_parity` function. We approximate the data set using the previously obtained two Principal Components: ``` X_rec = pca_X_Vast.reconstruct(principal_components) ``` We visualize the reconstruction of the first variable: ``` if save_plots: save_filename = '../images/plotting-pca-parity' plt = reduction.plot_parity(X[:,0], X_rec[:,0], x_label='Observed $T$', y_label='Reconstructed $T$', save_filename=save_filename) ```
github_jupyter
save_plots = False from PCAfold import preprocess from PCAfold import reduction from PCAfold import PCA import matplotlib.pyplot as plt from matplotlib import gridspec import numpy as np # Set some initial parameters: global_color = '#6a6e7a' k1_color = '#0e7da7' k2_color = '#ceca70' PC_color = '#000000' data_point = 4 font_text = 20 line_width = 1 n_points = 1000 # Fonts: csfont = {'fontname':'Charter', 'fontweight':'regular'} hfont = {'fontname':'Charter', 'fontweight':'bold'} # Function for plotting: def plot_data_set(x, y, title_text=''): figure = plt.figure(figsize=(8, 5)) figureSubplot = plt.subplot(1,1,1) plt.scatter(x, y, color=global_color, marker='.', linewidth=data_point-2) plt.xticks([]), plt.yticks([]) plt.grid(alpha=0.2) plt.title(title_text, **csfont, fontsize=font_text, color=PC_color) def local_pca(X, idx): n_clusters = len(np.unique(idx)) # Initialize the outputs: eigenvectors = [] eigenvalues = [] principal_components = [] for k in range(0, n_clusters): # Extract local cluster: X_k = X[idx==k,:] # Perform PCA in a local cluster: pca = PCA(X_k, scaling='none', n_components=2, use_eigendec=True) Z = pca.transform(X_k, nocenter=False) # Save the local eigenvectors, eigenvalues and PCs: eigenvectors.append(pca.A) eigenvalues.append(pca.L) principal_components.append(Z) return (eigenvectors, eigenvalues, principal_components) mean_global = [0,1] covariance_global = [[3.4, 1.1], [1.1, 2.1]] x_noise, y_noise = np.random.multivariate_normal(mean_global, covariance_global, n_points).T y_global = np.linspace(0,4,n_points) x_global = -(y_global**2) + 7*y_global + 4 y_global = y_global + y_noise x_global = x_global + x_noise Dataset_global = np.hstack((x_global[:,np.newaxis], y_global[:,np.newaxis])) plot_data_set(x_global, y_global, 'Synthetic data set for global PCA') if save_plots==True: plt.savefig('../images/tutorial-pca-data-set-for-global-pca.png', dpi = 500, bbox_inches='tight') # Perform PCA: pca = PCA(Dataset_global, 'none', n_components=2) PC_scores_global = pca.transform(Dataset_global, nocenter=False) eigenvectors_global = pca.A eigenvalues_global = pca.L # Centered data set: Dataset_global_pp = pca.X_cs mean_local_1 = [0,1] mean_local_2 = [6,4] covariance_local_1 = [[2, 0.5], [0.5, 0.5]] covariance_local_2 = [[3, 0.3], [0.3, 0.5]] x_noise_1, y_noise_1 = np.random.multivariate_normal(mean_local_1, covariance_local_1, n_points).T x_noise_2, y_noise_2 = np.random.multivariate_normal(mean_local_2, covariance_local_2, n_points).T x_local = np.concatenate([x_noise_1, x_noise_2]) y_local = np.concatenate([y_noise_1, y_noise_2]) Dataset_local = np.hstack((x_local[:,np.newaxis], y_local[:,np.newaxis])) plot_data_set(x_local, y_local, 'Synthetic data set for local PCA') if save_plots==True: plt.savefig('../images/tutorial-pca-data-set-for-local-pca.png', dpi = 500, bbox_inches='tight') idx = preprocess.predefined_variable_bins(Dataset_local[:,0], [2.5], verbose=False) centroids = preprocess.get_centroids(Dataset_local, idx) (eigenvectors_local, eigenvalues_local, _) = local_pca(Dataset_local, idx) figure = plt.figure(figsize=(13, 4)) gs = gridspec.GridSpec(1, 2, width_ratios=[1, 2]) # First subplot - global PCA: figureSubplot = plt.subplot(gs[0]) plt.scatter(Dataset_global_pp[:,0], Dataset_global_pp[:,1], s=data_point, color=global_color, marker='o', linewidth=line_width) # Plot global eigenvectors: plt.quiver(eigenvectors_global[0,0], eigenvectors_global[1,0], scale=30*(1-eigenvalues_global[0]), color=PC_color, width=0.014) plt.quiver(eigenvectors_global[0,1], eigenvectors_global[1,1], scale=10*(1-eigenvalues_global[1]), color=PC_color, width=0.014) plt.axis('equal') plt.yticks([]), plt.xticks([]) plt.title('Globally applied PCA', **csfont, fontsize=font_text, color=PC_color) # Plot global centroid: plt.scatter(0, 0, color=PC_color, marker='x', lineWidth=data_point, s=20); # Second subplot - local PCA: figureSubplot = plt.subplot(gs[1]) plt.scatter(Dataset_local[idx==0,0], Dataset_local[idx==0,1], s=data_point, c=k1_color, marker='o') plt.scatter(Dataset_local[idx==1,0], Dataset_local[idx==1,1], s=data_point, c=k2_color, marker='o') # Plot local eigenvectors: origin = [centroids[0][0]], [centroids[0][1]] plt.quiver(*origin, eigenvectors_local[0][0,0], eigenvectors_local[0][1,0], scale=30*(1-eigenvalues_local[0][0]), color=PC_color, width=0.007) plt.quiver(*origin, eigenvectors_local[0][0,1], eigenvectors_local[0][1,1], scale=20*(1-eigenvalues_local[0][1]), color=PC_color, width=0.007) origin = [centroids[1][0]], [centroids[1][1]] plt.quiver(*origin, eigenvectors_local[1][0,0], eigenvectors_local[1][1,0], scale=30*(1-eigenvalues_local[1][0]), color=PC_color, width=0.007) plt.quiver(*origin, eigenvectors_local[1][0,1], eigenvectors_local[1][1,1], scale=20*(1-eigenvalues_local[1][1]), color=PC_color, width=0.007) plt.axis('equal') plt.yticks([]), plt.xticks([]) plt.title('Locally applied PCA', **csfont, fontsize=font_text, color=PC_color) # Plot local centroids: plt.scatter(centroids[:, 0], centroids[:, 1], color=PC_color, marker='x', lineWidth=data_point, s=20); if save_plots==True: plt.savefig('../images/tutorial-pca-global-local-pca.png', dpi = 500, bbox_inches='tight') # Set some initial parameters: title = None save_filename = None X_names = ['$T$', '$H_2$', '$O_2$', '$O$', '$OH$', '$H_2O$', '$H$', '$HO_2$', '$CO$', '$CO_2$', '$HCO$'] # Upload the sample data set: X = np.genfromtxt('data-state-space.csv', delimiter=',') pca_X_Auto = PCA(X, scaling='auto', n_components=2) pca_X_Range = PCA(X, scaling='range', n_components=2) pca_X_Vast = PCA(X, scaling='vast', n_components=2) pca_X_Pareto = PCA(X, scaling='pareto', n_components=2) if save_plots == True: save_filename = 'plotting-pca' plt = reduction.plot_eigenvectors(pca_X_Auto.A[:,0], eigenvectors_indices=[], variable_names=X_names, plot_absolute=False, save_path='../images/', save_filename=save_filename) if save_plots == True: save_filename = 'plotting-pca-absolute' plt = reduction.plot_eigenvectors(pca_X_Auto.A[:,0], eigenvectors_indices=[], variable_names=X_names, plot_absolute=True, save_path='../images/', save_filename=save_filename) if save_plots == True: save_filename = '../images/plotting-pca-eigenvectors-comparison' plt = reduction.plot_eigenvectors_comparison((pca_X_Auto.A[:,0], pca_X_Range.A[:,0], pca_X_Vast.A[:,0]), legend_labels=['Auto', 'Range', 'Vast'], variable_names=X_names, plot_absolute=False, color_map='coolwarm', save_filename=save_filename) if save_plots == True: save_filename = '../images/plotting-pca-eigenvectors-comparison-absolute' plt = reduction.plot_eigenvectors_comparison((pca_X_Auto.A[:,0], pca_X_Range.A[:,0], pca_X_Vast.A[:,0]), legend_labels=['Auto', 'Range', 'Vast'], variable_names=X_names, plot_absolute=True, color_map='coolwarm', save_filename=save_filename) if save_plots == True: save_filename = '../images/plotting-pca-eigenvalue-distribution' plt = reduction.plot_eigenvalue_distribution(pca_X_Auto.L, normalized=False, save_filename=save_filename) if save_plots == True: save_filename = '../images/plotting-pca-eigenvalue-distribution-normalized' plt = reduction.plot_eigenvalue_distribution(pca_X_Auto.L, normalized=True, save_filename=save_filename) if save_plots == True: save_filename = '../images/plotting-pca-eigenvalue-distribution-comparison' plt = reduction.plot_eigenvalue_distribution_comparison((pca_X_Auto.L, pca_X_Range.L, pca_X_Vast.L), legend_labels=['Auto', 'Range', 'Vast'], normalized=False, color_map='coolwarm', save_filename=save_filename) if save_plots == True: save_filename = '../images/plotting-pca-eigenvalue-distribution-comparison-normalized' plt = reduction.plot_eigenvalue_distribution_comparison((pca_X_Auto.L, pca_X_Range.L, pca_X_Vast.L), legend_labels=['Auto', 'Range', 'Vast'], normalized=True, color_map='coolwarm', save_filename=save_filename) if save_plots: save_filename = '../images/cumulative-variance' plt = reduction.plot_cumulative_variance(pca_X_Auto.L, n_components=0, save_filename=save_filename) if save_plots: save_filename = '../images/cumulative-variance-truncated' plt = reduction.plot_cumulative_variance(pca_X_Auto.L, n_components=5, save_filename=save_filename) principal_components = pca_X_Vast.transform(X) if save_plots: save_filename = '../images/plotting-pca-2d-manifold-black' plt = reduction.plot_2d_manifold(principal_components[:,0], principal_components[:,1], color_variable='k', x_label='$Z_1$', y_label='$Z_2$', colorbar_label=None, save_filename=save_filename) if save_plots: save_filename = '../images/plotting-pca-2d-manifold' plt = reduction.plot_2d_manifold(principal_components[:,0], principal_components[:,1], color_variable=X[:,0], x_label='$Z_1$', y_label='$Z_2$', colorbar_label='$T$ [-]', save_filename=save_filename) X_rec = pca_X_Vast.reconstruct(principal_components) if save_plots: save_filename = '../images/plotting-pca-parity' plt = reduction.plot_parity(X[:,0], X_rec[:,0], x_label='Observed $T$', y_label='Reconstructed $T$', save_filename=save_filename)
0.756717
0.944842
``` import nltk from nltk.corpus import twitter_samples nltk.download('twitter_samples') positive_tweets = twitter_samples.strings('positive_tweets.json') negative_tweets = twitter_samples.strings('negative_tweets.json') from nltk.tokenize import TweetTokenizer from nltk.corpus import stopwords from nltk.stem import PorterStemmer import string import re nltk.download('stopwords') def process_tweet(tweet, tokenizer,stemmer): tweet = re.sub(r'(http|https)?:\/\/.*[\r\n]*', '', tweet) tweet = re.sub(r'#','', tweet) tweet = re.sub(r'\n', ' ', tweet) tweet = re.sub(r'@\w+ ', '', tweet) tweet = tweet.lower() tokens = tokenizer.tokenize(tweet) tokens = [token for token in tokens if token not in stopwords.words('english')] tokens = [token for token in tokens if token not in string.punctuation] tokens = [stemmer.stem(token) for token in tokens] return tokens import numpy as np tweets = positive_tweets + negative_tweets tweets = np.array(tweets) tweets.shape labels = np.append(np.ones(5000), np.zeros(5000)) labels.shape from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(tweets, labels, test_size=0.3) X_train.shape X_test.shape frequencies = {'happy': (50,20,0.7), 'sad' : (10,12,-0.9)} frequencies frequencies.get('happy') frequencies.get('like', (0,0,0)) frequencies = {} sum_pos_freq = 0 sum_neg_freq = 0 vocabulary = set() tokenizer = TweetTokenizer() stemmer = PorterStemmer() for tweet, label in zip(X_train, y_train): for token in process_tweet(tweet, tokenizer, stemmer): vocabulary.add(token) pos_freq_count = frequencies.get(token, (0,0,0))[0] neg_freq_count = frequencies.get(token, (0,0,0))[1] if label == 1.0: pos_freq_count +=1 sum_pos_freq +=1 else: neg_freq_count += 1 sum_neg_freq += 1 frequencies[token] = (pos_freq_count, neg_freq_count, 0) print(frequencies) frequencies.get('good') frequencies.get('bad') sum_pos_freq sum_neg_freq len(vocabulary) import math for token in frequencies: pos_freq_count = frequencies.get(token, (0,0,0))[0] neg_freq_count = frequencies.get(token, (0,0,0))[1] pos_prob = (pos_freq_count + 1) / (sum_pos_freq + len(vocabulary)) neg_prob = (neg_freq_count + 1) / (sum_neg_freq + len(vocabulary)) lamda = math.log10(pos_prob / neg_prob) frequencies[token] = (pos_prob, neg_prob, lamda) print(frequencies) frequencies.get('good') frequencies.get('bad') frequencies.get('lost') frequencies.get('win') features = np.zeros((X_train.size, 3)) features.shape for i in range(len(X_train)): pos_log_likelyhood = 0 neg_log_likelyhood = 0 for token in process_tweet(X_train[i], tokenizer, stemmer): log_likelyhood = frequencies.get(token, (0,0,0))[2] if log_likelyhood > 0: pos_log_likelyhood += log_likelyhood else: neg_log_likelyhood += log_likelyhood features[i,:] = [pos_log_likelyhood, neg_log_likelyhood, y_train[i]] features import matplotlib.pyplot as plt np.max(features) np.min(features) colors = ['red', 'green'] plt.figure(figsize=(10,6)) plt.axis([0,10,-10,0]) plt.scatter(features[:,0], features[:,1], c=[colors[int(i)] for i in features[:,2]], marker = '.') plt.plot([0,10],[0,-10]) plt.show log_prior = np.count_nonzero(y_train) / (y_train.size - np.count_nonzero(y_train)) correct_predictions_count = 0 for tweet, label in zip(X_test, y_test): log_likelyhood = 0 for token in process_tweet(tweet, tokenizer,stemmer): log_likelyhood += frequencies.get(token, (0,0,0))[2] inference = log_prior + log_likelyhood if inference >= 1 and label == 1.0: correct_predictions_count += 1 elif inference < 1 and label == 0.0: correct_predictions_count += 1 correct_predictions_count ``` ## percentage of accuracy prediction ``` correct_predictions_count / y_test.size ```
github_jupyter
import nltk from nltk.corpus import twitter_samples nltk.download('twitter_samples') positive_tweets = twitter_samples.strings('positive_tweets.json') negative_tweets = twitter_samples.strings('negative_tweets.json') from nltk.tokenize import TweetTokenizer from nltk.corpus import stopwords from nltk.stem import PorterStemmer import string import re nltk.download('stopwords') def process_tweet(tweet, tokenizer,stemmer): tweet = re.sub(r'(http|https)?:\/\/.*[\r\n]*', '', tweet) tweet = re.sub(r'#','', tweet) tweet = re.sub(r'\n', ' ', tweet) tweet = re.sub(r'@\w+ ', '', tweet) tweet = tweet.lower() tokens = tokenizer.tokenize(tweet) tokens = [token for token in tokens if token not in stopwords.words('english')] tokens = [token for token in tokens if token not in string.punctuation] tokens = [stemmer.stem(token) for token in tokens] return tokens import numpy as np tweets = positive_tweets + negative_tweets tweets = np.array(tweets) tweets.shape labels = np.append(np.ones(5000), np.zeros(5000)) labels.shape from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(tweets, labels, test_size=0.3) X_train.shape X_test.shape frequencies = {'happy': (50,20,0.7), 'sad' : (10,12,-0.9)} frequencies frequencies.get('happy') frequencies.get('like', (0,0,0)) frequencies = {} sum_pos_freq = 0 sum_neg_freq = 0 vocabulary = set() tokenizer = TweetTokenizer() stemmer = PorterStemmer() for tweet, label in zip(X_train, y_train): for token in process_tweet(tweet, tokenizer, stemmer): vocabulary.add(token) pos_freq_count = frequencies.get(token, (0,0,0))[0] neg_freq_count = frequencies.get(token, (0,0,0))[1] if label == 1.0: pos_freq_count +=1 sum_pos_freq +=1 else: neg_freq_count += 1 sum_neg_freq += 1 frequencies[token] = (pos_freq_count, neg_freq_count, 0) print(frequencies) frequencies.get('good') frequencies.get('bad') sum_pos_freq sum_neg_freq len(vocabulary) import math for token in frequencies: pos_freq_count = frequencies.get(token, (0,0,0))[0] neg_freq_count = frequencies.get(token, (0,0,0))[1] pos_prob = (pos_freq_count + 1) / (sum_pos_freq + len(vocabulary)) neg_prob = (neg_freq_count + 1) / (sum_neg_freq + len(vocabulary)) lamda = math.log10(pos_prob / neg_prob) frequencies[token] = (pos_prob, neg_prob, lamda) print(frequencies) frequencies.get('good') frequencies.get('bad') frequencies.get('lost') frequencies.get('win') features = np.zeros((X_train.size, 3)) features.shape for i in range(len(X_train)): pos_log_likelyhood = 0 neg_log_likelyhood = 0 for token in process_tweet(X_train[i], tokenizer, stemmer): log_likelyhood = frequencies.get(token, (0,0,0))[2] if log_likelyhood > 0: pos_log_likelyhood += log_likelyhood else: neg_log_likelyhood += log_likelyhood features[i,:] = [pos_log_likelyhood, neg_log_likelyhood, y_train[i]] features import matplotlib.pyplot as plt np.max(features) np.min(features) colors = ['red', 'green'] plt.figure(figsize=(10,6)) plt.axis([0,10,-10,0]) plt.scatter(features[:,0], features[:,1], c=[colors[int(i)] for i in features[:,2]], marker = '.') plt.plot([0,10],[0,-10]) plt.show log_prior = np.count_nonzero(y_train) / (y_train.size - np.count_nonzero(y_train)) correct_predictions_count = 0 for tweet, label in zip(X_test, y_test): log_likelyhood = 0 for token in process_tweet(tweet, tokenizer,stemmer): log_likelyhood += frequencies.get(token, (0,0,0))[2] inference = log_prior + log_likelyhood if inference >= 1 and label == 1.0: correct_predictions_count += 1 elif inference < 1 and label == 0.0: correct_predictions_count += 1 correct_predictions_count correct_predictions_count / y_test.size
0.291687
0.329014
# 4 Classes ### 4.1 The `class` Statement The `class` statement starts a block of code and creates a new namespace. All namespace changes in the block, e.g. simple assignment and function definitions, are made in that new namespace. Finally it adds the class name to the namespace where the class statement appears. ``` class Number: __version__ = '1.0' def __init__(self, amount): self.amount = amount def add(self, value): return self.amount + value ``` ``` Number Number.__name__ Number.__class__ Number.__version__ ``` Instances of a class are created by calling the class. `Number.__init__(<new object>, ...)` is called automatically, and is passed the instance of the class already created by a call to the `__new__` method. ``` n1 = Number(1) Number.add ``` Accessing an attribute such as `add` on class instance `n1` returns a *method object* if `add` exists as a method in `Number` or its superclasses. A method object binds the class instance as the first argument to the method. ``` n1.add n1.add(2) ``` ### 4.2 The `type` callable "The class statement is just a way to call a function, take the result, and put it into a namespace." -- Glyph Lefkowitz in *Turtles All The Way Down: Demystifying Deferreds, Decorators, and Declarations* at PyCon 2010 - http://pyvideo.org/pycon-us-2010/pycon-2010--turtles-all-the-way-down--demystifyin.html `type(name, bases, dict)` is the default callable that gets called when Python evaluates a `class` statement. ``` def init(self, amount): self.amount = amount def add(self, value): return self.amount + value Number = type( 'Number', # The name of the class (), # Superclasses {'__version__': '2.0', '__init__': init, 'add': add}) # dict of class contents n2 = Number(2) type(n2) n2.__class__ n2.__dict__ n2.amount n2.add(3) ``` ### 4.3 Class Internals Let's poke around the internal structure of a class. ``` class Number: """A number class.""" __version__ = '2.0' def __init__(self, amount): self.amount = amount def add(self, value): """Add a value to the number.""" print(f'Call: add({self!r}, {value})') return self.amount + value Number Number.__version__ Number.__doc__ Number.__init__ Number.add dir(Number) def dir_public(obj): return [n for n in dir(obj) if not n.startswith('__')] dir_public(Number) n2 = Number(2) n2.amount n2 n2.__init__ n2.add dir_public(n2) set(dir(n2)) ^ set(dir(Number)) # symmetric_difference n2.__dict__ Number.__dict__ Number.__dict__['add'] Number.__dict__['add'] is Number.add n2.add n2.add(3) ``` Here's some unusual code ahead which will help us think carefully about how Python works. We defined this method earlier: ```python def add(self, value): return self.amount + value ``` ``` Number.add ``` ``` Number.add(2) Number.add(2, 3) Number.add(n2, 3) n2.add(3) ``` ``` Number.__init__ ``` Here's the `__init__` methed we defined earlier: ```python def __init__(self, amount): self.amount = amount ``` ``` Number.__init__? ``` Let's monkey patch the `Number` class to change it's `__init__` method. ``` def set_double_amount(num, initial_amount): num.amount = 2 * initial_amount Number.__init__ = set_double_amount Number.__init__ Number.__init__? n4 = Number(2) n4.amount # Will this be 2 or 4? n4.add n4.add(5) n4.__init__ n2.__init__ def multiply_by(num, value): return num.amount * value ``` Watch carefully. I add `mul` to the `n4` instance of the `Number` class. ``` n4.mul = multiply_by n4.mul n4.mul(5) n4.mul(n4, 5) ``` What differs between `mul` and `add`? ``` n4.mul n10 = Number(5) n10.mul dir_public(n10) n10.__dict__ dir_public(Number) dir_public(n4) Number.mul = multiply_by n10.mul n10.mul(5) n4.mul(5) dir_public(n10) dir_public(n4) n10.__dict__ n4.__dict__ n10.mul, n4.mul del n4.mul n4.__dict__ n10.mul, n4.mul ``` ``` dir_public(n4) n4.mul Number.mul n4.mul(5) ``` Bound methods are callable objects, similar to a function. ``` n4 add_4_to = n4.add add_4_to(6) ``` ``` double = (2).__mul__ double double(3) double(4) ``` Let's look behind the curtain to see how class instances work in Python. ``` Number n4 Number.add n4.add ``` ``` dir_public(n4) dir(n4.add) dir_public(n4.add) set(dir(n4.add)) - set(dir(Number.add)) n4.add.__self__ n4.add.__self__.amount n4.add.__self__ is n4 n4.add.__func__ n4.add.__func__ is Number.add n4.add.__func__ is n10.add.__func__ n4.add is n10.add n4.add(5) ``` So here's roughly what Python does to executes `n4.add(5)`: ``` n4.add.__func__(n4.add.__self__, 5) ``` ### 4.4 Exercises: Bound Methods ``` import keyword keyword.kwlist type(keyword.kwlist) 'pass' in keyword.kwlist list.__contains__? keyword.kwlist.__contains__('pass') is_keyword = keyword.kwlist.__contains__ is_keyword('len') is_keyword('pass') ``` ### 4.5 Metaclasses In this section we'll only touch on metaclasses briefly to understand how they work. A *metaclass* lets us customize the creation of classes. https://docs.python.org/3/reference/datamodel.html#customizing-class-creation > By default, classes are constructed using type(). The class body is > executed in a new namespace and the class name is bound locally to > the result of type(name, bases, namespace). > The class creation process can be customised by passing the > metaclass keyword argument in the class definition line, or by > inheriting from an existing class that included such an argument. Usually a metaclass is created by subclassing `type` and overriding one or more of its methods `__prepare__`, `__new__`, or `__init__`. However, any callable that matches the signature of `type` will work. Here's how we used the `type` callable earlier: ```python Number = type( 'Number', # The name of the class (), # Superclasses {'__version__': '2.0', '__init__': init, 'add': add}) # dict of class contents ``` Here's a simple metaclass that calls type to create the class. ``` def simple_metaclass_1(name, bases, dict): """Call type to create the class, but first print its arguments.""" print(f'simple_metaclass({name!r}, {bases!r}, {dict!r})') return type(name, bases, dict) ``` ``` class Number(metaclass=simple_metaclass_1): def __init__(self, amount): self.amount = amount def add(self, value): return self.amount + value ``` ``` n1 = Number(1) n1._dump() ``` Now let's add three lines to the metaclass function that will add a new method to the class (and also to any of its subclasses). ``` def simple_metaclass_2(name, bases, dict): print(f'simple_metaclass({name!r}, {bases!r}, {dict!r})') # 3 lines added: def _dump(self): print('__dict__:', self.__dict__) dict['_dump'] = _dump return type(name, bases, dict) class Number(metaclass=simple_metaclass_2): def __init__(self, amount): self.amount = amount def add(self, value): return self.amount + value n1 = Number(1) n1._dump() ``` ### 4.6 Exercises: Metaclasses Review: > By default, classes are constructed using type(). The class body is > executed in a new namespace and the class name is bound locally to > the result of type(name, bases, namespace). > The class creation process can be customised by passing the > metaclass keyword argument in the class definition line, or by > inheriting from an existing class that included such an argument. What will Python do with the following code? ``` def return_spam(name, bases, namespace): """Ignore all arguments and return 'spam'""" print(f'Call return_spam({name!r}, {bases!r}, {namespace!r})') return 'spam' class WeirdClass(metaclass=return_spam): pass ``` What object will the name `WeirdClass` be bound to? What is it's type? Try to figure it out before executing these statements: ``` WeirdClass type(WeirdClass) ``` ``` return_spam(None, None, None) WeirdClass = return_spam(None, None, None) WeirdClass ```
github_jupyter
class Number: __version__ = '1.0' def __init__(self, amount): self.amount = amount def add(self, value): return self.amount + value Number Number.__name__ Number.__class__ Number.__version__ n1 = Number(1) Number.add n1.add n1.add(2) def init(self, amount): self.amount = amount def add(self, value): return self.amount + value Number = type( 'Number', # The name of the class (), # Superclasses {'__version__': '2.0', '__init__': init, 'add': add}) # dict of class contents n2 = Number(2) type(n2) n2.__class__ n2.__dict__ n2.amount n2.add(3) class Number: """A number class.""" __version__ = '2.0' def __init__(self, amount): self.amount = amount def add(self, value): """Add a value to the number.""" print(f'Call: add({self!r}, {value})') return self.amount + value Number Number.__version__ Number.__doc__ Number.__init__ Number.add dir(Number) def dir_public(obj): return [n for n in dir(obj) if not n.startswith('__')] dir_public(Number) n2 = Number(2) n2.amount n2 n2.__init__ n2.add dir_public(n2) set(dir(n2)) ^ set(dir(Number)) # symmetric_difference n2.__dict__ Number.__dict__ Number.__dict__['add'] Number.__dict__['add'] is Number.add n2.add n2.add(3) def add(self, value): return self.amount + value ``` Here's the `__init__` methed we defined earlier: Let's monkey patch the `Number` class to change it's `__init__` method. Watch carefully. I add `mul` to the `n4` instance of the `Number` class. What differs between `mul` and `add`? Bound methods are callable objects, similar to a function. Let's look behind the curtain to see how class instances work in Python. So here's roughly what Python does to executes `n4.add(5)`: ### 4.4 Exercises: Bound Methods ### 4.5 Metaclasses In this section we'll only touch on metaclasses briefly to understand how they work. A *metaclass* lets us customize the creation of classes. https://docs.python.org/3/reference/datamodel.html#customizing-class-creation > By default, classes are constructed using type(). The class body is > executed in a new namespace and the class name is bound locally to > the result of type(name, bases, namespace). > The class creation process can be customised by passing the > metaclass keyword argument in the class definition line, or by > inheriting from an existing class that included such an argument. Usually a metaclass is created by subclassing `type` and overriding one or more of its methods `__prepare__`, `__new__`, or `__init__`. However, any callable that matches the signature of `type` will work. Here's how we used the `type` callable earlier: Here's a simple metaclass that calls type to create the class. Now let's add three lines to the metaclass function that will add a new method to the class (and also to any of its subclasses). ### 4.6 Exercises: Metaclasses Review: > By default, classes are constructed using type(). The class body is > executed in a new namespace and the class name is bound locally to > the result of type(name, bases, namespace). > The class creation process can be customised by passing the > metaclass keyword argument in the class definition line, or by > inheriting from an existing class that included such an argument. What will Python do with the following code? What object will the name `WeirdClass` be bound to? What is it's type? Try to figure it out before executing these statements:
0.884757
0.879716
# Racial data vs. Congressional districts We are now awash with data from different sources, but pulling it all together to gain insights can be difficult for many reasons. In this notebook we show how to combine data of very different types to show previously hidden relationships: * **"Big data"**: 300 million points indicating the location and racial or ethnic category of each resident of the USA in the 2010 census. See the [datashader census notebook](https://anaconda.org/jbednar/census) for a detailed analysis. Most tools would need to massively downsample this data before it could be displayed. * **Map data**: Image tiles from ArcGIS showing natural geographic boundaries. Requires alignment and overlaying to match the census data. * **Geographic shapes**: 2015 Congressional districts for the USA, downloaded from census.gov. Requires reprojection to match the coordinate system of the image tiles. Few if any tools can alone handle all of these data sources, but here we'll show how freely available Python packages can easily be combined to explore even large, complex datasets interactively in a web browser. The resulting plots make it simple to explore how the racial distribution of the USA population corresponds to the geographic features of each region and how both of these are reflected in the shape of US Congressional districts. For instance, here's an example of using this notebook to zoom in to Houston, revealing a very precisely [gerrymandered](https://en.wikipedia.org/wiki/Gerrymandering_in_the_United_States) [Hispanic district](https://green.house.gov/about/our-district): ![Houston district 29](../assets/images/houston_district29.png) Here the US population is rendered using racial category using the key shown, with more intense colors indicating a higher population density in that pixel, and the geographic background being dimly visible where population density is low. Racially integrated neighborhoods show up as intermediate or locally mixed colors, but most neighborhoods are quite segregated, and in this case the congressional district boundary shown clearly follows the borders of this segregation. If you run this notebook and zoom in on any urban region of interest, you can click on an area with a concentration of one racial or ethnic group to see for yourself if that district follows geographic features, state boundaries, the racial distribution, or some combination thereof. Numerous Python packages are required for this type of analysis to work, all coordinated using [conda](http://conda.pydata.org): * [Numba](http://numba.pydata.org): Compiles low-level numerical code written in Python into very fast machine code * [Dask](http://dask.pydata.org): Distributes these numba-based workloads across multiple processing cores in your machine * [Datashader](http://datashader.readthedocs.io): Using Numba and Dask, aggregates big datasets into a fixed-sized array suitable for display in the browser * [GeoViews](http://geo.holoviews.org/) (using [Cartopy](http://scitools.org.uk/cartopy)): Project longitude, latitude shapes into Web Mercator and create visible objects * [HoloViews](http://holoviews.org/): Flexibly combine each of the data sources into a just-in-time displayable, interactive plot * [Bokeh](http://bokeh.pydata.org/): Generate JavaScript-based interactive plot from HoloViews declarative specification Each package is maintained independently and focuses on doing one job really well, but they all combine seamlessly and with very little code to solve complex problems. ``` import holoviews as hv from holoviews import opts import geoviews as gv import datashader as ds import dask.dataframe as dd from cartopy import crs from holoviews.operation.datashader import datashade hv.extension('bokeh', width=95) opts.defaults( opts.Points(apply_ranges=False, ), opts.RGB(width=1200, height=682, xaxis=None, yaxis=None, show_grid=False), opts.Shape(fill_alpha=0, line_width=1.5, apply_ranges=False, tools=['tap']), opts.WMTS(alpha=0.5) ) ``` In this notebook, we'll load data from different sources and show it all overlaid together. First, let's define a color key for racial/ethnic categories: ``` color_key = {'w':'blue', 'b':'green', 'a':'red', 'h':'orange', 'o':'saddlebrown'} races = {'w':'White', 'b':'Black', 'a':'Asian', 'h':'Hispanic', 'o':'Other'} color_points = hv.NdOverlay( {races[k]: gv.Points([0,0], crs=crs.PlateCarree()).opts(color=v) for k, v in color_key.items()}) ``` Next, we'll load the 2010 US Census, with the location and race or ethnicity of every US resident as of that year (300 million data points), and define a plot using datashader to show this data with the given color key: ``` df = dd.io.parquet.read_parquet('../data/census.snappy.parq') df = df.persist() census_points = hv.Points(df, kdims=['easting', 'northing'], vdims=['race']) ``` Now we can datashade and render these points, coloring the points by race: ``` x_range, y_range = ((-13884029.0, -7453303.5), (2818291.5, 6335972.0)) # Continental USA shade_defaults = dict(x_range=x_range, y_range=y_range, x_sampling=10, y_sampling=10, width=1200, height=682, color_key=color_key, aggregator=ds.count_cat('race'),) shaded = datashade(census_points, **shade_defaults) shaded ``` Next, we'll load congressional districts from a publicly available [shapefile](https://www.census.gov/geo/maps-data/data/cbf/cbf_cds.html) and project them into Web Mercator format using GeoViews (which in turn calls Cartopy): ``` shape_path = '../data/cb_2015_us_cd114_5m.shp' districts = gv.Shape.from_shapefile(shape_path, crs=crs.PlateCarree()) districts = gv.project(districts) ``` Finally, we'll define some image tiles to use as a background, using any publicly available Web Mercator tile set: ``` tiles = gv.WMTS('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{Z}/{Y}/{X}.jpg') ``` Each of these data sources can be visualized on their own (just type their name in a separate cell), but they can also easily be combined into a single overlaid plot to see the relationships: ``` opts.defaults( opts.Polygons(fill_alpha=0)) shaded = datashade(census_points, **shade_defaults) tiles * shaded * color_points * districts ``` You should now be able to interactively explore these three linked datasets, to see how they all relate to each other. In a live notebook, this plot will support a variety of interactive features: * Pan/zoom: Select the "wheel zoom" tool at the left, and you can zoom in on any region of interest using your scroll wheel. The shapes should update immediately, while the map tiles will update as soon as they are loaded from the external server, and the racial data will be updated once it has been rendered for the current viewport by datashader. This behavior is the default for any HoloViews plot using a Bokeh backend. * Tapping: click on any region of the USA and the Congressional district for that region will be highlighted (and the rest dimmed). This behavior was enabled for the shape outlines by specifying the "tap" tool in the options above. Most of these interactive features are also available in the static HTML copy visible at [anaconda.org](https://anaconda.org/jbednar/census-hv-dask), with the restriction that because there is no Python process running, the racial/population data will be limited to the resolution at which it was initially rendered, rather than being dynamically re-rendered to fit the current zoom level. Thus in a static copy, the data will look pixelated, whereas in the live server you can zoom all the way down to individual datapoints (people) in each region.
github_jupyter
import holoviews as hv from holoviews import opts import geoviews as gv import datashader as ds import dask.dataframe as dd from cartopy import crs from holoviews.operation.datashader import datashade hv.extension('bokeh', width=95) opts.defaults( opts.Points(apply_ranges=False, ), opts.RGB(width=1200, height=682, xaxis=None, yaxis=None, show_grid=False), opts.Shape(fill_alpha=0, line_width=1.5, apply_ranges=False, tools=['tap']), opts.WMTS(alpha=0.5) ) color_key = {'w':'blue', 'b':'green', 'a':'red', 'h':'orange', 'o':'saddlebrown'} races = {'w':'White', 'b':'Black', 'a':'Asian', 'h':'Hispanic', 'o':'Other'} color_points = hv.NdOverlay( {races[k]: gv.Points([0,0], crs=crs.PlateCarree()).opts(color=v) for k, v in color_key.items()}) df = dd.io.parquet.read_parquet('../data/census.snappy.parq') df = df.persist() census_points = hv.Points(df, kdims=['easting', 'northing'], vdims=['race']) x_range, y_range = ((-13884029.0, -7453303.5), (2818291.5, 6335972.0)) # Continental USA shade_defaults = dict(x_range=x_range, y_range=y_range, x_sampling=10, y_sampling=10, width=1200, height=682, color_key=color_key, aggregator=ds.count_cat('race'),) shaded = datashade(census_points, **shade_defaults) shaded shape_path = '../data/cb_2015_us_cd114_5m.shp' districts = gv.Shape.from_shapefile(shape_path, crs=crs.PlateCarree()) districts = gv.project(districts) tiles = gv.WMTS('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{Z}/{Y}/{X}.jpg') opts.defaults( opts.Polygons(fill_alpha=0)) shaded = datashade(census_points, **shade_defaults) tiles * shaded * color_points * districts
0.364438
0.989213
# Tensorflow Image Recognition Tutorial This tutorial shows how we can use MLDB's [TensorFlow](https://www.tensorflow.org) integration to do image recognition. TensorFlow is Google's open source deep learning library. We will load the [Inception-v3 model](http://arxiv.org/abs/1512.00567) to generate descriptive labels for an image. The *Inception* model is a deep convolutional neural network and was trained on the [ImageNet](http://image-net.org) Large Visual Recognition Challenge dataset, where the task was to classify images into 1000 classes. To offer context and a basis for comparison, this notebook is inspired by [TensorFlow's Image Recognition tutorial](https://www.tensorflow.org/versions/r0.7/tutorials/image_recognition/index.html). ## Initializing pymldb and other imports The notebook cells below use `pymldb`'s `Connection` class to make [REST API](../../../../doc/#builtin/WorkingWithRest.md.html) calls. You can check out the [Using `pymldb` Tutorial](../../../../doc/nblink.html#_tutorials/Using pymldb Tutorial) for more details. ``` from pymldb import Connection mldb = Connection() ``` ## Loading a TensorFlow graph To load a pre-trained TensorFlow graphs in MLDB, we use the [`tensorflow.graph` function type](../../../../doc/#/v1/plugins/tensorflow/doc/TensorflowGraph.md.html). Below, we start by creating two functions. First, the `fetcher` function allows us to fetch a binary blob from a remote URL. Second, the `inception` function that will be used to execute the trained network and that we parameterize in the following way: - **modelFileUrl**: Path to the Inception-v3 model file. The `archive` prefix and `#` separator allow us to load a file inside a zip archive. ([more details](../../../../doc/#builtin/Url.md.html)) - **input**: As input to the graph, we provide the output of the `fetch` function called with the `url` parameter. When we call it later on, the image located at the specified URL will be downloaded and passed to the graph. - **output**: This specifies the layer from which to return the values. The `softmax` layer is the last layer in the network so we specify that one. ``` inceptionUrl = 'file://mldb/mldb_test_data/models/inception_dec_2015.zip' print mldb.put('/v1/functions/fetch', { "type": 'fetcher', "params": {} }) print mldb.put('/v1/functions/inception', { "type": 'tensorflow.graph', "params": { "modelFileUrl": 'archive+' + inceptionUrl + '#tensorflow_inception_graph.pb', "inputs": 'fetch({url})[content] AS "DecodeJpeg/contents"', "outputs": "softmax" } }) ``` ## Scoring an image To demonstrate how to run the network on an image, we re-use the same image as in the Tensorflow tutorial, the picture of [Admiral Grace Hopper](https://en.wikipedia.org/wiki/Grace_Hopper): <img src="https://www.tensorflow.org/versions/r0.7/images/grace_hopper.jpg" width=350> The following query applies the `inception` function on the URL of her picture: ``` amazingGrace = "https://www.tensorflow.org/versions/r0.7/images/grace_hopper.jpg" mldb.query("SELECT inception({url: '%s'}) as *" % amazingGrace) ``` This is great! With only 3 REST calls we were able to run a deep neural network on an arbitrary image off the internet. ## *Inception* as a real-time endpoint Not only is this function available in SQL queries within MLDB, but as all MLDB functions, it is also available as a REST endpoint. This means that when we created the `inception` function above, we essentially created an real-time API running the *Inception* model that any external service or device can call to get predictions back. The following REST call demonstrates how this looks: ``` result = mldb.get('/v1/functions/inception/application', input={"url": amazingGrace}) print result.url + '\n\n' + repr(result) + '\n' import numpy as np print "Shape:" print np.array(result.json()["output"]["softmax"]["val"]).shape ``` ## Interpreting the prediction Running the network gives us a 1008-dimensional vector. This is because the network was originally trained on the Image net categories and we created the `inception` function to return the *softmax* layer which is the output of the model. To allow us to interpret the predictions the network makes, we can import the ImageNet labels in an MLDB dataset like this: ``` print mldb.put("/v1/procedures/imagenet_labels_importer", { "type": "import.text", "params": { "dataFileUrl": 'archive+' + inceptionUrl + '#imagenet_comp_graph_label_strings.txt', "outputDataset": {"id": "imagenet_labels", "type": "sparse.mutable"}, "headers": ["label"], "named": "lineNumber() -1", "offset": 1, "runOnCreation": True } }) ``` The contents of the dataset look like this: ``` mldb.query("SELECT * FROM imagenet_labels LIMIT 5") ``` The labels line up with the *softmax* layer that we extract from the network. By joining the output of the network with the `imagenet_labels` dataset, we can essentially label the output of the network. The following query scores the image just as before, but then transposes the output and then joins the result to the labels dataset. We then sort on the score to keep only the 10 highest values: ``` mldb.query(""" SELECT scores.pred as score NAMED imagenet_labels.label FROM transpose( ( SELECT flatten(inception({url: '%s'})[softmax]) as * NAMED 'pred' ) ) AS scores LEFT JOIN imagenet_labels ON imagenet_labels.rowName() = scores.rowName() ORDER BY score DESC LIMIT 10 """ % amazingGrace) ``` ## Where to next? You can now look at the [Transfer Learning with Tensorflow](../../../../doc/nblink.html#_demos/Transfer Learning with Tensorflow) demo.
github_jupyter
from pymldb import Connection mldb = Connection() inceptionUrl = 'file://mldb/mldb_test_data/models/inception_dec_2015.zip' print mldb.put('/v1/functions/fetch', { "type": 'fetcher', "params": {} }) print mldb.put('/v1/functions/inception', { "type": 'tensorflow.graph', "params": { "modelFileUrl": 'archive+' + inceptionUrl + '#tensorflow_inception_graph.pb', "inputs": 'fetch({url})[content] AS "DecodeJpeg/contents"', "outputs": "softmax" } }) amazingGrace = "https://www.tensorflow.org/versions/r0.7/images/grace_hopper.jpg" mldb.query("SELECT inception({url: '%s'}) as *" % amazingGrace) result = mldb.get('/v1/functions/inception/application', input={"url": amazingGrace}) print result.url + '\n\n' + repr(result) + '\n' import numpy as np print "Shape:" print np.array(result.json()["output"]["softmax"]["val"]).shape print mldb.put("/v1/procedures/imagenet_labels_importer", { "type": "import.text", "params": { "dataFileUrl": 'archive+' + inceptionUrl + '#imagenet_comp_graph_label_strings.txt', "outputDataset": {"id": "imagenet_labels", "type": "sparse.mutable"}, "headers": ["label"], "named": "lineNumber() -1", "offset": 1, "runOnCreation": True } }) mldb.query("SELECT * FROM imagenet_labels LIMIT 5") mldb.query(""" SELECT scores.pred as score NAMED imagenet_labels.label FROM transpose( ( SELECT flatten(inception({url: '%s'})[softmax]) as * NAMED 'pred' ) ) AS scores LEFT JOIN imagenet_labels ON imagenet_labels.rowName() = scores.rowName() ORDER BY score DESC LIMIT 10 """ % amazingGrace)
0.345105
0.991836
## SVM model for 4class audio with 100ms frame size ## Important Libraries ``` import io import time from sklearn import metrics from scipy.stats import zscore from sklearn.model_selection import train_test_split from sklearn.model_selection import KFold from keras.models import Sequential from keras.layers.core import Dense, Activation from keras.callbacks import EarlyStopping import tensorflow as tf from sklearn import svm, datasets import matplotlib.pyplot as plt %matplotlib inline from sklearn.svm import SVC from sklearn.metrics import accuracy_score from sklearn.metrics import classification_report, confusion_matrix from sklearn.model_selection import cross_val_score from sklearn.model_selection import learning_curve import pickle from sklearn.metrics import roc_curve, auc from sklearn.metrics import log_loss from sklearn import preprocessing import matplotlib.pyplot as plt import numpy as np import pandas as pd import shutil import os import requests import base64 ``` ### Useful Functions ``` # Encode text values to dummy variables(i.e. [1,0,0],[0,1,0],[0,0,1] for red,green,blue) def encode_text_dummy(df, name): dummies = pd.get_dummies(df[name]) for x in dummies.columns: dummy_name = "{}-{}".format(name, x) df[dummy_name] = dummies[x] df.drop(name, axis=1, inplace=True) # Encode text values to a single dummy variable. The new columns (which do not replace the old) will have a 1 # at every location where the original column (name) matches each of the target_values. One column is added for # each target value. def encode_text_single_dummy(df, name, target_values): for tv in target_values: l = list(df[name].astype(str)) l = [1 if str(x) == str(tv) else 0 for x in l] name2 = "{}-{}".format(name, tv) df[name2] = l # Encode text values to indexes(i.e. [1],[2],[3] for red,green,blue). def encode_text_index(df, name): le = preprocessing.LabelEncoder() df[name] = le.fit_transform(df[name]) return le.classes_ # Encode a numeric column as zscores def encode_numeric_zscore(df, name, mean=None, sd=None): if mean is None: mean = df[name].mean() if sd is None: sd = df[name].std() df[name] = (df[name] - mean) / sd # Convert all missing values in the specified column to the median def missing_median(df, name): med = df[name].median() df[name] = df[name].fillna(med) # Convert all missing values in the specified column to the default def missing_default(df, name, default_value): df[name] = df[name].fillna(default_value) # Convert a Pandas dataframe to the x,y inputs that TensorFlow needs def to_xy(df, target): result = [] for x in df.columns: if x != target: result.append(x) # find out the type of the target column. Is it really this hard? :( target_type = df[target].dtypes target_type = target_type[0] if hasattr(target_type, '__iter__') else target_type # Encode to int for classification, float otherwise. TensorFlow likes 32 bits. if target_type in (np.int64, np.int32): # Classification dummies = pd.get_dummies(df[target]) return df.as_matrix(result).astype(np.float32), dummies.as_matrix().astype(np.float32) else: # Regression return df.as_matrix(result).astype(np.float32), df.as_matrix([target]).astype(np.float32) # Nicely formatted time string def hms_string(sec_elapsed): h = int(sec_elapsed / (60 * 60)) m = int((sec_elapsed % (60 * 60)) / 60) s = sec_elapsed % 60 return "{}:{:>02}:{:>05.2f}".format(h, m, s) # Regression chart. def chart_regression(pred,y,sort=True): t = pd.DataFrame({'pred' : pred, 'y' : y.flatten()}) if sort: t.sort_values(by=['y'],inplace=True) a = plt.plot(t['y'].tolist(),label='expected') b = plt.plot(t['pred'].tolist(),label='prediction') plt.ylabel('output') plt.legend() plt.show() # Remove all rows where the specified column is +/- sd standard deviations def remove_outliers(df, name, sd): drop_rows = df.index[(np.abs(df[name] - df[name].mean()) >= (sd * df[name].std()))] df.drop(drop_rows, axis=0, inplace=True) # Encode a column to a range between normalized_low and normalized_high. def encode_numeric_range(df, name, normalized_low=-1, normalized_high=1, data_low=None, data_high=None): if data_low is None: data_low = min(df[name]) data_high = max(df[name]) df[name] = ((df[name] - data_low) / (data_high - data_low)) \ * (normalized_high - normalized_low) + normalized_low # Plot a confusion matrix. # cm is the confusion matrix, names are the names of the classes. def plot_confusion_matrix(cm, names, title='Confusion matrix', cmap=plt.cm.Blues): plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(names)) plt.xticks(tick_marks, names, rotation=45) plt.yticks(tick_marks, names) plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') ``` #### Read MFCCs feature CSV file of audio of 500ms block ``` path="/home/bsplab/Desktop/manikanta/16khz_data/NEWFRAME_SHIFTING_DATA/SVM+MFCC_newshifting/100ms/training" df=pd.read_csv("/home/bsplab/Desktop/manikanta/16khz_data/NEWFRAME_SHIFTING_DATA/SVM+MFCC_newshifting/100ms/training/final_100ms.csv",na_values=['NA','?']) df.columns=['MFCC0', 'MFCC1','MFCC2','MFCC3','MFCC4','MFCC5','MFCC6','MFCC7','MFCC8', 'MFCC9', 'MFCC10' ,'MFCC11', 'MFCC12', 'Label'] filename_write = os.path.join(path,"/home/bsplab/Desktop/manikanta/16khz_data/NEWFRAME_SHIFTING_DATA/SVM+MFCC_newshifting/100ms/training/out-of-sample_mySVM_100ms.csv") df.head() ``` #### Shuffle ``` np.random.seed(42) df = df.reindex(np.random.permutation(df.index)) df.reset_index(inplace=True, drop=True) df.columns df.head() ``` #### Sperating Independent variable and Target Variable ``` X = df[['MFCC0', 'MFCC1', 'MFCC2', 'MFCC3', 'MFCC4', 'MFCC5', 'MFCC6', 'MFCC7', 'MFCC8', 'MFCC9', 'MFCC10', 'MFCC11', 'MFCC12']] y = df['Label'] ``` #### Encode to a 2D matrix for training ``` # Encode to a 2D matrix for training Label=encode_text_index(df,'Label') print("Labelling is:{}".format(Label)) ``` #### Keeping Holdout Data ``` # 25 % holdout data x_main, x_holdout, y_main, y_holdout = train_test_split(X, y, test_size=0.20,random_state = 0) print("Shape of X : {}".format(X.shape)) print("Shape of y : {}".format(y.shape)) print("Shape of x_main : {}".format(x_main.shape)) print("Shape of x_holdout : {}".format(x_holdout.shape)) print("Shape of y_main : {}".format(y_main.shape)) print("Shape of y_holdout : {}".format(y_holdout.shape)) ``` #### dividing X, y into train and test data ``` # dividing X, y into train and test data x_train, x_test, y_train, y_test = train_test_split(x_main, y_main, test_size=0.20,random_state = 0) print("Shape of x_train : {}".format(x_train.shape)) print("Shape of x_test : {}".format(x_test.shape)) print("Shape of y_train : {}".format(y_train.shape)) print("Shape of y_test : {}".format(y_test.shape)) ``` #### preprocessing of training data, testing data , holdout data ``` # preprocessing of training data scaler = preprocessing.StandardScaler().fit(x_train) #scaler X_train = scaler.transform(x_train) X_holdout = scaler.transform(x_holdout) # preprocessing of testing data X_test= scaler.transform(x_test) from sklearn.externals import joblib scaler_file = "my_scaler_100ms.save" joblib.dump(scaler, scaler_file) ``` ## Model Creation ## RBF kernel ### Training ``` ## RBF kernel training #### Training tic=time.time() svclassifier_rbf = SVC(kernel='rbf',C=1, max_iter=-1,verbose=True,probability=True) svclassifier_rbf.fit(X_train, y_train) #scores = cross_val_score( svclassifier_rbf, X_train, y_train, cv=5,scoring='f1_macro') toc=time.time() print(str(1000*(toc-tic))+"ms") ``` ### Validation ``` ## Testing tic=time.time() y_rbf = svclassifier_rbf.predict(X_test) toc=time.time() print(str(1000*(toc-tic))+"ms") # model accuracy for X_test accuracy = accuracy_score(y_test, y_rbf) print (accuracy) ## Evaluation of Algorithm print(confusion_matrix(y_test, y_rbf)) print(classification_report(y_test, y_rbf)) ``` ### Saving RBF kernel Trained Model ``` # save the model to disk filename = 'SVM_100ms_Rbf_model.save' joblib.dump(svclassifier_rbf, open(filename, 'wb')) # load the model from disk loaded_model_rbf = joblib.load(open(filename, 'rb')) ``` ### Holdout Predction ``` tic=time.time() holdout_pred_rbf = loaded_model_rbf.predict(X_holdout) toc=time.time() print(str(1000*(toc-tic))+"ms") rbf_score = accuracy_score(y_holdout, holdout_pred_rbf) print("Holdout accuracy with rbf kernel is: {}".format(rbf_score)) ## Turn off the scintific notation np.set_printoptions(suppress=True) cm = confusion_matrix(y_holdout, holdout_pred_rbf) np.set_printoptions(precision=2) print('Confusion matrix, without normalization') print(cm) plt.figure() plot_confusion_matrix(cm, Label) plt.savefig('cm_holdout_mySVM_100ms_mani_rbf.png',dpi=150) import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix import itertools def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print("Normalized confusion matrix") else: print('Confusion matrix, without normalization') plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') # Compute confusion matrix cnf_matrix = confusion_matrix(y_holdout, holdout_pred_rbf) np.set_printoptions(precision=2) # Plot non-normalized confusion matrix plt.figure(figsize=(5,3)) plot_confusion_matrix(cnf_matrix, classes=['ac&fan', 'crying','music', 'speech'], title='Confusion matrix') plt.savefig('mani1.png') print(classification_report(y_holdout, holdout_pred_rbf)) model_prob_rbf = loaded_model_rbf.predict_proba(X_holdout) ##need prob for getting logloss rbf_log_loss = log_loss(y_holdout, model_prob_rbf) print("Log loss score of Holdout data for RBF kernel: {}".format(rbf_log_loss)) ``` ## Loading Saved Model ``` from sklearn.externals import joblib import pandas as pd import numpy as np import time filename = 'SVM_100ms_Rbf_model.save' # call first saved model file # load the model from disk loaded_model_rbf1 = joblib.load(open(filename, 'rb')) ``` ### A ``` df1=pd.read_csv("/home/bsplab/Desktop/manikanta/16khz_data/NEWFRAME_SHIFTING_DATA/SVM+MFCC_newshifting/100ms/testing/cryingtest_100ms.csv",na_values=['NA','?']) df1.columns=['MFCC0', 'MFCC1','MFCC2','MFCC3','MFCC4','MFCC5','MFCC6','MFCC7','MFCC8', 'MFCC9', 'MFCC10' ,'MFCC11', 'MFCC12'] #filename_write = os.path.join(path,"7class-out-of-sample_mySVM_500ms.csv") df1.head() scaler_file = "my_scaler_100ms.save" scaler = joblib.load(scaler_file) X = scaler.transform(df1) ## Performing preprocessing on tested data tic=time.time() holdout_pred_rbf1 = loaded_model_rbf1.predict(X) toc=time.time() print(str(1000*(toc-tic))+"ms") p1=holdout_pred_rbf1.size print("The size of prediction " + str (p1)) a1=sum(holdout_pred_rbf1=="CRYING") print("Total no. of predcited Crying "+str(a1)) Acc1=a1/p1*100 print("The accuracy of the new environment crying data is "+ str(Acc1)+ " percent") ``` ### V ``` df6=pd.read_csv("/home/bsplab/Desktop/manikanta/16khz_data/NEWFRAME_SHIFTING_DATA/SVM+MFCC_newshifting/100ms/testing/musictest_100ms.csv",na_values=['NA','?']) df6.columns=['MFCC0', 'MFCC1','MFCC2','MFCC3','MFCC4','MFCC5','MFCC6','MFCC7','MFCC8', 'MFCC9', 'MFCC10' ,'MFCC11', 'MFCC12'] #filename_write = os.path.join(path,"7class-out-of-sample_mySVM_500ms.csv") X6= scaler.transform(df6) ## Direct Do this tic=time.time() holdout_pred_rbf6 = loaded_model_rbf1.predict(X6) toc=time.time() print(str(1000*(toc-tic))+"ms") p6=holdout_pred_rbf6.size print("The size of prediction " + str (p6)) a6=sum(holdout_pred_rbf6=="MUSIC") print("Total no. of predcited music "+str(a6)) Acc6=a6/p6*100 print("The accuracy of the new environment music data is "+ str(Acc6)+ " percent") df7=pd.read_csv("/home/bsplab/Desktop/manikanta/16khz_data/NEWFRAME_SHIFTING_DATA/SVM+MFCC_newshifting/100ms/testing/speechtest_100ms.csv",na_values=['NA','?']) df7.columns=['MFCC0', 'MFCC1','MFCC2','MFCC3','MFCC4','MFCC5','MFCC6','MFCC7','MFCC8', 'MFCC9', 'MFCC10' ,'MFCC11', 'MFCC12'] #filename_write = os.path.join(path,"7class-out-of-sample_mySVM_500ms.csv") df7.head() X7= scaler.transform(df7) ## Direct Do this tic=time.time() holdout_pred_rbf7 = loaded_model_rbf1.predict(X7) toc=time.time() print(str(1000*(toc-tic))+"ms") p7=holdout_pred_rbf7.size print("The size of prediction " + str (p7)) a7=sum(holdout_pred_rbf7=="SPEECH") print("Total no. of predcited speech "+str(a7)) Acc7=a7/p7*100 print("The accuracy of the new environment speech data is "+ str(Acc7)+ " percent") ``` #### S ``` df8=pd.read_csv("/home/bsplab/Desktop/manikanta/16khz_data/NEWFRAME_SHIFTING_DATA/SVM+MFCC_newshifting/100ms/testing/fanactest_100ms.csv",na_values=['NA','?']) df8.columns=['MFCC0', 'MFCC1','MFCC2','MFCC3','MFCC4','MFCC5','MFCC6','MFCC7','MFCC8', 'MFCC9', 'MFCC10' ,'MFCC11', 'MFCC12'] #filename_write = os.path.join(path,"7class-out-of-sample_mySVM_500ms.csv") df8.head() X8= scaler.transform(df8) ## Direct Do this tic=time.time() holdout_pred_rbf8 = loaded_model_rbf1.predict(X8) toc=time.time() print(str(1000*(toc-tic))+"ms") p8=holdout_pred_rbf8.size print("The size of prediction " + str (p8)) a8=sum(holdout_pred_rbf8=="AC & FAN") print("Total no. of predcited AC & FAN "+str(a8)) Acc8=a8/p8*100 print("The accuracy of the new environment AC & FAN data is "+ str(Acc8)+ " percent") ```
github_jupyter
import io import time from sklearn import metrics from scipy.stats import zscore from sklearn.model_selection import train_test_split from sklearn.model_selection import KFold from keras.models import Sequential from keras.layers.core import Dense, Activation from keras.callbacks import EarlyStopping import tensorflow as tf from sklearn import svm, datasets import matplotlib.pyplot as plt %matplotlib inline from sklearn.svm import SVC from sklearn.metrics import accuracy_score from sklearn.metrics import classification_report, confusion_matrix from sklearn.model_selection import cross_val_score from sklearn.model_selection import learning_curve import pickle from sklearn.metrics import roc_curve, auc from sklearn.metrics import log_loss from sklearn import preprocessing import matplotlib.pyplot as plt import numpy as np import pandas as pd import shutil import os import requests import base64 # Encode text values to dummy variables(i.e. [1,0,0],[0,1,0],[0,0,1] for red,green,blue) def encode_text_dummy(df, name): dummies = pd.get_dummies(df[name]) for x in dummies.columns: dummy_name = "{}-{}".format(name, x) df[dummy_name] = dummies[x] df.drop(name, axis=1, inplace=True) # Encode text values to a single dummy variable. The new columns (which do not replace the old) will have a 1 # at every location where the original column (name) matches each of the target_values. One column is added for # each target value. def encode_text_single_dummy(df, name, target_values): for tv in target_values: l = list(df[name].astype(str)) l = [1 if str(x) == str(tv) else 0 for x in l] name2 = "{}-{}".format(name, tv) df[name2] = l # Encode text values to indexes(i.e. [1],[2],[3] for red,green,blue). def encode_text_index(df, name): le = preprocessing.LabelEncoder() df[name] = le.fit_transform(df[name]) return le.classes_ # Encode a numeric column as zscores def encode_numeric_zscore(df, name, mean=None, sd=None): if mean is None: mean = df[name].mean() if sd is None: sd = df[name].std() df[name] = (df[name] - mean) / sd # Convert all missing values in the specified column to the median def missing_median(df, name): med = df[name].median() df[name] = df[name].fillna(med) # Convert all missing values in the specified column to the default def missing_default(df, name, default_value): df[name] = df[name].fillna(default_value) # Convert a Pandas dataframe to the x,y inputs that TensorFlow needs def to_xy(df, target): result = [] for x in df.columns: if x != target: result.append(x) # find out the type of the target column. Is it really this hard? :( target_type = df[target].dtypes target_type = target_type[0] if hasattr(target_type, '__iter__') else target_type # Encode to int for classification, float otherwise. TensorFlow likes 32 bits. if target_type in (np.int64, np.int32): # Classification dummies = pd.get_dummies(df[target]) return df.as_matrix(result).astype(np.float32), dummies.as_matrix().astype(np.float32) else: # Regression return df.as_matrix(result).astype(np.float32), df.as_matrix([target]).astype(np.float32) # Nicely formatted time string def hms_string(sec_elapsed): h = int(sec_elapsed / (60 * 60)) m = int((sec_elapsed % (60 * 60)) / 60) s = sec_elapsed % 60 return "{}:{:>02}:{:>05.2f}".format(h, m, s) # Regression chart. def chart_regression(pred,y,sort=True): t = pd.DataFrame({'pred' : pred, 'y' : y.flatten()}) if sort: t.sort_values(by=['y'],inplace=True) a = plt.plot(t['y'].tolist(),label='expected') b = plt.plot(t['pred'].tolist(),label='prediction') plt.ylabel('output') plt.legend() plt.show() # Remove all rows where the specified column is +/- sd standard deviations def remove_outliers(df, name, sd): drop_rows = df.index[(np.abs(df[name] - df[name].mean()) >= (sd * df[name].std()))] df.drop(drop_rows, axis=0, inplace=True) # Encode a column to a range between normalized_low and normalized_high. def encode_numeric_range(df, name, normalized_low=-1, normalized_high=1, data_low=None, data_high=None): if data_low is None: data_low = min(df[name]) data_high = max(df[name]) df[name] = ((df[name] - data_low) / (data_high - data_low)) \ * (normalized_high - normalized_low) + normalized_low # Plot a confusion matrix. # cm is the confusion matrix, names are the names of the classes. def plot_confusion_matrix(cm, names, title='Confusion matrix', cmap=plt.cm.Blues): plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(names)) plt.xticks(tick_marks, names, rotation=45) plt.yticks(tick_marks, names) plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') path="/home/bsplab/Desktop/manikanta/16khz_data/NEWFRAME_SHIFTING_DATA/SVM+MFCC_newshifting/100ms/training" df=pd.read_csv("/home/bsplab/Desktop/manikanta/16khz_data/NEWFRAME_SHIFTING_DATA/SVM+MFCC_newshifting/100ms/training/final_100ms.csv",na_values=['NA','?']) df.columns=['MFCC0', 'MFCC1','MFCC2','MFCC3','MFCC4','MFCC5','MFCC6','MFCC7','MFCC8', 'MFCC9', 'MFCC10' ,'MFCC11', 'MFCC12', 'Label'] filename_write = os.path.join(path,"/home/bsplab/Desktop/manikanta/16khz_data/NEWFRAME_SHIFTING_DATA/SVM+MFCC_newshifting/100ms/training/out-of-sample_mySVM_100ms.csv") df.head() np.random.seed(42) df = df.reindex(np.random.permutation(df.index)) df.reset_index(inplace=True, drop=True) df.columns df.head() X = df[['MFCC0', 'MFCC1', 'MFCC2', 'MFCC3', 'MFCC4', 'MFCC5', 'MFCC6', 'MFCC7', 'MFCC8', 'MFCC9', 'MFCC10', 'MFCC11', 'MFCC12']] y = df['Label'] # Encode to a 2D matrix for training Label=encode_text_index(df,'Label') print("Labelling is:{}".format(Label)) # 25 % holdout data x_main, x_holdout, y_main, y_holdout = train_test_split(X, y, test_size=0.20,random_state = 0) print("Shape of X : {}".format(X.shape)) print("Shape of y : {}".format(y.shape)) print("Shape of x_main : {}".format(x_main.shape)) print("Shape of x_holdout : {}".format(x_holdout.shape)) print("Shape of y_main : {}".format(y_main.shape)) print("Shape of y_holdout : {}".format(y_holdout.shape)) # dividing X, y into train and test data x_train, x_test, y_train, y_test = train_test_split(x_main, y_main, test_size=0.20,random_state = 0) print("Shape of x_train : {}".format(x_train.shape)) print("Shape of x_test : {}".format(x_test.shape)) print("Shape of y_train : {}".format(y_train.shape)) print("Shape of y_test : {}".format(y_test.shape)) # preprocessing of training data scaler = preprocessing.StandardScaler().fit(x_train) #scaler X_train = scaler.transform(x_train) X_holdout = scaler.transform(x_holdout) # preprocessing of testing data X_test= scaler.transform(x_test) from sklearn.externals import joblib scaler_file = "my_scaler_100ms.save" joblib.dump(scaler, scaler_file) ## RBF kernel training #### Training tic=time.time() svclassifier_rbf = SVC(kernel='rbf',C=1, max_iter=-1,verbose=True,probability=True) svclassifier_rbf.fit(X_train, y_train) #scores = cross_val_score( svclassifier_rbf, X_train, y_train, cv=5,scoring='f1_macro') toc=time.time() print(str(1000*(toc-tic))+"ms") ## Testing tic=time.time() y_rbf = svclassifier_rbf.predict(X_test) toc=time.time() print(str(1000*(toc-tic))+"ms") # model accuracy for X_test accuracy = accuracy_score(y_test, y_rbf) print (accuracy) ## Evaluation of Algorithm print(confusion_matrix(y_test, y_rbf)) print(classification_report(y_test, y_rbf)) # save the model to disk filename = 'SVM_100ms_Rbf_model.save' joblib.dump(svclassifier_rbf, open(filename, 'wb')) # load the model from disk loaded_model_rbf = joblib.load(open(filename, 'rb')) tic=time.time() holdout_pred_rbf = loaded_model_rbf.predict(X_holdout) toc=time.time() print(str(1000*(toc-tic))+"ms") rbf_score = accuracy_score(y_holdout, holdout_pred_rbf) print("Holdout accuracy with rbf kernel is: {}".format(rbf_score)) ## Turn off the scintific notation np.set_printoptions(suppress=True) cm = confusion_matrix(y_holdout, holdout_pred_rbf) np.set_printoptions(precision=2) print('Confusion matrix, without normalization') print(cm) plt.figure() plot_confusion_matrix(cm, Label) plt.savefig('cm_holdout_mySVM_100ms_mani_rbf.png',dpi=150) import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix import itertools def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print("Normalized confusion matrix") else: print('Confusion matrix, without normalization') plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') # Compute confusion matrix cnf_matrix = confusion_matrix(y_holdout, holdout_pred_rbf) np.set_printoptions(precision=2) # Plot non-normalized confusion matrix plt.figure(figsize=(5,3)) plot_confusion_matrix(cnf_matrix, classes=['ac&fan', 'crying','music', 'speech'], title='Confusion matrix') plt.savefig('mani1.png') print(classification_report(y_holdout, holdout_pred_rbf)) model_prob_rbf = loaded_model_rbf.predict_proba(X_holdout) ##need prob for getting logloss rbf_log_loss = log_loss(y_holdout, model_prob_rbf) print("Log loss score of Holdout data for RBF kernel: {}".format(rbf_log_loss)) from sklearn.externals import joblib import pandas as pd import numpy as np import time filename = 'SVM_100ms_Rbf_model.save' # call first saved model file # load the model from disk loaded_model_rbf1 = joblib.load(open(filename, 'rb')) df1=pd.read_csv("/home/bsplab/Desktop/manikanta/16khz_data/NEWFRAME_SHIFTING_DATA/SVM+MFCC_newshifting/100ms/testing/cryingtest_100ms.csv",na_values=['NA','?']) df1.columns=['MFCC0', 'MFCC1','MFCC2','MFCC3','MFCC4','MFCC5','MFCC6','MFCC7','MFCC8', 'MFCC9', 'MFCC10' ,'MFCC11', 'MFCC12'] #filename_write = os.path.join(path,"7class-out-of-sample_mySVM_500ms.csv") df1.head() scaler_file = "my_scaler_100ms.save" scaler = joblib.load(scaler_file) X = scaler.transform(df1) ## Performing preprocessing on tested data tic=time.time() holdout_pred_rbf1 = loaded_model_rbf1.predict(X) toc=time.time() print(str(1000*(toc-tic))+"ms") p1=holdout_pred_rbf1.size print("The size of prediction " + str (p1)) a1=sum(holdout_pred_rbf1=="CRYING") print("Total no. of predcited Crying "+str(a1)) Acc1=a1/p1*100 print("The accuracy of the new environment crying data is "+ str(Acc1)+ " percent") df6=pd.read_csv("/home/bsplab/Desktop/manikanta/16khz_data/NEWFRAME_SHIFTING_DATA/SVM+MFCC_newshifting/100ms/testing/musictest_100ms.csv",na_values=['NA','?']) df6.columns=['MFCC0', 'MFCC1','MFCC2','MFCC3','MFCC4','MFCC5','MFCC6','MFCC7','MFCC8', 'MFCC9', 'MFCC10' ,'MFCC11', 'MFCC12'] #filename_write = os.path.join(path,"7class-out-of-sample_mySVM_500ms.csv") X6= scaler.transform(df6) ## Direct Do this tic=time.time() holdout_pred_rbf6 = loaded_model_rbf1.predict(X6) toc=time.time() print(str(1000*(toc-tic))+"ms") p6=holdout_pred_rbf6.size print("The size of prediction " + str (p6)) a6=sum(holdout_pred_rbf6=="MUSIC") print("Total no. of predcited music "+str(a6)) Acc6=a6/p6*100 print("The accuracy of the new environment music data is "+ str(Acc6)+ " percent") df7=pd.read_csv("/home/bsplab/Desktop/manikanta/16khz_data/NEWFRAME_SHIFTING_DATA/SVM+MFCC_newshifting/100ms/testing/speechtest_100ms.csv",na_values=['NA','?']) df7.columns=['MFCC0', 'MFCC1','MFCC2','MFCC3','MFCC4','MFCC5','MFCC6','MFCC7','MFCC8', 'MFCC9', 'MFCC10' ,'MFCC11', 'MFCC12'] #filename_write = os.path.join(path,"7class-out-of-sample_mySVM_500ms.csv") df7.head() X7= scaler.transform(df7) ## Direct Do this tic=time.time() holdout_pred_rbf7 = loaded_model_rbf1.predict(X7) toc=time.time() print(str(1000*(toc-tic))+"ms") p7=holdout_pred_rbf7.size print("The size of prediction " + str (p7)) a7=sum(holdout_pred_rbf7=="SPEECH") print("Total no. of predcited speech "+str(a7)) Acc7=a7/p7*100 print("The accuracy of the new environment speech data is "+ str(Acc7)+ " percent") df8=pd.read_csv("/home/bsplab/Desktop/manikanta/16khz_data/NEWFRAME_SHIFTING_DATA/SVM+MFCC_newshifting/100ms/testing/fanactest_100ms.csv",na_values=['NA','?']) df8.columns=['MFCC0', 'MFCC1','MFCC2','MFCC3','MFCC4','MFCC5','MFCC6','MFCC7','MFCC8', 'MFCC9', 'MFCC10' ,'MFCC11', 'MFCC12'] #filename_write = os.path.join(path,"7class-out-of-sample_mySVM_500ms.csv") df8.head() X8= scaler.transform(df8) ## Direct Do this tic=time.time() holdout_pred_rbf8 = loaded_model_rbf1.predict(X8) toc=time.time() print(str(1000*(toc-tic))+"ms") p8=holdout_pred_rbf8.size print("The size of prediction " + str (p8)) a8=sum(holdout_pred_rbf8=="AC & FAN") print("Total no. of predcited AC & FAN "+str(a8)) Acc8=a8/p8*100 print("The accuracy of the new environment AC & FAN data is "+ str(Acc8)+ " percent")
0.587115
0.838878
### Import packages-libraries ``` import pandas as pd import numpy as np import urllib3 import requests from PIL import Image import matplotlib.pyplot as plt import seaborn as sns from wordcloud import WordCloud, STOPWORDS from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import KFold from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import classification_report, confusion_matrix from nltk.corpus import stopwords import spacy from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.feature_extraction.text import HashingVectorizer from sklearn.decomposition import TruncatedSVD from sklearn.feature_extraction.text import CountVectorizer from sklearn.metrics import classification_report, precision_score, recall_score, f1_score, accuracy_score from sklearn.pipeline import Pipeline from sklearn.svm import LinearSVC from sklearn import metrics from sklearn.svm import SVC from sklearn.model_selection import GridSearchCV from sklearn import preprocessing from sklearn.pipeline import make_pipeline from sklearn.model_selection import cross_val_score from sklearn.model_selection import cross_val_predict from sklearn.metrics import accuracy_score from sklearn.ensemble import RandomForestClassifier from sklearn.preprocessing import StandardScaler from sklearn.neighbors import KNeighborsClassifier from sklearn.naive_bayes import MultinomialNB from sklearn.naive_bayes import ComplementNB from nltk.stem.porter import * from nltk import word_tokenize from nltk.stem.snowball import SnowballStemmer from collections import Counter from nltk.stem import WordNetLemmatizer from nltk.corpus import wordnet from sklearn.metrics import accuracy_score import nltk nlp = spacy.load('en_core_web_sm') nltk.download('punkt') %matplotlib inline ``` ### Read from file ``` train_data = pd.read_csv('datasets/q1/train.csv', sep=',') test_data = pd.read_csv('datasets/q1/test_without_labels.csv', sep=',') #test_data['Label'] = train_data['Label'] expected_array = np.array(train_data.head(2000)[['Label']]).flatten() content_array = np.array(train_data.head(2000)[['Content']]).flatten() #X_train = train_data['Content'].head(2000) #Y_train = train_data['Label'].head(2000) #X_test = test_data['Content'] #Y_test = test_data['Label'] my_additional_stop_words = ['said','still','day','will','new','may','two','one','now','time','say','second','month','first','going','year','back','people','case','according'] stop_words = STOPWORDS.union(my_additional_stop_words) sns.countplot(x='Label',data=train_data) traindata = train_data.groupby('Label').count() print(traindata) ``` ### Cleaning Data ``` #df_entertainment = train_data[train_data['Label']=='Entertainment'].head(3900) #df_health = train_data[train_data['Label']=='Health'].head(1200) #df_business = train_data[train_data['Label']=='Business'].head(2700) #df_technology = train_data[train_data['Label']=='Technology'].head(3000) #df = pd.concat([df_entertainment,df_health,df_business,df_technology]) df = train_data.head(10000) X = df['Title'] + df['Content'] y = df['Label'] #X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42) ``` ### Wordcloud ``` #STOPWORDS.extend(['will', 'said', 'us', 'may', 'share','well']) def wordcloud(): business = str() entertainment = str() health = str() technology = str() for i in range(expected_array.shape[0]): if expected_array[i] == 'Business': business = business + ' ' + str(content_array[i]) elif expected_array[i] == 'Entertainment': entertainment = entertainment + ' ' + str(content_array[i]) elif expected_array[i] == 'Health': health = health + ' ' + str(content_array[i]) elif expected_array[i] == 'Technology': technology = technology + ' ' + str(content_array[i]) mask = np.array(Image.open(requests.get('http://www.clker.com/cliparts/3/0/a/1/11971238241310805346noonespillow_Simple_Cloud.svg.med.png',stream=True).raw)) wordcloud1 = WordCloud(stopwords=stop_words, background_color="white", mask=mask).generate(business) plt.imshow(wordcloud1,interpolation='bilinear') plt.axis("off") plt.savefig('q1/business.png') wordcloud2 = WordCloud(stopwords=stop_words,background_color="white",mask=mask).generate(entertainment) plt.imshow(wordcloud2,interpolation='bilinear') plt.axis("off") plt.savefig('q1/entertainment.png') wordcloud3 = WordCloud(stopwords=stop_words,background_color="white",mask=mask).generate(health) plt.imshow(wordcloud3,interpolation='bilinear') plt.axis("off") plt.savefig('q1/health.png') wordcloud4 = WordCloud(stopwords=stop_words,background_color="white",mask=mask).generate(technology) plt.imshow(wordcloud4,interpolation='bilinear') plt.axis("off") plt.savefig('q1/technology.png') from stop_words import get_stop_words stpw = get_stop_words('en') stpw.extend(my_additional_stop_words) stpw.extend(['can','also','like']) stpw.extend(['saying', 'said', 'say', 'yes', 'instead', 'meanwhile', 'right', 'really', 'finally', 'now', 'one', 'suggested', 'says', 'added', 'think', 'know', 'though', 'let', 'going', 'back', 'well', 'example', 'us', 'yet', 'perhaps', 'actually', 'oh', 'year', 'lastyear', 'last', 'old', 'first', 'good', 'maybe', 'ask', '.', ',', ':', 'take', 'made', 'n\'t', 'go', 'make', 'two', 'got', 'took', 'want', 'much', 'may', 'never', 'second', 'could', 'still', 'get', '?', 'would', '(', '\'', ')', '``', '/', "''", '%', '#', '!', 'next', "'s", ';', '[', ']', '...', 'might', "'m", "'d", 'also', 'something', 'even', 'new', 'lot', 'a', 'thing', 'time', 'way', 'always', 'whose', 'need', 'people', 'come', 'become', 'another', 'many', 'must', 'too', 'as', 'well']) def wordcloud2(): cat = {} for i,row in train_data.iterrows(): try: category = cat[row['Label']] except KeyError: cat[row['Label']] = {} category = cat[row['Label']] for word in row['Content'].lower().split(): #word = w.lower().split() if word in stpw: continue try: category[word] += 1 except KeyError: category[word] = 1 mask = np.array(Image.open(requests.get('http://www.clker.com/cliparts/3/0/a/1/11971238241310805346noonespillow_Simple_Cloud.svg.med.png',stream=True).raw)) wordcloud5 = WordCloud(stopwords=stop_words, background_color="white", mask=mask) for categ,wrds in cat.items(): wordcloud5.generate_from_frequencies(wrds) wordcloud5.to_file('q1/'+categ+'.jpg') wordcloud2() ``` ### Building Vectors ``` print("building Hashing vectorizer") hvect = HashingVectorizer(stop_words='english') print("building tfidf") vectorizer = TfidfVectorizer(stop_words = 'english',use_idf=True) #vectorizer = TfidfVectorizer(use_idf=True) print("Building SVD") #truncated svd lsa=TruncatedSVD(n_components = 80) svd_transformer = make_pipeline(vectorizer,lsa) #X_train_svd = svd_transformer.fit_transform(X_train) X = np.array(X).flatten() y = np.array(y).flatten() ``` ### SVM (Bag of Words) ``` #set candidate parameters #parameters = {'kernel':['rbf'], 'gamma': [0.1]} print("before determing model") #determine the model clf = SVC(kernel='linear',C=8,gamma=0.1) #clf = GridSearchCV(svc,parameters,cv=5) estimators1 = [("tf_idf",vectorizer),("svm",clf)] model1 = Pipeline(estimators1) kf = KFold(n_splits=5) accuracy,precision,recall,f1 = 0,0,0,0 for trainI,testI in kf.split(X): #kfTestCategIds = le.transform(y[testI]) model1.fit(X[trainI],y[trainI]) predictions = model1.predict(X[testI]) ret = precision_score(y[testI], predictions, average='macro') precision += ret ret = recall_score(y[testI], predictions, average='macro') recall += ret ret = f1_score(y[testI], predictions, average='macro') f1 += ret accuracy += accuracy_score(y[testI], predictions) #accuracy,precision,recall,f1 = accuracy/float(5),precision/float(5),recall/float(5),f1/float(5) accuracy,precision,recall,f1 = accuracy/5,precision/5,recall/5,f1/5 print("Accuracy = ",end=' ') print(accuracy) print("Precision = ",end=' ') print(precision) print("Recall = ",end=' ') print(recall) print("f1-score = ",end=' ') print(f1) ``` ### SVM (svd) ``` s = SVC(kernel='linear',C=8,gamma=1) estimators2 = [("svd",svd_transformer),("svm",s)] model2 = Pipeline(estimators2) kf = KFold(n_splits=5) accuracy,precision,recall,f1 = 0,0,0,0 for trainI,testI in kf.split(X): #kfTestCategIds = le.transform(y[testI]) model2.fit(X[trainI],y[trainI]) predictions = model2.predict(X[testI]) ret = precision_score(y[testI], predictions, average='macro') precision += ret ret = recall_score(y[testI], predictions, average='macro') recall += ret ret = f1_score(y[testI], predictions, average='macro') f1 += ret accuracy += accuracy_score(y[testI], predictions) #accuracy,precision,recall,f1 = accuracy/float(5),precision/float(5),recall/float(5),f1/float(5) accuracy,precision,recall,f1 = accuracy/5,precision/5,recall/5,f1/5 print("Accuracy = ",end=' ') print(accuracy) print("Precision = ",end=' ') print(precision) print("Recall = ",end=' ') print(recall) print("f1-score = ",end=' ') print(f1) ``` ### Random Forests (Bag of words) ``` rfc = RandomForestClassifier(n_estimators = 100) estimators3 = [("tf_idf",vectorizer),("rfc",rfc)] model3 = Pipeline(estimators3) kf = KFold(n_splits=5) accuracy,precision,recall,f1 = 0,0,0,0 for trainI,testI in kf.split(X): #kfTestCategIds = le.transform(y[testI]) model3.fit(X[trainI],y[trainI]) predictions = model3.predict(X[testI]) ret = precision_score(y[testI], predictions, average='macro') precision += ret ret = recall_score(y[testI], predictions, average='macro') recall += ret ret = f1_score(y[testI], predictions, average='macro') f1 += ret accuracy += accuracy_score(y[testI], predictions) #accuracy,precision,recall,f1 = accuracy/float(5),precision/float(5),recall/float(5),f1/float(5) accuracy,precision,recall,f1 = accuracy/5,precision/5,recall/5,f1/5 print("Accuracy = ",end=' ') print(accuracy) print("Precision = ",end=' ') print(precision) print("Recall = ",end=' ') print(recall) print("f1-score = ",end=' ') print(f1) ``` ### Random Forests (svd) ``` rfc1 = RandomForestClassifier(n_estimators=100) estimators4 = [("svd",svd_transformer),("rfc",rfc1)] model4 = Pipeline(estimators4) kf = KFold(n_splits=5) accuracy,precision,recall,f1 = 0,0,0,0 for trainI,testI in kf.split(X): #kfTestCategIds = le.transform(y[testI]) model4.fit(X[trainI],y[trainI]) predictions = model4.predict(X[testI]) ret = precision_score(y[testI], predictions, average='macro') precision += ret ret = recall_score(y[testI], predictions, average='macro') recall += ret ret = f1_score(y[testI], predictions, average='macro') f1 += ret accuracy += accuracy_score(y[testI], predictions) #accuracy,precision,recall,f1 = accuracy/float(5),precision/float(5),recall/float(5),f1/float(5) accuracy,precision,recall,f1 = accuracy/5,precision/5,recall/5,f1/5 print("Accuracy = ",end=' ') print(accuracy) print("Precision = ",end=' ') print(precision) print("Recall = ",end=' ') print(recall) print("f1-score = ",end=' ') print(f1) ``` ### My Method ``` nltk.download('stopwords') stopWords = stopwords.words('english') from nltk.stem import WordNetLemmatizer nltk.download('wordnet') import re from sklearn.naive_bayes import ComplementNB from sklearn.neighbors import KNeighborsClassifier stopWords.extend(['saying', 'said', 'say', 'yes', 'instead', 'meanwhile', 'right', 'really', 'finally', 'now', 'one', 'suggested', 'says', 'added', 'think', 'know', 'though', 'let', 'going', 'back', 'well', 'example', 'us', 'yet', 'perhaps', 'actually', 'oh', 'year', 'lastyear', 'last', 'old', 'first', 'good', 'maybe', 'ask', '.', ',', ':', 'take', 'made', 'n\'t', 'go', 'make', 'two', 'got', 'took', 'want', 'much', 'may', 'never', 'second', 'could', 'still', 'get', '?', 'would', '(', '\'', ')', '``', '/', "''", '%', '#', '!', 'next', "'s", ';', '[', ']', '...', 'might', "'m", "'d", 'also', 'something', 'even', 'new', 'lot', 'a', 'thing', 'time', 'way', 'always', 'whose', 'need', 'people', 'come', 'become', 'another', 'many', 'must', 'too', 'as', 'well']) stopWords.extend([' ','are','and','I','A','And','So','arnt','This','When','It','many','Many','so','cant','Yes','yes','No','no','These','these']) def processText(text): p_stemmer = SnowballStemmer(language='english') text = re.sub(r'[^\w\s]','',text) tokens = text.lower() tokens = tokens.split() #tokens = [wrd for wrd in tokens if(wrd not in stopWords)] #lemmatizer = WordNetLemmatizer() #tokens = [lemmatizer.lemmatize(t) for t in tokens] #tokens = [wrd for wrd in tokens if(wrd not in stopWords)] stems = [p_stemmer.stem(t) for t in tokens] return stems #X = 'ttt '+ df['Title']+' ttt '+ df['Title']+' ccc '+df['Content']+' ttt '+df['Title']+' ttt '+ df['Title'] X = df['Title'] + df['Title'] + df['Content'] + df['Title'] + df['Title'] y = df['Label'] X = np.array(X).flatten() y = np.array(y).flatten() vectorizer = TfidfVectorizer(tokenizer=processText, stop_words = stopWords,use_idf=True) #vectorizer = TfidfVectorizer(tokenizer=processText, use_idf=True) nb = SVC(kernel='rbf',C=8,gamma=0.1) #nb = KNeighborsClassifier(n_neighbors=3) #nb = ComplementNB() estimators = [("tf_idf",vectorizer),("svm",nb)] model = Pipeline(estimators) kf = KFold(n_splits=5) accuracy,precision,recall,f1 = 0,0,0,0 for trainI,testI in kf.split(X): #kfTestCategIds = le.transform(y[testI]) model.fit(X[trainI],y[trainI]) predictions = model.predict(X[testI]) ret = precision_score(y[testI], predictions, average='macro') precision += ret ret = recall_score(y[testI], predictions, average='macro') recall += ret ret = f1_score(y[testI], predictions, average='macro') f1 += ret accuracy += accuracy_score(y[testI], predictions) #accuracy,precision,recall,f1 = accuracy/float(5),precision/float(5),recall/float(5),f1/float(5) accuracy,precision,recall,f1 = accuracy/5,precision/5,recall/5,f1/5 print("Accuracy = ",end=' ') print(accuracy) print("Precision = ",end=' ') print(precision) print("Recall = ",end=' ') print(recall) print("f1-score = ",end=' ') print(f1) ``` ### Predicting Test file ``` df_test = test_data['Title']+test_data['Title']+test_data['Content']+test_data['Title']+test_data['Title'] #X_test_vector = vectorizer.transform(df_test) #pred_final = nb.predict(X_test_vector) pred_final = model.predict(df_test) to_print_arr = np.array(test_data[['Id']]).flatten() columns = pd.Index(['Id','Predicted']) data = np.column_stack((to_print_arr,pred_final)) df_final = pd.DataFrame(data, index=None, columns = columns) df_final.to_csv('q1/testSet_categories.csv', sep=',', index=False) ``` ### Requirement 1 complete
github_jupyter
import pandas as pd import numpy as np import urllib3 import requests from PIL import Image import matplotlib.pyplot as plt import seaborn as sns from wordcloud import WordCloud, STOPWORDS from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import KFold from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import classification_report, confusion_matrix from nltk.corpus import stopwords import spacy from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.feature_extraction.text import HashingVectorizer from sklearn.decomposition import TruncatedSVD from sklearn.feature_extraction.text import CountVectorizer from sklearn.metrics import classification_report, precision_score, recall_score, f1_score, accuracy_score from sklearn.pipeline import Pipeline from sklearn.svm import LinearSVC from sklearn import metrics from sklearn.svm import SVC from sklearn.model_selection import GridSearchCV from sklearn import preprocessing from sklearn.pipeline import make_pipeline from sklearn.model_selection import cross_val_score from sklearn.model_selection import cross_val_predict from sklearn.metrics import accuracy_score from sklearn.ensemble import RandomForestClassifier from sklearn.preprocessing import StandardScaler from sklearn.neighbors import KNeighborsClassifier from sklearn.naive_bayes import MultinomialNB from sklearn.naive_bayes import ComplementNB from nltk.stem.porter import * from nltk import word_tokenize from nltk.stem.snowball import SnowballStemmer from collections import Counter from nltk.stem import WordNetLemmatizer from nltk.corpus import wordnet from sklearn.metrics import accuracy_score import nltk nlp = spacy.load('en_core_web_sm') nltk.download('punkt') %matplotlib inline train_data = pd.read_csv('datasets/q1/train.csv', sep=',') test_data = pd.read_csv('datasets/q1/test_without_labels.csv', sep=',') #test_data['Label'] = train_data['Label'] expected_array = np.array(train_data.head(2000)[['Label']]).flatten() content_array = np.array(train_data.head(2000)[['Content']]).flatten() #X_train = train_data['Content'].head(2000) #Y_train = train_data['Label'].head(2000) #X_test = test_data['Content'] #Y_test = test_data['Label'] my_additional_stop_words = ['said','still','day','will','new','may','two','one','now','time','say','second','month','first','going','year','back','people','case','according'] stop_words = STOPWORDS.union(my_additional_stop_words) sns.countplot(x='Label',data=train_data) traindata = train_data.groupby('Label').count() print(traindata) #df_entertainment = train_data[train_data['Label']=='Entertainment'].head(3900) #df_health = train_data[train_data['Label']=='Health'].head(1200) #df_business = train_data[train_data['Label']=='Business'].head(2700) #df_technology = train_data[train_data['Label']=='Technology'].head(3000) #df = pd.concat([df_entertainment,df_health,df_business,df_technology]) df = train_data.head(10000) X = df['Title'] + df['Content'] y = df['Label'] #X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42) #STOPWORDS.extend(['will', 'said', 'us', 'may', 'share','well']) def wordcloud(): business = str() entertainment = str() health = str() technology = str() for i in range(expected_array.shape[0]): if expected_array[i] == 'Business': business = business + ' ' + str(content_array[i]) elif expected_array[i] == 'Entertainment': entertainment = entertainment + ' ' + str(content_array[i]) elif expected_array[i] == 'Health': health = health + ' ' + str(content_array[i]) elif expected_array[i] == 'Technology': technology = technology + ' ' + str(content_array[i]) mask = np.array(Image.open(requests.get('http://www.clker.com/cliparts/3/0/a/1/11971238241310805346noonespillow_Simple_Cloud.svg.med.png',stream=True).raw)) wordcloud1 = WordCloud(stopwords=stop_words, background_color="white", mask=mask).generate(business) plt.imshow(wordcloud1,interpolation='bilinear') plt.axis("off") plt.savefig('q1/business.png') wordcloud2 = WordCloud(stopwords=stop_words,background_color="white",mask=mask).generate(entertainment) plt.imshow(wordcloud2,interpolation='bilinear') plt.axis("off") plt.savefig('q1/entertainment.png') wordcloud3 = WordCloud(stopwords=stop_words,background_color="white",mask=mask).generate(health) plt.imshow(wordcloud3,interpolation='bilinear') plt.axis("off") plt.savefig('q1/health.png') wordcloud4 = WordCloud(stopwords=stop_words,background_color="white",mask=mask).generate(technology) plt.imshow(wordcloud4,interpolation='bilinear') plt.axis("off") plt.savefig('q1/technology.png') from stop_words import get_stop_words stpw = get_stop_words('en') stpw.extend(my_additional_stop_words) stpw.extend(['can','also','like']) stpw.extend(['saying', 'said', 'say', 'yes', 'instead', 'meanwhile', 'right', 'really', 'finally', 'now', 'one', 'suggested', 'says', 'added', 'think', 'know', 'though', 'let', 'going', 'back', 'well', 'example', 'us', 'yet', 'perhaps', 'actually', 'oh', 'year', 'lastyear', 'last', 'old', 'first', 'good', 'maybe', 'ask', '.', ',', ':', 'take', 'made', 'n\'t', 'go', 'make', 'two', 'got', 'took', 'want', 'much', 'may', 'never', 'second', 'could', 'still', 'get', '?', 'would', '(', '\'', ')', '``', '/', "''", '%', '#', '!', 'next', "'s", ';', '[', ']', '...', 'might', "'m", "'d", 'also', 'something', 'even', 'new', 'lot', 'a', 'thing', 'time', 'way', 'always', 'whose', 'need', 'people', 'come', 'become', 'another', 'many', 'must', 'too', 'as', 'well']) def wordcloud2(): cat = {} for i,row in train_data.iterrows(): try: category = cat[row['Label']] except KeyError: cat[row['Label']] = {} category = cat[row['Label']] for word in row['Content'].lower().split(): #word = w.lower().split() if word in stpw: continue try: category[word] += 1 except KeyError: category[word] = 1 mask = np.array(Image.open(requests.get('http://www.clker.com/cliparts/3/0/a/1/11971238241310805346noonespillow_Simple_Cloud.svg.med.png',stream=True).raw)) wordcloud5 = WordCloud(stopwords=stop_words, background_color="white", mask=mask) for categ,wrds in cat.items(): wordcloud5.generate_from_frequencies(wrds) wordcloud5.to_file('q1/'+categ+'.jpg') wordcloud2() print("building Hashing vectorizer") hvect = HashingVectorizer(stop_words='english') print("building tfidf") vectorizer = TfidfVectorizer(stop_words = 'english',use_idf=True) #vectorizer = TfidfVectorizer(use_idf=True) print("Building SVD") #truncated svd lsa=TruncatedSVD(n_components = 80) svd_transformer = make_pipeline(vectorizer,lsa) #X_train_svd = svd_transformer.fit_transform(X_train) X = np.array(X).flatten() y = np.array(y).flatten() #set candidate parameters #parameters = {'kernel':['rbf'], 'gamma': [0.1]} print("before determing model") #determine the model clf = SVC(kernel='linear',C=8,gamma=0.1) #clf = GridSearchCV(svc,parameters,cv=5) estimators1 = [("tf_idf",vectorizer),("svm",clf)] model1 = Pipeline(estimators1) kf = KFold(n_splits=5) accuracy,precision,recall,f1 = 0,0,0,0 for trainI,testI in kf.split(X): #kfTestCategIds = le.transform(y[testI]) model1.fit(X[trainI],y[trainI]) predictions = model1.predict(X[testI]) ret = precision_score(y[testI], predictions, average='macro') precision += ret ret = recall_score(y[testI], predictions, average='macro') recall += ret ret = f1_score(y[testI], predictions, average='macro') f1 += ret accuracy += accuracy_score(y[testI], predictions) #accuracy,precision,recall,f1 = accuracy/float(5),precision/float(5),recall/float(5),f1/float(5) accuracy,precision,recall,f1 = accuracy/5,precision/5,recall/5,f1/5 print("Accuracy = ",end=' ') print(accuracy) print("Precision = ",end=' ') print(precision) print("Recall = ",end=' ') print(recall) print("f1-score = ",end=' ') print(f1) s = SVC(kernel='linear',C=8,gamma=1) estimators2 = [("svd",svd_transformer),("svm",s)] model2 = Pipeline(estimators2) kf = KFold(n_splits=5) accuracy,precision,recall,f1 = 0,0,0,0 for trainI,testI in kf.split(X): #kfTestCategIds = le.transform(y[testI]) model2.fit(X[trainI],y[trainI]) predictions = model2.predict(X[testI]) ret = precision_score(y[testI], predictions, average='macro') precision += ret ret = recall_score(y[testI], predictions, average='macro') recall += ret ret = f1_score(y[testI], predictions, average='macro') f1 += ret accuracy += accuracy_score(y[testI], predictions) #accuracy,precision,recall,f1 = accuracy/float(5),precision/float(5),recall/float(5),f1/float(5) accuracy,precision,recall,f1 = accuracy/5,precision/5,recall/5,f1/5 print("Accuracy = ",end=' ') print(accuracy) print("Precision = ",end=' ') print(precision) print("Recall = ",end=' ') print(recall) print("f1-score = ",end=' ') print(f1) rfc = RandomForestClassifier(n_estimators = 100) estimators3 = [("tf_idf",vectorizer),("rfc",rfc)] model3 = Pipeline(estimators3) kf = KFold(n_splits=5) accuracy,precision,recall,f1 = 0,0,0,0 for trainI,testI in kf.split(X): #kfTestCategIds = le.transform(y[testI]) model3.fit(X[trainI],y[trainI]) predictions = model3.predict(X[testI]) ret = precision_score(y[testI], predictions, average='macro') precision += ret ret = recall_score(y[testI], predictions, average='macro') recall += ret ret = f1_score(y[testI], predictions, average='macro') f1 += ret accuracy += accuracy_score(y[testI], predictions) #accuracy,precision,recall,f1 = accuracy/float(5),precision/float(5),recall/float(5),f1/float(5) accuracy,precision,recall,f1 = accuracy/5,precision/5,recall/5,f1/5 print("Accuracy = ",end=' ') print(accuracy) print("Precision = ",end=' ') print(precision) print("Recall = ",end=' ') print(recall) print("f1-score = ",end=' ') print(f1) rfc1 = RandomForestClassifier(n_estimators=100) estimators4 = [("svd",svd_transformer),("rfc",rfc1)] model4 = Pipeline(estimators4) kf = KFold(n_splits=5) accuracy,precision,recall,f1 = 0,0,0,0 for trainI,testI in kf.split(X): #kfTestCategIds = le.transform(y[testI]) model4.fit(X[trainI],y[trainI]) predictions = model4.predict(X[testI]) ret = precision_score(y[testI], predictions, average='macro') precision += ret ret = recall_score(y[testI], predictions, average='macro') recall += ret ret = f1_score(y[testI], predictions, average='macro') f1 += ret accuracy += accuracy_score(y[testI], predictions) #accuracy,precision,recall,f1 = accuracy/float(5),precision/float(5),recall/float(5),f1/float(5) accuracy,precision,recall,f1 = accuracy/5,precision/5,recall/5,f1/5 print("Accuracy = ",end=' ') print(accuracy) print("Precision = ",end=' ') print(precision) print("Recall = ",end=' ') print(recall) print("f1-score = ",end=' ') print(f1) nltk.download('stopwords') stopWords = stopwords.words('english') from nltk.stem import WordNetLemmatizer nltk.download('wordnet') import re from sklearn.naive_bayes import ComplementNB from sklearn.neighbors import KNeighborsClassifier stopWords.extend(['saying', 'said', 'say', 'yes', 'instead', 'meanwhile', 'right', 'really', 'finally', 'now', 'one', 'suggested', 'says', 'added', 'think', 'know', 'though', 'let', 'going', 'back', 'well', 'example', 'us', 'yet', 'perhaps', 'actually', 'oh', 'year', 'lastyear', 'last', 'old', 'first', 'good', 'maybe', 'ask', '.', ',', ':', 'take', 'made', 'n\'t', 'go', 'make', 'two', 'got', 'took', 'want', 'much', 'may', 'never', 'second', 'could', 'still', 'get', '?', 'would', '(', '\'', ')', '``', '/', "''", '%', '#', '!', 'next', "'s", ';', '[', ']', '...', 'might', "'m", "'d", 'also', 'something', 'even', 'new', 'lot', 'a', 'thing', 'time', 'way', 'always', 'whose', 'need', 'people', 'come', 'become', 'another', 'many', 'must', 'too', 'as', 'well']) stopWords.extend([' ','are','and','I','A','And','So','arnt','This','When','It','many','Many','so','cant','Yes','yes','No','no','These','these']) def processText(text): p_stemmer = SnowballStemmer(language='english') text = re.sub(r'[^\w\s]','',text) tokens = text.lower() tokens = tokens.split() #tokens = [wrd for wrd in tokens if(wrd not in stopWords)] #lemmatizer = WordNetLemmatizer() #tokens = [lemmatizer.lemmatize(t) for t in tokens] #tokens = [wrd for wrd in tokens if(wrd not in stopWords)] stems = [p_stemmer.stem(t) for t in tokens] return stems #X = 'ttt '+ df['Title']+' ttt '+ df['Title']+' ccc '+df['Content']+' ttt '+df['Title']+' ttt '+ df['Title'] X = df['Title'] + df['Title'] + df['Content'] + df['Title'] + df['Title'] y = df['Label'] X = np.array(X).flatten() y = np.array(y).flatten() vectorizer = TfidfVectorizer(tokenizer=processText, stop_words = stopWords,use_idf=True) #vectorizer = TfidfVectorizer(tokenizer=processText, use_idf=True) nb = SVC(kernel='rbf',C=8,gamma=0.1) #nb = KNeighborsClassifier(n_neighbors=3) #nb = ComplementNB() estimators = [("tf_idf",vectorizer),("svm",nb)] model = Pipeline(estimators) kf = KFold(n_splits=5) accuracy,precision,recall,f1 = 0,0,0,0 for trainI,testI in kf.split(X): #kfTestCategIds = le.transform(y[testI]) model.fit(X[trainI],y[trainI]) predictions = model.predict(X[testI]) ret = precision_score(y[testI], predictions, average='macro') precision += ret ret = recall_score(y[testI], predictions, average='macro') recall += ret ret = f1_score(y[testI], predictions, average='macro') f1 += ret accuracy += accuracy_score(y[testI], predictions) #accuracy,precision,recall,f1 = accuracy/float(5),precision/float(5),recall/float(5),f1/float(5) accuracy,precision,recall,f1 = accuracy/5,precision/5,recall/5,f1/5 print("Accuracy = ",end=' ') print(accuracy) print("Precision = ",end=' ') print(precision) print("Recall = ",end=' ') print(recall) print("f1-score = ",end=' ') print(f1) df_test = test_data['Title']+test_data['Title']+test_data['Content']+test_data['Title']+test_data['Title'] #X_test_vector = vectorizer.transform(df_test) #pred_final = nb.predict(X_test_vector) pred_final = model.predict(df_test) to_print_arr = np.array(test_data[['Id']]).flatten() columns = pd.Index(['Id','Predicted']) data = np.column_stack((to_print_arr,pred_final)) df_final = pd.DataFrame(data, index=None, columns = columns) df_final.to_csv('q1/testSet_categories.csv', sep=',', index=False)
0.331985
0.628322
``` from math import log import matplotlib.pyplot as plt %matplotlib inline #定义文本框和箭头格式 decisionNode = dict(boxstyle="sawtooth", fc="0.8") #定义判断节点形态 leafNode = dict(boxstyle="round4", fc="0.8") #定义叶节点形态 arrow_args = dict(arrowstyle="<-") #定义箭头 #绘制带箭头的注解 #nodeTxt:节点的文字标注, centerPt:节点中心位置, #parentPt:箭头起点位置(上一节点位置), nodeType:节点属性 def plotNode(nodeTxt, centerPt, parentPt, nodeType): createPlot.ax1.annotate(nodeTxt, xy=parentPt, xycoords='axes fraction', xytext=centerPt, textcoords='axes fraction', va="center", ha="center", bbox=nodeType, arrowprops=arrow_args ) #计算叶节点数 def getNumLeafs(myTree): numLeafs = 0 firstStr = list(myTree.keys())[0] secondDict = myTree[firstStr] for key in list(secondDict.keys()): if type(secondDict[key]).__name__=='dict':#是否是字典 numLeafs += getNumLeafs(secondDict[key]) #递归调用getNumLeafs else: numLeafs +=1 #如果是叶节点,则叶节点+1 return numLeafs #计算数的层数 def getTreeDepth(myTree): maxDepth = 0 firstStr = list(myTree.keys())[0] secondDict = myTree[firstStr] for key in list(secondDict.keys()): if type(secondDict[key]).__name__=='dict':#是否是字典 thisDepth = 1 + getTreeDepth(secondDict[key]) #如果是字典,则层数加1,再递归调用getTreeDepth else: thisDepth = 1 #得到最大层数 if thisDepth > maxDepth: maxDepth = thisDepth return maxDepth #在父子节点间填充文本信息 #cntrPt:子节点位置, parentPt:父节点位置, txtString:标注内容 def plotMidText(cntrPt, parentPt, txtString): xMid = (parentPt[0]-cntrPt[0])/2.0 + cntrPt[0] yMid = (parentPt[1]-cntrPt[1])/2.0 + cntrPt[1] createPlot.ax1.text(xMid, yMid, txtString, va="center", ha="center", rotation=30) #绘制树形图 #myTree:树的字典, parentPt:父节点, nodeTxt:节点的文字标注 def plotTree(myTree, parentPt, nodeTxt): numLeafs = getNumLeafs(myTree) #树叶节点数 depth = getTreeDepth(myTree) #树的层数 firstStr = list(myTree.keys())[0] #节点标签 #计算当前节点的位置 cntrPt = (plotTree.xOff + (1.0 + float(numLeafs))/2.0/plotTree.totalW, plotTree.yOff) plotMidText(cntrPt, parentPt, nodeTxt) #在父子节点间填充文本信息 plotNode(firstStr, cntrPt, parentPt, decisionNode) #绘制带箭头的注解 secondDict = myTree[firstStr] plotTree.yOff = plotTree.yOff - 1.0/plotTree.totalD for key in secondDict.keys(): if type(secondDict[key]).__name__=='dict':#判断是不是字典, plotTree(secondDict[key],cntrPt,str(key)) #递归绘制树形图 else: #如果是叶节点 plotTree.xOff = plotTree.xOff + 1.0/plotTree.totalW plotNode(secondDict[key], (plotTree.xOff, plotTree.yOff), cntrPt, leafNode) plotMidText((plotTree.xOff, plotTree.yOff), cntrPt, str(key)) plotTree.yOff = plotTree.yOff + 1.0/plotTree.totalD #创建绘图区 def createPlot(inTree): fig = plt.figure(1, facecolor='white') fig.clf() axprops = dict(xticks=[], yticks=[]) createPlot.ax1 = plt.subplot(111, frameon=False, **axprops) plotTree.totalW = float(getNumLeafs(inTree)) #树的宽度 plotTree.totalD = float(getTreeDepth(inTree)) #树的深度 plotTree.xOff = -0.5/plotTree.totalW; plotTree.yOff = 1.0; plotTree(inTree, (0.5,1.0), '') plt.show() #创建数据集 def createDataSet(): dataSet = [[1, 1, 'yes'], [1, 1, 'yes'], [1, 0, 'no'], [0, 1, 'no'], [0, 1, 'no']] labels = ['no surfacing','flippers'] return dataSet, labels def calcShannonEnt(dataSet): numEntries = len(dataSet) #数据的个数 labelCounts = {} for featVec in dataSet: currentLabel = featVec[-1] #数据集最后一列作为当前标签 if currentLabel not in labelCounts.keys(): #如果当前标签不存在,则加入字典 labelCounts[currentLabel] = 0 labelCounts[currentLabel] += 1 #记录当前类别出现次数 print(labelCounts) shannonEnt = 0.0 for key in labelCounts: prob = float(labelCounts[key])/numEntries #计算各标签出现概率 shannonEnt -= prob * log(prob,2) #计算香农熵 return shannonEnt #参数axis是特征的index,参数value是特征的值 #划分数据集(删除featVec[axis] == value项,显示其余的项) def splitDataSet(dataSet, axis, value): retDataSet = [] for featVec in dataSet: if featVec[axis] == value: reducedFeatVec = featVec[:axis] reducedFeatVec.extend(featVec[axis+1:]) retDataSet.append(reducedFeatVec) return retDataSet def chooseBestFeatureToSplit(dataSet): numFeatures = len(dataSet[0]) - 1 #最后一列是标签,其余的是特征 baseEntropy = calcShannonEnt(dataSet) bestInfoGain = 0.0; bestFeature = -1 for i in range(numFeatures): #遍历所有特征 featList = [example[i] for example in dataSet]#第i列所有特征 uniqueVals = set(featList) #得到第i列不重复的特征,set用法见后面分析 newEntropy = 0.0 for value in uniqueVals: subDataSet = splitDataSet(dataSet, i, value) #对每个特征划分数据集 prob = len(subDataSet)/float(len(dataSet)) newEntropy += prob * calcShannonEnt(subDataSet) #计算新数据集的熵 #计算划分后的信息增益,得到最大增益 infoGain = baseEntropy - newEntropy if (infoGain > bestInfoGain): bestInfoGain = infoGain bestFeature = i return bestFeature #返回出现次数最多的类 def majorityCnt(classList): classCount={} for vote in classList: if vote not in classCount.keys(): classCount[vote] = 0 classCount[vote] += 1 sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True) return sortedClassCount[0][0] #返回字典中的第一个值,也就是出现次数最多的类 def createTree(dataSet,labels): classList = [example[-1] for example in dataSet] #最后一列是类别 if classList.count(classList[0]) == len(classList): #所有类标签相同,则返回该类标签 return classList[0] if len(dataSet[0]) == 1: #进行递归的过程中,特征会减少,当特征只有一个时(只有一列时),返回该列出现次数最多的标签 return majorityCnt(classList) bestFeat = chooseBestFeatureToSplit(dataSet) #返回最佳特征的索引 bestFeatLabel = labels[bestFeat] #该索引对应的标签 myTree = {bestFeatLabel:{}} del(labels[bestFeat]) # 每个标签只划分一次,所以标签会减少 # 根据最佳特征索引所对应的列的不同值, 划分成不同节点, 再对每个节点递归建树 featValues = [example[bestFeat] for example in dataSet] #返回最佳特征的索引对应的列的不同值 uniqueVals = set(featValues) for value in uniqueVals: subLabels = labels[:] # 复制类标签 myTree[bestFeatLabel][value] = createTree(splitDataSet(dataSet, bestFeat, value),subLabels) return myTree myDat,labels = createDataSet() myTree = createTree(myDat,labels) createPlot(myTree) ```
github_jupyter
from math import log import matplotlib.pyplot as plt %matplotlib inline #定义文本框和箭头格式 decisionNode = dict(boxstyle="sawtooth", fc="0.8") #定义判断节点形态 leafNode = dict(boxstyle="round4", fc="0.8") #定义叶节点形态 arrow_args = dict(arrowstyle="<-") #定义箭头 #绘制带箭头的注解 #nodeTxt:节点的文字标注, centerPt:节点中心位置, #parentPt:箭头起点位置(上一节点位置), nodeType:节点属性 def plotNode(nodeTxt, centerPt, parentPt, nodeType): createPlot.ax1.annotate(nodeTxt, xy=parentPt, xycoords='axes fraction', xytext=centerPt, textcoords='axes fraction', va="center", ha="center", bbox=nodeType, arrowprops=arrow_args ) #计算叶节点数 def getNumLeafs(myTree): numLeafs = 0 firstStr = list(myTree.keys())[0] secondDict = myTree[firstStr] for key in list(secondDict.keys()): if type(secondDict[key]).__name__=='dict':#是否是字典 numLeafs += getNumLeafs(secondDict[key]) #递归调用getNumLeafs else: numLeafs +=1 #如果是叶节点,则叶节点+1 return numLeafs #计算数的层数 def getTreeDepth(myTree): maxDepth = 0 firstStr = list(myTree.keys())[0] secondDict = myTree[firstStr] for key in list(secondDict.keys()): if type(secondDict[key]).__name__=='dict':#是否是字典 thisDepth = 1 + getTreeDepth(secondDict[key]) #如果是字典,则层数加1,再递归调用getTreeDepth else: thisDepth = 1 #得到最大层数 if thisDepth > maxDepth: maxDepth = thisDepth return maxDepth #在父子节点间填充文本信息 #cntrPt:子节点位置, parentPt:父节点位置, txtString:标注内容 def plotMidText(cntrPt, parentPt, txtString): xMid = (parentPt[0]-cntrPt[0])/2.0 + cntrPt[0] yMid = (parentPt[1]-cntrPt[1])/2.0 + cntrPt[1] createPlot.ax1.text(xMid, yMid, txtString, va="center", ha="center", rotation=30) #绘制树形图 #myTree:树的字典, parentPt:父节点, nodeTxt:节点的文字标注 def plotTree(myTree, parentPt, nodeTxt): numLeafs = getNumLeafs(myTree) #树叶节点数 depth = getTreeDepth(myTree) #树的层数 firstStr = list(myTree.keys())[0] #节点标签 #计算当前节点的位置 cntrPt = (plotTree.xOff + (1.0 + float(numLeafs))/2.0/plotTree.totalW, plotTree.yOff) plotMidText(cntrPt, parentPt, nodeTxt) #在父子节点间填充文本信息 plotNode(firstStr, cntrPt, parentPt, decisionNode) #绘制带箭头的注解 secondDict = myTree[firstStr] plotTree.yOff = plotTree.yOff - 1.0/plotTree.totalD for key in secondDict.keys(): if type(secondDict[key]).__name__=='dict':#判断是不是字典, plotTree(secondDict[key],cntrPt,str(key)) #递归绘制树形图 else: #如果是叶节点 plotTree.xOff = plotTree.xOff + 1.0/plotTree.totalW plotNode(secondDict[key], (plotTree.xOff, plotTree.yOff), cntrPt, leafNode) plotMidText((plotTree.xOff, plotTree.yOff), cntrPt, str(key)) plotTree.yOff = plotTree.yOff + 1.0/plotTree.totalD #创建绘图区 def createPlot(inTree): fig = plt.figure(1, facecolor='white') fig.clf() axprops = dict(xticks=[], yticks=[]) createPlot.ax1 = plt.subplot(111, frameon=False, **axprops) plotTree.totalW = float(getNumLeafs(inTree)) #树的宽度 plotTree.totalD = float(getTreeDepth(inTree)) #树的深度 plotTree.xOff = -0.5/plotTree.totalW; plotTree.yOff = 1.0; plotTree(inTree, (0.5,1.0), '') plt.show() #创建数据集 def createDataSet(): dataSet = [[1, 1, 'yes'], [1, 1, 'yes'], [1, 0, 'no'], [0, 1, 'no'], [0, 1, 'no']] labels = ['no surfacing','flippers'] return dataSet, labels def calcShannonEnt(dataSet): numEntries = len(dataSet) #数据的个数 labelCounts = {} for featVec in dataSet: currentLabel = featVec[-1] #数据集最后一列作为当前标签 if currentLabel not in labelCounts.keys(): #如果当前标签不存在,则加入字典 labelCounts[currentLabel] = 0 labelCounts[currentLabel] += 1 #记录当前类别出现次数 print(labelCounts) shannonEnt = 0.0 for key in labelCounts: prob = float(labelCounts[key])/numEntries #计算各标签出现概率 shannonEnt -= prob * log(prob,2) #计算香农熵 return shannonEnt #参数axis是特征的index,参数value是特征的值 #划分数据集(删除featVec[axis] == value项,显示其余的项) def splitDataSet(dataSet, axis, value): retDataSet = [] for featVec in dataSet: if featVec[axis] == value: reducedFeatVec = featVec[:axis] reducedFeatVec.extend(featVec[axis+1:]) retDataSet.append(reducedFeatVec) return retDataSet def chooseBestFeatureToSplit(dataSet): numFeatures = len(dataSet[0]) - 1 #最后一列是标签,其余的是特征 baseEntropy = calcShannonEnt(dataSet) bestInfoGain = 0.0; bestFeature = -1 for i in range(numFeatures): #遍历所有特征 featList = [example[i] for example in dataSet]#第i列所有特征 uniqueVals = set(featList) #得到第i列不重复的特征,set用法见后面分析 newEntropy = 0.0 for value in uniqueVals: subDataSet = splitDataSet(dataSet, i, value) #对每个特征划分数据集 prob = len(subDataSet)/float(len(dataSet)) newEntropy += prob * calcShannonEnt(subDataSet) #计算新数据集的熵 #计算划分后的信息增益,得到最大增益 infoGain = baseEntropy - newEntropy if (infoGain > bestInfoGain): bestInfoGain = infoGain bestFeature = i return bestFeature #返回出现次数最多的类 def majorityCnt(classList): classCount={} for vote in classList: if vote not in classCount.keys(): classCount[vote] = 0 classCount[vote] += 1 sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True) return sortedClassCount[0][0] #返回字典中的第一个值,也就是出现次数最多的类 def createTree(dataSet,labels): classList = [example[-1] for example in dataSet] #最后一列是类别 if classList.count(classList[0]) == len(classList): #所有类标签相同,则返回该类标签 return classList[0] if len(dataSet[0]) == 1: #进行递归的过程中,特征会减少,当特征只有一个时(只有一列时),返回该列出现次数最多的标签 return majorityCnt(classList) bestFeat = chooseBestFeatureToSplit(dataSet) #返回最佳特征的索引 bestFeatLabel = labels[bestFeat] #该索引对应的标签 myTree = {bestFeatLabel:{}} del(labels[bestFeat]) # 每个标签只划分一次,所以标签会减少 # 根据最佳特征索引所对应的列的不同值, 划分成不同节点, 再对每个节点递归建树 featValues = [example[bestFeat] for example in dataSet] #返回最佳特征的索引对应的列的不同值 uniqueVals = set(featValues) for value in uniqueVals: subLabels = labels[:] # 复制类标签 myTree[bestFeatLabel][value] = createTree(splitDataSet(dataSet, bestFeat, value),subLabels) return myTree myDat,labels = createDataSet() myTree = createTree(myDat,labels) createPlot(myTree)
0.307774
0.483587
<p style="z-index: 101;background: #fde073;text-align: center;line-height: 2.5;overflow: hidden;font-size:22px;">Please <a href="https://www.pycm.ir/doc/#Cite" target="_blank">cite us</a> if you use the software</p> # Example-6 (Unbalanced data) ## Environment check Checking that the notebook is running on Google Colab or not. ``` import sys try: import google.colab !{sys.executable} -m pip -q -q install pycm except: pass ``` ## Binary classification for unbalanced data ``` from pycm import ConfusionMatrix ``` ### Case1 (Both classes have a good result) $$Case_1=\begin{bmatrix}26900 & 40 \\25 & 500 \end{bmatrix}$$ ``` case1 = ConfusionMatrix(matrix={"Class1": {"Class1": 26900, "Class2":40}, "Class2": {"Class1": 25, "Class2": 500}}) case1.print_normalized_matrix() print('ACC:',case1.ACC) print('MCC:',case1.MCC) print('CEN:',case1.CEN) print('MCEN:',case1.MCEN) print('DP:',case1.DP) print('Kappa:',case1.Kappa) print('RCI:',case1.RCI) print('SOA1:',case1.SOA1) ``` ### Case2 (The first class has a good result) $$Case_2=\begin{bmatrix}26900 & 40 \\500 & 25 \end{bmatrix}$$ ``` case2 = ConfusionMatrix(matrix={"Class1": {"Class1": 29600, "Class2":40}, "Class2": {"Class1": 500, "Class2": 25}}) case2.print_normalized_matrix() print('ACC:',case2.ACC) print('MCC:',case2.MCC) print('CEN:',case2.CEN) print('MCEN:',case2.MCEN) print('DP:',case2.DP) print('Kappa:',case2.Kappa) print('RCI:',case2.RCI) print('SOA1:',case2.SOA1) ``` ### Case3 (Second class has a good result ) $$Case_3=\begin{bmatrix}40 & 26900 \\25 & 500 \end{bmatrix}$$ ``` case3 = ConfusionMatrix(matrix={"Class1": {"Class1": 40, "Class2":26900}, "Class2": {"Class1": 25, "Class2": 500}}) case3.print_normalized_matrix() print('ACC:',case3.ACC) print('MCC:',case3.MCC) print('CEN:',case3.CEN) print('MCEN:',case3.MCEN) print('DP:',case3.DP) print('Kappa:',case3.Kappa) print('RCI:',case3.RCI) print('SOA1:',case3.SOA1) ``` ## Multi-class classification for unbalanced data ### Case1 (All classes have good result and are unbalanced) $$Case_1=\begin{bmatrix}4 & 0 &0&1 \\0 & 4&1&0\\0&1&4&0\\0&0&1&4000 \end{bmatrix}$$ ``` case1 = ConfusionMatrix(matrix={"Class1": {"Class1": 4, "Class2":0, "Class3":0, "Class4":1}, "Class2": {"Class1": 0, "Class2":4, "Class3":1, "Class4":0}, "Class3": {"Class1": 0, "Class2":1, "Class3":4, "Class4":0}, "Class4": {"Class1": 0, "Class2":0, "Class3":1, "Class4":40000}}) case1.print_normalized_matrix() print('ACC:',case1.ACC) print('MCC:',case1.MCC) print('CEN:',case1.CEN) print('MCEN:',case1.MCEN) print('DP:',case1.DP) print('Kappa:',case1.Kappa) print('RCI:',case1.RCI) print('SOA1:',case1.SOA1) ``` ### Case2 (All classes have same result and are balanced) $$Case_2=\begin{bmatrix}1 & 1 &1&1 \\1 & 1&1&1\\1&1&1&1\\1&1&1&1 \end{bmatrix}$$ ``` case2 = ConfusionMatrix(matrix={"Class1": {"Class1": 1, "Class2":1, "Class3":1, "Class4":1}, "Class2": {"Class1": 1, "Class2":1, "Class3":1, "Class4":1}, "Class3": {"Class1": 1, "Class2":1, "Class3":1, "Class4":1}, "Class4": {"Class1": 1, "Class2":1, "Class3":1, "Class4":1}}) case2.print_normalized_matrix() print('ACC:',case2.ACC) print('MCC:',case2.MCC) print('CEN:',case2.CEN) print('MCEN:',case2.MCEN) print('DP:',case2.DP) print('Kappa:',case2.Kappa) print('RCI:',case2.RCI) print('SOA1:',case2.SOA1) ``` ### Case3 (A class has a bad result and is a bit unbalanced) $$Case_3=\begin{bmatrix}1 & 1 &1&1 \\1 & 1&1&1\\1&1&1&1\\10&1&1&1 \end{bmatrix}$$ ``` case3 = ConfusionMatrix(matrix={"Class1": {"Class1": 1, "Class2":1, "Class3":1, "Class4":1}, "Class2": {"Class1": 1, "Class2":1, "Class3":1, "Class4":1}, "Class3": {"Class1": 1, "Class2":1, "Class3":1, "Class4":1}, "Class4": {"Class1": 10, "Class2":1, "Class3":1, "Class4":1}}) case3.print_normalized_matrix() print('ACC:',case3.ACC) print('MCC:',case3.MCC) print('CEN:',case3.CEN) print('MCEN:',case3.MCEN) print('DP:',case3.DP) print('Kappa:',case3.Kappa) print('RCI:',case3.RCI) print('SOA1:',case3.SOA1) ``` ### Case4 (A class is very unbalaned and get bad result) $$Case_4=\begin{bmatrix}1 & 1 &1&1 \\1 & 1&1&1\\1&1&1&1\\10000&1&1&1 \end{bmatrix}$$ ``` case4 = ConfusionMatrix(matrix={"Class1": {"Class1": 1, "Class2":1, "Class3":1, "Class4":1}, "Class2": {"Class1": 1, "Class2":1, "Class3":1, "Class4":1}, "Class3": {"Class1": 1, "Class2":1, "Class3":1, "Class4":1}, "Class4": {"Class1": 10000, "Class2":1, "Class3":1, "Class4":1}}) case3.print_normalized_matrix() print('ACC:',case4.ACC) print('MCC:',case4.MCC) print('CEN:',case4.CEN) print('MCEN:',case4.MCEN) print('DP:',case4.DP) print('Kappa:',case4.Kappa) print('RCI:',case4.RCI) print('SOA1:',case4.SOA1) ``` ### Case5 (A class is very unbalaned and get bad result) $$Case_5=\begin{bmatrix}1 & 1 &1&1 \\1 & 1&1&1\\1&1&1&1\\10&10&10&10 \end{bmatrix}$$ ``` case5 = ConfusionMatrix(matrix={"Class1": {"Class1": 1, "Class2":1, "Class3":1, "Class4":1}, "Class2": {"Class1": 1, "Class2":1, "Class3":1, "Class4":1}, "Class3": {"Class1": 1, "Class2":1, "Class3":1, "Class4":1}, "Class4": {"Class1": 10, "Class2":10, "Class3":10, "Class4":10}}) case5.print_normalized_matrix() print('ACC:',case5.ACC) print('MCC:',case5.MCC) print('CEN:',case5.CEN) print('MCEN:',case5.MCEN) print('DP:',case5.DP) print('Kappa:',case5.Kappa) print('RCI:',case5.RCI) print('SOA1:',case5.SOA1) ``` ### Case6 (A class is very unbalaned and get bad result) $$Case_6=\begin{bmatrix}1 & 1 &1&1 \\1 & 1&1&1\\1&1&1&1\\10000&10000&10000&10000 \end{bmatrix}$$ ``` case6 = ConfusionMatrix(matrix={"Class1": {"Class1": 1, "Class2":1, "Class3":1, "Class4":1}, "Class2": {"Class1": 1, "Class2":1, "Class3":1, "Class4":1}, "Class3": {"Class1": 1, "Class2":1, "Class3":1, "Class4":1}, "Class4": {"Class1": 10000, "Class2":10000, "Class3":10000, "Class4":10000}}) case6.print_normalized_matrix() print('ACC:',case6.ACC) print('MCC:',case6.MCC) print('CEN:',case6.CEN) print('MCEN:',case6.MCEN) print('DP:',case6.DP) print('Kappa:',case6.Kappa) print('RCI:',case6.RCI) print('SOA1:',case6.SOA1) ```
github_jupyter
import sys try: import google.colab !{sys.executable} -m pip -q -q install pycm except: pass from pycm import ConfusionMatrix case1 = ConfusionMatrix(matrix={"Class1": {"Class1": 26900, "Class2":40}, "Class2": {"Class1": 25, "Class2": 500}}) case1.print_normalized_matrix() print('ACC:',case1.ACC) print('MCC:',case1.MCC) print('CEN:',case1.CEN) print('MCEN:',case1.MCEN) print('DP:',case1.DP) print('Kappa:',case1.Kappa) print('RCI:',case1.RCI) print('SOA1:',case1.SOA1) case2 = ConfusionMatrix(matrix={"Class1": {"Class1": 29600, "Class2":40}, "Class2": {"Class1": 500, "Class2": 25}}) case2.print_normalized_matrix() print('ACC:',case2.ACC) print('MCC:',case2.MCC) print('CEN:',case2.CEN) print('MCEN:',case2.MCEN) print('DP:',case2.DP) print('Kappa:',case2.Kappa) print('RCI:',case2.RCI) print('SOA1:',case2.SOA1) case3 = ConfusionMatrix(matrix={"Class1": {"Class1": 40, "Class2":26900}, "Class2": {"Class1": 25, "Class2": 500}}) case3.print_normalized_matrix() print('ACC:',case3.ACC) print('MCC:',case3.MCC) print('CEN:',case3.CEN) print('MCEN:',case3.MCEN) print('DP:',case3.DP) print('Kappa:',case3.Kappa) print('RCI:',case3.RCI) print('SOA1:',case3.SOA1) case1 = ConfusionMatrix(matrix={"Class1": {"Class1": 4, "Class2":0, "Class3":0, "Class4":1}, "Class2": {"Class1": 0, "Class2":4, "Class3":1, "Class4":0}, "Class3": {"Class1": 0, "Class2":1, "Class3":4, "Class4":0}, "Class4": {"Class1": 0, "Class2":0, "Class3":1, "Class4":40000}}) case1.print_normalized_matrix() print('ACC:',case1.ACC) print('MCC:',case1.MCC) print('CEN:',case1.CEN) print('MCEN:',case1.MCEN) print('DP:',case1.DP) print('Kappa:',case1.Kappa) print('RCI:',case1.RCI) print('SOA1:',case1.SOA1) case2 = ConfusionMatrix(matrix={"Class1": {"Class1": 1, "Class2":1, "Class3":1, "Class4":1}, "Class2": {"Class1": 1, "Class2":1, "Class3":1, "Class4":1}, "Class3": {"Class1": 1, "Class2":1, "Class3":1, "Class4":1}, "Class4": {"Class1": 1, "Class2":1, "Class3":1, "Class4":1}}) case2.print_normalized_matrix() print('ACC:',case2.ACC) print('MCC:',case2.MCC) print('CEN:',case2.CEN) print('MCEN:',case2.MCEN) print('DP:',case2.DP) print('Kappa:',case2.Kappa) print('RCI:',case2.RCI) print('SOA1:',case2.SOA1) case3 = ConfusionMatrix(matrix={"Class1": {"Class1": 1, "Class2":1, "Class3":1, "Class4":1}, "Class2": {"Class1": 1, "Class2":1, "Class3":1, "Class4":1}, "Class3": {"Class1": 1, "Class2":1, "Class3":1, "Class4":1}, "Class4": {"Class1": 10, "Class2":1, "Class3":1, "Class4":1}}) case3.print_normalized_matrix() print('ACC:',case3.ACC) print('MCC:',case3.MCC) print('CEN:',case3.CEN) print('MCEN:',case3.MCEN) print('DP:',case3.DP) print('Kappa:',case3.Kappa) print('RCI:',case3.RCI) print('SOA1:',case3.SOA1) case4 = ConfusionMatrix(matrix={"Class1": {"Class1": 1, "Class2":1, "Class3":1, "Class4":1}, "Class2": {"Class1": 1, "Class2":1, "Class3":1, "Class4":1}, "Class3": {"Class1": 1, "Class2":1, "Class3":1, "Class4":1}, "Class4": {"Class1": 10000, "Class2":1, "Class3":1, "Class4":1}}) case3.print_normalized_matrix() print('ACC:',case4.ACC) print('MCC:',case4.MCC) print('CEN:',case4.CEN) print('MCEN:',case4.MCEN) print('DP:',case4.DP) print('Kappa:',case4.Kappa) print('RCI:',case4.RCI) print('SOA1:',case4.SOA1) case5 = ConfusionMatrix(matrix={"Class1": {"Class1": 1, "Class2":1, "Class3":1, "Class4":1}, "Class2": {"Class1": 1, "Class2":1, "Class3":1, "Class4":1}, "Class3": {"Class1": 1, "Class2":1, "Class3":1, "Class4":1}, "Class4": {"Class1": 10, "Class2":10, "Class3":10, "Class4":10}}) case5.print_normalized_matrix() print('ACC:',case5.ACC) print('MCC:',case5.MCC) print('CEN:',case5.CEN) print('MCEN:',case5.MCEN) print('DP:',case5.DP) print('Kappa:',case5.Kappa) print('RCI:',case5.RCI) print('SOA1:',case5.SOA1) case6 = ConfusionMatrix(matrix={"Class1": {"Class1": 1, "Class2":1, "Class3":1, "Class4":1}, "Class2": {"Class1": 1, "Class2":1, "Class3":1, "Class4":1}, "Class3": {"Class1": 1, "Class2":1, "Class3":1, "Class4":1}, "Class4": {"Class1": 10000, "Class2":10000, "Class3":10000, "Class4":10000}}) case6.print_normalized_matrix() print('ACC:',case6.ACC) print('MCC:',case6.MCC) print('CEN:',case6.CEN) print('MCEN:',case6.MCEN) print('DP:',case6.DP) print('Kappa:',case6.Kappa) print('RCI:',case6.RCI) print('SOA1:',case6.SOA1)
0.170784
0.88573
Notebook for converting models to onnx (Obsolete as this is now also implemented in the main codebase) ``` from transformers.convert_graph_to_onnx import convert from transformers import GPT2Tokenizer, GPT2LMHeadModel from onnxruntime_tools import optimizer from os import environ from psutil import cpu_count import torch import torch.nn.functional as F import numpy as np from src.data_utils import encode, decode environ["OMP_NUM_THREADS"] = str(cpu_count(logical=True)) environ["OMP_WAIT_POLICY"] = 'ACTIVE' from onnxruntime import InferenceSession, SessionOptions, get_all_providers model_path = "output/nl2bash/07-31_14:57:12" model_name = "gpt2-medium" model = GPT2LMHeadModel.from_pretrained(model_path) model.to('cuda') tokenizer = GPT2Tokenizer.from_pretrained(model_name) convert(framework="pt", model=model_path, tokenizer=model_name, output="onnx/gpt2.onnx", opset=11) optimized_model = optimizer.optimize_model("onnx/gpt2.onnx", model_type=model_name) #optimized_model.convert_model_float32_to_float16() optimized_model.save_model_to_file("onnx/opt.onnx") def create_model_for_provider(model_path: str, provider: str) -> InferenceSession: assert provider in get_all_providers(), f"provider {provider} not found, {get_all_providers()}" # Few properties than might have an impact on performances (provided by MS) options = SessionOptions() options.intra_op_num_threads = 1 # Load the model as a graph and prepare the CPU backend return InferenceSession(model_path, options, providers=[provider]) onnx_model = create_model_for_provider("onnx/gpt2.onnx", "CUDAExecutionProvider") def onnx_predict(query): query = encode(query) model_inputs = tokenizer.encode_plus(query, return_tensors="pt") inputs_onnx = {k: v.cpu().detach().numpy() for k, v in model_inputs.items() if k=='input_ids'} # Run the model (None = get all the outputs) for _ in range(100): #print(inputs_onnx) logits = onnx_model.run(None, inputs_onnx)[0][:,-1,:] logits = model.lm_head(torch.tensor(logits).to('cuda')) log_probs = F.softmax(logits, dim=-1) _, prev = torch.topk(log_probs, k=1) token = prev.item() if token == 198: break inputs_onnx['input_ids'] = np.atleast_2d(np.append(inputs_onnx['input_ids'], prev.cpu().numpy())) return decode(tokenizer, inputs_onnx['input_ids'][0]) %%time print(onnx_predict('Rename "file.txt" in directories "v_1", "v_2", and "v_3" each to "v_1.txt", "v_2.txt", and "v_3.txt" respectively and print the conversion')) %load_ext line_profiler %lprun -f onnx_predict onnx_predict('Rename "file.txt" in directories "v_1", "v_2", and "v_3" each to "v_1.txt", "v_2.txt", and "v_3.txt" respectively and print the conversion') ```
github_jupyter
from transformers.convert_graph_to_onnx import convert from transformers import GPT2Tokenizer, GPT2LMHeadModel from onnxruntime_tools import optimizer from os import environ from psutil import cpu_count import torch import torch.nn.functional as F import numpy as np from src.data_utils import encode, decode environ["OMP_NUM_THREADS"] = str(cpu_count(logical=True)) environ["OMP_WAIT_POLICY"] = 'ACTIVE' from onnxruntime import InferenceSession, SessionOptions, get_all_providers model_path = "output/nl2bash/07-31_14:57:12" model_name = "gpt2-medium" model = GPT2LMHeadModel.from_pretrained(model_path) model.to('cuda') tokenizer = GPT2Tokenizer.from_pretrained(model_name) convert(framework="pt", model=model_path, tokenizer=model_name, output="onnx/gpt2.onnx", opset=11) optimized_model = optimizer.optimize_model("onnx/gpt2.onnx", model_type=model_name) #optimized_model.convert_model_float32_to_float16() optimized_model.save_model_to_file("onnx/opt.onnx") def create_model_for_provider(model_path: str, provider: str) -> InferenceSession: assert provider in get_all_providers(), f"provider {provider} not found, {get_all_providers()}" # Few properties than might have an impact on performances (provided by MS) options = SessionOptions() options.intra_op_num_threads = 1 # Load the model as a graph and prepare the CPU backend return InferenceSession(model_path, options, providers=[provider]) onnx_model = create_model_for_provider("onnx/gpt2.onnx", "CUDAExecutionProvider") def onnx_predict(query): query = encode(query) model_inputs = tokenizer.encode_plus(query, return_tensors="pt") inputs_onnx = {k: v.cpu().detach().numpy() for k, v in model_inputs.items() if k=='input_ids'} # Run the model (None = get all the outputs) for _ in range(100): #print(inputs_onnx) logits = onnx_model.run(None, inputs_onnx)[0][:,-1,:] logits = model.lm_head(torch.tensor(logits).to('cuda')) log_probs = F.softmax(logits, dim=-1) _, prev = torch.topk(log_probs, k=1) token = prev.item() if token == 198: break inputs_onnx['input_ids'] = np.atleast_2d(np.append(inputs_onnx['input_ids'], prev.cpu().numpy())) return decode(tokenizer, inputs_onnx['input_ids'][0]) %%time print(onnx_predict('Rename "file.txt" in directories "v_1", "v_2", and "v_3" each to "v_1.txt", "v_2.txt", and "v_3.txt" respectively and print the conversion')) %load_ext line_profiler %lprun -f onnx_predict onnx_predict('Rename "file.txt" in directories "v_1", "v_2", and "v_3" each to "v_1.txt", "v_2.txt", and "v_3.txt" respectively and print the conversion')
0.669529
0.519521
Comparing GOES XRS 15 and 16 - 1s from fido/sunpy and direct download of avg1min * 25-May-2020 IGH ``` import matplotlib import matplotlib.pyplot as plt from sunpy import timeseries as ts from sunpy.net import Fido from sunpy.net import attrs as a # Just setup plot fonts plt.rcParams.update({'font.size': 18,'font.family':"sans-serif",\ 'font.sans-serif':"Arial",'mathtext.default':"regular"}) # Find and download the GOES15 and 16 for event (which also have GOES14 and 17) trange=a.Time("2018-06-21 01:00","2018-06-21 01:30") # rg15 = Fido.search(trange, a.Instrument("XRS"), a.goes.SatelliteNumber(15)) # print(rg15) # rg16 = Fido.search(trange, a.Instrument("XRS"), a.goes.SatelliteNumber(16)) # print(rg16) # Download the data outdir='/Users/iain/sunpy/data/' # fg15 = Fido.fetch(rg15,path=outdir) # fg16 = Fido.fetch(rg16,path=outdir) # These are the default ones from Fido, which might not be optimal ones..... fn15=outdir+"sci_gxrs-l2-irrad_g15_d20180621_v0-0-0.nc" fn16=outdir+"sci_xrsf-l2-flx1s_g16_d20180621_v2-1-0.nc" # print(fn15,fn16) g15 = ts.TimeSeries(fn15, concatenate=True) g16 = ts.TimeSeries(fn16, concatenate=True) tg15=g15.truncate(trange.start.iso,trange.end.iso) tg16=g16.truncate(trange.start.iso,trange.end.iso) tg15_tims=tg15.index tg15_x05=tg15.quantity("xrsa").value tg15_x18=tg15.quantity("xrsb").value tg16_tims=tg16.index tg16_x05=tg16.quantity("xrsa").value tg16_x18=tg16.quantity("xrsb").value fig,ax = plt.subplots(figsize=(10, 6)) plt.plot(tg15_tims,tg15_x05,drawstyle='steps-post',marker=None,color='darkblue',lw=2,label='G15: $0.5-4\;\AA$') plt.plot(tg15_tims,tg15_x18,drawstyle='steps-post',marker=None,color='firebrick',lw=2,label='G15: $1-8\;\AA$') plt.plot(tg16_tims,tg16_x05,drawstyle='steps-post',marker=None,color='dodgerblue',lw=2,label='G16: $0.5-4\;\AA$') plt.plot(tg16_tims,tg16_x18,drawstyle='steps-post',marker=None,color='goldenrod',lw=2,label='G16: $1-8\;\AA$') ax.set_ylabel("GOES XRS [$\mathrm{W\;m^{-2}}$] ") ax.set_xlabel("Start Time "+trange.start.iso[:-4]) ax.set_yscale("log") ax.set_ylim([1e-9,4e-5]) ax.set_xlim([trange.start.datetime,trange.end.datetime]) # precisely control the x time labels myFmt = matplotlib.dates.DateFormatter('%H:%M') majorx= matplotlib.dates.MinuteLocator(interval=5) minorx= matplotlib.dates.MinuteLocator(interval=1) ax.xaxis.set_major_locator(majorx) ax.xaxis.set_minor_locator(minorx) ax.xaxis.set_major_formatter(myFmt) plt.legend() plt.show() # Manually have downloaded the avg1min for GOES15 and GOES16 and put in outdir, load in here # https://satdat.ngdc.noaa.gov/sem/goes/data/science/xrs/goes15/xrsf-l2-avg1m_science/2018/06/sci_xrsf-l2-avg1m_g15_d20180621_v1-0-0.nc # https://data.ngdc.noaa.gov/platforms/solar-space-observing-satellites/goes/goes16/l2/data/xrsf-l2-avg1m_science/2018/06/sci_xrsf-l2-avg1m_g16_d20180621_v2-1-0.nc fn15_1=outdir+"sci_xrsf-l2-avg1m_g15_d20180621_v1-0-0.nc" fn16_1=outdir+"sci_xrsf-l2-avg1m_g16_d20180621_v2-1-0.nc" g15_1 = ts.TimeSeries(fn15_1, concatenate=True) tg15_1=g15_1.truncate(trange.start.iso,trange.end.iso) tg15_1_tims=tg15_1.index tg15_1_x05=tg15_1.quantity("xrsa").value tg15_1_x18=tg15_1.quantity("xrsb").value g16_1 = ts.TimeSeries(fn16_1, concatenate=True) tg16_1=g16_1.truncate(trange.start.iso,trange.end.iso) tg16_1_tims=tg16_1.index tg16_1_x05=tg16_1.quantity("xrsa").value tg16_1_x18=tg16_1.quantity("xrsb").value fig,ax = plt.subplots(figsize=(10, 6)) plt.plot(tg15_tims,tg15_x05,drawstyle='steps-post',marker=None,color='darkblue',lw=2,label='G15: $0.5-4\;\AA$') plt.plot(tg15_tims,tg15_x18,drawstyle='steps-post',marker=None,color='firebrick',lw=2,label='G15: $1-8\;\AA$') plt.plot(tg15_1_tims,tg15_1_x05,drawstyle='steps-post',marker=None,color='limegreen',lw=2,label='G15_1: $0.5-4\;\AA$') plt.plot(tg15_1_tims,tg15_1_x18,drawstyle='steps-post',marker=None,color='sienna',lw=2,label='G15_1: $1-8\;\AA$') ax.set_ylabel("GOES XRS [$\mathrm{W\;m^{-2}}$] ") ax.set_xlabel("Start Time "+trange.start.iso[:-4]) ax.set_yscale("log") ax.set_ylim([1e-9,4e-5]) ax.set_xlim([trange.start.datetime,trange.end.datetime]) # precisely control the x time labels myFmt = matplotlib.dates.DateFormatter('%H:%M') majorx= matplotlib.dates.MinuteLocator(interval=5) minorx= matplotlib.dates.MinuteLocator(interval=1) ax.xaxis.set_major_locator(majorx) ax.xaxis.set_minor_locator(minorx) ax.xaxis.set_major_formatter(myFmt) plt.legend() plt.show() fig,ax = plt.subplots(figsize=(10, 6)) plt.plot(tg16_tims,tg16_x05,drawstyle='steps-post',marker=None,color='dodgerblue',lw=2,label='G16: $0.5-4\;\AA$') plt.plot(tg16_tims,tg16_x18,drawstyle='steps-post',marker=None,color='goldenrod',lw=2,label='G16: $1-8\;\AA$') plt.plot(tg16_1_tims,tg16_1_x05,drawstyle='steps-post',marker=None,color='limegreen',lw=2,label='G16_1: $0.5-4\;\AA$') plt.plot(tg16_1_tims,tg16_1_x18,drawstyle='steps-post',marker=None,color='sienna',lw=2,label='G16_1: $1-8\;\AA$') ax.set_ylabel("GOES XRS [$\mathrm{W\;m^{-2}}$] ") ax.set_xlabel("Start Time "+trange.start.iso[:-4]) ax.set_yscale("log") ax.set_ylim([1e-9,4e-5]) ax.set_xlim([trange.start.datetime,trange.end.datetime]) # precisely control the x time labels myFmt = matplotlib.dates.DateFormatter('%H:%M') majorx= matplotlib.dates.MinuteLocator(interval=5) minorx= matplotlib.dates.MinuteLocator(interval=1) ax.xaxis.set_major_locator(majorx) ax.xaxis.set_minor_locator(minorx) ax.xaxis.set_major_formatter(myFmt) plt.legend() plt.show() fig,ax = plt.subplots(figsize=(10, 6)) plt.plot(tg15_1_tims,tg15_1_x05,drawstyle='steps-post',marker=None,color='limegreen',ls='--',lw=2,label='G15_1: $0.5-4\;\AA$') plt.plot(tg15_1_tims,tg15_1_x18,drawstyle='steps-post',marker=None,color='sienna',ls='--',lw=2,label='G15_1: $1-8\;\AA$') plt.plot(tg16_1_tims,tg16_1_x05,drawstyle='steps-post',marker=None,color='limegreen',lw=2,label='G16_1: $0.5-4\;\AA$') plt.plot(tg16_1_tims,tg16_1_x18,drawstyle='steps-post',marker=None,color='sienna',lw=2,label='G16_1: $1-8\;\AA$') ax.set_ylabel("GOES XRS [$\mathrm{W\;m^{-2}}$] ") ax.set_xlabel("Start Time "+trange.start.iso[:-4]) ax.set_yscale("log") ax.set_ylim([1e-9,4e-5]) ax.set_xlim([trange.start.datetime,trange.end.datetime]) # precisely control the x time labels myFmt = matplotlib.dates.DateFormatter('%H:%M') majorx= matplotlib.dates.MinuteLocator(interval=5) minorx= matplotlib.dates.MinuteLocator(interval=1) ax.xaxis.set_major_locator(majorx) ax.xaxis.set_minor_locator(minorx) ax.xaxis.set_major_formatter(myFmt) plt.legend() plt.show() # Print max value - i.e. GOES Class print("GOES15: {0:.2e}".format(max(tg15_x18))) print("GOES15 avg1min: {0:.2e}".format(max(tg15_1_x18))) print("GOES16: {0:.2e}".format(max(tg16_x18))) print("GOES16 avg1min: {0:.2e}".format(max(tg16_1_x18))) ```
github_jupyter
import matplotlib import matplotlib.pyplot as plt from sunpy import timeseries as ts from sunpy.net import Fido from sunpy.net import attrs as a # Just setup plot fonts plt.rcParams.update({'font.size': 18,'font.family':"sans-serif",\ 'font.sans-serif':"Arial",'mathtext.default':"regular"}) # Find and download the GOES15 and 16 for event (which also have GOES14 and 17) trange=a.Time("2018-06-21 01:00","2018-06-21 01:30") # rg15 = Fido.search(trange, a.Instrument("XRS"), a.goes.SatelliteNumber(15)) # print(rg15) # rg16 = Fido.search(trange, a.Instrument("XRS"), a.goes.SatelliteNumber(16)) # print(rg16) # Download the data outdir='/Users/iain/sunpy/data/' # fg15 = Fido.fetch(rg15,path=outdir) # fg16 = Fido.fetch(rg16,path=outdir) # These are the default ones from Fido, which might not be optimal ones..... fn15=outdir+"sci_gxrs-l2-irrad_g15_d20180621_v0-0-0.nc" fn16=outdir+"sci_xrsf-l2-flx1s_g16_d20180621_v2-1-0.nc" # print(fn15,fn16) g15 = ts.TimeSeries(fn15, concatenate=True) g16 = ts.TimeSeries(fn16, concatenate=True) tg15=g15.truncate(trange.start.iso,trange.end.iso) tg16=g16.truncate(trange.start.iso,trange.end.iso) tg15_tims=tg15.index tg15_x05=tg15.quantity("xrsa").value tg15_x18=tg15.quantity("xrsb").value tg16_tims=tg16.index tg16_x05=tg16.quantity("xrsa").value tg16_x18=tg16.quantity("xrsb").value fig,ax = plt.subplots(figsize=(10, 6)) plt.plot(tg15_tims,tg15_x05,drawstyle='steps-post',marker=None,color='darkblue',lw=2,label='G15: $0.5-4\;\AA$') plt.plot(tg15_tims,tg15_x18,drawstyle='steps-post',marker=None,color='firebrick',lw=2,label='G15: $1-8\;\AA$') plt.plot(tg16_tims,tg16_x05,drawstyle='steps-post',marker=None,color='dodgerblue',lw=2,label='G16: $0.5-4\;\AA$') plt.plot(tg16_tims,tg16_x18,drawstyle='steps-post',marker=None,color='goldenrod',lw=2,label='G16: $1-8\;\AA$') ax.set_ylabel("GOES XRS [$\mathrm{W\;m^{-2}}$] ") ax.set_xlabel("Start Time "+trange.start.iso[:-4]) ax.set_yscale("log") ax.set_ylim([1e-9,4e-5]) ax.set_xlim([trange.start.datetime,trange.end.datetime]) # precisely control the x time labels myFmt = matplotlib.dates.DateFormatter('%H:%M') majorx= matplotlib.dates.MinuteLocator(interval=5) minorx= matplotlib.dates.MinuteLocator(interval=1) ax.xaxis.set_major_locator(majorx) ax.xaxis.set_minor_locator(minorx) ax.xaxis.set_major_formatter(myFmt) plt.legend() plt.show() # Manually have downloaded the avg1min for GOES15 and GOES16 and put in outdir, load in here # https://satdat.ngdc.noaa.gov/sem/goes/data/science/xrs/goes15/xrsf-l2-avg1m_science/2018/06/sci_xrsf-l2-avg1m_g15_d20180621_v1-0-0.nc # https://data.ngdc.noaa.gov/platforms/solar-space-observing-satellites/goes/goes16/l2/data/xrsf-l2-avg1m_science/2018/06/sci_xrsf-l2-avg1m_g16_d20180621_v2-1-0.nc fn15_1=outdir+"sci_xrsf-l2-avg1m_g15_d20180621_v1-0-0.nc" fn16_1=outdir+"sci_xrsf-l2-avg1m_g16_d20180621_v2-1-0.nc" g15_1 = ts.TimeSeries(fn15_1, concatenate=True) tg15_1=g15_1.truncate(trange.start.iso,trange.end.iso) tg15_1_tims=tg15_1.index tg15_1_x05=tg15_1.quantity("xrsa").value tg15_1_x18=tg15_1.quantity("xrsb").value g16_1 = ts.TimeSeries(fn16_1, concatenate=True) tg16_1=g16_1.truncate(trange.start.iso,trange.end.iso) tg16_1_tims=tg16_1.index tg16_1_x05=tg16_1.quantity("xrsa").value tg16_1_x18=tg16_1.quantity("xrsb").value fig,ax = plt.subplots(figsize=(10, 6)) plt.plot(tg15_tims,tg15_x05,drawstyle='steps-post',marker=None,color='darkblue',lw=2,label='G15: $0.5-4\;\AA$') plt.plot(tg15_tims,tg15_x18,drawstyle='steps-post',marker=None,color='firebrick',lw=2,label='G15: $1-8\;\AA$') plt.plot(tg15_1_tims,tg15_1_x05,drawstyle='steps-post',marker=None,color='limegreen',lw=2,label='G15_1: $0.5-4\;\AA$') plt.plot(tg15_1_tims,tg15_1_x18,drawstyle='steps-post',marker=None,color='sienna',lw=2,label='G15_1: $1-8\;\AA$') ax.set_ylabel("GOES XRS [$\mathrm{W\;m^{-2}}$] ") ax.set_xlabel("Start Time "+trange.start.iso[:-4]) ax.set_yscale("log") ax.set_ylim([1e-9,4e-5]) ax.set_xlim([trange.start.datetime,trange.end.datetime]) # precisely control the x time labels myFmt = matplotlib.dates.DateFormatter('%H:%M') majorx= matplotlib.dates.MinuteLocator(interval=5) minorx= matplotlib.dates.MinuteLocator(interval=1) ax.xaxis.set_major_locator(majorx) ax.xaxis.set_minor_locator(minorx) ax.xaxis.set_major_formatter(myFmt) plt.legend() plt.show() fig,ax = plt.subplots(figsize=(10, 6)) plt.plot(tg16_tims,tg16_x05,drawstyle='steps-post',marker=None,color='dodgerblue',lw=2,label='G16: $0.5-4\;\AA$') plt.plot(tg16_tims,tg16_x18,drawstyle='steps-post',marker=None,color='goldenrod',lw=2,label='G16: $1-8\;\AA$') plt.plot(tg16_1_tims,tg16_1_x05,drawstyle='steps-post',marker=None,color='limegreen',lw=2,label='G16_1: $0.5-4\;\AA$') plt.plot(tg16_1_tims,tg16_1_x18,drawstyle='steps-post',marker=None,color='sienna',lw=2,label='G16_1: $1-8\;\AA$') ax.set_ylabel("GOES XRS [$\mathrm{W\;m^{-2}}$] ") ax.set_xlabel("Start Time "+trange.start.iso[:-4]) ax.set_yscale("log") ax.set_ylim([1e-9,4e-5]) ax.set_xlim([trange.start.datetime,trange.end.datetime]) # precisely control the x time labels myFmt = matplotlib.dates.DateFormatter('%H:%M') majorx= matplotlib.dates.MinuteLocator(interval=5) minorx= matplotlib.dates.MinuteLocator(interval=1) ax.xaxis.set_major_locator(majorx) ax.xaxis.set_minor_locator(minorx) ax.xaxis.set_major_formatter(myFmt) plt.legend() plt.show() fig,ax = plt.subplots(figsize=(10, 6)) plt.plot(tg15_1_tims,tg15_1_x05,drawstyle='steps-post',marker=None,color='limegreen',ls='--',lw=2,label='G15_1: $0.5-4\;\AA$') plt.plot(tg15_1_tims,tg15_1_x18,drawstyle='steps-post',marker=None,color='sienna',ls='--',lw=2,label='G15_1: $1-8\;\AA$') plt.plot(tg16_1_tims,tg16_1_x05,drawstyle='steps-post',marker=None,color='limegreen',lw=2,label='G16_1: $0.5-4\;\AA$') plt.plot(tg16_1_tims,tg16_1_x18,drawstyle='steps-post',marker=None,color='sienna',lw=2,label='G16_1: $1-8\;\AA$') ax.set_ylabel("GOES XRS [$\mathrm{W\;m^{-2}}$] ") ax.set_xlabel("Start Time "+trange.start.iso[:-4]) ax.set_yscale("log") ax.set_ylim([1e-9,4e-5]) ax.set_xlim([trange.start.datetime,trange.end.datetime]) # precisely control the x time labels myFmt = matplotlib.dates.DateFormatter('%H:%M') majorx= matplotlib.dates.MinuteLocator(interval=5) minorx= matplotlib.dates.MinuteLocator(interval=1) ax.xaxis.set_major_locator(majorx) ax.xaxis.set_minor_locator(minorx) ax.xaxis.set_major_formatter(myFmt) plt.legend() plt.show() # Print max value - i.e. GOES Class print("GOES15: {0:.2e}".format(max(tg15_x18))) print("GOES15 avg1min: {0:.2e}".format(max(tg15_1_x18))) print("GOES16: {0:.2e}".format(max(tg16_x18))) print("GOES16 avg1min: {0:.2e}".format(max(tg16_1_x18)))
0.264833
0.674493
``` import sys,os os.chdir('.\..\..') import deep_nn.deep_nn_model as nn import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.preprocessing import MinMaxScaler from keras.models import Sequential from keras.layers import Dense from keras.wrappers.scikit_learn import KerasRegressor from keras import optimizers train100 = pd.read_csv("./data_analysis/projekt1/regression/data.activation.train.100.csv") test100 = pd.read_csv("./data_analysis/projekt1/regression/data.activation.test.100.csv") len(train100) plt.scatter(train100.x, train100.y) X = train100.x.values.reshape(1, -1) print(X.shape) Y = train100.y.values.reshape(1, -1) print(Y.shape) Xt = test100.x.values.reshape(1, -1) print(Xt.shape) Yt = test100.y.values.reshape(1, -1) print(Yt.shape) X_scaler = MinMaxScaler() Y_scaler = MinMaxScaler() X_scaled = X_scaler.fit_transform(train100.x.values.reshape(-1, 1)).reshape(1, -1) Y_scaled = Y_scaler.fit_transform(train100.y.values.reshape(-1, 1)).reshape(1, -1) Xt_scaled = X_scaler.transform(test100.x.values.reshape(-1, 1)).reshape(1, -1) Yt_scaled = Y_scaler.transform(test100.y.values.reshape(-1, 1)).reshape(1, -1) model_builder = nn.SequentialBuilder() model_builder.add_dense(1, "relu") model_builder.add_dense(12, "relu") model_builder.add_dense(12, "relu") model_builder.add_dense(12, "relu") model_builder.add_dense(12, "relu") model_builder.add_dense(1, "linear") model = model_builder.compile("MSE") parameters2, costs = model.fit(X_scaled, Y_scaled, learning_rate=0.05, momentum=0.9, mini_batch_size=64, num_epochs=10000) plt.plot(costs) yp = model.predict(X_scaled) plt.autoscale(enable=True, axis='both', tight=None) plt.scatter(X_scaled, Y_scaled) plt.scatter(X_scaled, yp) plt.show() yp = model.predict(Xt_scaled) yt = model.predict(Xt_scaled) plt.autoscale(enable=True, axis='both', tight=None) plt.scatter(Xt_scaled, Yt_scaled) plt.scatter(Xt_scaled, yt) plt.show() # define base model def baseline_model(): # create model model = Sequential() #[1, 12, 12, 12, 12, 1] model.add(Dense(1, input_dim=1, kernel_initializer='normal', activation='relu')) model.add(Dense(12, kernel_initializer='normal', activation='relu')) model.add(Dense(12, kernel_initializer='normal', activation='relu')) model.add(Dense(12, kernel_initializer='normal', activation='relu')) model.add(Dense(12, kernel_initializer='normal', activation='relu')) model.add(Dense(1, kernel_initializer='normal', activation='linear')) # Compile model sgd = optimizers.Adam(lr=0.1) model.compile(loss='mean_squared_error', optimizer=sgd) return model estimator = KerasRegressor(build_fn=baseline_model, epochs=1000) X_s = X_scaled.T print(X_s.shape) Y_s = Y_scaled.T print(Y_s.shape) history = estimator.fit(X_s, Y_s) plt.plot(history.history['loss']) y_pred_keras = estimator.predict(X_s) plt.autoscale(enable=True, axis='both', tight=None) plt.scatter(X_s, Y_s) plt.scatter(X_s, y_pred_keras) plt.show() ```
github_jupyter
import sys,os os.chdir('.\..\..') import deep_nn.deep_nn_model as nn import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.preprocessing import MinMaxScaler from keras.models import Sequential from keras.layers import Dense from keras.wrappers.scikit_learn import KerasRegressor from keras import optimizers train100 = pd.read_csv("./data_analysis/projekt1/regression/data.activation.train.100.csv") test100 = pd.read_csv("./data_analysis/projekt1/regression/data.activation.test.100.csv") len(train100) plt.scatter(train100.x, train100.y) X = train100.x.values.reshape(1, -1) print(X.shape) Y = train100.y.values.reshape(1, -1) print(Y.shape) Xt = test100.x.values.reshape(1, -1) print(Xt.shape) Yt = test100.y.values.reshape(1, -1) print(Yt.shape) X_scaler = MinMaxScaler() Y_scaler = MinMaxScaler() X_scaled = X_scaler.fit_transform(train100.x.values.reshape(-1, 1)).reshape(1, -1) Y_scaled = Y_scaler.fit_transform(train100.y.values.reshape(-1, 1)).reshape(1, -1) Xt_scaled = X_scaler.transform(test100.x.values.reshape(-1, 1)).reshape(1, -1) Yt_scaled = Y_scaler.transform(test100.y.values.reshape(-1, 1)).reshape(1, -1) model_builder = nn.SequentialBuilder() model_builder.add_dense(1, "relu") model_builder.add_dense(12, "relu") model_builder.add_dense(12, "relu") model_builder.add_dense(12, "relu") model_builder.add_dense(12, "relu") model_builder.add_dense(1, "linear") model = model_builder.compile("MSE") parameters2, costs = model.fit(X_scaled, Y_scaled, learning_rate=0.05, momentum=0.9, mini_batch_size=64, num_epochs=10000) plt.plot(costs) yp = model.predict(X_scaled) plt.autoscale(enable=True, axis='both', tight=None) plt.scatter(X_scaled, Y_scaled) plt.scatter(X_scaled, yp) plt.show() yp = model.predict(Xt_scaled) yt = model.predict(Xt_scaled) plt.autoscale(enable=True, axis='both', tight=None) plt.scatter(Xt_scaled, Yt_scaled) plt.scatter(Xt_scaled, yt) plt.show() # define base model def baseline_model(): # create model model = Sequential() #[1, 12, 12, 12, 12, 1] model.add(Dense(1, input_dim=1, kernel_initializer='normal', activation='relu')) model.add(Dense(12, kernel_initializer='normal', activation='relu')) model.add(Dense(12, kernel_initializer='normal', activation='relu')) model.add(Dense(12, kernel_initializer='normal', activation='relu')) model.add(Dense(12, kernel_initializer='normal', activation='relu')) model.add(Dense(1, kernel_initializer='normal', activation='linear')) # Compile model sgd = optimizers.Adam(lr=0.1) model.compile(loss='mean_squared_error', optimizer=sgd) return model estimator = KerasRegressor(build_fn=baseline_model, epochs=1000) X_s = X_scaled.T print(X_s.shape) Y_s = Y_scaled.T print(Y_s.shape) history = estimator.fit(X_s, Y_s) plt.plot(history.history['loss']) y_pred_keras = estimator.predict(X_s) plt.autoscale(enable=True, axis='both', tight=None) plt.scatter(X_s, Y_s) plt.scatter(X_s, y_pred_keras) plt.show()
0.681939
0.487429
RNN for text generation We will create a language model based on Shakespear's writings, and use it to generate new text similar to that of Shakespear. ``` import torch import torch.nn as nn import torch.autograd as autograd import torch.cuda as cuda import torch.optim as optim from torch.autograd import Variable import numpy as np import os ``` **Helper class to read in the texts, convert the words to integer indexes and provide lookup tables to convert any word to it's index and vice versa** ``` class Dictionary(object): def __init__(self): self.word2idx = {} self.idx2word = [] def add_word(self, word): if word not in self.word2idx: self.idx2word.append(word) self.word2idx[word] = len(self.idx2word) - 1 return self.word2idx[word] def __len__(self): return len(self.idx2word) class Corpus(object): def __init__(self, path): self.dictionary = Dictionary() # This is very english language specific # We will ingest only these characters: self.whitelist = [chr(i) for i in range(32, 127)] self.train = self.tokenize(os.path.join(path, 'train.txt')) self.valid = self.tokenize(os.path.join(path, 'valid.txt')) def tokenize(self, path): """Tokenizes a text file.""" assert os.path.exists(path) # Add words to the dictionary with open(path, 'r', encoding="utf8") as f: tokens = 0 for line in f: line = ''.join([c for c in line if c in self.whitelist]) words = line.split() + ['<eos>'] tokens += len(words) for word in words: self.dictionary.add_word(word) # Tokenize file content with open(path, 'r', encoding="utf8") as f: ids = torch.LongTensor(tokens) token = 0 for line in f: line = ''.join([c for c in line if c in self.whitelist]) words = line.split() + ['<eos>'] for word in words: ids[token] = self.dictionary.word2idx[word] token += 1 return ids !ls data/shakespear corpus = Corpus('./data/shakespear') print(corpus.dictionary.idx2word[10]) print(corpus.dictionary.word2idx['That']) print(corpus.train.size()) print(corpus.valid.size()) id = corpus.train[112] corpus.dictionary.idx2word[id] vocab_size = len(corpus.dictionary) print(vocab_size) ``` **The RNN model (using GRU cells)** ``` class RNNModel(nn.Module): def __init__(self, vocab_size, embed_size, hidden_size, num_layers, dropout=0.5): super(RNNModel, self).__init__() self.encoder = nn.Embedding(vocab_size, embed_size) self.drop1 = nn.Dropout(dropout) self.drop2 = nn.Dropout(dropout) self.rnn = nn.GRU(embed_size, hidden_size, num_layers, dropout=dropout) self.decoder = nn.Linear(hidden_size, vocab_size) self.init_weights() self.hidden_size = hidden_size self.num_layers = num_layers def init_weights(self): initrange = 0.1 self.encoder.weight.data.uniform_(-initrange, initrange) self.decoder.bias.data.fill_(0) self.decoder.weight.data.uniform_(-initrange, initrange) def forward(self, input, hidden): emb = self.drop1(self.encoder(input)) output, hidden = self.rnn(emb, hidden) output = self.drop2(output) decoded = self.decoder(output.view(output.size(0)*output.size(1), output.size(2))) return decoded.view(output.size(0), output.size(1), decoded.size(1)), hidden def init_hidden(self, batch_size): weight = next(self.parameters()).data return Variable(weight.new(self.num_layers, batch_size, self.hidden_size).zero_()) def batchify(data, batch_size): # Work out how cleanly we can divide the dataset into bsz parts. nbatch = data.size(0) // batch_size # Trim off any extra elements that wouldn't cleanly fit (remainders). data = data.narrow(0, 0, nbatch * batch_size) # Evenly divide the data across the bsz batches. data = data.view(batch_size, -1).t().contiguous() if cuda.is_available(): data = data.cuda() return data dummy_data = "Once upon a time there was a good king and a queen" dummy_data_idx = [corpus.dictionary.word2idx[w] for w in dummy_data.split()] dummy_tensor = torch.LongTensor(dummy_data_idx) op = batchify(dummy_tensor, 2) for row in op: print("%10s %10s" % (corpus.dictionary.idx2word[row[0]], corpus.dictionary.idx2word[row[1]])) bs_train = 20 # batch size for training set bs_valid = 10 # batch size for validation set bptt_size = 35 # number of times to unroll the graph for back propagation through time clip = 0.25 # gradient clipping to check exploding gradient embed_size = 200 # size of the embedding vector hidden_size = 200 # size of the hidden state in the RNN num_layers = 2 # number of RNN layres to use dropout_pct = 0.5 # %age of neurons to drop out for regularization train_data = batchify(corpus.train, bs_train) val_data = batchify(corpus.valid, bs_valid) train_data.shape model = RNNModel(vocab_size, embed_size, hidden_size, num_layers, dropout_pct) if cuda.is_available(): model.cuda() criterion = nn.CrossEntropyLoss() def get_batch(source, i, evaluation=False): seq_len = min(bptt_size, len(source) - 1 - i) data = Variable(source[i:i+seq_len], volatile=evaluation) target = Variable(source[i+1:i+1+seq_len].view(-1)) if cuda.is_available(): data = data.cuda() target = target.cuda() return data, target data, target = get_batch(train_data, 1) data.shape target.shape ``` **Model Training** ``` def train(data_source, lr): # Turn on training mode which enables dropout. model.train() total_loss = 0 hidden = model.init_hidden(bs_train) optimizer = optim.Adam(model.parameters(), lr=lr) for batch, i in enumerate(range(0, data_source.size(0) - 1, bptt_size)): data, targets = get_batch(data_source, i) # Starting each batch, we detach the hidden state from how it was previously produced. # If we didn't, the model would try backpropagating all the way to start of the dataset. hidden = Variable(hidden.data) if cuda.is_available(): hidden = hidden.cuda() # model.zero_grad() optimizer.zero_grad() output, hidden = model(data, hidden) loss = criterion(output.view(-1, vocab_size), targets) loss.backward() # `clip_grad_norm` helps prevent the exploding gradient problem in RNNs / LSTMs. torch.nn.utils.clip_grad_norm(model.parameters(), clip) optimizer.step() total_loss += len(data) * loss.data return total_loss[0] / len(data_source) def evaluate(data_source): # Turn on evaluation mode which disables dropout. model.eval() total_loss = 0 hidden = model.init_hidden(bs_valid) for i in range(0, data_source.size(0) - 1, bptt_size): data, targets = get_batch(data_source, i, evaluation=True) if cuda.is_available(): hidden = hidden.cuda() output, hidden = model(data, hidden) output_flat = output.view(-1, vocab_size) total_loss += len(data) * criterion(output_flat, targets).data hidden = Variable(hidden.data) return total_loss[0] / len(data_source) # Loop over epochs. best_val_loss = None def run(epochs, lr): global best_val_loss for epoch in range(0, epochs): train_loss = train(train_data, lr) val_loss = evaluate(val_data) print("Train Loss: ", train_loss, "Valid Loss: ", val_loss) if not best_val_loss or val_loss < best_val_loss: best_val_loss = val_loss torch.save(model.state_dict(), "./4.model.pth") run(5, 0.001) run(5, 0.001) ``` **Text Generation** ``` num_words = 200 temperature = 1 model = RNNModel(vocab_size, embed_size, hidden_size, num_layers, dropout_pct) model.load_state_dict(torch.load("./4.model.pth")) if cuda.is_available(): model.cuda() model.eval() # https://nlp.stanford.edu/blog/maximum-likelihood-decoding-with-rnns-the-good-the-bad-and-the-ugly/ # Which sample is better? It depends on your personal taste. The high temperature # sample displays greater linguistic variety, but the low temperature sample is # more grammatically correct. Such is the world of temperature sampling - lowering # the temperature allows you to focus on higher probability output sequences and # smooth over deficiencies of the model. # If we set a high temperature, we can get more entropic (*noisier*) probabilities # Often we want to sample with low temperatures to produce sharp probabilities temperature = 0.8 hidden = model.init_hidden(1) idx = corpus.dictionary.word2idx['I'] input = Variable(torch.LongTensor([[idx]]).long(), volatile=True) if cuda.is_available(): input.data = input.data.cuda() print(corpus.dictionary.idx2word[idx], '', end='') for i in range(num_words): output, hidden = model(input, hidden) word_weights = output.squeeze().data.div(temperature).exp().cpu() word_idx = torch.multinomial(word_weights, 1)[0] input.data.fill_(word_idx) word = corpus.dictionary.idx2word[word_idx] if word == '<eos>': print('') else: print(word + ' ', end='') ``` **Things to explore** * Play with the hyperparameters * Play with the model architecture * Run this on a different dataset * Experiment with attention * Compare perplexity
github_jupyter
import torch import torch.nn as nn import torch.autograd as autograd import torch.cuda as cuda import torch.optim as optim from torch.autograd import Variable import numpy as np import os class Dictionary(object): def __init__(self): self.word2idx = {} self.idx2word = [] def add_word(self, word): if word not in self.word2idx: self.idx2word.append(word) self.word2idx[word] = len(self.idx2word) - 1 return self.word2idx[word] def __len__(self): return len(self.idx2word) class Corpus(object): def __init__(self, path): self.dictionary = Dictionary() # This is very english language specific # We will ingest only these characters: self.whitelist = [chr(i) for i in range(32, 127)] self.train = self.tokenize(os.path.join(path, 'train.txt')) self.valid = self.tokenize(os.path.join(path, 'valid.txt')) def tokenize(self, path): """Tokenizes a text file.""" assert os.path.exists(path) # Add words to the dictionary with open(path, 'r', encoding="utf8") as f: tokens = 0 for line in f: line = ''.join([c for c in line if c in self.whitelist]) words = line.split() + ['<eos>'] tokens += len(words) for word in words: self.dictionary.add_word(word) # Tokenize file content with open(path, 'r', encoding="utf8") as f: ids = torch.LongTensor(tokens) token = 0 for line in f: line = ''.join([c for c in line if c in self.whitelist]) words = line.split() + ['<eos>'] for word in words: ids[token] = self.dictionary.word2idx[word] token += 1 return ids !ls data/shakespear corpus = Corpus('./data/shakespear') print(corpus.dictionary.idx2word[10]) print(corpus.dictionary.word2idx['That']) print(corpus.train.size()) print(corpus.valid.size()) id = corpus.train[112] corpus.dictionary.idx2word[id] vocab_size = len(corpus.dictionary) print(vocab_size) class RNNModel(nn.Module): def __init__(self, vocab_size, embed_size, hidden_size, num_layers, dropout=0.5): super(RNNModel, self).__init__() self.encoder = nn.Embedding(vocab_size, embed_size) self.drop1 = nn.Dropout(dropout) self.drop2 = nn.Dropout(dropout) self.rnn = nn.GRU(embed_size, hidden_size, num_layers, dropout=dropout) self.decoder = nn.Linear(hidden_size, vocab_size) self.init_weights() self.hidden_size = hidden_size self.num_layers = num_layers def init_weights(self): initrange = 0.1 self.encoder.weight.data.uniform_(-initrange, initrange) self.decoder.bias.data.fill_(0) self.decoder.weight.data.uniform_(-initrange, initrange) def forward(self, input, hidden): emb = self.drop1(self.encoder(input)) output, hidden = self.rnn(emb, hidden) output = self.drop2(output) decoded = self.decoder(output.view(output.size(0)*output.size(1), output.size(2))) return decoded.view(output.size(0), output.size(1), decoded.size(1)), hidden def init_hidden(self, batch_size): weight = next(self.parameters()).data return Variable(weight.new(self.num_layers, batch_size, self.hidden_size).zero_()) def batchify(data, batch_size): # Work out how cleanly we can divide the dataset into bsz parts. nbatch = data.size(0) // batch_size # Trim off any extra elements that wouldn't cleanly fit (remainders). data = data.narrow(0, 0, nbatch * batch_size) # Evenly divide the data across the bsz batches. data = data.view(batch_size, -1).t().contiguous() if cuda.is_available(): data = data.cuda() return data dummy_data = "Once upon a time there was a good king and a queen" dummy_data_idx = [corpus.dictionary.word2idx[w] for w in dummy_data.split()] dummy_tensor = torch.LongTensor(dummy_data_idx) op = batchify(dummy_tensor, 2) for row in op: print("%10s %10s" % (corpus.dictionary.idx2word[row[0]], corpus.dictionary.idx2word[row[1]])) bs_train = 20 # batch size for training set bs_valid = 10 # batch size for validation set bptt_size = 35 # number of times to unroll the graph for back propagation through time clip = 0.25 # gradient clipping to check exploding gradient embed_size = 200 # size of the embedding vector hidden_size = 200 # size of the hidden state in the RNN num_layers = 2 # number of RNN layres to use dropout_pct = 0.5 # %age of neurons to drop out for regularization train_data = batchify(corpus.train, bs_train) val_data = batchify(corpus.valid, bs_valid) train_data.shape model = RNNModel(vocab_size, embed_size, hidden_size, num_layers, dropout_pct) if cuda.is_available(): model.cuda() criterion = nn.CrossEntropyLoss() def get_batch(source, i, evaluation=False): seq_len = min(bptt_size, len(source) - 1 - i) data = Variable(source[i:i+seq_len], volatile=evaluation) target = Variable(source[i+1:i+1+seq_len].view(-1)) if cuda.is_available(): data = data.cuda() target = target.cuda() return data, target data, target = get_batch(train_data, 1) data.shape target.shape def train(data_source, lr): # Turn on training mode which enables dropout. model.train() total_loss = 0 hidden = model.init_hidden(bs_train) optimizer = optim.Adam(model.parameters(), lr=lr) for batch, i in enumerate(range(0, data_source.size(0) - 1, bptt_size)): data, targets = get_batch(data_source, i) # Starting each batch, we detach the hidden state from how it was previously produced. # If we didn't, the model would try backpropagating all the way to start of the dataset. hidden = Variable(hidden.data) if cuda.is_available(): hidden = hidden.cuda() # model.zero_grad() optimizer.zero_grad() output, hidden = model(data, hidden) loss = criterion(output.view(-1, vocab_size), targets) loss.backward() # `clip_grad_norm` helps prevent the exploding gradient problem in RNNs / LSTMs. torch.nn.utils.clip_grad_norm(model.parameters(), clip) optimizer.step() total_loss += len(data) * loss.data return total_loss[0] / len(data_source) def evaluate(data_source): # Turn on evaluation mode which disables dropout. model.eval() total_loss = 0 hidden = model.init_hidden(bs_valid) for i in range(0, data_source.size(0) - 1, bptt_size): data, targets = get_batch(data_source, i, evaluation=True) if cuda.is_available(): hidden = hidden.cuda() output, hidden = model(data, hidden) output_flat = output.view(-1, vocab_size) total_loss += len(data) * criterion(output_flat, targets).data hidden = Variable(hidden.data) return total_loss[0] / len(data_source) # Loop over epochs. best_val_loss = None def run(epochs, lr): global best_val_loss for epoch in range(0, epochs): train_loss = train(train_data, lr) val_loss = evaluate(val_data) print("Train Loss: ", train_loss, "Valid Loss: ", val_loss) if not best_val_loss or val_loss < best_val_loss: best_val_loss = val_loss torch.save(model.state_dict(), "./4.model.pth") run(5, 0.001) run(5, 0.001) num_words = 200 temperature = 1 model = RNNModel(vocab_size, embed_size, hidden_size, num_layers, dropout_pct) model.load_state_dict(torch.load("./4.model.pth")) if cuda.is_available(): model.cuda() model.eval() # https://nlp.stanford.edu/blog/maximum-likelihood-decoding-with-rnns-the-good-the-bad-and-the-ugly/ # Which sample is better? It depends on your personal taste. The high temperature # sample displays greater linguistic variety, but the low temperature sample is # more grammatically correct. Such is the world of temperature sampling - lowering # the temperature allows you to focus on higher probability output sequences and # smooth over deficiencies of the model. # If we set a high temperature, we can get more entropic (*noisier*) probabilities # Often we want to sample with low temperatures to produce sharp probabilities temperature = 0.8 hidden = model.init_hidden(1) idx = corpus.dictionary.word2idx['I'] input = Variable(torch.LongTensor([[idx]]).long(), volatile=True) if cuda.is_available(): input.data = input.data.cuda() print(corpus.dictionary.idx2word[idx], '', end='') for i in range(num_words): output, hidden = model(input, hidden) word_weights = output.squeeze().data.div(temperature).exp().cpu() word_idx = torch.multinomial(word_weights, 1)[0] input.data.fill_(word_idx) word = corpus.dictionary.idx2word[word_idx] if word == '<eos>': print('') else: print(word + ' ', end='')
0.87834
0.81309
# Parse Tracefiles to characterise variance You must change the location of the script dir if you want to use relative paths to the trace. Or , set the absolute path to the location of the directory containing the tracefiles. ``` import logging import pandas as pd import cx_Oracle import matplotlib.pyplot as plt import os import re import glob #abspath = os.path.abspath(__file__) #dname = os.path.dirname(abspath) #os.chdir(f"{dname}/") os.chdir("C:\\Users\\David Olivari\\Documents\\ONGOING DB WORK\\carsprd\\tracefiles_stuff\\bin") trcs = glob.glob('../*.trc') re_sess= re.compile('^\*\*\* SESSION ID:\((\d+\.\d+)\) (.+)$') re_systime=re.compile('^.+tim=*([0-9]+) .+') ``` ## parse the file convert durations to secs note how variables are initialised in the for loop ``` columns = ['filename','SessIdentifier' , 'sess_start' , 'sys_tm_max' , 'sys_tm_min', 'duration_secs'] sessions_list=[] for trace in trcs: with open(trace ) as f: min_sys_ts=999999999999999999 max_sys_ts=0 for line in f: sess_detail = re_sess.match(line) sys_ts = re_systime.match(line) if sess_detail: sess_tuple = sess_detail.groups(0) if sys_ts: t = int(sys_ts.groups(0)[0]) if min_sys_ts > t: min_sys_ts = t else: # may seem unnecessary, but tm doesn't have to be in order # e.g.loops if max_sys_ts < t: max_sys_ts = t duration = (max_sys_ts - min_sys_ts)/1000000 complete_tuple = tuple([os.path.basename(trace)]) + sess_tuple + (max_sys_ts,min_sys_ts,duration) sessions_list.append(complete_tuple) sessions_df =pd.DataFrame(sessions_list,columns = columns) sessions_df.describe() sessions_df.info() sessions_df.head(2) sessions_df['sess_start']=pd.to_datetime(sessions_df['sess_start'],errors='ignore') sessions_df.info() sessions_df.set_index('sess_start',inplace=True) sessions_df.sort_index(inplace=True) sessions_df ``` ## Scatter plot sessions vs duration ``` sessions_df.reset_index().plot.scatter(x = 'sess_start', y = 'duration_secs', grid =True, rot=45 ) ``` ## Sorted Data set by duration (descending) ``` sessions_df.sort_values(['duration_secs'],ascending=False) ``` ## Seaborn visual WIP ``` import seaborn as sns import matplotlib.pyplot as plt # Draw a scatter plot while assigning point colors and sizes to different # variables in the dataset f, ax = plt.subplots(figsize=(6.5, 6.5)) sns.despine(f, left=True, bottom=True) sns.scatterplot(x="sess_start", y="duration_secs", #hue="clarity", size="depth", palette="ch:r=-.2,d=.3_r", sizes=(1, 8), linewidth=0, data=sessions_df.reset_index(), ax=ax) ```
github_jupyter
import logging import pandas as pd import cx_Oracle import matplotlib.pyplot as plt import os import re import glob #abspath = os.path.abspath(__file__) #dname = os.path.dirname(abspath) #os.chdir(f"{dname}/") os.chdir("C:\\Users\\David Olivari\\Documents\\ONGOING DB WORK\\carsprd\\tracefiles_stuff\\bin") trcs = glob.glob('../*.trc') re_sess= re.compile('^\*\*\* SESSION ID:\((\d+\.\d+)\) (.+)$') re_systime=re.compile('^.+tim=*([0-9]+) .+') columns = ['filename','SessIdentifier' , 'sess_start' , 'sys_tm_max' , 'sys_tm_min', 'duration_secs'] sessions_list=[] for trace in trcs: with open(trace ) as f: min_sys_ts=999999999999999999 max_sys_ts=0 for line in f: sess_detail = re_sess.match(line) sys_ts = re_systime.match(line) if sess_detail: sess_tuple = sess_detail.groups(0) if sys_ts: t = int(sys_ts.groups(0)[0]) if min_sys_ts > t: min_sys_ts = t else: # may seem unnecessary, but tm doesn't have to be in order # e.g.loops if max_sys_ts < t: max_sys_ts = t duration = (max_sys_ts - min_sys_ts)/1000000 complete_tuple = tuple([os.path.basename(trace)]) + sess_tuple + (max_sys_ts,min_sys_ts,duration) sessions_list.append(complete_tuple) sessions_df =pd.DataFrame(sessions_list,columns = columns) sessions_df.describe() sessions_df.info() sessions_df.head(2) sessions_df['sess_start']=pd.to_datetime(sessions_df['sess_start'],errors='ignore') sessions_df.info() sessions_df.set_index('sess_start',inplace=True) sessions_df.sort_index(inplace=True) sessions_df sessions_df.reset_index().plot.scatter(x = 'sess_start', y = 'duration_secs', grid =True, rot=45 ) sessions_df.sort_values(['duration_secs'],ascending=False) import seaborn as sns import matplotlib.pyplot as plt # Draw a scatter plot while assigning point colors and sizes to different # variables in the dataset f, ax = plt.subplots(figsize=(6.5, 6.5)) sns.despine(f, left=True, bottom=True) sns.scatterplot(x="sess_start", y="duration_secs", #hue="clarity", size="depth", palette="ch:r=-.2,d=.3_r", sizes=(1, 8), linewidth=0, data=sessions_df.reset_index(), ax=ax)
0.240418
0.636466
``` ! pip install -U pip ! pip install -U torch==1.5.0 ! pip install -U torchtext==0.6.0 ! pip install -U matplotlib==3.2.1 ! pip install -U trains>=0.15.0 ! pip install -U tensorboard==2.2.1 import os import time import torch import torch.nn as nn import torch.nn.functional as F import torchtext from torchtext.datasets import text_classification from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter from trains import Task %matplotlib inline task = Task.init(project_name='Text Example', task_name='text classifier') configuration_dict = {'number_of_epochs': 6, 'batch_size': 16, 'ngrams': 2, 'base_lr': 1.0} configuration_dict = task.connect(configuration_dict) # enabling configuration override by trains print(configuration_dict) # printing actual configuration (after override in remote mode) if not os.path.isdir('./data'): os.mkdir('./data') train_dataset, test_dataset = text_classification.DATASETS['AG_NEWS'](root='./data', ngrams=configuration_dict.get('ngrams', 2)) vocabulary = train_dataset.get_vocab() def generate_batch(batch): label = torch.tensor([entry[0] for entry in batch]) # original data batch input are packed into a list and concatenated as a single tensor text = [entry[1] for entry in batch] # offsets is a tensor of delimiters to represent the beginning index of each sequence in the text tensor. offsets = [0] + [len(entry) for entry in text] # torch.Tensor.cumsum returns the cumulative sum of elements in the dimension dim. offsets = torch.tensor(offsets[:-1]).cumsum(dim=0) text = torch.cat(text) return text, offsets, label train_loader = torch.utils.data.DataLoader(train_dataset, batch_size = configuration_dict.get('batch_size', 16), shuffle = True, pin_memory=True, collate_fn=generate_batch) test_loader = torch.utils.data.DataLoader(test_dataset, batch_size = configuration_dict.get('batch_size', 16), shuffle = False, pin_memory=True, collate_fn=generate_batch) classes = ("World", "Sports", "Business", "Sci/Tec") class TextSentiment(nn.Module): def __init__(self, vocab_size, embed_dim, num_class): super().__init__() self.embedding = nn.EmbeddingBag(vocab_size, embed_dim, sparse=True) self.fc = nn.Linear(embed_dim, num_class) self.init_weights() def init_weights(self): initrange = 0.5 self.embedding.weight.data.uniform_(-initrange, initrange) self.fc.weight.data.uniform_(-initrange, initrange) self.fc.bias.data.zero_() def forward(self, text, offsets): embedded = self.embedding(text, offsets) return self.fc(embedded) VOCAB_SIZE = len(train_dataset.get_vocab()) EMBED_DIM = 32 NUN_CLASS = len(train_dataset.get_labels()) model = TextSentiment(VOCAB_SIZE, EMBED_DIM, NUN_CLASS) device = torch.cuda.current_device() if torch.cuda.is_available() else torch.device('cpu') print('Device to use: {}'.format(device)) model.to(device) criterion = torch.nn.CrossEntropyLoss().to(device) optimizer = torch.optim.SGD(model.parameters(), lr=configuration_dict.get('base_lr', 1.0)) scheduler = torch.optim.lr_scheduler.StepLR(optimizer, 2, gamma=0.9) tensorboard_writer = SummaryWriter('./tensorboard_logs') def train_func(data, epoch): # Train the model train_loss = 0 train_acc = 0 for batch_idx, (text, offsets, cls) in enumerate(data): optimizer.zero_grad() text, offsets, cls = text.to(device), offsets.to(device), cls.to(device) output = model(text, offsets) loss = criterion(output, cls) train_loss += loss.item() loss.backward() optimizer.step() train_acc += (output.argmax(1) == cls).sum().item() iteration = epoch * len(train_loader) + batch_idx if batch_idx % log_interval == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}' .format(epoch, batch_idx * len(cls), len(train_dataset), 100. * batch_idx / len(train_loader), loss)) tensorboard_writer.add_scalar('training loss/loss', loss, iteration) tensorboard_writer.add_scalar('learning rate/lr', optimizer.param_groups[0]['lr'], iteration) # Adjust the learning rate scheduler.step() return train_loss / len(train_dataset), train_acc / len(train_dataset) def test(data, epoch): loss = 0 acc = 0 for idx, (text, offsets, cls) in enumerate(data): text, offsets, cls = text.to(device), offsets.to(device), cls.to(device) with torch.no_grad(): output = model(text, offsets) predicted = output.argmax(1) loss = criterion(output, cls) loss += loss.item() acc += (predicted == cls).sum().item() iteration = (epoch + 1) * len(train_loader) if idx % debug_interval == 0: # report debug text every "debug_interval" mini-batches offsets = offsets.tolist() + [len(text)] for n, (pred, label) in enumerate(zip(predicted, cls)): ids_to_text = [vocabulary.itos[id] for id in text[offsets[n]:offsets[n+1]]] series = '{}_{}_label_{}_pred_{}'.format(idx, n, classes[label], classes[pred]) tensorboard_writer.add_text('Test text samples/{}'.format(series), ' '.join(ids_to_text), iteration) return loss / len(test_dataset), acc / len(test_dataset) log_interval = 200 debug_interval = 500 for epoch in range(configuration_dict.get('number_of_epochs', 6)): start_time = time.time() train_loss, train_acc = train_func(train_loader, epoch) test_loss, test_acc = test(test_loader, epoch) secs = int(time.time() - start_time) print('Epoch: %d' %(epoch + 1), " | time in %d minutes, %d seconds" %(secs / 60, secs % 60)) print(f'\tLoss: {train_loss:.4f}(train)\t|\tAcc: {train_acc * 100:.1f}%(train)') print(f'\tLoss: {test_loss:.4f}(test)\t|\tAcc: {test_acc * 100:.1f}%(test)') tensorboard_writer.add_scalar('accuracy/train', train_acc, (epoch + 1) * len(train_loader)) tensorboard_writer.add_scalar('accuracy/test', test_acc, (epoch + 1) * len(train_loader)) import re from torchtext.data.utils import ngrams_iterator from torchtext.data.utils import get_tokenizer def predict(text, model, vocab, ngrams): tokenizer = get_tokenizer("basic_english") with torch.no_grad(): text = torch.tensor([vocab[token] for token in ngrams_iterator(tokenizer(text), ngrams)]) output = model(text, torch.tensor([0])) return output.argmax(1).item() ex_text_str = "MEMPHIS, Tenn. – Four days ago, Jon Rahm was \ enduring the season’s worst weather conditions on Sunday at The \ Open on his way to a closing 75 at Royal Portrush, which \ considering the wind and the rain was a respectable showing. \ Thursday’s first round at the WGC-FedEx St. Jude Invitational \ was another story. With temperatures in the mid-80s and hardly any \ wind, the Spaniard was 13 strokes better in a flawless round. \ Thanks to his best putting performance on the PGA Tour, Rahm \ finished with an 8-under 62 for a three-stroke lead, which \ was even more impressive considering he’d never played the \ front nine at TPC Southwind." ans = predict(ex_text_str, model.to("cpu"), vocabulary, configuration_dict.get('ngrams', 2)) print("This is a %s news" %classes[ans]) ```
github_jupyter
! pip install -U pip ! pip install -U torch==1.5.0 ! pip install -U torchtext==0.6.0 ! pip install -U matplotlib==3.2.1 ! pip install -U trains>=0.15.0 ! pip install -U tensorboard==2.2.1 import os import time import torch import torch.nn as nn import torch.nn.functional as F import torchtext from torchtext.datasets import text_classification from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter from trains import Task %matplotlib inline task = Task.init(project_name='Text Example', task_name='text classifier') configuration_dict = {'number_of_epochs': 6, 'batch_size': 16, 'ngrams': 2, 'base_lr': 1.0} configuration_dict = task.connect(configuration_dict) # enabling configuration override by trains print(configuration_dict) # printing actual configuration (after override in remote mode) if not os.path.isdir('./data'): os.mkdir('./data') train_dataset, test_dataset = text_classification.DATASETS['AG_NEWS'](root='./data', ngrams=configuration_dict.get('ngrams', 2)) vocabulary = train_dataset.get_vocab() def generate_batch(batch): label = torch.tensor([entry[0] for entry in batch]) # original data batch input are packed into a list and concatenated as a single tensor text = [entry[1] for entry in batch] # offsets is a tensor of delimiters to represent the beginning index of each sequence in the text tensor. offsets = [0] + [len(entry) for entry in text] # torch.Tensor.cumsum returns the cumulative sum of elements in the dimension dim. offsets = torch.tensor(offsets[:-1]).cumsum(dim=0) text = torch.cat(text) return text, offsets, label train_loader = torch.utils.data.DataLoader(train_dataset, batch_size = configuration_dict.get('batch_size', 16), shuffle = True, pin_memory=True, collate_fn=generate_batch) test_loader = torch.utils.data.DataLoader(test_dataset, batch_size = configuration_dict.get('batch_size', 16), shuffle = False, pin_memory=True, collate_fn=generate_batch) classes = ("World", "Sports", "Business", "Sci/Tec") class TextSentiment(nn.Module): def __init__(self, vocab_size, embed_dim, num_class): super().__init__() self.embedding = nn.EmbeddingBag(vocab_size, embed_dim, sparse=True) self.fc = nn.Linear(embed_dim, num_class) self.init_weights() def init_weights(self): initrange = 0.5 self.embedding.weight.data.uniform_(-initrange, initrange) self.fc.weight.data.uniform_(-initrange, initrange) self.fc.bias.data.zero_() def forward(self, text, offsets): embedded = self.embedding(text, offsets) return self.fc(embedded) VOCAB_SIZE = len(train_dataset.get_vocab()) EMBED_DIM = 32 NUN_CLASS = len(train_dataset.get_labels()) model = TextSentiment(VOCAB_SIZE, EMBED_DIM, NUN_CLASS) device = torch.cuda.current_device() if torch.cuda.is_available() else torch.device('cpu') print('Device to use: {}'.format(device)) model.to(device) criterion = torch.nn.CrossEntropyLoss().to(device) optimizer = torch.optim.SGD(model.parameters(), lr=configuration_dict.get('base_lr', 1.0)) scheduler = torch.optim.lr_scheduler.StepLR(optimizer, 2, gamma=0.9) tensorboard_writer = SummaryWriter('./tensorboard_logs') def train_func(data, epoch): # Train the model train_loss = 0 train_acc = 0 for batch_idx, (text, offsets, cls) in enumerate(data): optimizer.zero_grad() text, offsets, cls = text.to(device), offsets.to(device), cls.to(device) output = model(text, offsets) loss = criterion(output, cls) train_loss += loss.item() loss.backward() optimizer.step() train_acc += (output.argmax(1) == cls).sum().item() iteration = epoch * len(train_loader) + batch_idx if batch_idx % log_interval == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}' .format(epoch, batch_idx * len(cls), len(train_dataset), 100. * batch_idx / len(train_loader), loss)) tensorboard_writer.add_scalar('training loss/loss', loss, iteration) tensorboard_writer.add_scalar('learning rate/lr', optimizer.param_groups[0]['lr'], iteration) # Adjust the learning rate scheduler.step() return train_loss / len(train_dataset), train_acc / len(train_dataset) def test(data, epoch): loss = 0 acc = 0 for idx, (text, offsets, cls) in enumerate(data): text, offsets, cls = text.to(device), offsets.to(device), cls.to(device) with torch.no_grad(): output = model(text, offsets) predicted = output.argmax(1) loss = criterion(output, cls) loss += loss.item() acc += (predicted == cls).sum().item() iteration = (epoch + 1) * len(train_loader) if idx % debug_interval == 0: # report debug text every "debug_interval" mini-batches offsets = offsets.tolist() + [len(text)] for n, (pred, label) in enumerate(zip(predicted, cls)): ids_to_text = [vocabulary.itos[id] for id in text[offsets[n]:offsets[n+1]]] series = '{}_{}_label_{}_pred_{}'.format(idx, n, classes[label], classes[pred]) tensorboard_writer.add_text('Test text samples/{}'.format(series), ' '.join(ids_to_text), iteration) return loss / len(test_dataset), acc / len(test_dataset) log_interval = 200 debug_interval = 500 for epoch in range(configuration_dict.get('number_of_epochs', 6)): start_time = time.time() train_loss, train_acc = train_func(train_loader, epoch) test_loss, test_acc = test(test_loader, epoch) secs = int(time.time() - start_time) print('Epoch: %d' %(epoch + 1), " | time in %d minutes, %d seconds" %(secs / 60, secs % 60)) print(f'\tLoss: {train_loss:.4f}(train)\t|\tAcc: {train_acc * 100:.1f}%(train)') print(f'\tLoss: {test_loss:.4f}(test)\t|\tAcc: {test_acc * 100:.1f}%(test)') tensorboard_writer.add_scalar('accuracy/train', train_acc, (epoch + 1) * len(train_loader)) tensorboard_writer.add_scalar('accuracy/test', test_acc, (epoch + 1) * len(train_loader)) import re from torchtext.data.utils import ngrams_iterator from torchtext.data.utils import get_tokenizer def predict(text, model, vocab, ngrams): tokenizer = get_tokenizer("basic_english") with torch.no_grad(): text = torch.tensor([vocab[token] for token in ngrams_iterator(tokenizer(text), ngrams)]) output = model(text, torch.tensor([0])) return output.argmax(1).item() ex_text_str = "MEMPHIS, Tenn. – Four days ago, Jon Rahm was \ enduring the season’s worst weather conditions on Sunday at The \ Open on his way to a closing 75 at Royal Portrush, which \ considering the wind and the rain was a respectable showing. \ Thursday’s first round at the WGC-FedEx St. Jude Invitational \ was another story. With temperatures in the mid-80s and hardly any \ wind, the Spaniard was 13 strokes better in a flawless round. \ Thanks to his best putting performance on the PGA Tour, Rahm \ finished with an 8-under 62 for a three-stroke lead, which \ was even more impressive considering he’d never played the \ front nine at TPC Southwind." ans = predict(ex_text_str, model.to("cpu"), vocabulary, configuration_dict.get('ngrams', 2)) print("This is a %s news" %classes[ans])
0.846895
0.471649
# Canary Rollout with Seldon and Ambassador ## Setup Seldon Core Use the setup notebook to [Setup Cluster](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.html#Setup-Cluster) with [Ambassador Ingress](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.html#Ambassador) and [Install Seldon Core](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.html#Install-Seldon-Core). Instructions [also online](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.html). ``` !kubectl create namespace seldon !kubectl config set-context $(kubectl config current-context) --namespace=seldon from IPython.core.magic import register_line_cell_magic @register_line_cell_magic def writetemplate(line, cell): with open(line, "w") as f: f.write(cell.format(**globals())) VERSION=!cat ../../../version.txt VERSION=VERSION[0] VERSION ``` ## Launch main model We will create a very simple Seldon Deployment with a dummy model image `seldonio/mock_classifier:1.0`. This deployment is named `example`. ``` %%writetemplate model.yaml apiVersion: machinelearning.seldon.io/v1alpha2 kind: SeldonDeployment metadata: labels: app: seldon name: example spec: name: canary-example predictors: - componentSpecs: - spec: containers: - image: seldonio/mock_classifier:{VERSION} imagePullPolicy: IfNotPresent name: classifier terminationGracePeriodSeconds: 1 graph: children: [] endpoint: type: REST name: classifier type: MODEL name: main replicas: 1 !kubectl create -f model.yaml !kubectl rollout status deploy/$(kubectl get deploy -l seldon-deployment-id=example -o jsonpath='{.items[0].metadata.name}') ``` ### Get predictions ``` from seldon_core.seldon_client import SeldonClient sc = SeldonClient(deployment_name="example", namespace="seldon") ``` #### REST Request ``` r = sc.predict(gateway="ambassador", transport="rest") assert r.success == True print(r) ``` ## Launch Canary We will now extend the existing graph and add a new predictor as a canary using a new model `seldonio/mock_classifier_rest:1.1`. We will add traffic values to split traffic 75/25 to the main and canary. ``` %%writetemplate canary.yaml apiVersion: machinelearning.seldon.io/v1alpha2 kind: SeldonDeployment metadata: labels: app: seldon name: example spec: name: canary-example predictors: - componentSpecs: - spec: containers: - image: seldonio/mock_classifier:{VERSION} imagePullPolicy: IfNotPresent name: classifier terminationGracePeriodSeconds: 1 graph: children: [] endpoint: type: REST name: classifier type: MODEL name: main replicas: 1 traffic: 75 - componentSpecs: - spec: containers: - image: seldonio/mock_classifier:{VERSION} imagePullPolicy: IfNotPresent name: classifier terminationGracePeriodSeconds: 1 graph: children: [] endpoint: type: REST name: classifier type: MODEL name: canary replicas: 1 traffic: 25 !kubectl apply -f canary.yaml !kubectl rollout status deploy/$(kubectl get deploy -l seldon-deployment-id=example -o jsonpath='{.items[0].metadata.name}') !kubectl rollout status deploy/$(kubectl get deploy -l seldon-deployment-id=example -o jsonpath='{.items[1].metadata.name}') ``` Show our REST requests are now split with roughly 25% going to the canary. ``` sc.predict(gateway="ambassador", transport="rest") from collections import defaultdict counts = defaultdict(int) n = 100 for i in range(n): r = sc.predict(gateway="ambassador", transport="rest") ``` Following checks number of prediction requests processed by default/canary predictors respectively. ``` default_count=!kubectl logs $(kubectl get pod -lseldon-app=example-main -o jsonpath='{.items[0].metadata.name}') classifier | grep "root:predict" | wc -l canary_count=!kubectl logs $(kubectl get pod -lseldon-app=example-canary -o jsonpath='{.items[0].metadata.name}') classifier | grep "root:predict" | wc -l canary_percentage = float(canary_count[0]) / float(default_count[0]) print(canary_percentage) assert canary_percentage > 0.1 and canary_percentage < 0.5 !kubectl delete -f canary.yaml ```
github_jupyter
!kubectl create namespace seldon !kubectl config set-context $(kubectl config current-context) --namespace=seldon from IPython.core.magic import register_line_cell_magic @register_line_cell_magic def writetemplate(line, cell): with open(line, "w") as f: f.write(cell.format(**globals())) VERSION=!cat ../../../version.txt VERSION=VERSION[0] VERSION %%writetemplate model.yaml apiVersion: machinelearning.seldon.io/v1alpha2 kind: SeldonDeployment metadata: labels: app: seldon name: example spec: name: canary-example predictors: - componentSpecs: - spec: containers: - image: seldonio/mock_classifier:{VERSION} imagePullPolicy: IfNotPresent name: classifier terminationGracePeriodSeconds: 1 graph: children: [] endpoint: type: REST name: classifier type: MODEL name: main replicas: 1 !kubectl create -f model.yaml !kubectl rollout status deploy/$(kubectl get deploy -l seldon-deployment-id=example -o jsonpath='{.items[0].metadata.name}') from seldon_core.seldon_client import SeldonClient sc = SeldonClient(deployment_name="example", namespace="seldon") r = sc.predict(gateway="ambassador", transport="rest") assert r.success == True print(r) %%writetemplate canary.yaml apiVersion: machinelearning.seldon.io/v1alpha2 kind: SeldonDeployment metadata: labels: app: seldon name: example spec: name: canary-example predictors: - componentSpecs: - spec: containers: - image: seldonio/mock_classifier:{VERSION} imagePullPolicy: IfNotPresent name: classifier terminationGracePeriodSeconds: 1 graph: children: [] endpoint: type: REST name: classifier type: MODEL name: main replicas: 1 traffic: 75 - componentSpecs: - spec: containers: - image: seldonio/mock_classifier:{VERSION} imagePullPolicy: IfNotPresent name: classifier terminationGracePeriodSeconds: 1 graph: children: [] endpoint: type: REST name: classifier type: MODEL name: canary replicas: 1 traffic: 25 !kubectl apply -f canary.yaml !kubectl rollout status deploy/$(kubectl get deploy -l seldon-deployment-id=example -o jsonpath='{.items[0].metadata.name}') !kubectl rollout status deploy/$(kubectl get deploy -l seldon-deployment-id=example -o jsonpath='{.items[1].metadata.name}') sc.predict(gateway="ambassador", transport="rest") from collections import defaultdict counts = defaultdict(int) n = 100 for i in range(n): r = sc.predict(gateway="ambassador", transport="rest") default_count=!kubectl logs $(kubectl get pod -lseldon-app=example-main -o jsonpath='{.items[0].metadata.name}') classifier | grep "root:predict" | wc -l canary_count=!kubectl logs $(kubectl get pod -lseldon-app=example-canary -o jsonpath='{.items[0].metadata.name}') classifier | grep "root:predict" | wc -l canary_percentage = float(canary_count[0]) / float(default_count[0]) print(canary_percentage) assert canary_percentage > 0.1 and canary_percentage < 0.5 !kubectl delete -f canary.yaml
0.432063
0.941331
# Linear Systems Solving linear systems of the form $$ A \mathbf{x} = \mathbf{b} $$ where $A$ is symmetric positive definite is arguably one of the most fundamental computations in statistics, machine learning and scientific computation at large. Many problems can be reduced to the solution of one or many (large-scale) linear systems. Some examples include least-squares regression, kernel methods, second-order optimization, quadratic programming, Kalman filtering, linear differential equations and all Gaussian (process) inference. Here, we will solve such a system using a *probabilistic linear solver*. ``` # Make inline plots vector graphics instead of raster graphics %matplotlib inline from IPython.display import set_matplotlib_formats set_matplotlib_formats('pdf', 'svg') # Plotting import matplotlib.pyplot as plt plt.style.use('../probnum.mplstyle') ``` We begin by creating a random linear system with a symmetric positive definite matrix. ``` import numpy as np from scipy.sparse import diags # Random linear system np.random.seed(42) n = 25 k = 10 A = diags(np.concatenate([np.arange(1, k + 1), np.arange(k + 1, 0, step=-1)]), np.arange(-k, k + 1), shape=(n, n)).toarray() A += np.random.normal(size=(n, n)) A = 0.5 * (A + A.T) + 10 * np.eye(n) # Symmetrize and make diagonally dominant A /= k b = np.random.normal(size=(n, 1)) print("Matrix condition: {:.2f}".format(np.linalg.cond(A))) print("Eigenvalues: {}".format(np.linalg.eigvalsh(A))) # Plot linear system fig, axes = plt.subplots(nrows=1, ncols=4, figsize=(5, 3.5), sharey=True, squeeze=False, gridspec_kw={'width_ratios': [4, .25, .25, .25]}) vmax = np.abs(np.max(np.hstack([A, b]))) vmin = -vmax axes[0, 0].imshow(A, cmap="bwr", vmin=vmin, vmax=vmax) axes[0, 0].set_title("$A$", fontsize=24) axes[0, 1].text(.5, A.shape[0]/2, "$\\bm{x}$", va='center', ha='center', fontsize=32) axes[0, 1].axis("off") axes[0, 2].text(.5, A.shape[0]/2, "$=$", va='center', ha='center', fontsize=32) axes[0, 2].axis("off") axes[0, 3].imshow(b, cmap="bwr", vmin=vmin, vmax=vmax) axes[0, 3].set_title("$\\bm{b}$", fontsize=24) for ax in axes[0, :]: ax.set_xticks([]) ax.set_yticks([]) plt.tight_layout() plt.show() ``` ## Prior Information We might have access to prior information about the inverse of $A$. Suppose we know something about the eigenvalue structure of $H=A^{-1}$. This is for example the case for Gram matrices generated by a specific kernel. In this case we assume that the average eigenvalue of the inverse is $\bar{\sigma}=\text{avg}(\sigma(H)) \approx 0.6$. ``` # Average eigenvalue of inverse print(np.mean(1 / np.linalg.eigvalsh(A))) ``` Prior information is encoded in random variables modelling $A$ and $H$. Here, we will use our prior information about the spectrum by providing a prior mean for the inverse of the form $H_0 = \operatorname{diag}(\bar{\sigma})$. ``` from probnum import random_variables as rvs from probnum.linalg.linops import Identity, ScalarMult, SymmetricKronecker from probnum.linalg import problinsolve # Prior distribution on A W0H = Identity(n) covA = SymmetricKronecker(W0H) Ainv0 = rvs.Normal(mean=ScalarMult((n, n), scalar=.6), cov=covA) ``` ## Probabilistic Linear Solvers We now use a *probabilistic linear solver*, taking into account the prior information we just specified, to solve the linear system. The algorithm iteratively chooses *actions* $\mathbf{s}$ and makes linear *observations* $\mathbf{y}=A \mathbf{s}$ to update its belief over the solution, the matrix and its inverse. ``` # Probabilistic linear solver x, Ahat, Ainv, info = problinsolve(A=A, b=b, Ainv0=Ainv0, maxiter=6) print(info) print(Ainv) ``` ## Numerical Uncertainty The solver returns random variables $\mathsf{x}$, $\mathsf{A}$ and $\mathsf{H}$, which quantify numerical uncertainty in the solution, the linear operator itself and the estimate of the inverse. For illustration we stopped the solver early after $k=6$ iterations. We plot means and samples from the resulting distributions of $\mathsf{A}$ and $\mathsf{H}$. ``` # Draw samples np.random.seed(42) Ahat_samples = Ahat.sample(3) Ainv_samples = Ainv.sample(3) # Plot rvdict = {"$A$" : A, "$\mathbb{E}(\mathsf{A})$" : Ahat.mean.todense(), "$\mathsf{A}_1$" : Ahat_samples[0], "$\mathsf{A}_2$" : Ahat_samples[1]} fig, axes = plt.subplots(nrows=1, ncols=len(rvdict), figsize=(10, 3), sharey=True) for i, (title, rv) in enumerate(rvdict.items()): axes[i].imshow(rv, vmin=vmin, vmax=vmax, cmap="bwr") axes[i].set_axis_off() axes[i].title.set_text(title) plt.tight_layout() # Plot rvdict = {"$A^{-1}": np.linalg.inv(A), "$\mathbb{E}(\mathsf{H})" : Ainv.mean.todense(), "$\mathsf{H}_1" : Ainv_samples[0], "$\mathsf{H}_2" : Ainv_samples[1]} fig, axes = plt.subplots(nrows=2, ncols=len(rvdict), figsize=(10, 6), sharey=True) for i, (title, rv) in enumerate(rvdict.items()): axes[0, i].imshow(rv, vmin=vmin, vmax=vmax, cmap="bwr") axes[0, i].set_axis_off() axes[0, i].title.set_text(title + "$") axes[1, i].imshow(rv @ A, vmin=vmin, vmax=vmax, cmap="bwr") axes[1, i].set_axis_off() axes[1, i].title.set_text(title + "A$") plt.tight_layout() ``` Even though the solver has only explored a subspace of dimension $k \ll n$, the estimates for the matrix and its inverse are already close. This is primarily due to the informative prior that we used. We can see that the uncertainty of the solver about these quantities is still relatively high by looking at the samples from $\mathsf{A}$ and $\mathsf{H}$ .
github_jupyter
# Make inline plots vector graphics instead of raster graphics %matplotlib inline from IPython.display import set_matplotlib_formats set_matplotlib_formats('pdf', 'svg') # Plotting import matplotlib.pyplot as plt plt.style.use('../probnum.mplstyle') import numpy as np from scipy.sparse import diags # Random linear system np.random.seed(42) n = 25 k = 10 A = diags(np.concatenate([np.arange(1, k + 1), np.arange(k + 1, 0, step=-1)]), np.arange(-k, k + 1), shape=(n, n)).toarray() A += np.random.normal(size=(n, n)) A = 0.5 * (A + A.T) + 10 * np.eye(n) # Symmetrize and make diagonally dominant A /= k b = np.random.normal(size=(n, 1)) print("Matrix condition: {:.2f}".format(np.linalg.cond(A))) print("Eigenvalues: {}".format(np.linalg.eigvalsh(A))) # Plot linear system fig, axes = plt.subplots(nrows=1, ncols=4, figsize=(5, 3.5), sharey=True, squeeze=False, gridspec_kw={'width_ratios': [4, .25, .25, .25]}) vmax = np.abs(np.max(np.hstack([A, b]))) vmin = -vmax axes[0, 0].imshow(A, cmap="bwr", vmin=vmin, vmax=vmax) axes[0, 0].set_title("$A$", fontsize=24) axes[0, 1].text(.5, A.shape[0]/2, "$\\bm{x}$", va='center', ha='center', fontsize=32) axes[0, 1].axis("off") axes[0, 2].text(.5, A.shape[0]/2, "$=$", va='center', ha='center', fontsize=32) axes[0, 2].axis("off") axes[0, 3].imshow(b, cmap="bwr", vmin=vmin, vmax=vmax) axes[0, 3].set_title("$\\bm{b}$", fontsize=24) for ax in axes[0, :]: ax.set_xticks([]) ax.set_yticks([]) plt.tight_layout() plt.show() # Average eigenvalue of inverse print(np.mean(1 / np.linalg.eigvalsh(A))) from probnum import random_variables as rvs from probnum.linalg.linops import Identity, ScalarMult, SymmetricKronecker from probnum.linalg import problinsolve # Prior distribution on A W0H = Identity(n) covA = SymmetricKronecker(W0H) Ainv0 = rvs.Normal(mean=ScalarMult((n, n), scalar=.6), cov=covA) # Probabilistic linear solver x, Ahat, Ainv, info = problinsolve(A=A, b=b, Ainv0=Ainv0, maxiter=6) print(info) print(Ainv) # Draw samples np.random.seed(42) Ahat_samples = Ahat.sample(3) Ainv_samples = Ainv.sample(3) # Plot rvdict = {"$A$" : A, "$\mathbb{E}(\mathsf{A})$" : Ahat.mean.todense(), "$\mathsf{A}_1$" : Ahat_samples[0], "$\mathsf{A}_2$" : Ahat_samples[1]} fig, axes = plt.subplots(nrows=1, ncols=len(rvdict), figsize=(10, 3), sharey=True) for i, (title, rv) in enumerate(rvdict.items()): axes[i].imshow(rv, vmin=vmin, vmax=vmax, cmap="bwr") axes[i].set_axis_off() axes[i].title.set_text(title) plt.tight_layout() # Plot rvdict = {"$A^{-1}": np.linalg.inv(A), "$\mathbb{E}(\mathsf{H})" : Ainv.mean.todense(), "$\mathsf{H}_1" : Ainv_samples[0], "$\mathsf{H}_2" : Ainv_samples[1]} fig, axes = plt.subplots(nrows=2, ncols=len(rvdict), figsize=(10, 6), sharey=True) for i, (title, rv) in enumerate(rvdict.items()): axes[0, i].imshow(rv, vmin=vmin, vmax=vmax, cmap="bwr") axes[0, i].set_axis_off() axes[0, i].title.set_text(title + "$") axes[1, i].imshow(rv @ A, vmin=vmin, vmax=vmax, cmap="bwr") axes[1, i].set_axis_off() axes[1, i].title.set_text(title + "A$") plt.tight_layout()
0.735642
0.977543
<a href="https://colab.research.google.com/github/krakowiakpawel9/machine-learning-bootcamp/blob/master/unsupervised/01_clustering/06_clustering_comparison.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> * @author: [email protected] * @site: e-smartdata.org ### scikit-learn Strona biblioteki: [https://scikit-learn.org](https://scikit-learn.org) Dokumentacja/User Guide: [https://scikit-learn.org/stable/user_guide.html](https://scikit-learn.org/stable/user_guide.html) Podstawowa biblioteka do uczenia maszynowego w języku Python. Aby zainstalować bibliotekę scikit-learn, użyj polecenia poniżej: ``` !pip install scikit-learn ``` Aby zaktualizować do najnowszej wersji bibliotekę scikit-learn, użyj polecenia poniżej: ``` !pip install --upgrade scikit-learn ``` Kurs stworzony w oparciu o wersję `0.22.1` ### Spis treści: 1. [Import bibliotek](#0) 2. [Wygenerowanie danych i wizualizacja](#1) 3. [Porównanie algorytmów - blobs data](#2) 4. [Porównanie algorytmów - cirlce data](#3) 5. [Porównanie algorytmów - moons data](#4) 6. [Porównanie algorytmów - random data](#5) ### <a name='0'></a> Import bibliotek ``` import numpy as np import pandas as pd import plotly.express as px ``` ### <a name='1'></a> Wygenerowanie danych i wizualizacja ``` from sklearn.datasets import make_blobs blobs_data = make_blobs(n_samples=1000, cluster_std=0.7, random_state=24, center_box=(-4.0, 4.0))[0] blobs = pd.DataFrame(blobs_data, columns=['x1', 'x2']) px.scatter(blobs, 'x1', 'x2', width=950, height=500, title='blobs data', template='plotly_dark') from sklearn.datasets import make_circles circle_data = make_circles(n_samples=1000, factor=0.5, noise=0.05)[0] circle = pd.DataFrame(circle_data, columns=['x1', 'x2']) px.scatter(circle, 'x1', 'x2', width=950, height=500, title='circle data', template='plotly_dark') from sklearn.datasets import make_moons moons_data = make_moons(n_samples=1000, noise=0.05)[0] moons = pd.DataFrame(moons_data, columns=['x1', 'x2']) px.scatter(moons, 'x1', 'x2', width=950, height=500, title='moons data', template='plotly_dark') random_data = np.random.rand(1500, 2) random = pd.DataFrame(random_data, columns=['x1', 'x2']) px.scatter(random, 'x1', 'x2', width=950, height=500, title='random data', template='plotly_dark') ``` ### <a name='2'></a> Porównanie algorytmów - blobs data - 3 klastry ``` from plotly.subplots import make_subplots fig = make_subplots(rows=1, cols=3, shared_yaxes=True, horizontal_spacing=0.01) from sklearn.cluster import KMeans kmeans = KMeans(n_clusters=3) kmeans.fit(blobs_data) clusters = kmeans.predict(blobs_data) blobs['cluster'] = clusters trace1 = px.scatter(blobs, 'x1', 'x2', 'cluster', width=800, height=500)['data'][0] fig.add_trace(trace1, row=1, col=1) from sklearn.cluster import AgglomerativeClustering agglo = AgglomerativeClustering(n_clusters=3, affinity='euclidean') clusters = agglo.fit_predict(blobs_data) blobs['cluster'] = clusters trace2 = px.scatter(blobs, 'x1', 'x2', 'cluster', width=800, height=500)['data'][0] fig.add_trace(trace2, row=1, col=2) from sklearn.cluster import DBSCAN dbscan = DBSCAN(eps=0.5, min_samples=5) dbscan.fit(blobs_data) clusters = dbscan.labels_ blobs['cluster'] = clusters trace3 = px.scatter(blobs, 'x1', 'x2', 'cluster', width=800, height=500)['data'][0] fig.add_trace(trace3, row=1, col=3) fig.update_layout(title='KMeans vs. Agglomerative Clustering vs. DBSCAN - blobs data', template='plotly_dark', coloraxis = {'colorscale':'viridis'}) fig.show() ``` ### <a name='3'></a> Porównanie algorytmów - cirlce data - 2 klastry ``` fig = make_subplots(rows=1, cols=3, shared_yaxes=True, horizontal_spacing=0.01) # KMeans kmeans = KMeans(n_clusters=3) kmeans.fit(circle_data) clusters = kmeans.predict(circle_data) circle['cluster'] = clusters trace1 = px.scatter(circle, 'x1', 'x2', 'cluster', width=800, height=500)['data'][0] fig.add_trace(trace1, row=1, col=1) # AgglomerativeClustering agglo = AgglomerativeClustering(n_clusters=3, affinity='euclidean') clusters = agglo.fit_predict(circle_data) circle['cluster'] = clusters trace2 = px.scatter(circle, 'x1', 'x2', 'cluster', width=800, height=500)['data'][0] fig.add_trace(trace2, row=1, col=2) # DBSCAN dbscan = DBSCAN(eps=0.1, min_samples=5) dbscan.fit(circle_data) clusters = dbscan.labels_ circle['cluster'] = clusters trace3 = px.scatter(circle, 'x1', 'x2', 'cluster', width=800, height=500)['data'][0] fig.add_trace(trace3, row=1, col=3) fig.update_layout(title='KMeans vs. Agglomerative Clustering vs. DBSCAN - circle data', template='plotly_dark', coloraxis = {'colorscale':'viridis'}) ``` ### <a name='4'></a> Porównanie algorytmów - moons data - 2 klastry ``` fig = make_subplots(rows=1, cols=3, shared_yaxes=True, horizontal_spacing=0.01) # KMeans kmeans = KMeans(n_clusters=2) kmeans.fit(moons_data) clusters = kmeans.predict(moons_data) moons['cluster'] = clusters trace1 = px.scatter(moons, 'x1', 'x2', 'cluster', width=800, height=500)['data'][0] fig.add_trace(trace1, row=1, col=1) # AgglomerativeClustering agglo = AgglomerativeClustering(n_clusters=2, affinity='euclidean') clusters = agglo.fit_predict(moons_data) moons['cluster'] = clusters trace2 = px.scatter(moons, 'x1', 'x2', 'cluster', width=800, height=500)['data'][0] fig.add_trace(trace2, row=1, col=2) # DBSCAN dbscan = DBSCAN(eps=0.07, min_samples=5) dbscan.fit(moons_data) clusters = dbscan.labels_ moons['cluster'] = clusters trace3 = px.scatter(moons, 'x1', 'x2', 'cluster', width=800, height=500)['data'][0] fig.add_trace(trace3, row=1, col=3) fig.update_layout(title='KMeans vs. Agglomerative Clustering vs. DBSCAN - moons data', template='plotly_dark', coloraxis = {'colorscale':'viridis'}) ``` ### <a name='4'></a> Porównanie algorytmów - random data ``` fig = make_subplots(rows=1, cols=3, shared_yaxes=True, horizontal_spacing=0.01) # KMeans kmeans = KMeans(n_clusters=5) kmeans.fit(random_data) clusters = kmeans.predict(random_data) random['cluster'] = clusters trace1 = px.scatter(random, 'x1', 'x2', 'cluster', width=800, height=500)['data'][0] fig.add_trace(trace1, row=1, col=1) # AgglomerativeClustering agglo = AgglomerativeClustering(n_clusters=5, affinity='euclidean') clusters = agglo.fit_predict(random_data) random['cluster'] = clusters trace2 = px.scatter(random, 'x1', 'x2', 'cluster', width=800, height=500)['data'][0] fig.add_trace(trace2, row=1, col=2) # DBSCAN dbscan = DBSCAN(eps=0.05, min_samples=5) dbscan.fit(random_data) clusters = dbscan.labels_ random['cluster'] = clusters trace3 = px.scatter(random, 'x1', 'x2', 'cluster', width=800, height=500)['data'][0] fig.add_trace(trace3, row=1, col=3) fig.update_layout(title='KMeans vs. Agglomerative Clustering vs.DBSCAN - random data', template='plotly_dark', coloraxis = {'colorscale':'viridis'}) ```
github_jupyter
!pip install scikit-learn !pip install --upgrade scikit-learn import numpy as np import pandas as pd import plotly.express as px from sklearn.datasets import make_blobs blobs_data = make_blobs(n_samples=1000, cluster_std=0.7, random_state=24, center_box=(-4.0, 4.0))[0] blobs = pd.DataFrame(blobs_data, columns=['x1', 'x2']) px.scatter(blobs, 'x1', 'x2', width=950, height=500, title='blobs data', template='plotly_dark') from sklearn.datasets import make_circles circle_data = make_circles(n_samples=1000, factor=0.5, noise=0.05)[0] circle = pd.DataFrame(circle_data, columns=['x1', 'x2']) px.scatter(circle, 'x1', 'x2', width=950, height=500, title='circle data', template='plotly_dark') from sklearn.datasets import make_moons moons_data = make_moons(n_samples=1000, noise=0.05)[0] moons = pd.DataFrame(moons_data, columns=['x1', 'x2']) px.scatter(moons, 'x1', 'x2', width=950, height=500, title='moons data', template='plotly_dark') random_data = np.random.rand(1500, 2) random = pd.DataFrame(random_data, columns=['x1', 'x2']) px.scatter(random, 'x1', 'x2', width=950, height=500, title='random data', template='plotly_dark') from plotly.subplots import make_subplots fig = make_subplots(rows=1, cols=3, shared_yaxes=True, horizontal_spacing=0.01) from sklearn.cluster import KMeans kmeans = KMeans(n_clusters=3) kmeans.fit(blobs_data) clusters = kmeans.predict(blobs_data) blobs['cluster'] = clusters trace1 = px.scatter(blobs, 'x1', 'x2', 'cluster', width=800, height=500)['data'][0] fig.add_trace(trace1, row=1, col=1) from sklearn.cluster import AgglomerativeClustering agglo = AgglomerativeClustering(n_clusters=3, affinity='euclidean') clusters = agglo.fit_predict(blobs_data) blobs['cluster'] = clusters trace2 = px.scatter(blobs, 'x1', 'x2', 'cluster', width=800, height=500)['data'][0] fig.add_trace(trace2, row=1, col=2) from sklearn.cluster import DBSCAN dbscan = DBSCAN(eps=0.5, min_samples=5) dbscan.fit(blobs_data) clusters = dbscan.labels_ blobs['cluster'] = clusters trace3 = px.scatter(blobs, 'x1', 'x2', 'cluster', width=800, height=500)['data'][0] fig.add_trace(trace3, row=1, col=3) fig.update_layout(title='KMeans vs. Agglomerative Clustering vs. DBSCAN - blobs data', template='plotly_dark', coloraxis = {'colorscale':'viridis'}) fig.show() fig = make_subplots(rows=1, cols=3, shared_yaxes=True, horizontal_spacing=0.01) # KMeans kmeans = KMeans(n_clusters=3) kmeans.fit(circle_data) clusters = kmeans.predict(circle_data) circle['cluster'] = clusters trace1 = px.scatter(circle, 'x1', 'x2', 'cluster', width=800, height=500)['data'][0] fig.add_trace(trace1, row=1, col=1) # AgglomerativeClustering agglo = AgglomerativeClustering(n_clusters=3, affinity='euclidean') clusters = agglo.fit_predict(circle_data) circle['cluster'] = clusters trace2 = px.scatter(circle, 'x1', 'x2', 'cluster', width=800, height=500)['data'][0] fig.add_trace(trace2, row=1, col=2) # DBSCAN dbscan = DBSCAN(eps=0.1, min_samples=5) dbscan.fit(circle_data) clusters = dbscan.labels_ circle['cluster'] = clusters trace3 = px.scatter(circle, 'x1', 'x2', 'cluster', width=800, height=500)['data'][0] fig.add_trace(trace3, row=1, col=3) fig.update_layout(title='KMeans vs. Agglomerative Clustering vs. DBSCAN - circle data', template='plotly_dark', coloraxis = {'colorscale':'viridis'}) fig = make_subplots(rows=1, cols=3, shared_yaxes=True, horizontal_spacing=0.01) # KMeans kmeans = KMeans(n_clusters=2) kmeans.fit(moons_data) clusters = kmeans.predict(moons_data) moons['cluster'] = clusters trace1 = px.scatter(moons, 'x1', 'x2', 'cluster', width=800, height=500)['data'][0] fig.add_trace(trace1, row=1, col=1) # AgglomerativeClustering agglo = AgglomerativeClustering(n_clusters=2, affinity='euclidean') clusters = agglo.fit_predict(moons_data) moons['cluster'] = clusters trace2 = px.scatter(moons, 'x1', 'x2', 'cluster', width=800, height=500)['data'][0] fig.add_trace(trace2, row=1, col=2) # DBSCAN dbscan = DBSCAN(eps=0.07, min_samples=5) dbscan.fit(moons_data) clusters = dbscan.labels_ moons['cluster'] = clusters trace3 = px.scatter(moons, 'x1', 'x2', 'cluster', width=800, height=500)['data'][0] fig.add_trace(trace3, row=1, col=3) fig.update_layout(title='KMeans vs. Agglomerative Clustering vs. DBSCAN - moons data', template='plotly_dark', coloraxis = {'colorscale':'viridis'}) fig = make_subplots(rows=1, cols=3, shared_yaxes=True, horizontal_spacing=0.01) # KMeans kmeans = KMeans(n_clusters=5) kmeans.fit(random_data) clusters = kmeans.predict(random_data) random['cluster'] = clusters trace1 = px.scatter(random, 'x1', 'x2', 'cluster', width=800, height=500)['data'][0] fig.add_trace(trace1, row=1, col=1) # AgglomerativeClustering agglo = AgglomerativeClustering(n_clusters=5, affinity='euclidean') clusters = agglo.fit_predict(random_data) random['cluster'] = clusters trace2 = px.scatter(random, 'x1', 'x2', 'cluster', width=800, height=500)['data'][0] fig.add_trace(trace2, row=1, col=2) # DBSCAN dbscan = DBSCAN(eps=0.05, min_samples=5) dbscan.fit(random_data) clusters = dbscan.labels_ random['cluster'] = clusters trace3 = px.scatter(random, 'x1', 'x2', 'cluster', width=800, height=500)['data'][0] fig.add_trace(trace3, row=1, col=3) fig.update_layout(title='KMeans vs. Agglomerative Clustering vs.DBSCAN - random data', template='plotly_dark', coloraxis = {'colorscale':'viridis'})
0.777046
0.960361
``` cuse = spark.read.csv('data/cuse_binary.csv', header=True, inferSchema=True) cuse.show(5) cuse.columns[0:3] # cuse.select('age').distinct().show() cuse.select('age').rdd.countByValue() # cuse.select('education').rdd.countByValue() # string index each categorical string columns from pyspark.ml.feature import StringIndexer from pyspark.ml import Pipeline indexers = [StringIndexer(inputCol=column, outputCol="indexed_"+column) for column in ('age', 'education', 'wantsMore')] pipeline = Pipeline(stages=indexers) indexed_cuse = pipeline.fit(cuse).transform(cuse) indexed_cuse.select('age', 'indexed_age').distinct().show(5) # onehotencode each indexed categorical columns from pyspark.ml.feature import OneHotEncoder columns = indexed_cuse.columns[0:3] onehoteencoders = [OneHotEncoder(inputCol="indexed_"+column, outputCol="onehotencode_"+column) for column in columns] pipeline = Pipeline(stages=onehoteencoders) onehotencode_columns = ['onehotencode_age', 'onehotencode_education', 'onehotencode_wantsMore', 'y'] onehotencode_cuse = pipeline.fit(indexed_cuse).transform(indexed_cuse).select(onehotencode_columns) onehotencode_cuse.distinct().show(5) # assemble all feature columns into on single vector column from pyspark.ml.feature import VectorAssembler assembler = VectorAssembler(inputCols=['onehotencode_age', 'onehotencode_education', 'onehotencode_wantsMore'], outputCol='features') cuse_df_2 = assembler.transform(onehotencode_cuse).withColumnRenamed('y', 'label') cuse_df_2.show(5) # split data into training and test datasets training, test = cuse_df_2.randomSplit([0.8, 0.2], seed=1234) training.show(5) ## ======= build cross validation model =========== # estimator from pyspark.ml.regression import GeneralizedLinearRegression glm = GeneralizedLinearRegression(featuresCol='features', labelCol='label', family='binomial') # parameter grid from pyspark.ml.tuning import ParamGridBuilder param_grid = ParamGridBuilder().\ addGrid(glm.regParam, [0, 0.5, 1, 2, 4]).\ build() # evaluator from pyspark.ml.evaluation import BinaryClassificationEvaluator evaluator = BinaryClassificationEvaluator(rawPredictionCol='prediction') # build cross-validation model from pyspark.ml.tuning import CrossValidator cv = CrossValidator(estimator=glm, estimatorParamMaps=param_grid, evaluator=evaluator, numFolds=4) # fit model # cv_model = cv.fit(training) cv_model = cv.fit(cuse_df_2) # prediction pred_training_cv = cv_model.transform(training) pred_test_cv = cv_model.transform(test) pred_training_cv.show(5) pred_test_cv.show(5, truncate=False) cv_model.bestModel.coefficients cv_model.bestModel.intercept cv_model.bestModel evaluator.evaluate(pred_training_cv) evaluator.evaluate(pred_test_cv) cv_model.bestModel import pandas as pd pdf = pd.DataFrame({ 'x1': ['a','a','b','c'], 'x2': ['apple', 'orange', 'orange', 'peach'], 'x3': [1, 1, 2, 4], 'x4': [2.4, 2.5, 3.5, 1.4], 'y1': [1, 0, 0, 1], 'y2': ['yes', 'no', 'no', 'yes'] }) df = spark.createDataFrame(pdf) df.show() ```
github_jupyter
cuse = spark.read.csv('data/cuse_binary.csv', header=True, inferSchema=True) cuse.show(5) cuse.columns[0:3] # cuse.select('age').distinct().show() cuse.select('age').rdd.countByValue() # cuse.select('education').rdd.countByValue() # string index each categorical string columns from pyspark.ml.feature import StringIndexer from pyspark.ml import Pipeline indexers = [StringIndexer(inputCol=column, outputCol="indexed_"+column) for column in ('age', 'education', 'wantsMore')] pipeline = Pipeline(stages=indexers) indexed_cuse = pipeline.fit(cuse).transform(cuse) indexed_cuse.select('age', 'indexed_age').distinct().show(5) # onehotencode each indexed categorical columns from pyspark.ml.feature import OneHotEncoder columns = indexed_cuse.columns[0:3] onehoteencoders = [OneHotEncoder(inputCol="indexed_"+column, outputCol="onehotencode_"+column) for column in columns] pipeline = Pipeline(stages=onehoteencoders) onehotencode_columns = ['onehotencode_age', 'onehotencode_education', 'onehotencode_wantsMore', 'y'] onehotencode_cuse = pipeline.fit(indexed_cuse).transform(indexed_cuse).select(onehotencode_columns) onehotencode_cuse.distinct().show(5) # assemble all feature columns into on single vector column from pyspark.ml.feature import VectorAssembler assembler = VectorAssembler(inputCols=['onehotencode_age', 'onehotencode_education', 'onehotencode_wantsMore'], outputCol='features') cuse_df_2 = assembler.transform(onehotencode_cuse).withColumnRenamed('y', 'label') cuse_df_2.show(5) # split data into training and test datasets training, test = cuse_df_2.randomSplit([0.8, 0.2], seed=1234) training.show(5) ## ======= build cross validation model =========== # estimator from pyspark.ml.regression import GeneralizedLinearRegression glm = GeneralizedLinearRegression(featuresCol='features', labelCol='label', family='binomial') # parameter grid from pyspark.ml.tuning import ParamGridBuilder param_grid = ParamGridBuilder().\ addGrid(glm.regParam, [0, 0.5, 1, 2, 4]).\ build() # evaluator from pyspark.ml.evaluation import BinaryClassificationEvaluator evaluator = BinaryClassificationEvaluator(rawPredictionCol='prediction') # build cross-validation model from pyspark.ml.tuning import CrossValidator cv = CrossValidator(estimator=glm, estimatorParamMaps=param_grid, evaluator=evaluator, numFolds=4) # fit model # cv_model = cv.fit(training) cv_model = cv.fit(cuse_df_2) # prediction pred_training_cv = cv_model.transform(training) pred_test_cv = cv_model.transform(test) pred_training_cv.show(5) pred_test_cv.show(5, truncate=False) cv_model.bestModel.coefficients cv_model.bestModel.intercept cv_model.bestModel evaluator.evaluate(pred_training_cv) evaluator.evaluate(pred_test_cv) cv_model.bestModel import pandas as pd pdf = pd.DataFrame({ 'x1': ['a','a','b','c'], 'x2': ['apple', 'orange', 'orange', 'peach'], 'x3': [1, 1, 2, 4], 'x4': [2.4, 2.5, 3.5, 1.4], 'y1': [1, 0, 0, 1], 'y2': ['yes', 'no', 'no', 'yes'] }) df = spark.createDataFrame(pdf) df.show()
0.558809
0.641099
``` import panel as pn pn.extension('plotly') ``` The ``Plotly`` pane renders Plotly plots inside a panel. It optimizes the plot rendering by using binary serialization for any array data found on the Plotly object, providing efficient updates. Note that to use the Plotly pane in a Jupyter notebook, the Panel extension has to be loaded with 'plotly' as an argument to ensure that Plotly.js is initialized. #### Parameters: For layout and styling related parameters see the [customization user guide](../../user_guide/Customization.ipynb). * **``object``** (object): The Plotly figure being displayed ___ As with most other types ``Panel`` will automatically convert a Plotly figure to a ``Plotly`` pane if it is passed to the ``pn.panel`` function or a panel layout, but a ``Plotly`` pane can be constructed directly using the ``pn.pane.Plotly`` constructor: ``` import numpy as np import plotly.graph_objs as go xx = np.linspace(-3.5, 3.5, 100) yy = np.linspace(-3.5, 3.5, 100) x, y = np.meshgrid(xx, yy) z = np.exp(-(x-1)**2-y**2)-(x**3+y**4-x/5)*np.exp(-(x**2+y**2)) surface = go.Surface(z=z) layout = go.Layout( title='Plotly 3D Plot', autosize=False, width=500, height=500, margin=dict(t=50, b=50, r=50, l=50) ) fig = dict(data=[surface], layout=layout) plotly_pane = pn.pane.Plotly(fig) plotly_pane ``` Once created the plot can be updated by modifying the Plotly traces and then triggering an update by setting or triggering an event on the pane ``object``. Note that this only works if the ``Figure`` is defined as a dictionary, since Plotly will make copies of the traces, which means that modifying them in place has no effect. Modifying an array will send just the array using a binary protocol, leading to fast and efficient updates. ``` surface.z = np.sin(z+1) plotly_pane.object = fig ``` Similarly, modifying the plot ``layout`` will only modify the layout, leaving the traces unaffected. ``` fig['layout']['width'] = 800 plotly_pane.object = fig ``` The Plotly pane supports layouts and subplots of arbitrary complexity, allowing even deeply nested Plotly figures to be displayed: ``` from plotly import subplots heatmap = go.Heatmap( z=[[1, 20, 30], [20, 1, 60], [30, 60, 1]], showscale=False) y0 = np.random.randn(50) y1 = np.random.randn(50)+1 box_1 = go.Box(y=y0) box_2 = go.Box(y=y1) data = [heatmap, box_1, box_2] fig = subplots.make_subplots( rows=2, cols=2, specs=[[{}, {}], [{'colspan': 2}, None]], subplot_titles=('First Subplot','Second Subplot', 'Third Subplot') ) fig.append_trace(box_1, 1, 1) fig.append_trace(box_2, 1, 2) fig.append_trace(heatmap, 2, 1) fig['layout'].update(height=600, width=600, title='i <3 subplots') fig = fig.to_dict() subplot_panel = pn.pane.Plotly(fig) subplot_panel ``` Just like in the single-subplot case we can modify just certain aspects of a plot and then trigger an update. E.g. here we replace the overall title text: ``` fig['layout']['title']['text'] = 'i <3 updating subplots' subplot_panel.object = fig ``` Lastly, Plotly plots can be made responsive using the `autosize` option on a Plotly layout: ``` import pandas as pd import plotly.express as px data = pd.DataFrame([ ('Monday', 7), ('Tuesday', 4), ('Wednesday', 9), ('Thursday', 4), ('Friday', 4), ('Saturday', 4), ('Sunay', 4)], columns=['Day', 'Orders'] ) fig = px.line(data, x="Day", y="Orders") fig.update_traces(mode="lines+markers", marker=dict(size=10), line=dict(width=4)) fig.layout.autosize = True responsive = pn.pane.Plotly(fig, config={'responsive': True}) pn.Column('# A responsive plot', responsive, sizing_mode='stretch_width') ``` ### Controls The `Plotly` pane exposes a number of options which can be changed from both Python and Javascript try out the effect of these parameters interactively: ``` pn.Row(responsive.controls(jslink=True), responsive) ```
github_jupyter
import panel as pn pn.extension('plotly') import numpy as np import plotly.graph_objs as go xx = np.linspace(-3.5, 3.5, 100) yy = np.linspace(-3.5, 3.5, 100) x, y = np.meshgrid(xx, yy) z = np.exp(-(x-1)**2-y**2)-(x**3+y**4-x/5)*np.exp(-(x**2+y**2)) surface = go.Surface(z=z) layout = go.Layout( title='Plotly 3D Plot', autosize=False, width=500, height=500, margin=dict(t=50, b=50, r=50, l=50) ) fig = dict(data=[surface], layout=layout) plotly_pane = pn.pane.Plotly(fig) plotly_pane surface.z = np.sin(z+1) plotly_pane.object = fig fig['layout']['width'] = 800 plotly_pane.object = fig from plotly import subplots heatmap = go.Heatmap( z=[[1, 20, 30], [20, 1, 60], [30, 60, 1]], showscale=False) y0 = np.random.randn(50) y1 = np.random.randn(50)+1 box_1 = go.Box(y=y0) box_2 = go.Box(y=y1) data = [heatmap, box_1, box_2] fig = subplots.make_subplots( rows=2, cols=2, specs=[[{}, {}], [{'colspan': 2}, None]], subplot_titles=('First Subplot','Second Subplot', 'Third Subplot') ) fig.append_trace(box_1, 1, 1) fig.append_trace(box_2, 1, 2) fig.append_trace(heatmap, 2, 1) fig['layout'].update(height=600, width=600, title='i <3 subplots') fig = fig.to_dict() subplot_panel = pn.pane.Plotly(fig) subplot_panel fig['layout']['title']['text'] = 'i <3 updating subplots' subplot_panel.object = fig import pandas as pd import plotly.express as px data = pd.DataFrame([ ('Monday', 7), ('Tuesday', 4), ('Wednesday', 9), ('Thursday', 4), ('Friday', 4), ('Saturday', 4), ('Sunay', 4)], columns=['Day', 'Orders'] ) fig = px.line(data, x="Day", y="Orders") fig.update_traces(mode="lines+markers", marker=dict(size=10), line=dict(width=4)) fig.layout.autosize = True responsive = pn.pane.Plotly(fig, config={'responsive': True}) pn.Column('# A responsive plot', responsive, sizing_mode='stretch_width') pn.Row(responsive.controls(jslink=True), responsive)
0.532182
0.950824
# Allowing storage of yaml file Here we will correct the model so that it can be stored in `.yml` format, and do some tests to check all is in place. Benjamín J. Sánchez, 2020-05-06 ## 1. Non-compliant notes ``` import cobra model = cobra.io.read_sbml_model("../model/p-thermo.xml") cobra.io.save_yaml_model(model,"../model/p-thermo.yml") ``` It seems that the character `⇢` is not allowed in yaml files, so I'll replace it locally with `->` instead. After doing it, let's check if it worked: ``` model = cobra.io.read_sbml_model("../model/p-thermo.xml") cobra.io.save_yaml_model(model,"../model/p-thermo.yml") ``` Now the file can properly get stored, hooray! But there are still characters not compliant with `.yml`, as they are saved as `�`. After inspecting them, they all correspond to `’` in the original `.xml`, as in: ``` model.metabolites.pydx5p_c.notes ``` Sadly we cannot replace those characters with e.g. `'`, as they would get stored as `&apos;` in both the `.xml` and `.yml`. So we will just keep them as `’` in `.xml` and `�` in `.yml`, as they are the only characters that get stored like that. ## 2. Updating yaml from cobrapy The final thing is to update our cobrapy fork to by default store the `.yml` file everytime the `.xml` is updated using `write_sbml_model`. This is done in commit [`b9b867f`](https://github.com/BenjaSanchez/cobrapy/commit/b9b867f3861362c3a3214c753a671992204dbfe9), and although not ideal (as the saving of each file should remain separate), as we are relying on this fork already it is the easiest way as it requires no changes on the user side (just to upgrade their cobra version). Eventually, after all the changes to make cobrapy & cobratoolbox fully compatible are integrated, we will switch to use the official cobrapy version, and then develop a wrapper function of the type `write_thermo_model` that saves both the `.xml` and `.yml` files. An issue will be open for this to remember to do it. Let's test if the new addition works, by deleting the `.yml` file locally and then doing a normal I/O cycle: ``` model = cobra.io.read_sbml_model("../model/p-thermo.xml") cobra.io.write_sbml_model(model,"../model/p-thermo.xml") ``` We can see that the `.yml` file gets re-created. Success! The `.xml` file changed a little, as the character `>` is not SBML compliant and we had not saved the model as `.xml` before. Although the end result is not the prettiest (character gets saved as `&gt;` instead), it is compliant with the metabolite names, which already used that format.
github_jupyter
import cobra model = cobra.io.read_sbml_model("../model/p-thermo.xml") cobra.io.save_yaml_model(model,"../model/p-thermo.yml") model = cobra.io.read_sbml_model("../model/p-thermo.xml") cobra.io.save_yaml_model(model,"../model/p-thermo.yml") model.metabolites.pydx5p_c.notes model = cobra.io.read_sbml_model("../model/p-thermo.xml") cobra.io.write_sbml_model(model,"../model/p-thermo.xml")
0.19046
0.788217
``` from iobjectspy import (Point2D, QueryParameter, open_datasource, create_datasource, SpatialQueryMode) import os # 设置示例数据路径 example_data_dir = '' # 设置结果输出路径 out_dir = os.path.join(example_data_dir, 'out') if not os.path.exists(out_dir): os.makedirs(out_dir) def _write_result_recordset(recordset): """将查询的结果记录集写入数据源中""" record_out_path = os.path.join(out_dir, 'out_query_data.udb') if not os.path.exists(record_out_path): ds = create_datasource(record_out_path) else: ds = open_datasource(record_out_path) assert ds is not None, '打开结果数据源失败' result_dt = ds.write_recordset(recordset, out_dataset_name=recordset.dataset.name + '_query') if result_dt is not None: print('写入查询结果记录集到数据集 ' + ds.connection_info.server + '|' + result_dt.name + ' 成功') else: print('写入查询结果记录集失败') ds.close() def attribute_filter_query_test(): """对数据集 landr 进行属性查询,并将查询结果输出到结果数据源中""" ds = open_datasource(os.path.join(example_data_dir, 'example_data.udb')) assert ds is not None, '打开数据源失败' dataset = ds['landr'] assert dataset is not None, '获取数据集失败' recordset = dataset.query_with_filter('R_AREA > 500 and R_AREA < 5000', cursor_type='STATIC') assert recordset is not None, '查询记录集失败' print('属性查询结果记录数为: ' + str(recordset.get_record_count())) _write_result_recordset(recordset) ds.close() def bounds_query_test(): """对数据集 landr 进行地理范围查询,并将查询结果输出到结果数据源中""" ds = open_datasource(os.path.join(example_data_dir, 'example_data.udb')) assert ds is not None, '打开数据源失败' dataset = ds['landr'] assert dataset is not None, '获取数据集失败' rc = ds['adminR'].get_geometries('SmID == 2')[0].bounds recordset = dataset.query_with_bounds(rc, cursor_type='STATIC') assert recordset is not None, '查询记录集失败' print('范围查询结果记录数为: ' + str(recordset.get_record_count())) _write_result_recordset(recordset) ds.close() def distance_query_test(): """对数据集 landp 进行距离查询, 查询距离为100米, 并将查询结果输出到结果数据源中""" ds = open_datasource(os.path.join(example_data_dir, 'example_data.udb')) assert ds is not None, '打开数据源失败' dataset = ds['landp'] assert dataset is not None, '获取数据集失败' recordset = dataset.query_with_distance(Point2D(315.782892179537, 260.119529494306), 100, unit='Meter', cursor_type='STATIC') assert recordset is not None, '查询记录集失败' print('距离查询结果记录数为: ' + str(recordset.get_record_count())) _write_result_recordset(recordset) ds.close() def spatial_query_test(): """对数据集 landp 进行空间查询查询, 并将查询结果输出到结果数据源中""" ds = open_datasource(os.path.join(example_data_dir, 'example_data.udb')) assert ds is not None, '打开数据源失败' dataset = ds['landp'] assert dataset is not None, '获取数据集失败' query_geo = ds['adminR'].get_geometries('SmID == 2')[0] query_parameter = (QueryParameter().set_spatial_query_mode(SpatialQueryMode.CONTAIN). set_spatial_query_object(query_geo).set_cursor_type('static')) recordset = dataset.query(query_parameter) assert recordset is not None, '查询记录集失败' print('空间查询结果记录数为: ' + str(recordset.get_record_count())) _write_result_recordset(recordset) ds.close() if __name__ == '__main__': # 属性查询 attribute_filter_query_test() # 范围查询 bounds_query_test() # 距离查询 distance_query_test() # 空间查询 spatial_query_test() ```
github_jupyter
from iobjectspy import (Point2D, QueryParameter, open_datasource, create_datasource, SpatialQueryMode) import os # 设置示例数据路径 example_data_dir = '' # 设置结果输出路径 out_dir = os.path.join(example_data_dir, 'out') if not os.path.exists(out_dir): os.makedirs(out_dir) def _write_result_recordset(recordset): """将查询的结果记录集写入数据源中""" record_out_path = os.path.join(out_dir, 'out_query_data.udb') if not os.path.exists(record_out_path): ds = create_datasource(record_out_path) else: ds = open_datasource(record_out_path) assert ds is not None, '打开结果数据源失败' result_dt = ds.write_recordset(recordset, out_dataset_name=recordset.dataset.name + '_query') if result_dt is not None: print('写入查询结果记录集到数据集 ' + ds.connection_info.server + '|' + result_dt.name + ' 成功') else: print('写入查询结果记录集失败') ds.close() def attribute_filter_query_test(): """对数据集 landr 进行属性查询,并将查询结果输出到结果数据源中""" ds = open_datasource(os.path.join(example_data_dir, 'example_data.udb')) assert ds is not None, '打开数据源失败' dataset = ds['landr'] assert dataset is not None, '获取数据集失败' recordset = dataset.query_with_filter('R_AREA > 500 and R_AREA < 5000', cursor_type='STATIC') assert recordset is not None, '查询记录集失败' print('属性查询结果记录数为: ' + str(recordset.get_record_count())) _write_result_recordset(recordset) ds.close() def bounds_query_test(): """对数据集 landr 进行地理范围查询,并将查询结果输出到结果数据源中""" ds = open_datasource(os.path.join(example_data_dir, 'example_data.udb')) assert ds is not None, '打开数据源失败' dataset = ds['landr'] assert dataset is not None, '获取数据集失败' rc = ds['adminR'].get_geometries('SmID == 2')[0].bounds recordset = dataset.query_with_bounds(rc, cursor_type='STATIC') assert recordset is not None, '查询记录集失败' print('范围查询结果记录数为: ' + str(recordset.get_record_count())) _write_result_recordset(recordset) ds.close() def distance_query_test(): """对数据集 landp 进行距离查询, 查询距离为100米, 并将查询结果输出到结果数据源中""" ds = open_datasource(os.path.join(example_data_dir, 'example_data.udb')) assert ds is not None, '打开数据源失败' dataset = ds['landp'] assert dataset is not None, '获取数据集失败' recordset = dataset.query_with_distance(Point2D(315.782892179537, 260.119529494306), 100, unit='Meter', cursor_type='STATIC') assert recordset is not None, '查询记录集失败' print('距离查询结果记录数为: ' + str(recordset.get_record_count())) _write_result_recordset(recordset) ds.close() def spatial_query_test(): """对数据集 landp 进行空间查询查询, 并将查询结果输出到结果数据源中""" ds = open_datasource(os.path.join(example_data_dir, 'example_data.udb')) assert ds is not None, '打开数据源失败' dataset = ds['landp'] assert dataset is not None, '获取数据集失败' query_geo = ds['adminR'].get_geometries('SmID == 2')[0] query_parameter = (QueryParameter().set_spatial_query_mode(SpatialQueryMode.CONTAIN). set_spatial_query_object(query_geo).set_cursor_type('static')) recordset = dataset.query(query_parameter) assert recordset is not None, '查询记录集失败' print('空间查询结果记录数为: ' + str(recordset.get_record_count())) _write_result_recordset(recordset) ds.close() if __name__ == '__main__': # 属性查询 attribute_filter_query_test() # 范围查询 bounds_query_test() # 距离查询 distance_query_test() # 空间查询 spatial_query_test()
0.283881
0.399665
# Auto-Generated Altair Examples All the following notebooks are auto-generated from the Python examples in the Altair source code repository here: https://github.com/altair-viz/altair/tree/master/altair/vegalite/v2/examples - [Aggregate Bar Chart](aggregate_bar_chart.ipynb) - [Airports](airports.ipynb) - [Anscombe Plot](anscombe_plot.ipynb) - [Bar](bar.ipynb) - [Bar Chart With Highlight](bar_chart_with_highlight.ipynb) - [Bar Chat With Labels](bar_chat_with_labels.ipynb) - [Beckers Barley Trellis Plot](beckers_barley_trellis_plot.ipynb) - [Binned Scatterplot](binned_scatterplot.ipynb) - [Boxplot Max Min](boxplot_max_min.ipynb) - [Bubble Plot](bubble_plot.ipynb) - [Candlestick Chart](candlestick_chart.ipynb) - [Choropleth](choropleth.ipynb) - [Choropleth Repeat](choropleth_repeat.ipynb) - [Connected Scatterplot](connected_scatterplot.ipynb) - [Cumulative Wiki Donations](cumulative_wiki_donations.ipynb) - [Diverging Stacked Bar Chart](diverging_stacked_bar_chart.ipynb) - [Dot Dash Plot](dot_dash_plot.ipynb) - [Error Bars With Ci](error_bars_with_ci.ipynb) - [Falkensee](falkensee.ipynb) - [Gantt Chart](gantt_chart.ipynb) - [Gapminder Bubble Plot](gapminder_bubble_plot.ipynb) - [Grouped Bar Chart](grouped_bar_chart.ipynb) - [Histogram](histogram.ipynb) - [Histogram With A Global Mean Overlay](histogram_with_a_global_mean_overlay.ipynb) - [Horizon Graph](horizon_graph.ipynb) - [Horizontal Stacked Bar Chart](horizontal_stacked_bar_chart.ipynb) - [Interactive Brush](interactive_brush.ipynb) - [Interactive Cross Highlight](interactive_cross_highlight.ipynb) - [Interactive Layered Crossfilter](interactive_layered_crossfilter.ipynb) - [Interactive Scatter Plot](interactive_scatter_plot.ipynb) - [Interval Selection](interval_selection.ipynb) - [Layer Line Color Rule](layer_line_color_rule.ipynb) - [Layered Bar Chart](layered_bar_chart.ipynb) - [Layered Chart Bar Mark](layered_chart_bar_mark.ipynb) - [Layered Heatmap Text](layered_heatmap_text.ipynb) - [Layered Histogram](layered_histogram.ipynb) - [Layered Plot With Dual Axis](layered_plot_with_dual_axis.ipynb) - [Line Percent](line_percent.ipynb) - [Line With Ci](line_with_ci.ipynb) - [London Tube](london_tube.ipynb) - [Mean Overlay Over Precipitiation Chart](mean_overlay_over_precipitiation_chart.ipynb) - [Multi Series Line](multi_series_line.ipynb) - [Multifeature Scatter Plot](multifeature_scatter_plot.ipynb) - [Multiline Highlight](multiline_highlight.ipynb) - [Multiline Tooltip](multiline_tooltip.ipynb) - [Multiple Marks](multiple_marks.ipynb) - [Natural Disasters](natural_disasters.ipynb) - [Normalized Stacked Bar Chart](normalized_stacked_bar_chart.ipynb) - [One Dot Per Zipcode](one_dot_per_zipcode.ipynb) - [Poly Fit](poly_fit.ipynb) - [Ranged Dot Plot](ranged_dot_plot.ipynb) - [Scatter Linked Brush](scatter_linked_brush.ipynb) - [Scatter Matrix](scatter_matrix.ipynb) - [Scatter With Labels](scatter_with_labels.ipynb) - [Seattle Weather Interactive](seattle_weather_interactive.ipynb) - [Select Detail](select_detail.ipynb) - [Selection Histogram](selection_histogram.ipynb) - [Selection Layer Bar Month](selection_layer_bar_month.ipynb) - [Simple Scatter](simple_scatter.ipynb) - [Slope Graph](slope_graph.ipynb) - [Stacked Area Chart](stacked_area_chart.ipynb) - [Stacked Bar Chart](stacked_bar_chart.ipynb) - [Stem And Leaf](stem_and_leaf.ipynb) - [Step Chart](step_chart.ipynb) - [Streamgraph](streamgraph.ipynb) - [Strip Plot](strip_plot.ipynb) - [Table Binned Heatmap](table_binned_heatmap.ipynb) - [Table Bubble Plot Github](table_bubble_plot_github.ipynb) - [Trellis Area](trellis_area.ipynb) - [Trellis Histogram](trellis_histogram.ipynb) - [Trellis Scatter Plot](trellis_scatter_plot.ipynb) - [Trellis Stacked Bar Chart](trellis_stacked_bar_chart.ipynb) - [Us Population Over Time](us_population_over_time.ipynb) - [Us State Capitals](us_state_capitals.ipynb) - [World Projections](world_projections.ipynb)
github_jupyter
# Auto-Generated Altair Examples All the following notebooks are auto-generated from the Python examples in the Altair source code repository here: https://github.com/altair-viz/altair/tree/master/altair/vegalite/v2/examples - [Aggregate Bar Chart](aggregate_bar_chart.ipynb) - [Airports](airports.ipynb) - [Anscombe Plot](anscombe_plot.ipynb) - [Bar](bar.ipynb) - [Bar Chart With Highlight](bar_chart_with_highlight.ipynb) - [Bar Chat With Labels](bar_chat_with_labels.ipynb) - [Beckers Barley Trellis Plot](beckers_barley_trellis_plot.ipynb) - [Binned Scatterplot](binned_scatterplot.ipynb) - [Boxplot Max Min](boxplot_max_min.ipynb) - [Bubble Plot](bubble_plot.ipynb) - [Candlestick Chart](candlestick_chart.ipynb) - [Choropleth](choropleth.ipynb) - [Choropleth Repeat](choropleth_repeat.ipynb) - [Connected Scatterplot](connected_scatterplot.ipynb) - [Cumulative Wiki Donations](cumulative_wiki_donations.ipynb) - [Diverging Stacked Bar Chart](diverging_stacked_bar_chart.ipynb) - [Dot Dash Plot](dot_dash_plot.ipynb) - [Error Bars With Ci](error_bars_with_ci.ipynb) - [Falkensee](falkensee.ipynb) - [Gantt Chart](gantt_chart.ipynb) - [Gapminder Bubble Plot](gapminder_bubble_plot.ipynb) - [Grouped Bar Chart](grouped_bar_chart.ipynb) - [Histogram](histogram.ipynb) - [Histogram With A Global Mean Overlay](histogram_with_a_global_mean_overlay.ipynb) - [Horizon Graph](horizon_graph.ipynb) - [Horizontal Stacked Bar Chart](horizontal_stacked_bar_chart.ipynb) - [Interactive Brush](interactive_brush.ipynb) - [Interactive Cross Highlight](interactive_cross_highlight.ipynb) - [Interactive Layered Crossfilter](interactive_layered_crossfilter.ipynb) - [Interactive Scatter Plot](interactive_scatter_plot.ipynb) - [Interval Selection](interval_selection.ipynb) - [Layer Line Color Rule](layer_line_color_rule.ipynb) - [Layered Bar Chart](layered_bar_chart.ipynb) - [Layered Chart Bar Mark](layered_chart_bar_mark.ipynb) - [Layered Heatmap Text](layered_heatmap_text.ipynb) - [Layered Histogram](layered_histogram.ipynb) - [Layered Plot With Dual Axis](layered_plot_with_dual_axis.ipynb) - [Line Percent](line_percent.ipynb) - [Line With Ci](line_with_ci.ipynb) - [London Tube](london_tube.ipynb) - [Mean Overlay Over Precipitiation Chart](mean_overlay_over_precipitiation_chart.ipynb) - [Multi Series Line](multi_series_line.ipynb) - [Multifeature Scatter Plot](multifeature_scatter_plot.ipynb) - [Multiline Highlight](multiline_highlight.ipynb) - [Multiline Tooltip](multiline_tooltip.ipynb) - [Multiple Marks](multiple_marks.ipynb) - [Natural Disasters](natural_disasters.ipynb) - [Normalized Stacked Bar Chart](normalized_stacked_bar_chart.ipynb) - [One Dot Per Zipcode](one_dot_per_zipcode.ipynb) - [Poly Fit](poly_fit.ipynb) - [Ranged Dot Plot](ranged_dot_plot.ipynb) - [Scatter Linked Brush](scatter_linked_brush.ipynb) - [Scatter Matrix](scatter_matrix.ipynb) - [Scatter With Labels](scatter_with_labels.ipynb) - [Seattle Weather Interactive](seattle_weather_interactive.ipynb) - [Select Detail](select_detail.ipynb) - [Selection Histogram](selection_histogram.ipynb) - [Selection Layer Bar Month](selection_layer_bar_month.ipynb) - [Simple Scatter](simple_scatter.ipynb) - [Slope Graph](slope_graph.ipynb) - [Stacked Area Chart](stacked_area_chart.ipynb) - [Stacked Bar Chart](stacked_bar_chart.ipynb) - [Stem And Leaf](stem_and_leaf.ipynb) - [Step Chart](step_chart.ipynb) - [Streamgraph](streamgraph.ipynb) - [Strip Plot](strip_plot.ipynb) - [Table Binned Heatmap](table_binned_heatmap.ipynb) - [Table Bubble Plot Github](table_bubble_plot_github.ipynb) - [Trellis Area](trellis_area.ipynb) - [Trellis Histogram](trellis_histogram.ipynb) - [Trellis Scatter Plot](trellis_scatter_plot.ipynb) - [Trellis Stacked Bar Chart](trellis_stacked_bar_chart.ipynb) - [Us Population Over Time](us_population_over_time.ipynb) - [Us State Capitals](us_state_capitals.ipynb) - [World Projections](world_projections.ipynb)
0.820218
0.905907
``` import numpy as np import panel as pn import xarray as xr import holoviews as hv import geoviews as gv import cartopy.crs as ccrs from earthsim.annotators import PolyAnnotator, PolyExporter, paths_to_polys from earthsim.grabcut import GrabCutPanel, SelectRegionPanel gv.extension('bokeh') ``` The GrabCut algorithm provides a way to annotate an image using polygons or lines to demark the foreground and background. The algorithm estimates the color distribution of the target object and that of the background using a Gaussian mixture model. This is used to construct a Markov random field over the pixel labels, with an energy function that prefers connected regions having the same label, and running a graph cut based optimization to infer their values. This procedure is repeated until convergence, resulting in an image mask denoting the foreground and background. In this example this algorithm is applied to map tiles to automatically extract a coast- and shoreline contour. First we specify a region to download the map tiles in using the `SelectRegionPanel`, then we can declare the ``GrabCutPanel`` to annotate the region and let the algorithm compute a contour. ``` select_region = SelectRegionPanel(hv.Bounds((-77.5, 34.45, -77.3, 34.75)), magnification=1) pn.Row(select_region.param, select_region.view()) ``` The toolbar in the plot on the left contains two polygon/polyline drawing tools to annotate the image with foreground and background regions respectively. To demonstrate this process in a static notebook there are already two polygons declared, one marking the sea as the foreground and one marking the land as the background. ``` background = np.array([ [-77.3777271 , 34.66037492], [-77.35987035, 34.62251189], [-77.34130751, 34.64016586], [-77.35563287, 34.65360275], [-77.36083954, 34.66560481], [-77.3777271 , 34.66037492] ]) foreground = np.array([ [-77.46585666, 34.66965009], [-77.46451121, 34.62795592], [-77.43105867, 34.64501054], [-77.41376085, 34.62573423], [-77.37886112,34.63780581], [-77.41283172, 34.6800562 ], [-77.46585666, 34.66965009] ]) dashboard = GrabCutPanel(select_region.get_tiff(), fg_data=[foreground], bg_data=[background], minimum_size=500, tolerance=0.001) pn.Row(dashboard.param, dashboard.view()) ``` We can trigger an update in the extracted contour by pressing the ``Update contour`` button and filter smaller contours using the ``Filter Contour`` button. To speed up the calculation we can also downsample the image before applying the Grabcut algorithm. Next we can further edit the extracted contour using the ``PolyAnnotator`` class: ``` annotator = PolyAnnotator(polys=dashboard.result) annotator.panel() ``` Once we are done we can convert the paths to a polygon and view the result in a separate cell: ``` gv.tile_sources.ESRI * paths_to_polys(annotator.poly_stream.element).options(width=500, height=500, color_index=None) ```
github_jupyter
import numpy as np import panel as pn import xarray as xr import holoviews as hv import geoviews as gv import cartopy.crs as ccrs from earthsim.annotators import PolyAnnotator, PolyExporter, paths_to_polys from earthsim.grabcut import GrabCutPanel, SelectRegionPanel gv.extension('bokeh') select_region = SelectRegionPanel(hv.Bounds((-77.5, 34.45, -77.3, 34.75)), magnification=1) pn.Row(select_region.param, select_region.view()) background = np.array([ [-77.3777271 , 34.66037492], [-77.35987035, 34.62251189], [-77.34130751, 34.64016586], [-77.35563287, 34.65360275], [-77.36083954, 34.66560481], [-77.3777271 , 34.66037492] ]) foreground = np.array([ [-77.46585666, 34.66965009], [-77.46451121, 34.62795592], [-77.43105867, 34.64501054], [-77.41376085, 34.62573423], [-77.37886112,34.63780581], [-77.41283172, 34.6800562 ], [-77.46585666, 34.66965009] ]) dashboard = GrabCutPanel(select_region.get_tiff(), fg_data=[foreground], bg_data=[background], minimum_size=500, tolerance=0.001) pn.Row(dashboard.param, dashboard.view()) annotator = PolyAnnotator(polys=dashboard.result) annotator.panel() gv.tile_sources.ESRI * paths_to_polys(annotator.poly_stream.element).options(width=500, height=500, color_index=None)
0.400163
0.951414
# Linear Regression ``` %matplotlib inline import matplotlib.pyplot as plt import pandas as pd import numpy as np df = pd.read_csv('../data/weight-height.csv') df.head() df.plot(kind='scatter', x='Height', y='Weight', title='Weight and Height in adults') df.plot(kind='scatter', x='Height', y='Weight', title='Weight and Height in adults') # Here we're plotting the red line 'by hand' with fixed values # We'll try to learn this line with an algorithm below plt.plot([55, 78], [75, 250], color='red', linewidth=3) def line(x, w=0, b=0): return x * w + b x = np.linspace(55, 80, 100) x yhat = line(x, w=2, b=1) yhat df.plot(kind='scatter', x='Height', y='Weight', title='Weight and Height in adults') plt.plot(x, yhat, color='red', linewidth=3) ``` ### Cost Function ``` def mean_squared_error(y_true, y_pred): s = (y_true - y_pred)**2 return s.mean() X = df[['Height']].values y_true = df['Weight'].values y_true y_pred = line(X) y_pred mean_squared_error(y_true, y_pred.ravel()) ``` ### you do it! Try changing the values of the parameters b and w in the line above and plot it again to see how the plot and the cost change. ``` plt.figure(figsize=(10, 5)) # we are going to draw 2 plots in the same figure # first plot, data and a few lines ax1 = plt.subplot(121) df.plot(kind='scatter', x='Height', y='Weight', title='Weight and Height in adults', ax=ax1) # let's explore the cost function for a few values of b between -100 and +150 bbs = np.array([0,25, 50]) mses = [] # we will append the values of the cost here, for each line for b in bbs: y_pred = line(X, w=2, b=b) mse = mean_squared_error(y_true, y_pred) mses.append(mse) plt.plot(X, y_pred) # second plot: Cost function ax2 = plt.subplot(122) plt.plot(bbs, mses, 'o-') plt.title('Cost as a function of b') plt.xlabel('b') ``` ## Linear Regression with Keras ``` from keras.models import Sequential from keras.layers import Dense from keras.optimizers import Adam, SGD model = Sequential() model.add(Dense(1, input_shape=(1,))) model.summary() model.compile(Adam(lr=0.8), 'mean_squared_error') model.fit(X, y_true, epochs=40) print(y_true) model.add(Dense(1, input_shape=(1,))) model.summary() model.compile(Adam(lr=0.8), 'mean_squared_error') model.fit(X, y_true, epochs=40) y_pred = model.predict(X) print(y_pred) df.plot(kind='scatter', x='Height', y='Weight', title='Weight and Height in adults') plt.plot(X, y_pred, color='red') W, B = model.get_weights() W B ``` ## Evaluating Model Performance ``` from sklearn.metrics import r2_score print("The R2 score is {:0.3f}".format(r2_score(y_true, y_pred))) ``` ### Train Test Split ``` from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y_true, test_size=0.2) len(X_train) len(X_test) W[0, 0] = 0.0 B[0] = 0.0 model.set_weights((W, B)) model.fit(X_train, y_train, epochs=50, verbose=0) y_train_pred = model.predict(X_train).ravel() y_test_pred = model.predict(X_test).ravel() from sklearn.metrics import mean_squared_error as mse print("The Mean Squared Error on the Train set is:\t{:0.1f}".format(mse(y_train, y_train_pred))) print("The Mean Squared Error on the Test set is:\t{:0.1f}".format(mse(y_test, y_test_pred))) print("The R2 score on the Train set is:\t{:0.3f}".format(r2_score(y_train, y_train_pred))) print("The R2 score on the Test set is:\t{:0.3f}".format(r2_score(y_test, y_test_pred))) print("The Mean Squared Error on the Train set is:\t{:0.1f}".format(mse(y_train, y_train_pred))) print("The Mean Squared Error on the Test set is:\t{:0.1f}".format(mse(y_test, y_test_pred))) print("The R2 score on the Train set is:\t{:0.3f}".format(r2_score(y_train, y_train_pred))) print("The R2 score on the Test set is:\t{:0.3f}".format(r2_score(y_test, y_test_pred))) ``` # Classification ``` df = pd.read_csv('../data/user_visit_duration.csv') df.head() df.plot(kind='scatter', x='Time (min)', y='Buy') model = Sequential() model.add(Dense(1, input_shape=(1,), activation='sigmoid')) model = Sequential() model.add(Dense(1, input_shape=(1,), activation='sigmoid')) model.compile(SGD(lr=0.5), 'binary_crossentropy', metrics=['accuracy']) model.summary() model.fit(X, y, epochs=25) from sklearn.metrics import accuracy_score print("The accuracy score is {:0.3f}".format(accuracy_score(y, y_class_pred))) model.summary() X = df[['Time (min)']].values y = df['Buy'].values model.fit(X, y, epochs=25) ax = df.plot(kind='scatter', x='Time (min)', y='Buy', title='Purchase behavior VS time spent on site') temp = np.linspace(0, 4) ax.plot(temp, model.predict(temp), color='orange') plt.legend(['model', 'data']) temp_class = model.predict(temp) > 0.5 ax = df.plot(kind='scatter', x='Time (min)', y='Buy', title='Purchase behavior VS time spent on site') temp = np.linspace(0, 4) ax.plot(temp, temp_class, color='orange') plt.legend(['model', 'data']) y_pred = model.predict(X) y_class_pred = y_pred > 0.5 from sklearn.metrics import accuracy_score print("The accuracy score is {:0.3f}".format(accuracy_score(y, y_class_pred))) ``` ### Train/Test split ``` X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) params = model.get_weights() params = [np.zeros(w.shape) for w in params] model.set_weights(params) print("The accuracy score is {:0.3f}".format(accuracy_score(y, model.predict(X) > 0.5))) model.fit(X_train, y_train, epochs=25, verbose=0) print("The train accuracy score is {:0.3f}".format(accuracy_score(y_train, model.predict(X_train) > 0.5))) print("The test accuracy score is {:0.3f}".format(accuracy_score(y_test, model.predict(X_test) > 0.5))) ``` ## Cross Validation ``` def build_logistic_regression_model(): model = Sequential() model.add(Dense(1, input_shape=(1,), activation='sigmoid')) model.compile(SGD(lr=0.5), 'binary_crossentropy', metrics=['accuracy']) return model from keras.wrappers.scikit_learn import KerasClassifier from sklearn.model_selection import cross_val_score, KFold model = KerasClassifier(build_fn=build_logistic_regression_model, epochs=25, verbose=0) cv = KFold(3, shuffle=True) scores = cross_val_score(model, X, y, cv=cv) scores print("The cross validation accuracy is {:0.4f} ± {:0.4f}".format(scores.mean(), scores.std())) scores ``` ## Confusion Matrix ``` from sklearn.metrics import confusion_matrix confusion_matrix(y, y_class_pred) def pretty_confusion_matrix(y_true, y_pred, labels=["False", "True"]): cm = confusion_matrix(y_true, y_pred) pred_labels = ['Predicted '+ l for l in labels] df = pd.DataFrame(cm, index=labels, columns=pred_labels) return df pretty_confusion_matrix(y, y_class_pred, ['Not Buy', 'Buy']) from sklearn.metrics import precision_score, recall_score, f1_score print("Precision:\t{:0.3f}".format(precision_score(y, y_class_pred))) print("Recall: \t{:0.3f}".format(recall_score(y, y_class_pred))) print("F1 Score:\t{:0.3f}".format(f1_score(y, y_class_pred))) from sklearn.metrics import classification_report ``` ## Feature Preprocessing ### Categorical Features ``` df = pd.read_csv('../data/weight-height.csv') df.head() df['Gender'].unique() pd.get_dummies(df['Gender'], prefix='Gender').head() ``` ## Feature Transformations #### 1) Rescale with fixed factor ``` df['Height (feet)'] = df['Height']/12.0 df['Weight (100 lbs)'] = df['Weight']/100.0 df.describe().round(2) ``` #### MinMax normalization ``` from sklearn.preprocessing import MinMaxScaler mms = MinMaxScaler() df['Weight_mms'] = mms.fit_transform(df[['Weight']]) df['Height_mms'] = mms.fit_transform(df[['Height']]) df.describe().round(2) ``` #### 3) Standard normalization ``` from sklearn.preprocessing import StandardScaler ss = StandardScaler() df['Weight_ss'] = ss.fit_transform(df[['Weight']]) df['Height_ss'] = ss.fit_transform(df[['Height']]) df.describe().round(2) plt.figure(figsize=(15, 5)) for i, feature in enumerate(['Height', 'Height (feet)', 'Height_mms', 'Height_ss']): plt.subplot(1, 4, i+1) df[feature].plot(kind='hist', title=feature) plt.xlabel(feature) ``` # Machine Learning Exercises ## Exercise 1 You've just been hired at a real estate investment firm and they would like you to build a model for pricing houses. You are given a dataset that contains data for house prices and a few features like number of bedrooms, size in square feet and age of the house. Let's see if you can build a model that is able to predict the price. In this exercise we extend what we have learned about linear regression to a dataset with more than one feature. Here are the steps to complete it: 1. Load the dataset ../data/housing-data.csv - plot the histograms for each feature - create 2 variables called X and y: X shall be a matrix with 3 columns (sqft,bdrms,age) and y shall be a vector with 1 column (price) - create a linear regression model in Keras with the appropriate number of inputs and output - split the data into train and test with a 20% test size - train the model on the training set and check its accuracy on training and test set - how's your model doing? Is the loss growing smaller? - try to improve your model with these experiments: - normalize the input features with one of the rescaling techniques mentioned above - use a different value for the learning rate of your model - use a different optimizer - once you're satisfied with training, check the R2score on the test set ``` df = pd.read_csv('../data/housing-data.csv') df.head() df.hist(column='sqft') df.hist(column='bdrms') df.hist(column='age') df.hist(column='price') ss = StandardScaler() X = ss.fit_transform(df[['sqft','bdrms','age']]) y = ss.fit_transform(df[['price']]) model = Sequential() model.add(Dense(1, input_shape=(3,))) model.summary() model.compile(Adam(lr=0.8), 'mean_squared_error') model.fit(X, y, epochs=40) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) model.fit(X_train, y_train, epochs=40) y_train_pred = model.predict(X_train) y_test_pred = model.predict(X_test) x = list(range(0,len(pred))) plt.plot(y_train_pred,'r') plt.plot(y_train) plt.show() plt.plot(y_test_pred,'r') plt.plot(y_test) plt.show() from sklearn.metrics import mean_squared_error as mse print("The Mean Squared Error on the Train set is:\t{:0.1f}".format(mse(y_train, y_train_pred))) print("The Mean Squared Error on the Test set is:\t{:0.1f}".format(mse(y_test, y_test_pred))) print("The R2 score on the Train set is:\t{:0.3f}".format(r2_score(y_train, y_train_pred))) print("The R2 score on the Test set is:\t{:0.3f}".format(r2_score(y_test, y_test_pred))) ``` ## Exercise 2 Your boss was extremely happy with your work on the housing price prediction model and decided to entrust you with a more challenging task. They've seen a lot of people leave the company recently and they would like to understand why that's happening. They have collected historical data on employees and they would like you to build a model that is able to predict which employee will leave next. The would like a model that is better than random guessing. They also prefer false negatives than false positives, in this first phase. Fields in the dataset include: - Employee satisfaction level - Last evaluation - Number of projects - Average monthly hours - Time spent at the company - Whether they have had a work accident - Whether they have had a promotion in the last 5 years - Department - Salary - Whether the employee has left Your goal is to predict the binary outcome variable `left` using the rest of the data. Since the outcome is binary, this is a classification problem. Here are some things you may want to try out: 1. load the dataset at ../data/HR_comma_sep.csv, inspect it with `.head()`, `.info()` and `.describe()`. - Establish a benchmark: what would be your accuracy score if you predicted everyone stay? - Check if any feature needs rescaling. You may plot a histogram of the feature to decide which rescaling method is more appropriate. - convert the categorical features into binary dummy columns. You will then have to combine them with the numerical features using `pd.concat`. - do the usual train/test split with a 20% test size - play around with learning rate and optimizer - check the confusion matrix, precision and recall - check if you still get the same results if you use a 5-Fold cross validation on all the data - Is the model good enough for your boss? As you will see in this exercise, the a logistic regression model is not good enough to help your boss. In the next chapter we will learn how to go beyond linear models. This dataset comes from https://www.kaggle.com/ludobenistant/hr-analytics/ and is released under [CC BY-SA 4.0 License](https://creativecommons.org/licenses/by-sa/4.0/). ``` df = pd.read_csv('../data/HR_comma_sep.csv') df.describe() df = pd.get_dummies(df) fig, axes = plt.subplots(len(df.columns)//3, 3, figsize=(12, 48)) i = 0 for triaxis in axes: for axis in triaxis: df.hist(column = df.columns[i], bins = 100, ax=axis) i = i+1 mms = MinMaxScaler() df[['average_montly_hours', 'number_project']] = mms.fit_transform(df[['average_montly_hours','number_project']]) print("Accuracy if everyone stays:",len(df.query("left == 0"))/len(df)*100) X = df.loc[:,df.columns!='left'] y = df[['left']] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) X_train.info() model = Sequential() model.add(Dense(1, input_shape=(20,), activation='sigmoid')) model.compile(Adam(0.001), 'binary_crossentropy', metrics=['accuracy']) model.summary() def build_logistic_regression_model(): model = Sequential() model.add(Dense(1, input_shape=(20,), activation='sigmoid')) model.compile(Adam(0.001), 'binary_crossentropy', metrics=['accuracy']) return model from keras.wrappers.scikit_learn import KerasClassifier from sklearn.model_selection import cross_val_score, KFold model = KerasClassifier(build_fn=build_logistic_regression_model, epochs=25, verbose=0) cv = KFold(3, shuffle=True) scores = cross_val_score(model, X, y, cv=cv) scores print("The cross validation accuracy is {:0.4f} ± {:0.4f}".format(scores.mean(), scores.std())) scores history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=50, verbose=1) # summarize history for accuracy plt.plot(history.history['acc']) plt.plot(history.history['val_acc']) plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) # plot 3 so that we can better see our model's accuracy plt.axhline(y=1, color='g', linestyle='--') plt.axhline(y=0.95, color='orange', linestyle='--') plt.axhline(y=0.9, color='r', linestyle='--') plt.title('model - accuracy and loss') plt.ylabel('accuracy/loss') plt.xlabel('epoch') plt.legend(['train_acc', 'test_acc', 'train_loss', 'val_loss'], loc='upper left') y_train_pred = model.predict(X_train) > 0.5 y_test_pred = model.predict(X_test) > 0.5 from sklearn.metrics import accuracy_score,classification_report print("The accuracy train score is {:0.3f}".format(accuracy_score(y_train, y_train_pred))) print(classification_report(y_train, y_train_pred)) print("The accuracy test score is {:0.3f}".format(accuracy_score(y_test, y_test_pred))) print(classification_report(y_test, y_test_pred)) ```
github_jupyter
%matplotlib inline import matplotlib.pyplot as plt import pandas as pd import numpy as np df = pd.read_csv('../data/weight-height.csv') df.head() df.plot(kind='scatter', x='Height', y='Weight', title='Weight and Height in adults') df.plot(kind='scatter', x='Height', y='Weight', title='Weight and Height in adults') # Here we're plotting the red line 'by hand' with fixed values # We'll try to learn this line with an algorithm below plt.plot([55, 78], [75, 250], color='red', linewidth=3) def line(x, w=0, b=0): return x * w + b x = np.linspace(55, 80, 100) x yhat = line(x, w=2, b=1) yhat df.plot(kind='scatter', x='Height', y='Weight', title='Weight and Height in adults') plt.plot(x, yhat, color='red', linewidth=3) def mean_squared_error(y_true, y_pred): s = (y_true - y_pred)**2 return s.mean() X = df[['Height']].values y_true = df['Weight'].values y_true y_pred = line(X) y_pred mean_squared_error(y_true, y_pred.ravel()) plt.figure(figsize=(10, 5)) # we are going to draw 2 plots in the same figure # first plot, data and a few lines ax1 = plt.subplot(121) df.plot(kind='scatter', x='Height', y='Weight', title='Weight and Height in adults', ax=ax1) # let's explore the cost function for a few values of b between -100 and +150 bbs = np.array([0,25, 50]) mses = [] # we will append the values of the cost here, for each line for b in bbs: y_pred = line(X, w=2, b=b) mse = mean_squared_error(y_true, y_pred) mses.append(mse) plt.plot(X, y_pred) # second plot: Cost function ax2 = plt.subplot(122) plt.plot(bbs, mses, 'o-') plt.title('Cost as a function of b') plt.xlabel('b') from keras.models import Sequential from keras.layers import Dense from keras.optimizers import Adam, SGD model = Sequential() model.add(Dense(1, input_shape=(1,))) model.summary() model.compile(Adam(lr=0.8), 'mean_squared_error') model.fit(X, y_true, epochs=40) print(y_true) model.add(Dense(1, input_shape=(1,))) model.summary() model.compile(Adam(lr=0.8), 'mean_squared_error') model.fit(X, y_true, epochs=40) y_pred = model.predict(X) print(y_pred) df.plot(kind='scatter', x='Height', y='Weight', title='Weight and Height in adults') plt.plot(X, y_pred, color='red') W, B = model.get_weights() W B from sklearn.metrics import r2_score print("The R2 score is {:0.3f}".format(r2_score(y_true, y_pred))) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y_true, test_size=0.2) len(X_train) len(X_test) W[0, 0] = 0.0 B[0] = 0.0 model.set_weights((W, B)) model.fit(X_train, y_train, epochs=50, verbose=0) y_train_pred = model.predict(X_train).ravel() y_test_pred = model.predict(X_test).ravel() from sklearn.metrics import mean_squared_error as mse print("The Mean Squared Error on the Train set is:\t{:0.1f}".format(mse(y_train, y_train_pred))) print("The Mean Squared Error on the Test set is:\t{:0.1f}".format(mse(y_test, y_test_pred))) print("The R2 score on the Train set is:\t{:0.3f}".format(r2_score(y_train, y_train_pred))) print("The R2 score on the Test set is:\t{:0.3f}".format(r2_score(y_test, y_test_pred))) print("The Mean Squared Error on the Train set is:\t{:0.1f}".format(mse(y_train, y_train_pred))) print("The Mean Squared Error on the Test set is:\t{:0.1f}".format(mse(y_test, y_test_pred))) print("The R2 score on the Train set is:\t{:0.3f}".format(r2_score(y_train, y_train_pred))) print("The R2 score on the Test set is:\t{:0.3f}".format(r2_score(y_test, y_test_pred))) df = pd.read_csv('../data/user_visit_duration.csv') df.head() df.plot(kind='scatter', x='Time (min)', y='Buy') model = Sequential() model.add(Dense(1, input_shape=(1,), activation='sigmoid')) model = Sequential() model.add(Dense(1, input_shape=(1,), activation='sigmoid')) model.compile(SGD(lr=0.5), 'binary_crossentropy', metrics=['accuracy']) model.summary() model.fit(X, y, epochs=25) from sklearn.metrics import accuracy_score print("The accuracy score is {:0.3f}".format(accuracy_score(y, y_class_pred))) model.summary() X = df[['Time (min)']].values y = df['Buy'].values model.fit(X, y, epochs=25) ax = df.plot(kind='scatter', x='Time (min)', y='Buy', title='Purchase behavior VS time spent on site') temp = np.linspace(0, 4) ax.plot(temp, model.predict(temp), color='orange') plt.legend(['model', 'data']) temp_class = model.predict(temp) > 0.5 ax = df.plot(kind='scatter', x='Time (min)', y='Buy', title='Purchase behavior VS time spent on site') temp = np.linspace(0, 4) ax.plot(temp, temp_class, color='orange') plt.legend(['model', 'data']) y_pred = model.predict(X) y_class_pred = y_pred > 0.5 from sklearn.metrics import accuracy_score print("The accuracy score is {:0.3f}".format(accuracy_score(y, y_class_pred))) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) params = model.get_weights() params = [np.zeros(w.shape) for w in params] model.set_weights(params) print("The accuracy score is {:0.3f}".format(accuracy_score(y, model.predict(X) > 0.5))) model.fit(X_train, y_train, epochs=25, verbose=0) print("The train accuracy score is {:0.3f}".format(accuracy_score(y_train, model.predict(X_train) > 0.5))) print("The test accuracy score is {:0.3f}".format(accuracy_score(y_test, model.predict(X_test) > 0.5))) def build_logistic_regression_model(): model = Sequential() model.add(Dense(1, input_shape=(1,), activation='sigmoid')) model.compile(SGD(lr=0.5), 'binary_crossentropy', metrics=['accuracy']) return model from keras.wrappers.scikit_learn import KerasClassifier from sklearn.model_selection import cross_val_score, KFold model = KerasClassifier(build_fn=build_logistic_regression_model, epochs=25, verbose=0) cv = KFold(3, shuffle=True) scores = cross_val_score(model, X, y, cv=cv) scores print("The cross validation accuracy is {:0.4f} ± {:0.4f}".format(scores.mean(), scores.std())) scores from sklearn.metrics import confusion_matrix confusion_matrix(y, y_class_pred) def pretty_confusion_matrix(y_true, y_pred, labels=["False", "True"]): cm = confusion_matrix(y_true, y_pred) pred_labels = ['Predicted '+ l for l in labels] df = pd.DataFrame(cm, index=labels, columns=pred_labels) return df pretty_confusion_matrix(y, y_class_pred, ['Not Buy', 'Buy']) from sklearn.metrics import precision_score, recall_score, f1_score print("Precision:\t{:0.3f}".format(precision_score(y, y_class_pred))) print("Recall: \t{:0.3f}".format(recall_score(y, y_class_pred))) print("F1 Score:\t{:0.3f}".format(f1_score(y, y_class_pred))) from sklearn.metrics import classification_report df = pd.read_csv('../data/weight-height.csv') df.head() df['Gender'].unique() pd.get_dummies(df['Gender'], prefix='Gender').head() df['Height (feet)'] = df['Height']/12.0 df['Weight (100 lbs)'] = df['Weight']/100.0 df.describe().round(2) from sklearn.preprocessing import MinMaxScaler mms = MinMaxScaler() df['Weight_mms'] = mms.fit_transform(df[['Weight']]) df['Height_mms'] = mms.fit_transform(df[['Height']]) df.describe().round(2) from sklearn.preprocessing import StandardScaler ss = StandardScaler() df['Weight_ss'] = ss.fit_transform(df[['Weight']]) df['Height_ss'] = ss.fit_transform(df[['Height']]) df.describe().round(2) plt.figure(figsize=(15, 5)) for i, feature in enumerate(['Height', 'Height (feet)', 'Height_mms', 'Height_ss']): plt.subplot(1, 4, i+1) df[feature].plot(kind='hist', title=feature) plt.xlabel(feature) df = pd.read_csv('../data/housing-data.csv') df.head() df.hist(column='sqft') df.hist(column='bdrms') df.hist(column='age') df.hist(column='price') ss = StandardScaler() X = ss.fit_transform(df[['sqft','bdrms','age']]) y = ss.fit_transform(df[['price']]) model = Sequential() model.add(Dense(1, input_shape=(3,))) model.summary() model.compile(Adam(lr=0.8), 'mean_squared_error') model.fit(X, y, epochs=40) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) model.fit(X_train, y_train, epochs=40) y_train_pred = model.predict(X_train) y_test_pred = model.predict(X_test) x = list(range(0,len(pred))) plt.plot(y_train_pred,'r') plt.plot(y_train) plt.show() plt.plot(y_test_pred,'r') plt.plot(y_test) plt.show() from sklearn.metrics import mean_squared_error as mse print("The Mean Squared Error on the Train set is:\t{:0.1f}".format(mse(y_train, y_train_pred))) print("The Mean Squared Error on the Test set is:\t{:0.1f}".format(mse(y_test, y_test_pred))) print("The R2 score on the Train set is:\t{:0.3f}".format(r2_score(y_train, y_train_pred))) print("The R2 score on the Test set is:\t{:0.3f}".format(r2_score(y_test, y_test_pred))) df = pd.read_csv('../data/HR_comma_sep.csv') df.describe() df = pd.get_dummies(df) fig, axes = plt.subplots(len(df.columns)//3, 3, figsize=(12, 48)) i = 0 for triaxis in axes: for axis in triaxis: df.hist(column = df.columns[i], bins = 100, ax=axis) i = i+1 mms = MinMaxScaler() df[['average_montly_hours', 'number_project']] = mms.fit_transform(df[['average_montly_hours','number_project']]) print("Accuracy if everyone stays:",len(df.query("left == 0"))/len(df)*100) X = df.loc[:,df.columns!='left'] y = df[['left']] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) X_train.info() model = Sequential() model.add(Dense(1, input_shape=(20,), activation='sigmoid')) model.compile(Adam(0.001), 'binary_crossentropy', metrics=['accuracy']) model.summary() def build_logistic_regression_model(): model = Sequential() model.add(Dense(1, input_shape=(20,), activation='sigmoid')) model.compile(Adam(0.001), 'binary_crossentropy', metrics=['accuracy']) return model from keras.wrappers.scikit_learn import KerasClassifier from sklearn.model_selection import cross_val_score, KFold model = KerasClassifier(build_fn=build_logistic_regression_model, epochs=25, verbose=0) cv = KFold(3, shuffle=True) scores = cross_val_score(model, X, y, cv=cv) scores print("The cross validation accuracy is {:0.4f} ± {:0.4f}".format(scores.mean(), scores.std())) scores history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=50, verbose=1) # summarize history for accuracy plt.plot(history.history['acc']) plt.plot(history.history['val_acc']) plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) # plot 3 so that we can better see our model's accuracy plt.axhline(y=1, color='g', linestyle='--') plt.axhline(y=0.95, color='orange', linestyle='--') plt.axhline(y=0.9, color='r', linestyle='--') plt.title('model - accuracy and loss') plt.ylabel('accuracy/loss') plt.xlabel('epoch') plt.legend(['train_acc', 'test_acc', 'train_loss', 'val_loss'], loc='upper left') y_train_pred = model.predict(X_train) > 0.5 y_test_pred = model.predict(X_test) > 0.5 from sklearn.metrics import accuracy_score,classification_report print("The accuracy train score is {:0.3f}".format(accuracy_score(y_train, y_train_pred))) print(classification_report(y_train, y_train_pred)) print("The accuracy test score is {:0.3f}".format(accuracy_score(y_test, y_test_pred))) print(classification_report(y_test, y_test_pred))
0.722918
0.908658
``` %%capture import os import site os.sys.path.insert(0, '/home/schirrmr/code/reversible/reversible2/') os.sys.path.insert(0, '/home/schirrmr/braindecode/code/braindecode/') os.sys.path.insert(0, '/home/schirrmr/code/explaining/reversible//') %cd /home/schirrmr/ %load_ext autoreload %autoreload 2 import numpy as np import logging log = logging.getLogger() log.setLevel('INFO') import sys logging.basicConfig(format='%(asctime)s %(levelname)s : %(message)s', level=logging.INFO, stream=sys.stdout) import matplotlib from matplotlib import pyplot as plt from matplotlib import cm %matplotlib inline %config InlineBackend.figure_format = 'png' matplotlib.rcParams['figure.figsize'] = (12.0, 1.0) matplotlib.rcParams['font.size'] = 14 from matplotlib import rcParams, cycler import seaborn seaborn.set_style('darkgrid') from reversible.sliced import sliced_from_samples from numpy.random import RandomState import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np import copy import math import itertools from reversible.plot import create_bw_image import torch as th from braindecode.torch_ext.util import np_to_var, var_to_np from reversible.revnet import ResidualBlock, invert, SubsampleSplitter, ViewAs, ReversibleBlockOld from spectral_norm import spectral_norm from conv_spectral_norm import conv_spectral_norm def display_text(text, fontsize=18): fig = plt.figure(figsize=(12,0.1)) plt.title(text, fontsize=fontsize) plt.axis('off') display(fig) plt.close(fig) from braindecode.datasets.bbci import BBCIDataset from braindecode.mne_ext.signalproc import mne_apply # we loaded all sensors to always get same cleaning results independent of sensor selection # There is an inbuilt heuristic that tries to use only EEG channels and that definitely # works for datasets in our paper #train_loader = BBCIDataset('/data/schirrmr/schirrmr/HGD-public/reduced/train/13.mat') #test_loader = BBCIDataset('/data/schirrmr/schirrmr/HGD-public/reduced/test/13.mat') start_cnt = BBCIDataset('/data/schirrmr/schirrmr/HGD-public/reduced/train/4.mat',).load() start_cnt = start_cnt.drop_channels(['STI 014']) def car(a): return a - np.mean(a, keepdims=True, axis=0) start_cnt = mne_apply( car, start_cnt) start_cnt = start_cnt.reorder_channels(['C3', 'C4']) from collections import OrderedDict from braindecode.datautil.trial_segment import create_signal_target_from_raw_mne marker_def = OrderedDict([('Right Hand', [1]), ('Left Hand', [2],), ('Rest', [3]), ('Feet', [4])]) ival = [500,1500] from braindecode.mne_ext.signalproc import mne_apply, resample_cnt from braindecode.datautil.signalproc import exponential_running_standardize, bandpass_cnt log.info("Resampling train...") cnt = resample_cnt(start_cnt, 250.0) log.info("Standardizing train...") cnt = mne_apply(lambda a: exponential_running_standardize(a.T ,factor_new=1e-3, init_block_size=1000, eps=1e-4).T, cnt) cnt = resample_cnt(cnt, 32.0) cnt = resample_cnt(cnt, 64.0) #cnt = mne_apply( # lambda a: bandpass_cnt(a, 0, 2, cnt.info['sfreq'], # filt_order=10, # axis=1), cnt) train_set = create_signal_target_from_raw_mne(cnt, marker_def, ival) cnt_bandpassed = mne_apply( lambda a: bandpass_cnt(a, 8, 13, cnt.info['sfreq'], filt_order=10, axis=1), cnt) alpha_set = create_signal_target_from_raw_mne(cnt_bandpassed, marker_def, ival) x_alpha_right = alpha_set.X[alpha_set.y == 0] x_alpha_rest = alpha_set.X[alpha_set.y == 2] alpha_a = np_to_var(x_alpha_right[:160,0:1,:,None], dtype=np.float32) alpha_b = np_to_var(x_alpha_rest[:160,0:1,:,None], dtype=np.float32) inputs_alpha = [alpha_a, alpha_b] plt.figure(figsize=(8,3)) plt.plot(var_to_np(inputs_alpha[0][:3]).squeeze().T); def rev_block(n_c, n_i_c): return ReversibleBlockOld( nn.Sequential( nn.Linear(n_c // 2, n_i_c,), nn.ReLU(), nn.Linear(n_i_c, n_c // 2,)), nn.Sequential( nn.Linear(n_c // 2, n_i_c,), nn.ReLU(), nn.Linear(n_i_c, n_c // 2)) ) fig = plt.figure(figsize=(12,12)) emp_cov = np.cov(var_to_np(inputs_alpha[0]).squeeze().T) plt.imshow(emp_cov, cmap=cm.coolwarm, vmin=-np.max(np.abs(emp_cov)), vmax=np.max(np.abs(emp_cov))) cbar = plt.colorbar() cbar.set_label("Real Covariance") display(fig) plt.close(fig) fig = plt.figure(figsize=(12,12)) emp_cov = np.abs(np.cov(var_to_np(inputs_alpha[0]).squeeze().T)) plt.imshow(emp_cov, cmap=cm.coolwarm, vmin=0, vmax=np.percentile(np.abs(emp_cov), 30)) cbar = plt.colorbar() cbar.set_label("Real Covariance") display(fig) plt.close(fig) ```
github_jupyter
%%capture import os import site os.sys.path.insert(0, '/home/schirrmr/code/reversible/reversible2/') os.sys.path.insert(0, '/home/schirrmr/braindecode/code/braindecode/') os.sys.path.insert(0, '/home/schirrmr/code/explaining/reversible//') %cd /home/schirrmr/ %load_ext autoreload %autoreload 2 import numpy as np import logging log = logging.getLogger() log.setLevel('INFO') import sys logging.basicConfig(format='%(asctime)s %(levelname)s : %(message)s', level=logging.INFO, stream=sys.stdout) import matplotlib from matplotlib import pyplot as plt from matplotlib import cm %matplotlib inline %config InlineBackend.figure_format = 'png' matplotlib.rcParams['figure.figsize'] = (12.0, 1.0) matplotlib.rcParams['font.size'] = 14 from matplotlib import rcParams, cycler import seaborn seaborn.set_style('darkgrid') from reversible.sliced import sliced_from_samples from numpy.random import RandomState import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np import copy import math import itertools from reversible.plot import create_bw_image import torch as th from braindecode.torch_ext.util import np_to_var, var_to_np from reversible.revnet import ResidualBlock, invert, SubsampleSplitter, ViewAs, ReversibleBlockOld from spectral_norm import spectral_norm from conv_spectral_norm import conv_spectral_norm def display_text(text, fontsize=18): fig = plt.figure(figsize=(12,0.1)) plt.title(text, fontsize=fontsize) plt.axis('off') display(fig) plt.close(fig) from braindecode.datasets.bbci import BBCIDataset from braindecode.mne_ext.signalproc import mne_apply # we loaded all sensors to always get same cleaning results independent of sensor selection # There is an inbuilt heuristic that tries to use only EEG channels and that definitely # works for datasets in our paper #train_loader = BBCIDataset('/data/schirrmr/schirrmr/HGD-public/reduced/train/13.mat') #test_loader = BBCIDataset('/data/schirrmr/schirrmr/HGD-public/reduced/test/13.mat') start_cnt = BBCIDataset('/data/schirrmr/schirrmr/HGD-public/reduced/train/4.mat',).load() start_cnt = start_cnt.drop_channels(['STI 014']) def car(a): return a - np.mean(a, keepdims=True, axis=0) start_cnt = mne_apply( car, start_cnt) start_cnt = start_cnt.reorder_channels(['C3', 'C4']) from collections import OrderedDict from braindecode.datautil.trial_segment import create_signal_target_from_raw_mne marker_def = OrderedDict([('Right Hand', [1]), ('Left Hand', [2],), ('Rest', [3]), ('Feet', [4])]) ival = [500,1500] from braindecode.mne_ext.signalproc import mne_apply, resample_cnt from braindecode.datautil.signalproc import exponential_running_standardize, bandpass_cnt log.info("Resampling train...") cnt = resample_cnt(start_cnt, 250.0) log.info("Standardizing train...") cnt = mne_apply(lambda a: exponential_running_standardize(a.T ,factor_new=1e-3, init_block_size=1000, eps=1e-4).T, cnt) cnt = resample_cnt(cnt, 32.0) cnt = resample_cnt(cnt, 64.0) #cnt = mne_apply( # lambda a: bandpass_cnt(a, 0, 2, cnt.info['sfreq'], # filt_order=10, # axis=1), cnt) train_set = create_signal_target_from_raw_mne(cnt, marker_def, ival) cnt_bandpassed = mne_apply( lambda a: bandpass_cnt(a, 8, 13, cnt.info['sfreq'], filt_order=10, axis=1), cnt) alpha_set = create_signal_target_from_raw_mne(cnt_bandpassed, marker_def, ival) x_alpha_right = alpha_set.X[alpha_set.y == 0] x_alpha_rest = alpha_set.X[alpha_set.y == 2] alpha_a = np_to_var(x_alpha_right[:160,0:1,:,None], dtype=np.float32) alpha_b = np_to_var(x_alpha_rest[:160,0:1,:,None], dtype=np.float32) inputs_alpha = [alpha_a, alpha_b] plt.figure(figsize=(8,3)) plt.plot(var_to_np(inputs_alpha[0][:3]).squeeze().T); def rev_block(n_c, n_i_c): return ReversibleBlockOld( nn.Sequential( nn.Linear(n_c // 2, n_i_c,), nn.ReLU(), nn.Linear(n_i_c, n_c // 2,)), nn.Sequential( nn.Linear(n_c // 2, n_i_c,), nn.ReLU(), nn.Linear(n_i_c, n_c // 2)) ) fig = plt.figure(figsize=(12,12)) emp_cov = np.cov(var_to_np(inputs_alpha[0]).squeeze().T) plt.imshow(emp_cov, cmap=cm.coolwarm, vmin=-np.max(np.abs(emp_cov)), vmax=np.max(np.abs(emp_cov))) cbar = plt.colorbar() cbar.set_label("Real Covariance") display(fig) plt.close(fig) fig = plt.figure(figsize=(12,12)) emp_cov = np.abs(np.cov(var_to_np(inputs_alpha[0]).squeeze().T)) plt.imshow(emp_cov, cmap=cm.coolwarm, vmin=0, vmax=np.percentile(np.abs(emp_cov), 30)) cbar = plt.colorbar() cbar.set_label("Real Covariance") display(fig) plt.close(fig)
0.523908
0.273993
``` import sys from pathlib import Path portfolio_management_path = Path.cwd().parent sys.path.insert(0, str(portfolio_management_path)) import xarray as xr import numpy as np import pandas as pd from portfolio_management.database.manager import Manager from portfolio_management.database.retrieve import get_dataframe database_name = 'test_feature' symbol_list = ["ETHBTC"] interval = '5m' start = "2021-01-01" end = "2021-03-01" manager = Manager( database_name=database_name, echo=False, reset_tables=True ) manager.insert( symbol_list=symbol_list, interval=interval, start=start, end=end, ) df = get_dataframe(database_name='test_feature', symbol='ETHBTC', interval='5m') def get_relative_change(value): return value.shift(1)/value def get_relative_to(value, reference): return value/reference # relative change df['r_open'] = get_relative_change(df['open']) df['r_close'] = get_relative_change(df['close']) df['r_high'] = get_relative_change(df['high']) df['r_low'] = get_relative_change(df['low']) # relative to open df['rto_close'] = get_relative_to(df['close'], df['open']) df['rto_low'] = get_relative_to(df['low'], df['open']) df['rto_high'] = get_relative_to(df['high'], df['open']) df import numpy as np from matplotlib import pyplot as plt from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler def get_PCA(df, epsilon=10e-9, pca_num_componants=5, means=None, stds=None, pca_components=None): df[['open_s', 'low_s', 'close_s', 'high_s']] = df[['open', 'low', 'close', 'high']].shift(1) nominator = np.array(df[['open_s', 'low_s', 'close_s', 'high_s', 'open', 'low', 'close', 'high']]) denominator = np.array(df[['open', 'low', 'close', 'high']]) nominator = np.nan_to_num(nominator, nan=0.0) denominator = np.nan_to_num(denominator, nan=0.0) epsilon = 10e-9 nominator = nominator + epsilon denominator = denominator + epsilon nominator_ = np.reshape(np.repeat(nominator, 4), (-1,8,4)) denominator_ = np.tile(np.expand_dims(denominator, axis=1), (1,8,1)) new = nominator_/denominator_ features = new.reshape(new.shape[0], -1) scaler = StandardScaler() # todo find what to do with the scaler, mean std all data, put in config file scaler.fit(features) scaled_features = scaler.transform(features) pca = PCA(n_components=pca_num_componants) # todo idem for PCA pca.fit(scaled_features) data = pca.transform(scaled_features) columns = [f'pca_{i}' for i in range(pca_num_componants)] return pd.DataFrame(data, columns=columns) get_PCA(df) df[['open_s', 'low_s', 'close_s', 'high_s']] = df[['open', 'low', 'close', 'high']].shift(1) nominator = np.array(df[['open_s', 'low_s', 'close_s', 'high_s', 'open', 'low', 'close', 'high']]) denominator = np.array(df[['open', 'low', 'close', 'high']]) nominator = np.nan_to_num(nominator, nan=0.0) denominator = np.nan_to_num(denominator, nan=0.0) epsilon = 10e-9 nominator = nominator + epsilon denominator = denominator + epsilon nominator print(denominator.shape) denominator[-1] print(nominator.shape) nominator[-1] nominator_ = np.reshape(np.repeat(nominator, 4), (-1,8,4)) print(nominator_.shape) nominator_[-1] denominator_ = np.tile(np.expand_dims(denominator, axis=1), (1,8,1)) print(denominator_.shape) denominator_[-1] new = nominator_/denominator_ new[-1] import numpy as np from matplotlib import pyplot as plt from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler features = new.reshape(new.shape[0], -1) scaler = StandardScaler() scaler.fit(features) scaled_features = scaler.transform(features) pca = PCA(n_components=8) pca.fit(scaled_features) print(f'{pca.components_.shape=}') print(f'{scaled_features.shape=}') pca.explained_variance_ratio_ plt.rcParams['figure.figsize'] = [10, 7] scaled_features.shape plt.plot(range(1, len(pca.explained_variance_ratio_)+1), np.cumsum(pca.explained_variance_ratio_), color='r') plt.xlabel('number of components') plt.ylabel('cumulative explained variance') plt.grid(color='k', linestyle='-', linewidth=0.5) plt.plot(range(1, len(pca.explained_variance_ratio_)+1), pca.explained_variance_ratio_, color='r') plt.grid(color='k', linestyle='-', linewidth=0.5) pca.components_ pca.transform(scaled_features) df_describe = pd.DataFrame(pca.transform(scaled_features), columns=[f'pca_{i}' for i in range(8)]) df_describe.describe() [f'pca_{i}' for i in range(8)] ```
github_jupyter
import sys from pathlib import Path portfolio_management_path = Path.cwd().parent sys.path.insert(0, str(portfolio_management_path)) import xarray as xr import numpy as np import pandas as pd from portfolio_management.database.manager import Manager from portfolio_management.database.retrieve import get_dataframe database_name = 'test_feature' symbol_list = ["ETHBTC"] interval = '5m' start = "2021-01-01" end = "2021-03-01" manager = Manager( database_name=database_name, echo=False, reset_tables=True ) manager.insert( symbol_list=symbol_list, interval=interval, start=start, end=end, ) df = get_dataframe(database_name='test_feature', symbol='ETHBTC', interval='5m') def get_relative_change(value): return value.shift(1)/value def get_relative_to(value, reference): return value/reference # relative change df['r_open'] = get_relative_change(df['open']) df['r_close'] = get_relative_change(df['close']) df['r_high'] = get_relative_change(df['high']) df['r_low'] = get_relative_change(df['low']) # relative to open df['rto_close'] = get_relative_to(df['close'], df['open']) df['rto_low'] = get_relative_to(df['low'], df['open']) df['rto_high'] = get_relative_to(df['high'], df['open']) df import numpy as np from matplotlib import pyplot as plt from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler def get_PCA(df, epsilon=10e-9, pca_num_componants=5, means=None, stds=None, pca_components=None): df[['open_s', 'low_s', 'close_s', 'high_s']] = df[['open', 'low', 'close', 'high']].shift(1) nominator = np.array(df[['open_s', 'low_s', 'close_s', 'high_s', 'open', 'low', 'close', 'high']]) denominator = np.array(df[['open', 'low', 'close', 'high']]) nominator = np.nan_to_num(nominator, nan=0.0) denominator = np.nan_to_num(denominator, nan=0.0) epsilon = 10e-9 nominator = nominator + epsilon denominator = denominator + epsilon nominator_ = np.reshape(np.repeat(nominator, 4), (-1,8,4)) denominator_ = np.tile(np.expand_dims(denominator, axis=1), (1,8,1)) new = nominator_/denominator_ features = new.reshape(new.shape[0], -1) scaler = StandardScaler() # todo find what to do with the scaler, mean std all data, put in config file scaler.fit(features) scaled_features = scaler.transform(features) pca = PCA(n_components=pca_num_componants) # todo idem for PCA pca.fit(scaled_features) data = pca.transform(scaled_features) columns = [f'pca_{i}' for i in range(pca_num_componants)] return pd.DataFrame(data, columns=columns) get_PCA(df) df[['open_s', 'low_s', 'close_s', 'high_s']] = df[['open', 'low', 'close', 'high']].shift(1) nominator = np.array(df[['open_s', 'low_s', 'close_s', 'high_s', 'open', 'low', 'close', 'high']]) denominator = np.array(df[['open', 'low', 'close', 'high']]) nominator = np.nan_to_num(nominator, nan=0.0) denominator = np.nan_to_num(denominator, nan=0.0) epsilon = 10e-9 nominator = nominator + epsilon denominator = denominator + epsilon nominator print(denominator.shape) denominator[-1] print(nominator.shape) nominator[-1] nominator_ = np.reshape(np.repeat(nominator, 4), (-1,8,4)) print(nominator_.shape) nominator_[-1] denominator_ = np.tile(np.expand_dims(denominator, axis=1), (1,8,1)) print(denominator_.shape) denominator_[-1] new = nominator_/denominator_ new[-1] import numpy as np from matplotlib import pyplot as plt from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler features = new.reshape(new.shape[0], -1) scaler = StandardScaler() scaler.fit(features) scaled_features = scaler.transform(features) pca = PCA(n_components=8) pca.fit(scaled_features) print(f'{pca.components_.shape=}') print(f'{scaled_features.shape=}') pca.explained_variance_ratio_ plt.rcParams['figure.figsize'] = [10, 7] scaled_features.shape plt.plot(range(1, len(pca.explained_variance_ratio_)+1), np.cumsum(pca.explained_variance_ratio_), color='r') plt.xlabel('number of components') plt.ylabel('cumulative explained variance') plt.grid(color='k', linestyle='-', linewidth=0.5) plt.plot(range(1, len(pca.explained_variance_ratio_)+1), pca.explained_variance_ratio_, color='r') plt.grid(color='k', linestyle='-', linewidth=0.5) pca.components_ pca.transform(scaled_features) df_describe = pd.DataFrame(pca.transform(scaled_features), columns=[f'pca_{i}' for i in range(8)]) df_describe.describe() [f'pca_{i}' for i in range(8)]
0.391755
0.293664
``` import pandas as pd import os import re import json base_dir = 'data/mgnify/studies' def gen_study_dir_contents(): """Iterate over every study directory and yield all file paths within each one.""" for name in os.listdir(base_dir): study_dir = os.path.join(base_dir, name) file_paths = [] ana_path = os.path.join(study_dir, 'analyses.json') with open(ana_path) as fd: ana_json = json.load(fd) exp_types = [] for analysis in ana_json['data']: exp_type = analysis['attributes']['experiment-type'] sample_id = analysis['relationships']['sample']['data']['id'] exp_types.append((exp_type, sample_id)) for name2 in os.listdir(study_dir): file_paths.append(os.path.join(study_dir, name2)) yield (study_dir, exp_types, file_paths) def gen_study_files_match(pattern): """Generate all files within study directories matching a substring pattern""" for (study_dir, exp_types, file_paths) in gen_study_dir_contents(): for file_path in file_paths: if re.search(pattern, file_path): yield file_path, exp_types def count_features(key, tsv_paths): """Count all unique features""" features = dict() for (path, exp_types) in tsv_paths: df = pd.read_csv(path, sep='\t') if key not in df: print(f'"{key}" column not found in this table: {path}') continue if exp_type not in features: features[exp_type] = set() features[exp_type].update(set(df[key])) counts = {key: len(val) for key, val in features.items()} print(json.dumps(counts, indent=2)) # print(features) def count_examples(tsv_paths): """Count total number of examples (eg samples or runs) grouped by experiment type""" examples = dict() # Regex pattern for column names that represent mgnify ids pattern = r'^[A-Z]+\d+$' for (path, exp_type) in tsv_paths: df = pd.read_csv(path, sep='\t') if exp_type not in features: examples[exp_type] = 0 example_count = len([key for key in df.keys() if re.match(pattern, key)]) examples[exp_type] += example_count return examples phylum_tsv_paths = list(gen_study_files_match('.+phylum_taxonomy.+\.tsv$')) print('Phylum file count:', len(phylum_tsv_paths)) print('Example:', phylum_tsv_paths[-1]) full_tax_tsv_paths = list(gen_study_files_match(r'.+\d_taxonomy_abundances_.+\.tsv$')) print('Full file count:', len(full_tax_tsv_paths)) print('Example:', full_tax_tsv_paths[0]) go_tsv_paths = list(gen_study_files_match(r'.+GO_abundances.+\.tsv$')) print('Gene Ontology file count:', len(go_tsv_paths)) print('Example:', go_tsv_paths[0]) print('Phylum-only feature stats:') count_features('phylum', phylum_tsv_paths) print('Full taxonomy feature stats:') count_features('#SampleID', full_tax_tsv_paths) print('Full Gene Ontology feature stats:') count_features('GO', go_tsv_paths) print("Phylum abundance examples (total counts of run or samples)") print(json.dumps(count_examples(phylum_tsv_paths), indent=2)) ```
github_jupyter
import pandas as pd import os import re import json base_dir = 'data/mgnify/studies' def gen_study_dir_contents(): """Iterate over every study directory and yield all file paths within each one.""" for name in os.listdir(base_dir): study_dir = os.path.join(base_dir, name) file_paths = [] ana_path = os.path.join(study_dir, 'analyses.json') with open(ana_path) as fd: ana_json = json.load(fd) exp_types = [] for analysis in ana_json['data']: exp_type = analysis['attributes']['experiment-type'] sample_id = analysis['relationships']['sample']['data']['id'] exp_types.append((exp_type, sample_id)) for name2 in os.listdir(study_dir): file_paths.append(os.path.join(study_dir, name2)) yield (study_dir, exp_types, file_paths) def gen_study_files_match(pattern): """Generate all files within study directories matching a substring pattern""" for (study_dir, exp_types, file_paths) in gen_study_dir_contents(): for file_path in file_paths: if re.search(pattern, file_path): yield file_path, exp_types def count_features(key, tsv_paths): """Count all unique features""" features = dict() for (path, exp_types) in tsv_paths: df = pd.read_csv(path, sep='\t') if key not in df: print(f'"{key}" column not found in this table: {path}') continue if exp_type not in features: features[exp_type] = set() features[exp_type].update(set(df[key])) counts = {key: len(val) for key, val in features.items()} print(json.dumps(counts, indent=2)) # print(features) def count_examples(tsv_paths): """Count total number of examples (eg samples or runs) grouped by experiment type""" examples = dict() # Regex pattern for column names that represent mgnify ids pattern = r'^[A-Z]+\d+$' for (path, exp_type) in tsv_paths: df = pd.read_csv(path, sep='\t') if exp_type not in features: examples[exp_type] = 0 example_count = len([key for key in df.keys() if re.match(pattern, key)]) examples[exp_type] += example_count return examples phylum_tsv_paths = list(gen_study_files_match('.+phylum_taxonomy.+\.tsv$')) print('Phylum file count:', len(phylum_tsv_paths)) print('Example:', phylum_tsv_paths[-1]) full_tax_tsv_paths = list(gen_study_files_match(r'.+\d_taxonomy_abundances_.+\.tsv$')) print('Full file count:', len(full_tax_tsv_paths)) print('Example:', full_tax_tsv_paths[0]) go_tsv_paths = list(gen_study_files_match(r'.+GO_abundances.+\.tsv$')) print('Gene Ontology file count:', len(go_tsv_paths)) print('Example:', go_tsv_paths[0]) print('Phylum-only feature stats:') count_features('phylum', phylum_tsv_paths) print('Full taxonomy feature stats:') count_features('#SampleID', full_tax_tsv_paths) print('Full Gene Ontology feature stats:') count_features('GO', go_tsv_paths) print("Phylum abundance examples (total counts of run or samples)") print(json.dumps(count_examples(phylum_tsv_paths), indent=2))
0.31542
0.162679
``` import csv import seaborn as sns from matplotlib import pyplot as plt import numpy as np import pandas as pd %matplotlib inline %load_ext autoreload %autoreload 2 from scipy.optimize import least_squares from scipy.stats import expon from scipy.stats import weibull_min as weibull # cdf(x, c, loc=0, scale=1) week_range = np.arange(0,1092,7) def expo_cdf(x, max_dur=week_range.size, start=1): return 1- 1/np.exp(x*np.arange(start,max_dur)) def ssr_cdf(x,other_cdf,start): return other_cdf-expo_cdf(x,max_dur=other_cdf.size+start,start=start) # adj_exp = least_squares(ssr_cdf,0.12,args=(cdf_T_ger['fraction'],1)) ``` ## STU Expansion ``` # Opening data with open("results/STU96.csv", 'rt') as f: reader = csv.reader(f) data = list(reader) # Passing data to lists, then to arrays (should change this to make it all in one) days_stu = [] spell_stu = [] dtin_stu = [] for row in data[1:]: if row[0]== '' or row[1] == '': pass else: days_stu.append(float(row[0])) spell_stu.append(float(row[1])) dtin_stu.append(int(row[2])) first_spell_stu = [] second_spell_stu = [] for idx in range(len(days_stu)): if spell_stu[idx]==1: first_spell_stu.append(days_stu[idx]) elif spell_stu[idx]==2: second_spell_stu.append(days_stu[idx]) ``` ## Non-Employment ``` # Opening data with open("results/NE96.csv", 'rt') as f: reader = csv.reader(f) data = list(reader) # Passing data to lists, then to arrays (should change this to make it all in one) days_ne = [] spell_ne = [] dtin_ne = [] for row in data[1:]: if row[0]== '' or row[1] == '': pass else: days_ne.append(float(row[0])) spell_ne.append(float(row[1])) dtin_ne.append(int(row[2])) first_spell_ne = [] second_spell_ne = [] for idx in range(len(days_ne)): if spell_ne[idx]==1: first_spell_ne.append(days_ne[idx]) elif spell_ne[idx]==2: second_spell_ne.append(days_ne[idx]) ``` ## Spell Adjustment ``` # Opening data with open("results/Upper96.csv", 'rt') as f: reader = csv.reader(f) data = list(reader) # Passing data to lists, then to arrays (should change this to make it all in one) days_SAdj = [] spell_SAdj = [] dtin_SAdj = [] for row in data[1:]: if row[0]== '' or row[1] == '': pass else: days_SAdj.append(float(row[0])) spell_SAdj.append(float(row[1])) dtin_SAdj.append(int(row[2])) first_spell_SAdj = [] second_spell_SAdj = [] for idx in range(len(days_SAdj)): if spell_SAdj[idx]==1: first_spell_SAdj.append(days_SAdj[idx]) elif spell_SAdj[idx]==2: second_spell_SAdj.append(days_SAdj[idx]) # Opening data with open("results/Upper_only1.csv", 'rt') as f: reader = csv.reader(f) data = list(reader) # Passing data to lists, then to arrays (should change this to make it all in one) days_SAdj = [] spell_SAdj = [] dtin_SAdj = [] for row in data[1:]: if row[0]== '' or row[1] == '': pass else: days_SAdj.append(float(row[0])) spell_SAdj.append(float(row[1])) dtin_SAdj.append(int(row[2])) first_spell_SAdj1 = [] for idx in range(len(days_SAdj)): if spell_SAdj[idx]==1: first_spell_SAdj1.append(days_SAdj[idx]) ``` ## LTU Expansion ``` # Opening data with open("results/Lower96.csv", 'rt') as f: reader = csv.reader(f) data = list(reader) # Passing data to lists, then to arrays (should change this to make it all in one) days2 = [] spell2 = [] dtin2 = [] for row in data[1:]: if row[0]== '' or row[1] == '': pass else: days2.append(float(row[0])) spell2.append(float(row[1])) dtin2.append(int(row[2])) first_spell2 = [] second_spell2 = [] for idx in range(len(days2)): if spell2[idx]==1: first_spell2.append(days2[idx]) elif spell2[idx]==2: second_spell2.append(days2[idx]) ``` ## Raw data ``` # Opening data with open("results/LLower96.csv", 'rt') as f: reader = csv.reader(f) data = list(reader) # Passing data to lists, then to arrays (should change this to make it all in one) days3 = [] spell3 = [] for row in data[1:]: if row[0]== '' or row[1] == '': pass else: days3.append(float(row[0])) spell3.append(float(row[1])) first_spell3 = [] second_spell3 = [] for idx in range(len(days3)): if spell3[idx]==1: first_spell3.append(days3[idx]) elif spell3[idx]==2: second_spell3.append(days3[idx]) ``` # Plots ``` sns.set_style("whitegrid") # LTU data_21, bins21 = np.histogram(first_spell2,week_range) data_22, bins22 = np.histogram(second_spell2,week_range) # Raw data_31, bins31 = np.histogram(first_spell3,week_range) data_32, bins32 = np.histogram(second_spell3,week_range) # STU data_stu, bins_stu = np.histogram(first_spell_SAdj,week_range) data_stu2, bins_stu2 = np.histogram(second_spell_SAdj,week_range) # STU - 1 only data_stu1, bins_stu1 = np.histogram(first_spell_SAdj1,week_range) # NE data_ne, bins_ne = np.histogram(first_spell_ne,week_range) data_21 = data_21 / float(sum(data_21)) data_31 = data_31 / float(sum(data_31)) data_stu = data_stu / float(sum(data_stu)) data_stu1 = data_stu1 / float(sum(data_stu1)) data_ne = data_ne / float(sum(data_ne)) data_22 = data_22 / float(sum(data_22)) data_32 = data_32 / float(sum(data_32)) data_stu2 = data_stu2 / float(sum(data_stu2)) T = 12*10 plt.figure(figsize=(6,5)) # plt.title('Decreasing hazard rate (duration dependence)',fontsize=14) # h_data, bins = np.histogram(data_stu, bins=np.arange(0,T,1)) h_data= data_stu/np.sum(data_stu) # hc_data, bins = np.histogram(sample_constant, bins=np.arange(0,T,1)) # hc_data= hc_data/np.sum(hc_data) adj_exp = least_squares(ssr_cdf,0.04,args=(np.cumsum(h_data),1)) plt.plot(bins_stu, np.hstack((1,1-np.cumsum(h_data))), c='darkorange', label = r"STU") # $\lambda$ = {:,.2f}, $k$ = {:,.2f}".format(1/med_lbda,k) plt.plot(week_range,np.hstack((1,1-expo_cdf(adj_exp.x[0],max_dur=week_range.size))),ls='--',c='k',alpha=1, label = r"$\lambda$={:,.4f}".format(adj_exp.x[0])) plt.legend(fontsize=14) plt.xlabel('months',fontsize=13) plt.xticks(week_range[::8],(week_range[::8]/28).astype(int)) plt.xlim(0,1085) plt.ylim(0,1) # plt.savefig('./plots/simulation1.eps',format='eps') plt.show() # print(r"Weibull$\lambda$ = {:,.2f}, $k$ = {:,.3f}".format(1/med_lbda,k)) # print(r"Exponential $\lambda$ = {:,.3f}".format(1/implied_lambda)) T = 12*10 plt.figure(figsize=(12,5)) # plt.title('Decreasing hazard rate (duration dependence)',fontsize=14) plt.subplot(121) h_data= data_stu/np.sum(data_stu) adj_exp = least_squares(ssr_cdf,0.04,args=(np.cumsum(h_data),1)) plt.plot(bins_stu, np.hstack((1,1-np.cumsum(h_data))), c='darkorange', label = r"STU - 2 spells") # $\lambda$ = {:,.2f}, $k$ = {:,.2f}".format(1/med_lbda,k) plt.plot(week_range,np.hstack((1,1-expo_cdf(adj_exp.x[0],max_dur=week_range.size))),ls='--',c='k',alpha=1, label = r"$\lambda$={:,.4f}".format(adj_exp.x[0])) plt.legend(fontsize=14) plt.xlabel('months',fontsize=13) plt.xticks(week_range[::8],(week_range[::8]/28).astype(int)) plt.xlim(0,1085) plt.ylim(0,1) # ------------------------------------------------------------------------------ plt.subplot(122) h_data1= data_stu1/np.sum(data_stu1) adj_exp1 = least_squares(ssr_cdf,0.04,args=(np.cumsum(h_data1),1)) plt.plot(bins_stu1, np.hstack((1,1-np.cumsum(h_data1))), label = r"STU - 1 spell") # $\lambda$ = {:,.2f}, $k$ = {:,.2f}".format(1/med_lbda,k) plt.plot(week_range,np.hstack((1,1-expo_cdf(adj_exp1.x[0],max_dur=week_range.size))),ls='--',c='k',alpha=1, label = r"$\lambda$={:,.4f}".format(adj_exp1.x[0])) plt.legend(fontsize=14) plt.xlabel('months',fontsize=13) plt.xticks(week_range[::8],(week_range[::8]/28).astype(int)) plt.xlim(0,1085) plt.ylim(0,1) # plt.savefig('./plots/simulation1.eps',format='eps') plt.show() # print(r"Weibull$\lambda$ = {:,.2f}, $k$ = {:,.3f}".format(1/med_lbda,k)) # print(r"Exponential $\lambda$ = {:,.3f}".format(1/implied_lambda)) T = 12*10 plt.figure(figsize=(6,5)) # plt.title('Decreasing hazard rate (duration dependence)',fontsize=14) h_data1= data_stu1/np.sum(data_stu1) adj_exp1 = least_squares(ssr_cdf,0.04,args=(np.cumsum(h_data1),1)) plt.plot(bins_stu1, np.hstack((1,1-np.cumsum(h_data1))), label = r"1 spell only") # $\lambda$ = {:,.2f}, $k$ = {:,.2f}".format(1/med_lbda,k) # plt.plot(week_range,np.hstack((1,1-expo_cdf(adj_exp1.x[0],max_dur=week_range.size))),ls='--',c='navy',alpha=1, # label = r"$\lambda$={:,.3f}".format(adj_exp1.x[0])) # ------------------------------------------------------------------------------ h_data= data_stu/np.sum(data_stu) adj_exp = least_squares(ssr_cdf,0.04,args=(np.cumsum(h_data),1)) plt.plot(bins_stu, np.hstack((1,1-np.cumsum(h_data))), c='darkorange', label = r"2 or more spells") # $\lambda$ = {:,.2f}, $k$ = {:,.2f}".format(1/med_lbda,k) # plt.plot(week_range,np.hstack((1,1-expo_cdf(adj_exp.x[0],max_dur=week_range.size))),ls='--', c='darkorange',alpha=1, # label = r"$\lambda$={:,.3f}".format(adj_exp.x[0])) plt.legend(fontsize=14) plt.xlabel('months',fontsize=13) plt.xticks(week_range[::8],(week_range[::8]/28).astype(int)) plt.xlim(0,1085) plt.ylim(0,1) # plt.savefig('./plots/simulation1.eps',format='eps') plt.show() # print(r"Weibull$\lambda$ = {:,.2f}, $k$ = {:,.3f}".format(1/med_lbda,k)) # print(r"Exponential $\lambda$ = {:,.3f}".format(1/implied_lambda)) ``` # First and Second Spells ``` plt.figure(figsize=(20,8)) #plt.suptitle('Hazard rate by Spell Number', fontsize=22) plt.subplot(131) plt.plot(data_31, c= 'purple', label='First Spell') plt.plot(data_32, c='b', label='Second Spell') plt.legend(loc='best', fontsize=16) plt.title('MCVL Original', fontsize=20) plt.ylim(0,0.08) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.subplot(132) plt.plot(data_21, c='purple', label='First Spell') plt.plot(data_22, c='b', label='Second Spell') plt.legend(loc='best', fontsize=16) plt.title('LTU Expansion', fontsize=20) plt.ylim(0,0.08) plt.xlabel('Spell duration in weeks',fontsize=16 ) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.subplot(133) plt.plot(data_stu, c='purple', label='First Spell') plt.plot(data_stu2, c='b', label='Second Spell') plt.legend(loc='best', fontsize=16) plt.title('STU Expansion', fontsize=20) plt.ylim(0,0.08) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.tight_layout() plt.savefig("plots/n_spell.png", format='png', box_inches='tight') plt.show() ```
github_jupyter
import csv import seaborn as sns from matplotlib import pyplot as plt import numpy as np import pandas as pd %matplotlib inline %load_ext autoreload %autoreload 2 from scipy.optimize import least_squares from scipy.stats import expon from scipy.stats import weibull_min as weibull # cdf(x, c, loc=0, scale=1) week_range = np.arange(0,1092,7) def expo_cdf(x, max_dur=week_range.size, start=1): return 1- 1/np.exp(x*np.arange(start,max_dur)) def ssr_cdf(x,other_cdf,start): return other_cdf-expo_cdf(x,max_dur=other_cdf.size+start,start=start) # adj_exp = least_squares(ssr_cdf,0.12,args=(cdf_T_ger['fraction'],1)) # Opening data with open("results/STU96.csv", 'rt') as f: reader = csv.reader(f) data = list(reader) # Passing data to lists, then to arrays (should change this to make it all in one) days_stu = [] spell_stu = [] dtin_stu = [] for row in data[1:]: if row[0]== '' or row[1] == '': pass else: days_stu.append(float(row[0])) spell_stu.append(float(row[1])) dtin_stu.append(int(row[2])) first_spell_stu = [] second_spell_stu = [] for idx in range(len(days_stu)): if spell_stu[idx]==1: first_spell_stu.append(days_stu[idx]) elif spell_stu[idx]==2: second_spell_stu.append(days_stu[idx]) # Opening data with open("results/NE96.csv", 'rt') as f: reader = csv.reader(f) data = list(reader) # Passing data to lists, then to arrays (should change this to make it all in one) days_ne = [] spell_ne = [] dtin_ne = [] for row in data[1:]: if row[0]== '' or row[1] == '': pass else: days_ne.append(float(row[0])) spell_ne.append(float(row[1])) dtin_ne.append(int(row[2])) first_spell_ne = [] second_spell_ne = [] for idx in range(len(days_ne)): if spell_ne[idx]==1: first_spell_ne.append(days_ne[idx]) elif spell_ne[idx]==2: second_spell_ne.append(days_ne[idx]) # Opening data with open("results/Upper96.csv", 'rt') as f: reader = csv.reader(f) data = list(reader) # Passing data to lists, then to arrays (should change this to make it all in one) days_SAdj = [] spell_SAdj = [] dtin_SAdj = [] for row in data[1:]: if row[0]== '' or row[1] == '': pass else: days_SAdj.append(float(row[0])) spell_SAdj.append(float(row[1])) dtin_SAdj.append(int(row[2])) first_spell_SAdj = [] second_spell_SAdj = [] for idx in range(len(days_SAdj)): if spell_SAdj[idx]==1: first_spell_SAdj.append(days_SAdj[idx]) elif spell_SAdj[idx]==2: second_spell_SAdj.append(days_SAdj[idx]) # Opening data with open("results/Upper_only1.csv", 'rt') as f: reader = csv.reader(f) data = list(reader) # Passing data to lists, then to arrays (should change this to make it all in one) days_SAdj = [] spell_SAdj = [] dtin_SAdj = [] for row in data[1:]: if row[0]== '' or row[1] == '': pass else: days_SAdj.append(float(row[0])) spell_SAdj.append(float(row[1])) dtin_SAdj.append(int(row[2])) first_spell_SAdj1 = [] for idx in range(len(days_SAdj)): if spell_SAdj[idx]==1: first_spell_SAdj1.append(days_SAdj[idx]) # Opening data with open("results/Lower96.csv", 'rt') as f: reader = csv.reader(f) data = list(reader) # Passing data to lists, then to arrays (should change this to make it all in one) days2 = [] spell2 = [] dtin2 = [] for row in data[1:]: if row[0]== '' or row[1] == '': pass else: days2.append(float(row[0])) spell2.append(float(row[1])) dtin2.append(int(row[2])) first_spell2 = [] second_spell2 = [] for idx in range(len(days2)): if spell2[idx]==1: first_spell2.append(days2[idx]) elif spell2[idx]==2: second_spell2.append(days2[idx]) # Opening data with open("results/LLower96.csv", 'rt') as f: reader = csv.reader(f) data = list(reader) # Passing data to lists, then to arrays (should change this to make it all in one) days3 = [] spell3 = [] for row in data[1:]: if row[0]== '' or row[1] == '': pass else: days3.append(float(row[0])) spell3.append(float(row[1])) first_spell3 = [] second_spell3 = [] for idx in range(len(days3)): if spell3[idx]==1: first_spell3.append(days3[idx]) elif spell3[idx]==2: second_spell3.append(days3[idx]) sns.set_style("whitegrid") # LTU data_21, bins21 = np.histogram(first_spell2,week_range) data_22, bins22 = np.histogram(second_spell2,week_range) # Raw data_31, bins31 = np.histogram(first_spell3,week_range) data_32, bins32 = np.histogram(second_spell3,week_range) # STU data_stu, bins_stu = np.histogram(first_spell_SAdj,week_range) data_stu2, bins_stu2 = np.histogram(second_spell_SAdj,week_range) # STU - 1 only data_stu1, bins_stu1 = np.histogram(first_spell_SAdj1,week_range) # NE data_ne, bins_ne = np.histogram(first_spell_ne,week_range) data_21 = data_21 / float(sum(data_21)) data_31 = data_31 / float(sum(data_31)) data_stu = data_stu / float(sum(data_stu)) data_stu1 = data_stu1 / float(sum(data_stu1)) data_ne = data_ne / float(sum(data_ne)) data_22 = data_22 / float(sum(data_22)) data_32 = data_32 / float(sum(data_32)) data_stu2 = data_stu2 / float(sum(data_stu2)) T = 12*10 plt.figure(figsize=(6,5)) # plt.title('Decreasing hazard rate (duration dependence)',fontsize=14) # h_data, bins = np.histogram(data_stu, bins=np.arange(0,T,1)) h_data= data_stu/np.sum(data_stu) # hc_data, bins = np.histogram(sample_constant, bins=np.arange(0,T,1)) # hc_data= hc_data/np.sum(hc_data) adj_exp = least_squares(ssr_cdf,0.04,args=(np.cumsum(h_data),1)) plt.plot(bins_stu, np.hstack((1,1-np.cumsum(h_data))), c='darkorange', label = r"STU") # $\lambda$ = {:,.2f}, $k$ = {:,.2f}".format(1/med_lbda,k) plt.plot(week_range,np.hstack((1,1-expo_cdf(adj_exp.x[0],max_dur=week_range.size))),ls='--',c='k',alpha=1, label = r"$\lambda$={:,.4f}".format(adj_exp.x[0])) plt.legend(fontsize=14) plt.xlabel('months',fontsize=13) plt.xticks(week_range[::8],(week_range[::8]/28).astype(int)) plt.xlim(0,1085) plt.ylim(0,1) # plt.savefig('./plots/simulation1.eps',format='eps') plt.show() # print(r"Weibull$\lambda$ = {:,.2f}, $k$ = {:,.3f}".format(1/med_lbda,k)) # print(r"Exponential $\lambda$ = {:,.3f}".format(1/implied_lambda)) T = 12*10 plt.figure(figsize=(12,5)) # plt.title('Decreasing hazard rate (duration dependence)',fontsize=14) plt.subplot(121) h_data= data_stu/np.sum(data_stu) adj_exp = least_squares(ssr_cdf,0.04,args=(np.cumsum(h_data),1)) plt.plot(bins_stu, np.hstack((1,1-np.cumsum(h_data))), c='darkorange', label = r"STU - 2 spells") # $\lambda$ = {:,.2f}, $k$ = {:,.2f}".format(1/med_lbda,k) plt.plot(week_range,np.hstack((1,1-expo_cdf(adj_exp.x[0],max_dur=week_range.size))),ls='--',c='k',alpha=1, label = r"$\lambda$={:,.4f}".format(adj_exp.x[0])) plt.legend(fontsize=14) plt.xlabel('months',fontsize=13) plt.xticks(week_range[::8],(week_range[::8]/28).astype(int)) plt.xlim(0,1085) plt.ylim(0,1) # ------------------------------------------------------------------------------ plt.subplot(122) h_data1= data_stu1/np.sum(data_stu1) adj_exp1 = least_squares(ssr_cdf,0.04,args=(np.cumsum(h_data1),1)) plt.plot(bins_stu1, np.hstack((1,1-np.cumsum(h_data1))), label = r"STU - 1 spell") # $\lambda$ = {:,.2f}, $k$ = {:,.2f}".format(1/med_lbda,k) plt.plot(week_range,np.hstack((1,1-expo_cdf(adj_exp1.x[0],max_dur=week_range.size))),ls='--',c='k',alpha=1, label = r"$\lambda$={:,.4f}".format(adj_exp1.x[0])) plt.legend(fontsize=14) plt.xlabel('months',fontsize=13) plt.xticks(week_range[::8],(week_range[::8]/28).astype(int)) plt.xlim(0,1085) plt.ylim(0,1) # plt.savefig('./plots/simulation1.eps',format='eps') plt.show() # print(r"Weibull$\lambda$ = {:,.2f}, $k$ = {:,.3f}".format(1/med_lbda,k)) # print(r"Exponential $\lambda$ = {:,.3f}".format(1/implied_lambda)) T = 12*10 plt.figure(figsize=(6,5)) # plt.title('Decreasing hazard rate (duration dependence)',fontsize=14) h_data1= data_stu1/np.sum(data_stu1) adj_exp1 = least_squares(ssr_cdf,0.04,args=(np.cumsum(h_data1),1)) plt.plot(bins_stu1, np.hstack((1,1-np.cumsum(h_data1))), label = r"1 spell only") # $\lambda$ = {:,.2f}, $k$ = {:,.2f}".format(1/med_lbda,k) # plt.plot(week_range,np.hstack((1,1-expo_cdf(adj_exp1.x[0],max_dur=week_range.size))),ls='--',c='navy',alpha=1, # label = r"$\lambda$={:,.3f}".format(adj_exp1.x[0])) # ------------------------------------------------------------------------------ h_data= data_stu/np.sum(data_stu) adj_exp = least_squares(ssr_cdf,0.04,args=(np.cumsum(h_data),1)) plt.plot(bins_stu, np.hstack((1,1-np.cumsum(h_data))), c='darkorange', label = r"2 or more spells") # $\lambda$ = {:,.2f}, $k$ = {:,.2f}".format(1/med_lbda,k) # plt.plot(week_range,np.hstack((1,1-expo_cdf(adj_exp.x[0],max_dur=week_range.size))),ls='--', c='darkorange',alpha=1, # label = r"$\lambda$={:,.3f}".format(adj_exp.x[0])) plt.legend(fontsize=14) plt.xlabel('months',fontsize=13) plt.xticks(week_range[::8],(week_range[::8]/28).astype(int)) plt.xlim(0,1085) plt.ylim(0,1) # plt.savefig('./plots/simulation1.eps',format='eps') plt.show() # print(r"Weibull$\lambda$ = {:,.2f}, $k$ = {:,.3f}".format(1/med_lbda,k)) # print(r"Exponential $\lambda$ = {:,.3f}".format(1/implied_lambda)) plt.figure(figsize=(20,8)) #plt.suptitle('Hazard rate by Spell Number', fontsize=22) plt.subplot(131) plt.plot(data_31, c= 'purple', label='First Spell') plt.plot(data_32, c='b', label='Second Spell') plt.legend(loc='best', fontsize=16) plt.title('MCVL Original', fontsize=20) plt.ylim(0,0.08) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.subplot(132) plt.plot(data_21, c='purple', label='First Spell') plt.plot(data_22, c='b', label='Second Spell') plt.legend(loc='best', fontsize=16) plt.title('LTU Expansion', fontsize=20) plt.ylim(0,0.08) plt.xlabel('Spell duration in weeks',fontsize=16 ) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.subplot(133) plt.plot(data_stu, c='purple', label='First Spell') plt.plot(data_stu2, c='b', label='Second Spell') plt.legend(loc='best', fontsize=16) plt.title('STU Expansion', fontsize=20) plt.ylim(0,0.08) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.tight_layout() plt.savefig("plots/n_spell.png", format='png', box_inches='tight') plt.show()
0.163713
0.726256
``` #Import libraries import pandas as pd import matplotlib.pyplot as plt ``` # Domain Specific Dataset Analysis ## 1. Domain: COVID-19 Research Article Abstracts Source: COVID-19 Open Research Dataset Challenge ([CORD-19](https://www.kaggle.com/allen-institute-for-ai/CORD-19-research-challenge)). CORD-19 is a resource of over 200,000 scholarly articles, including over 100,000 with full text, about COVID-19, SARS-CoV-2, and related coronaviruses. In this assignment, we will use the abstracts of these articles as a domain sepcific dataset for analysis. ``` df1 = pd.read_csv('../datasets/CORD19/metadata_sample.csv', dtype=str) df1.head(2).abstract.values #sample ``` ### 1a.Tokenization and Stemming ``` import nltk nltk.download('punkt') word_tokens = nltk.word_tokenize(df1.iloc[0].abstract) '|'.join(word_tokens) from nltk.stem.snowball import SnowballStemmer stemmer = SnowballStemmer("english") stemmed = [stemmer.stem(word) for word in word_tokens] '|'.join(stemmed) def analyse_stem(stemmer, original_): length_dist_original = [] length_dist_stemmed = [] for original in original_: original = nltk.word_tokenize(original) stemmed = [stemmer.stem(word) for word in original] #print("Number of distinct tokens for original", len(set(original))) #print("Number of distinct tokens for stemmed", len(set(stemmed))) length_dist_original.extend([len(word) for word in original]) length_dist_stemmed.extend([len(word) for word in stemmed]) print("Original Average:", sum(length_dist_original)/len(length_dist_original)) print("Stemmed Average:", sum(length_dist_stemmed)/len(length_dist_stemmed)) plt.hist(length_dist_original, bins=20, alpha=0.5, label='original') plt.hist(length_dist_stemmed, bins=20, alpha=0.5, label='stemmed') plt.legend() plt.xlabel('Length of a token in number of characters') plt.ylabel('Number of tokens') plt.title('Effect of stemming on CORD-19 tokens') all_tokens=[] for index, row in df1.iterrows(): all_tokens.append(row.abstract) analyse_stem(stemmer, all_tokens) ``` ### 1b. Sentence Segmentation ``` sent_tokens = nltk.sent_tokenize(df1.iloc[0].abstract) [len(nltk.word_tokenize(sent_token)) for sent_token in sent_tokens] ``` ### 1c. POS Tagging ``` nltk.download('averaged_perceptron_tagger') word_tokens = nltk.word_tokenize(sent_tokens[0]) nltk.pos_tag(word_tokens) ``` ##2. Domain: Wikipedia Math Equations Source: AsciiMath Equations Collected From Wikipedia. The [dataset](https://www.kaggle.com/finalepoch/asciimath-equations-collected-from-wikipedia) contains collection of simple equations written in AsciiMath. ``` df2 = pd.read_csv("../datasets/asciimath/math_eqn.csv", dtype=str) df2.head(5) ``` ### 2a. Tokenization and Stemming ``` df2.Math_Eqns.values[4] word_tokens = nltk.word_tokenize(df2.Math_Eqns.values[4]) " ".join(word_tokens) all_tokens=[] for index, row in df2.iterrows(): all_tokens.append(row.Math_Eqns) analyse_stem(stemmer, all_tokens) ``` ### 2b. Sentence Segmentation ``` sent_tokens = nltk.sent_tokenize(df2.iloc[0].Math_Eqns) [len(nltk.word_tokenize(sent_token)) for sent_token in sent_tokens] ``` ### 2c. POS Tagging ``` nltk.sent_tokenize(df1.iloc[8].abstract)[0] nltk.sent_tokenize(df2.iloc[17].Math_Eqns)[0] word_tokens = nltk.word_tokenize(nltk.sent_tokenize(df2.iloc[17].Math_Eqns)[0]) nltk.pos_tag(word_tokens) ``` ## 3. Domain: World Financial News ``` financial_tweets = pd.read_csv('../datasets/financialtweets/stockerbot-export.csv', dtype=str,warn_bad_lines=True, error_bad_lines=False) df3 = financial_tweets['text'].head(150) df3 ``` ### 3a. Tokenization and Stemming ``` import nltk nltk.download('punkt') word_tokens = [] for i in range(df3.shape[0]): word_tokens = word_tokens + nltk.word_tokenize(df3[i]) "|".join(word_tokens) from nltk.stem.snowball import SnowballStemmer stemmer = SnowballStemmer("english") stemmed = [stemmer.stem(word) for word in word_tokens] '|'.join(stemmed) def analyse_stem(stemmer, original_): length_dist_original = [] length_dist_stemmed = [] for original in original_: original = nltk.word_tokenize(original) stemmed = [stemmer.stem(word) for word in original] #print("Number of distinct tokens for original", len(set(original))) #print("Number of distinct tokens for stemmed", len(set(stemmed))) length_dist_original.extend([len(word) for word in original]) length_dist_stemmed.extend([len(word) for word in stemmed]) print("Original Average:", sum(length_dist_original)/len(length_dist_original)) print("Stemmed Average:", sum(length_dist_stemmed)/len(length_dist_stemmed)) plt.hist(length_dist_original, bins=20, alpha=0.5, label='original') plt.hist(length_dist_stemmed, bins=20, alpha=0.5, label='stemmed') plt.legend() plt.xlabel('Length of a token in number of characters') plt.ylabel('Number of tokens') plt.title('Effect of stemming on Finance Tweets tokens') analyse_stem(stemmer, word_tokens) ``` ### 3b. Sentence Segmentation ``` sent_tokens = nltk.sent_tokenize(df3.iloc[3]) [len(nltk.word_tokenize(sent_token)) for sent_token in sent_tokens] ``` ### 3c. POS Tagging ``` nltk.download('averaged_perceptron_tagger') word_tokens = nltk.word_tokenize(sent_tokens[0]) nltk.pos_tag(word_tokens) ``` ##4. Sentence Segmentation Analysis for all 3 datasets ``` sent_length_1 = [] for index, row in df1.iterrows(): sent_length_1.extend([len(nltk.word_tokenize(sent_token)) for sent_token in nltk.sent_tokenize(row.abstract)]) sent_length_2 = [] for index, row in df2.iterrows(): sent_length_2.extend([len(nltk.word_tokenize(sent_token)) for sent_token in nltk.sent_tokenize(row.Math_Eqns)]) sent_length_3 = [] for index, row in financial_tweets.head(20).iterrows(): sent_length_3.extend([len(nltk.word_tokenize(sent_token)) for sent_token in nltk.sent_tokenize(row.text)]) print("Dataset 1:", sum(sent_length_1)/len(sent_length_1)) print("Dataset 2:", sum(sent_length_2)/len(sent_length_2)) print("Dataset 3:", sum(sent_length_3)/len(sent_length_3)) plt.hist(sent_length_1, bins=10, alpha=0.5, label='CORD-19', density=True) plt.hist(sent_length_2, bins=10, alpha=0.5, label='ASCII Math', density=True) plt.hist(sent_length_3, bins=10, alpha=0.5, label='Financial Tweets', density=True, range=[0,100]) plt.legend() plt.xlabel('Length of a sentence in number of tokens') plt.ylabel('Percentage of sentenches') plt.title('Effect of sentence segmentation on different datasets') ```
github_jupyter
#Import libraries import pandas as pd import matplotlib.pyplot as plt df1 = pd.read_csv('../datasets/CORD19/metadata_sample.csv', dtype=str) df1.head(2).abstract.values #sample import nltk nltk.download('punkt') word_tokens = nltk.word_tokenize(df1.iloc[0].abstract) '|'.join(word_tokens) from nltk.stem.snowball import SnowballStemmer stemmer = SnowballStemmer("english") stemmed = [stemmer.stem(word) for word in word_tokens] '|'.join(stemmed) def analyse_stem(stemmer, original_): length_dist_original = [] length_dist_stemmed = [] for original in original_: original = nltk.word_tokenize(original) stemmed = [stemmer.stem(word) for word in original] #print("Number of distinct tokens for original", len(set(original))) #print("Number of distinct tokens for stemmed", len(set(stemmed))) length_dist_original.extend([len(word) for word in original]) length_dist_stemmed.extend([len(word) for word in stemmed]) print("Original Average:", sum(length_dist_original)/len(length_dist_original)) print("Stemmed Average:", sum(length_dist_stemmed)/len(length_dist_stemmed)) plt.hist(length_dist_original, bins=20, alpha=0.5, label='original') plt.hist(length_dist_stemmed, bins=20, alpha=0.5, label='stemmed') plt.legend() plt.xlabel('Length of a token in number of characters') plt.ylabel('Number of tokens') plt.title('Effect of stemming on CORD-19 tokens') all_tokens=[] for index, row in df1.iterrows(): all_tokens.append(row.abstract) analyse_stem(stemmer, all_tokens) sent_tokens = nltk.sent_tokenize(df1.iloc[0].abstract) [len(nltk.word_tokenize(sent_token)) for sent_token in sent_tokens] nltk.download('averaged_perceptron_tagger') word_tokens = nltk.word_tokenize(sent_tokens[0]) nltk.pos_tag(word_tokens) df2 = pd.read_csv("../datasets/asciimath/math_eqn.csv", dtype=str) df2.head(5) df2.Math_Eqns.values[4] word_tokens = nltk.word_tokenize(df2.Math_Eqns.values[4]) " ".join(word_tokens) all_tokens=[] for index, row in df2.iterrows(): all_tokens.append(row.Math_Eqns) analyse_stem(stemmer, all_tokens) sent_tokens = nltk.sent_tokenize(df2.iloc[0].Math_Eqns) [len(nltk.word_tokenize(sent_token)) for sent_token in sent_tokens] nltk.sent_tokenize(df1.iloc[8].abstract)[0] nltk.sent_tokenize(df2.iloc[17].Math_Eqns)[0] word_tokens = nltk.word_tokenize(nltk.sent_tokenize(df2.iloc[17].Math_Eqns)[0]) nltk.pos_tag(word_tokens) financial_tweets = pd.read_csv('../datasets/financialtweets/stockerbot-export.csv', dtype=str,warn_bad_lines=True, error_bad_lines=False) df3 = financial_tweets['text'].head(150) df3 import nltk nltk.download('punkt') word_tokens = [] for i in range(df3.shape[0]): word_tokens = word_tokens + nltk.word_tokenize(df3[i]) "|".join(word_tokens) from nltk.stem.snowball import SnowballStemmer stemmer = SnowballStemmer("english") stemmed = [stemmer.stem(word) for word in word_tokens] '|'.join(stemmed) def analyse_stem(stemmer, original_): length_dist_original = [] length_dist_stemmed = [] for original in original_: original = nltk.word_tokenize(original) stemmed = [stemmer.stem(word) for word in original] #print("Number of distinct tokens for original", len(set(original))) #print("Number of distinct tokens for stemmed", len(set(stemmed))) length_dist_original.extend([len(word) for word in original]) length_dist_stemmed.extend([len(word) for word in stemmed]) print("Original Average:", sum(length_dist_original)/len(length_dist_original)) print("Stemmed Average:", sum(length_dist_stemmed)/len(length_dist_stemmed)) plt.hist(length_dist_original, bins=20, alpha=0.5, label='original') plt.hist(length_dist_stemmed, bins=20, alpha=0.5, label='stemmed') plt.legend() plt.xlabel('Length of a token in number of characters') plt.ylabel('Number of tokens') plt.title('Effect of stemming on Finance Tweets tokens') analyse_stem(stemmer, word_tokens) sent_tokens = nltk.sent_tokenize(df3.iloc[3]) [len(nltk.word_tokenize(sent_token)) for sent_token in sent_tokens] nltk.download('averaged_perceptron_tagger') word_tokens = nltk.word_tokenize(sent_tokens[0]) nltk.pos_tag(word_tokens) sent_length_1 = [] for index, row in df1.iterrows(): sent_length_1.extend([len(nltk.word_tokenize(sent_token)) for sent_token in nltk.sent_tokenize(row.abstract)]) sent_length_2 = [] for index, row in df2.iterrows(): sent_length_2.extend([len(nltk.word_tokenize(sent_token)) for sent_token in nltk.sent_tokenize(row.Math_Eqns)]) sent_length_3 = [] for index, row in financial_tweets.head(20).iterrows(): sent_length_3.extend([len(nltk.word_tokenize(sent_token)) for sent_token in nltk.sent_tokenize(row.text)]) print("Dataset 1:", sum(sent_length_1)/len(sent_length_1)) print("Dataset 2:", sum(sent_length_2)/len(sent_length_2)) print("Dataset 3:", sum(sent_length_3)/len(sent_length_3)) plt.hist(sent_length_1, bins=10, alpha=0.5, label='CORD-19', density=True) plt.hist(sent_length_2, bins=10, alpha=0.5, label='ASCII Math', density=True) plt.hist(sent_length_3, bins=10, alpha=0.5, label='Financial Tweets', density=True, range=[0,100]) plt.legend() plt.xlabel('Length of a sentence in number of tokens') plt.ylabel('Percentage of sentenches') plt.title('Effect of sentence segmentation on different datasets')
0.291384
0.88573
# OpenMP* Device Parallelism (Fortran) #### Sections - [Learning Objectives](#Learning-Objectives) - [Device Parallelism](#Device-Parallelism) - [GPU Architecture](#GPU-Architecture) - ["Normal" OpenMP constructs](#"Normal"-OpenMP-constructs) - [League of Teams](#League-of-Teams) - [Worksharing with Teams](#Worksharing-with-Teams) - _Code:_ [Lab Exercise: OpenMP Device Parallelism](#Lab-Exercise:-OpenMP-Device-Parallelism) ## Learning Objectives * Explain basic GPU Architecture * Be able to use OpenMP offload worksharing constructs to fully utilize the GPU ### Prerequisites Basic understanding of OpenMP constructs are assumed for this module. You also should have already went through the [Introduction to OpenMP Offload module](../intro/intro_f.ipynb) and [Managing Device Data module](../datatransfer/datatransfer_f.ipynb), where the basics of using the Jupyter notebooks with the Intel® DevCloud and an introduction to the OpenMP `target` and `target data` constructs were discussed. *** ## Device Parallelism As we've discussed in the previous modules, the OpenMP `target` construct transfers the control flow to the target device. However, the transfer of control is sequential and synchronous. In OpenMP, offload and parallelism are separate, so programmers need to explicitly create parallel regions on the target device. In theory, constructs that create parallelism on offload devices can be combined with any OpenMP construct, but in practice, only a subset of OpenMP constructs are useful for the target device. ## GPU Architecture Before diving into OpenMP parallelism constructs for target divices, let's first examine Intel® GPU architecture. <img src="Assets/GPU_Arch.png"> Intel® GPUs contain 1 or more slices. Each slice is composed of several Subslices. Each Subslice contain multiple EUs (likely 8 or more), has it's own thread dispatcher unit, instruction cache, share local memory, and other resources. EUs are compute processors that drive the SIMD ALUs. The following table displays how the OpenMP concepts of League, Team, Thread, and SIMD are mapped to GPU hardware. |OpenMP | GPU Hardware | |:----:|:----| |SIMD | SIMD Lane (Channel)| |Thread | SIMD Thread mapped to an EU | |Team | Group of threads mapped to a Subslice | |League | Multiple Teams mapped to a GPU | ## "Normal" OpenMP constructs OpenMP GPU offload support all "normal" OpenMP constructs such as `parallel`, `do`, `barrier`, `sections`, `tasks`, etc. However, not every construct will be useful for the GPU. When using these constructs, the full threading model is only supported with in a subslice, this is because there's no synchronization among subslices, and there's no coherence and memory fence among subslices' L1 caches. Let's examine the following example. ```fortran subroutine saxpy(a, x, y, sz) ! Declarations Omitted !$omp target map(to:x(1:sz)) map(tofrom(y(1:sz)) !$omp parallel do simd do i=1,sz y(i) = a * x(i) + y(i); end do !$omp end target end subroutine ``` Here, we use the `target` pragma to offload the execution to the GPU. We then use `parallel` to create a team of threads, `do` to distribute loop iterations to those threads, and `simd` to request iteration vectorization with SIMD instructions. However, due to the restrictions aforementioned, only one GPU subslice is utilized here, so the GPU would be significantly underutilized. In some cases, the compiler may deduce `team distribute` from `parallel for` and still use the entire GPU. ## League of Teams To take advantage of multiple subslices, use the `teams` pragma to create multiple **master** threads for execution. When combined with the `parallel` pragma, these master threads become a league of thread teams. Becuase there's no synchronization across teams of threads, the teams could then be assigned to different GPU subslices. <img src="Assets/teams.JPG"> When using the `teams` construct, the number of teams created is implementation defined. Although, you may optionally specify an upper limit with the **num_teams** clause. The **thread_limit** clause of the `teams` pragma can be optionally used to limit the number of threads in each team. Example: `!$omp teams num_teams(8) thread_limit(16)` ## Worksharing with Teams After a league of teams is created by `teams`, use the `distribute` construct to distribute chunks of iterations of a loop across the different teams in the league. This is analogous to what the `do` construct does for `parallel` regions. The `distribute` pragma is associated with a loop nest inside a teams region. For nested loops, the **collapse** clause can be used to specify how many loops are associated with the `distribute` pragma. You may specify a **collapse** clause with a parameter value greater than 1 to collapse associated loops into one large loop. You can also use **dist_schedule** clause on the `distribute` construct to manually specify the chunk size that are distributed to master threads of each team. For example, `!$omp distribute dist_schedule(static, 512)` would create chunks of 512 iterations. ### Example with Combined Constructs For convenience, OpenMP supports combined constructs for OpenMP offload. The code below shows how a single line can encompass all of the directives that we've discussed. ```fortran subroutine saxpy(a, x, y, sz) ! Declarations Omitted !$omp target teams distribute parallel do simd map(to:x(1:sz)) map(tofrom(y(1:sz)) do i=1,sz y(i) = a * x(i) + y(i); end do !$omp end target teams distribute parallel do simd end subroutine ``` When these constructs are used without additional clauses, the number of teams created, the number of threads created per team, and how loop iterations are distributed are all implementation defined. The following diagram breaks down the effects of each pragma in the previous example. Here we assume that there are a total of 128 loop iterations and that 4 teams, and 4 threads per team are created by the implementation. 1. The `omp target` pragma offloads the execution to device 2. The `omp teams` pragma creates multiple master threads, 4 thread teams in this diagram. 3. The `omp distribute` pragma distributes loop iterations to those 4 thread teams, 32 threads for each team shown. 4. The `omp parallel` pragma creates a team of threads for each master thread (team), 4 threads created for each team shown. 5. The `omp do` pragma distributes the 32 iterations to each of the 4 threads. 6. The `omp simd` pragma specifies that multiple iterations of the loop can be executed using SIMD instructions. <img src="Assets/distribute.JPG"> ## Lab Exercise: OpenMP Device Parallelism In this exercise, we will practice using the offload worksharing constructs on the saxpy function that we've already worked with in the previous modules. ``` #Optional, see the contents of main.cpp %pycat main.f90 ``` In the cell below, add an OpenMP directive before the outer loop to perform the following tasks. 1. Offload execution to the GPU, use the clause `map(tofrom:y) map(to:x) map(from:is_cpu, num_teams)` 2. Create NUM_BLOCKS of **master** threads, use the clause `num_teams(NUM_BLOCKS)` 3. Distribute the outer loop iterations to the varoius master threads. Ensure to also include the appropriate end directive. ``` %%writefile lab/saxpy_func_parallel.f90 ! Add combined directive here to ! 1. Offload execution to the GPU, use the cause map(tofrom:y) ! map(to: x) map(from:is_cpu) map(from:num_teams) ! 2. Create multiple master threads use clause num_teams(NUM_BLOCKS) ! 3. Distribute loop iterations to the various master threads. do ib=1,ARRAY_SIZE, NUM_BLOCKS if (ib==1) then !Test if target is the CPU host or the GPU device is_cpu=omp_is_initial_device() !Query number of teams created num_teams=omp_get_num_teams() end if do i=ib, ib+NUM_BLOCKS-1 y(i) = a*x(i) + y(i) end do end do !TODO add the appropriate end directive here ``` Next, compile code using *compile_f.sh*. If you would like to see the contents of compile_f.sh execute the following cell. ``` %pycat compile_f.sh #Execute this cell to compile the code ! chmod 755 compile_f.sh; ./compile_f.sh; ``` Once the code has been successfully compiled, run the code by executing the _run.sh_ script. ``` #Optionally examine the run script by executing this cell. %pycat run.sh ``` Execute the following cell to execute the program. Make sure you see the "Passed!" message. ``` ! chmod 755 q; chmod 755 run.sh;if [ -x "$(command -v qsub)" ]; then ./q run.sh; else ./run.sh; fi ``` _If the Jupyter cells are not responsive or if they error out when you compile the samples, please restart the Kernel and compile the samples again_ Execute the following cell to see the solution. ``` %pycat saxpy_func_parallel_solution.f90 ``` # Summary In this module, you have learned the following: * High-level overview of GPU architecture and how OpenMP constructs map to it. * Create multiple master threads that can be assigned to GPU subslices using the `teams` construct. * Distribute loop iterations to those master threads using the `distribute` construct. * Use the `teams` and `distribute` constructs combined with other OpenMP constructs for better performance. *** @Intel Corporation | [\*Trademark](https://www.intel.com/content/www/us/en/legal/trademarks.html)
github_jupyter
subroutine saxpy(a, x, y, sz) ! Declarations Omitted !$omp target map(to:x(1:sz)) map(tofrom(y(1:sz)) !$omp parallel do simd do i=1,sz y(i) = a * x(i) + y(i); end do !$omp end target end subroutine subroutine saxpy(a, x, y, sz) ! Declarations Omitted !$omp target teams distribute parallel do simd map(to:x(1:sz)) map(tofrom(y(1:sz)) do i=1,sz y(i) = a * x(i) + y(i); end do !$omp end target teams distribute parallel do simd end subroutine #Optional, see the contents of main.cpp %pycat main.f90 %%writefile lab/saxpy_func_parallel.f90 ! Add combined directive here to ! 1. Offload execution to the GPU, use the cause map(tofrom:y) ! map(to: x) map(from:is_cpu) map(from:num_teams) ! 2. Create multiple master threads use clause num_teams(NUM_BLOCKS) ! 3. Distribute loop iterations to the various master threads. do ib=1,ARRAY_SIZE, NUM_BLOCKS if (ib==1) then !Test if target is the CPU host or the GPU device is_cpu=omp_is_initial_device() !Query number of teams created num_teams=omp_get_num_teams() end if do i=ib, ib+NUM_BLOCKS-1 y(i) = a*x(i) + y(i) end do end do !TODO add the appropriate end directive here %pycat compile_f.sh #Execute this cell to compile the code ! chmod 755 compile_f.sh; ./compile_f.sh; #Optionally examine the run script by executing this cell. %pycat run.sh ! chmod 755 q; chmod 755 run.sh;if [ -x "$(command -v qsub)" ]; then ./q run.sh; else ./run.sh; fi %pycat saxpy_func_parallel_solution.f90
0.292393
0.914787
# DCGAN on MNIST Digits dataset Following the original GAN [1], Deep Convolutional Generative Adversarial Network (DCGAN) [2] is replacing some of the layers with convolutional layers. The result is similar but taking advantage of the properties of the convolutional layers: less parameters to train, space invariance. ## Learning goals - Starting from the GAN implementation notebook ([HTML](MNIST_GAN.html) / [Jupyter](MNIST_GAN.ipynb)), use convolutional layers ``` COLAB = True if COLAB: from google.colab import drive drive.mount('/content/drive') !pip install tensorview import sys import tensorflow as tf import numpy as np from tensorflow.keras import models, layers, losses, optimizers, metrics import tensorflow_datasets as tf_ds import tensorview as tv import matplotlib.pyplot as plt from pathlib import Path if COLAB: model_path = Path('/content/drive/My Drive/Colab Notebooks/DsStepByStep') else: model_path = Path('model') batch_size = 200 latent_dim = 100 # Padding to 32x32 for better filtering by convo image_width, image_height, image_channels = 32, 32, 1 mnist_dim = image_width * image_height * image_channels disc_learning_rate = 2e-4 gen_learning_rate = 2e-4 relu_alpha = 0.001 ``` # Data MNIST dataset is optimized to be stored efficiently: images are closely cropped at 28x28 pixels and stored as 1 byte per pixel (uint8 format). However, to get proper performance we need to modify the input data to insert some padding around and convert the pixel format to float on 32 bits. ``` def normalize_img(image, label): """Normalizes images: `uint8` -> `float32` and pad to 32 x 32""" image_float = tf.cast(image, tf.float32)/ 128. - 1. image_padded = tf.pad(image_float, [[0, 0], [2, 2], [2, 2], [0, 0]]) return image_padded, label (ds_train, ds_test) = tf_ds.load('mnist', split=['train', 'test'], batch_size=batch_size, as_supervised=True) ds_train = ds_train.map(normalize_img) #ds_train.batch(batch_size) ds_train = ds_train.cache() ds_test = ds_test.map(normalize_img) #ds_test = ds_test.batch(batch_size) ds_test = ds_test.cache() ds_train, ds_test ``` # Models GAN model is built out of a generator and a discriminator: - The generator gets as input some random noise on space of 100 dimensions, and issues an image (32x32 pixel raster) - The discriminator is trained to distinguish generated images by the generator (i.e. _fakes_), and reference images from the MNIST The generator and discriminator architecture are more or less symmetrical. The generator is increasing the output space dimension step by step using upsampling layers after convolutional layers. The discriminator is similar to other classification networks reducing the input space dimensions down to the binary classification layer using strides on the convolutional layer. An alternative implementation of the generator is based on the transpose convolution whose stride is able to upsample. The "game" is to jointly train the generator and discriminator in order to have the best generator but still being able to detect generated images. ``` generator = models.Sequential([ layers.Dense(128 * 8 * 8, input_dim=latent_dim, name='g_1'), layers.LeakyReLU(relu_alpha), layers.Reshape((8, 8, 128)), layers.BatchNormalization(), layers.UpSampling2D((2, 2)), layers.Dropout(0.3), layers.Conv2D(64, kernel_size=(5, 5), padding="same", name='g_c1'), layers.LeakyReLU(relu_alpha), layers.BatchNormalization(), layers.UpSampling2D((2, 2)), layers.Conv2D(1, kernel_size=(5, 5), padding="same", activation='tanh', name='g_c2') ], name='generator') generator.compile() generator.summary() discriminator = models.Sequential([ layers.Conv2D(8, kernel_size=(5, 5), strides=(2, 2), padding="same", name='d_c1', input_shape=[32, 32, 1]), layers.LeakyReLU(relu_alpha), layers.Dropout(0.3), layers.Conv2D(64, kernel_size=(5, 5), strides=(2, 2), padding="same", name='d_c2'), layers.LeakyReLU(relu_alpha), layers.Flatten(), layers.Dense(1, name='d_1') # activation='sigmoid', ], name='discriminator') discriminator.compile() discriminator.summary() ``` # Training Training is alternatively on the distriminator and generator. The discriminator is trained on a batch made of half genuine images and half trained images. The generator is trained with its output fed into the discriminator (whose wheights are frozen in this phase). GAN reputation as difficult to be trained is well deserved and originates in the joint optimization which is similar to a minimax problem (min discrination error, max fidelity of the fakes). As seen below, the noise on the losses and accuracies is high. The main facilitators helping this training are: - Use of leaky ReLU activations to avoid gradient vanishing - Small learning rate to decrease the noise and instability - Batch normalization layers to reduce variance at layer inputs These are actually the recommendations of the DCGAN paper. Due to the use of convolutional layers, and the small images at input, the number of trainable parameters of the discriminator is low. The number of parameters ot the generator is not that low since the dense layer is connected to all 100 inputs. ``` epochs = 60 batch_per_epoch = 60000/batch_size loss_object = tf.keras.losses.BinaryCrossentropy(from_logits=True) def generator_loss(disc_generated_output): return loss_object(tf.ones_like(disc_generated_output), disc_generated_output) def discriminator_loss(disc_real_output, disc_generated_output): real_loss = loss_object(tf.ones_like(disc_real_output), disc_real_output) generated_loss = loss_object(tf.zeros_like(disc_generated_output), disc_generated_output) return real_loss + generated_loss @tf.function def train_step(generator, discriminator, generator_optimizer, discriminator_optimizer, generator_latent, batch, epoch): with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape: gen_latent = generator_latent() gen_output = generator(gen_latent, training=True) disc_real_output = discriminator(batch, training=True) disc_generated_output = discriminator(gen_output, training=True) gen_loss = generator_loss(disc_generated_output) disc_loss = discriminator_loss(disc_real_output, disc_generated_output) generator_gradients = gen_tape.gradient(gen_loss, generator.trainable_variables) discriminator_gradients = disc_tape.gradient(disc_loss, discriminator.trainable_variables) generator_optimizer.apply_gradients(zip(generator_gradients, generator.trainable_variables)) discriminator_optimizer.apply_gradients(zip(discriminator_gradients, discriminator.trainable_variables)) return gen_loss, disc_loss generator_optimizer = tf.keras.optimizers.Adam(gen_learning_rate, beta_1=0.05) discriminator_optimizer = tf.keras.optimizers.Adam(disc_learning_rate, beta_1=0.05) tv_plot = tv.train.PlotMetrics(wait_num=200, columns=2, iter_num=epochs * batch_per_epoch) def generator_latent(): return tf.random.normal((batch_size, latent_dim), 0, 1) for epoch in range(epochs): for train_batch in iter(ds_train): g_loss, d_loss = train_step(generator, discriminator, generator_optimizer, discriminator_optimizer, generator_latent, train_batch[0], epoch) # Plot tv_plot.update({ 'discriminator_loss': d_loss,# 'discriminator_acc': d_acc, 'generator_loss': g_loss, # 'generator_acc': g_acc }) tv_plot.draw() gen_latent = generator_latent() gen_imgs = generator(gen_latent, training=True) fig, axes = plt.subplots(8, 8, sharex=True, sharey=True, figsize=(10, 10)) for img, ax in zip(gen_imgs, axes.ravel()): # imgs.numpy() ax.imshow(img.numpy().reshape(image_width, image_height), interpolation='nearest', cmap='gray') ax.axis('off') fig.tight_layout() discriminator.save(model_path / 'mnist_dcgan_discriminator.h5') generator.save(model_path / 'mnist_dcgan_generator.h5') ``` # Conclusion Compared to the original GAN implementation, the disriminator accuracy is not sticking above 90%. The generator seems more able to create convincing fakes. But also the variance on the metrics is high. Visually, there is less noise on the background, digits are rounder. The straight digits like 7 and 1 seems harder to generate to this mode. And there are still some "ghosts" around the main shape. ## Where to go from here - The original GAN based on dense layers ([HTML](MNIST_GAN.html) / [Jupyter](MNIST_GAN.ipynb)) - Revisit the fundamentals about deep neural networks in the CNN versus Dense classification ([HTML](../cnn/CnnVsDense-Part1.html) / [Jupyter](../cnn/CnnVsDense-Part1.jupyter) ) ## References 1. ["Generative adversarial nets"](http://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf), I. Goodfellow, J. Pouget-Abadie, M. Mirza, B. Xu, D. Warde-Farley, S. Ozair, A. Courville, Y. Bengio, NIPS 2014 2. ["Unsupervised representation learning with deep convolutional generative adversarial networks"](https://arxiv.org/pdf/1511.06434.pdf), A. Radford, L. Metz, S. Chintala, ICLR 2016 ``` ```
github_jupyter
COLAB = True if COLAB: from google.colab import drive drive.mount('/content/drive') !pip install tensorview import sys import tensorflow as tf import numpy as np from tensorflow.keras import models, layers, losses, optimizers, metrics import tensorflow_datasets as tf_ds import tensorview as tv import matplotlib.pyplot as plt from pathlib import Path if COLAB: model_path = Path('/content/drive/My Drive/Colab Notebooks/DsStepByStep') else: model_path = Path('model') batch_size = 200 latent_dim = 100 # Padding to 32x32 for better filtering by convo image_width, image_height, image_channels = 32, 32, 1 mnist_dim = image_width * image_height * image_channels disc_learning_rate = 2e-4 gen_learning_rate = 2e-4 relu_alpha = 0.001 def normalize_img(image, label): """Normalizes images: `uint8` -> `float32` and pad to 32 x 32""" image_float = tf.cast(image, tf.float32)/ 128. - 1. image_padded = tf.pad(image_float, [[0, 0], [2, 2], [2, 2], [0, 0]]) return image_padded, label (ds_train, ds_test) = tf_ds.load('mnist', split=['train', 'test'], batch_size=batch_size, as_supervised=True) ds_train = ds_train.map(normalize_img) #ds_train.batch(batch_size) ds_train = ds_train.cache() ds_test = ds_test.map(normalize_img) #ds_test = ds_test.batch(batch_size) ds_test = ds_test.cache() ds_train, ds_test generator = models.Sequential([ layers.Dense(128 * 8 * 8, input_dim=latent_dim, name='g_1'), layers.LeakyReLU(relu_alpha), layers.Reshape((8, 8, 128)), layers.BatchNormalization(), layers.UpSampling2D((2, 2)), layers.Dropout(0.3), layers.Conv2D(64, kernel_size=(5, 5), padding="same", name='g_c1'), layers.LeakyReLU(relu_alpha), layers.BatchNormalization(), layers.UpSampling2D((2, 2)), layers.Conv2D(1, kernel_size=(5, 5), padding="same", activation='tanh', name='g_c2') ], name='generator') generator.compile() generator.summary() discriminator = models.Sequential([ layers.Conv2D(8, kernel_size=(5, 5), strides=(2, 2), padding="same", name='d_c1', input_shape=[32, 32, 1]), layers.LeakyReLU(relu_alpha), layers.Dropout(0.3), layers.Conv2D(64, kernel_size=(5, 5), strides=(2, 2), padding="same", name='d_c2'), layers.LeakyReLU(relu_alpha), layers.Flatten(), layers.Dense(1, name='d_1') # activation='sigmoid', ], name='discriminator') discriminator.compile() discriminator.summary() epochs = 60 batch_per_epoch = 60000/batch_size loss_object = tf.keras.losses.BinaryCrossentropy(from_logits=True) def generator_loss(disc_generated_output): return loss_object(tf.ones_like(disc_generated_output), disc_generated_output) def discriminator_loss(disc_real_output, disc_generated_output): real_loss = loss_object(tf.ones_like(disc_real_output), disc_real_output) generated_loss = loss_object(tf.zeros_like(disc_generated_output), disc_generated_output) return real_loss + generated_loss @tf.function def train_step(generator, discriminator, generator_optimizer, discriminator_optimizer, generator_latent, batch, epoch): with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape: gen_latent = generator_latent() gen_output = generator(gen_latent, training=True) disc_real_output = discriminator(batch, training=True) disc_generated_output = discriminator(gen_output, training=True) gen_loss = generator_loss(disc_generated_output) disc_loss = discriminator_loss(disc_real_output, disc_generated_output) generator_gradients = gen_tape.gradient(gen_loss, generator.trainable_variables) discriminator_gradients = disc_tape.gradient(disc_loss, discriminator.trainable_variables) generator_optimizer.apply_gradients(zip(generator_gradients, generator.trainable_variables)) discriminator_optimizer.apply_gradients(zip(discriminator_gradients, discriminator.trainable_variables)) return gen_loss, disc_loss generator_optimizer = tf.keras.optimizers.Adam(gen_learning_rate, beta_1=0.05) discriminator_optimizer = tf.keras.optimizers.Adam(disc_learning_rate, beta_1=0.05) tv_plot = tv.train.PlotMetrics(wait_num=200, columns=2, iter_num=epochs * batch_per_epoch) def generator_latent(): return tf.random.normal((batch_size, latent_dim), 0, 1) for epoch in range(epochs): for train_batch in iter(ds_train): g_loss, d_loss = train_step(generator, discriminator, generator_optimizer, discriminator_optimizer, generator_latent, train_batch[0], epoch) # Plot tv_plot.update({ 'discriminator_loss': d_loss,# 'discriminator_acc': d_acc, 'generator_loss': g_loss, # 'generator_acc': g_acc }) tv_plot.draw() gen_latent = generator_latent() gen_imgs = generator(gen_latent, training=True) fig, axes = plt.subplots(8, 8, sharex=True, sharey=True, figsize=(10, 10)) for img, ax in zip(gen_imgs, axes.ravel()): # imgs.numpy() ax.imshow(img.numpy().reshape(image_width, image_height), interpolation='nearest', cmap='gray') ax.axis('off') fig.tight_layout() discriminator.save(model_path / 'mnist_dcgan_discriminator.h5') generator.save(model_path / 'mnist_dcgan_generator.h5')
0.718199
0.943971
# Finding MetaCharacters Here’s a complete list of the metacharacters used in regular expressions: ```python . ^ $ * + ? { } [ ] \ | ( ) ``` As we mentioned in the previous lesson, these metacharacters are used to give special instructions and can't be searched for directly. If we want to search for these metacharacters directly in strings we need to escape them first. Just like with Python string literals, we can use the backslash (`\`) to escape all the metacharacters. Let’s see an example. Let's try to find the period (`.`) at the end of our `sample_text` again, but this time we will use a backslash (`\`) in our regular expression to remove the period's special meaning, as shown in the code below: ``` # Import re module import re # Sample text sample_text = 'Alice and Walter are walking to the store.' # Create a regular expression object with the regular expression '\.' regex = re.compile(r'\.') # Search the sample_text for the regular expression matches = regex.finditer(sample_text) # Print all the matches for match in matches: print(match) ``` We can see that now, we have managed to find only the period (`.`) at the end of the `sample_text` string, as was intended. To search for any of the other metacharacters we can do exactly the same thing. # TODO: Find All The MetaCharacters In the cell below, we have a string that contains all the metacharacters. Write a single regular expression to check that you can match all the metacharacters using a backslash, and save the regular expression object in a variable called `regex`. Then use the `.finditer()` method to search the `sample_text` string for the given regular expression. Then, write a loop to print all the `matches` found by the `.finditer()` method. Finally, use the ` match.span()` method to print the match from the `sample_text` string. ``` # Import re module import re # Sample text sample_text = '. ^ $ * + ? { } [ ] \ | ( )' # Create a regular expression object with the regular expression regex = re.compile(r'\. \^ \$ \* \+ \? \{ \} \[ \] \\ \| \( \)') # Search the sample_text for the regular expression matches = regex.finditer(sample_text) # Print all the matches for match in matches: print(match) ``` # TODO: Find The Price In the cell below, write a regular expression that matches the price of the coat bought by John and save the regular expression object in a variable called `regex`. Then use the `.finditer()` method to search the `sample_text` string for the given regular expression. Then, write a loop to print all the `matches` found by the `.finditer()` method . Finally, use the ` match.span()` method to print the match from the `sample_text` string. ``` # Import re module import re # Sample text sample_text = 'John bought a winter coat for $25.99 dollars.' # Create a regular expression object with the regular expression regex = re.compile(r'[$[0-9|0-9|.|]') # Search the sample_text for the regular expression matches = regex.finditer(sample_text) # Print all the matches for match in matches: print(match) ``` # Solution [Solution notebook](finding_metacharacters_solution.ipynb)
github_jupyter
. ^ $ * + ? { } [ ] \ | ( ) # Import re module import re # Sample text sample_text = 'Alice and Walter are walking to the store.' # Create a regular expression object with the regular expression '\.' regex = re.compile(r'\.') # Search the sample_text for the regular expression matches = regex.finditer(sample_text) # Print all the matches for match in matches: print(match) # Import re module import re # Sample text sample_text = '. ^ $ * + ? { } [ ] \ | ( )' # Create a regular expression object with the regular expression regex = re.compile(r'\. \^ \$ \* \+ \? \{ \} \[ \] \\ \| \( \)') # Search the sample_text for the regular expression matches = regex.finditer(sample_text) # Print all the matches for match in matches: print(match) # Import re module import re # Sample text sample_text = 'John bought a winter coat for $25.99 dollars.' # Create a regular expression object with the regular expression regex = re.compile(r'[$[0-9|0-9|.|]') # Search the sample_text for the regular expression matches = regex.finditer(sample_text) # Print all the matches for match in matches: print(match)
0.498779
0.964689
``` import graphlab products = graphlab.SFrame('Amazon_baby.sframe/') selected_words = ['awesome', 'great', 'fantastic', 'amazing', 'love', 'horrible', 'bad', 'terrible', 'awful', 'wow', 'hate'] products['words_count'] = graphlab.text_analytics.count_words(products['review']) def count_word(words_count,word): if word in words_count: return words_count[word] else: return 0 for curr_word in selected_words: products[curr_word] = products['words_count'].apply(lambda dic : count_word(dic,curr_word)) products for curr_word in selected_words: print products[curr_word].sum() # remove neutral products = products[products['rating'] != 3] products['sentiment'] = products['rating'] >= 4 train_data, test_data = products.random_split(.8,seed=0) selected_words_model = graphlab.logistic_classifier.create(train_data,target='sentiment',features=selected_words,validation_set=test_data) coffs=selected_words_model['coefficients'] coffs weights = coffs['value'].sort(ascending=True) weights name_weights = coffs[['name','value']].sort('value') name_weights # evaluate our model selected_words_model.evaluate(test_data) pos_rev=test_data[ test_data['sentiment'] == 1] pos_rev.num_rows()*1.0 / test_data.num_rows() baby_diaper_reviews = products[products['name'] == 'Baby Trend Diaper Champ'] len(baby_diaper_reviews) baby_diaper_reviews['predicted_sentiment'] = selected_words_model.predict(baby_diaper_reviews,output_type='probability') baby_diaper_reviews baby_diaper_reviews[baby_diaper_reviews['review'] == "My baby is now 8 months and the can has been helpful. I think it's great to make sure the really smelly ones are sealed, especially if I can't run to dump the trash outside. I do usually bag the really bad ones, so I don't dirty the the entry. It's also great now that the baby is crawling. She can easily knock over a trash can, but the Diaper Champ is much heavier and she hasn't been able to get into it. I doubt she will be able to get into it even when she is older.The bags are easily replaceable and affordable, far more than other options. My friends recommended against the other options, which they claimed they worked for awhile, but soon became cost ineffective and smelled. My friends liked my choice.You do have to empty the Diaper Champ can and clean it, but since it holds some pretty toxic trash, I would recommend that with any disposal system. I'm extremely satisfied."] baby_diaper_reviews.sort('predicted_sentiment',ascending=False) ```
github_jupyter
import graphlab products = graphlab.SFrame('Amazon_baby.sframe/') selected_words = ['awesome', 'great', 'fantastic', 'amazing', 'love', 'horrible', 'bad', 'terrible', 'awful', 'wow', 'hate'] products['words_count'] = graphlab.text_analytics.count_words(products['review']) def count_word(words_count,word): if word in words_count: return words_count[word] else: return 0 for curr_word in selected_words: products[curr_word] = products['words_count'].apply(lambda dic : count_word(dic,curr_word)) products for curr_word in selected_words: print products[curr_word].sum() # remove neutral products = products[products['rating'] != 3] products['sentiment'] = products['rating'] >= 4 train_data, test_data = products.random_split(.8,seed=0) selected_words_model = graphlab.logistic_classifier.create(train_data,target='sentiment',features=selected_words,validation_set=test_data) coffs=selected_words_model['coefficients'] coffs weights = coffs['value'].sort(ascending=True) weights name_weights = coffs[['name','value']].sort('value') name_weights # evaluate our model selected_words_model.evaluate(test_data) pos_rev=test_data[ test_data['sentiment'] == 1] pos_rev.num_rows()*1.0 / test_data.num_rows() baby_diaper_reviews = products[products['name'] == 'Baby Trend Diaper Champ'] len(baby_diaper_reviews) baby_diaper_reviews['predicted_sentiment'] = selected_words_model.predict(baby_diaper_reviews,output_type='probability') baby_diaper_reviews baby_diaper_reviews[baby_diaper_reviews['review'] == "My baby is now 8 months and the can has been helpful. I think it's great to make sure the really smelly ones are sealed, especially if I can't run to dump the trash outside. I do usually bag the really bad ones, so I don't dirty the the entry. It's also great now that the baby is crawling. She can easily knock over a trash can, but the Diaper Champ is much heavier and she hasn't been able to get into it. I doubt she will be able to get into it even when she is older.The bags are easily replaceable and affordable, far more than other options. My friends recommended against the other options, which they claimed they worked for awhile, but soon became cost ineffective and smelled. My friends liked my choice.You do have to empty the Diaper Champ can and clean it, but since it holds some pretty toxic trash, I would recommend that with any disposal system. I'm extremely satisfied."] baby_diaper_reviews.sort('predicted_sentiment',ascending=False)
0.182717
0.487063
<!--BOOK_INFORMATION--> <a href="https://www.packtpub.com/big-data-and-business-intelligence/machine-learning-opencv" target="_blank"><img align="left" src="data/cover.jpg" style="width: 76px; height: 100px; background: white; padding: 1px; border: 1px solid black; margin-right:10px;"></a> *This notebook contains an excerpt from the book [Machine Learning for OpenCV](https://www.packtpub.com/big-data-and-business-intelligence/machine-learning-opencv) by Michael Beyeler. The code is released under the [MIT license](https://opensource.org/licenses/MIT), and is available on [GitHub](https://github.com/mbeyeler/opencv-machine-learning).* *Note that this excerpt contains only the raw code - the book is rich with additional explanations and illustrations. If you find this content useful, please consider supporting the work by [buying the book](https://www.packtpub.com/big-data-and-business-intelligence/machine-learning-opencv)!* <!--NAVIGATION--> < [Combining Different Models Into a Voting Classifier](10.05-Combining-Different-Models-Into-a-Voting-Classifier.ipynb) | [Contents](../README.md) | [Evaluating a Model](11.01-Evaluating-a-Model.ipynb) > # Selecting the Right Model with Hyper-Parameter Tuning In this chapter, we will dive deeper into **model evaluation** and **hyperparameter tuning**. Assume that we have two different models that might apply to our task. How can we know which one is better? Answering this question often involves repeatedly fitting different versions of our model to different subsets of the data, such as in **cross-validation** and **bootstrapping**. In combination with different scoring functions, we can obtain reliable estimates of the generalization performance of our models. But what if two different models give similar results? Can we be sure that the two models are equivalent, or is it possible that one of them just got lucky? How can we know whether one of them is significantly better than the other? Answering these questions will lead us to discussing some useful statistical tests such as **Students t-test** and **McNemar's test**. As we will get familiar with these techniques, we will also want to answer the following questions: - What's the best strategy to tweak the hyperparameters of a model? - How can we compare the performance of different models in a fair way? - How do we select the right machine learning tool for the task at hand? ## Outline - [Evaluating a Model](11.01-Evaluating-a-Model.ipynb) - [Understanding Cross-Validation, Bootstrapping, and McNemar's Test](11.02-Understanding-Cross-Validation-Bootstrapping-and-McNemar's-Test.ipynb) - [Tuning Hyperparameters with Grid Search](11.03-Tuning-Hyperparameters-with-Grid-Search.ipynb) - [Chaining Algorithms Together to Form a Pipeline](11.04-Chaining-Algorithms-Together-to-Form-a-Pipeline.ipynb) <!--NAVIGATION--> < [Combining Different Models Into a Voting Classifier](10.05-Combining-Different-Models-Into-a-Voting-Classifier.ipynb) | [Contents](../README.md) | [Evaluating a Model](11.01-Evaluating-a-Model.ipynb) >
github_jupyter
<!--BOOK_INFORMATION--> <a href="https://www.packtpub.com/big-data-and-business-intelligence/machine-learning-opencv" target="_blank"><img align="left" src="data/cover.jpg" style="width: 76px; height: 100px; background: white; padding: 1px; border: 1px solid black; margin-right:10px;"></a> *This notebook contains an excerpt from the book [Machine Learning for OpenCV](https://www.packtpub.com/big-data-and-business-intelligence/machine-learning-opencv) by Michael Beyeler. The code is released under the [MIT license](https://opensource.org/licenses/MIT), and is available on [GitHub](https://github.com/mbeyeler/opencv-machine-learning).* *Note that this excerpt contains only the raw code - the book is rich with additional explanations and illustrations. If you find this content useful, please consider supporting the work by [buying the book](https://www.packtpub.com/big-data-and-business-intelligence/machine-learning-opencv)!* <!--NAVIGATION--> < [Combining Different Models Into a Voting Classifier](10.05-Combining-Different-Models-Into-a-Voting-Classifier.ipynb) | [Contents](../README.md) | [Evaluating a Model](11.01-Evaluating-a-Model.ipynb) > # Selecting the Right Model with Hyper-Parameter Tuning In this chapter, we will dive deeper into **model evaluation** and **hyperparameter tuning**. Assume that we have two different models that might apply to our task. How can we know which one is better? Answering this question often involves repeatedly fitting different versions of our model to different subsets of the data, such as in **cross-validation** and **bootstrapping**. In combination with different scoring functions, we can obtain reliable estimates of the generalization performance of our models. But what if two different models give similar results? Can we be sure that the two models are equivalent, or is it possible that one of them just got lucky? How can we know whether one of them is significantly better than the other? Answering these questions will lead us to discussing some useful statistical tests such as **Students t-test** and **McNemar's test**. As we will get familiar with these techniques, we will also want to answer the following questions: - What's the best strategy to tweak the hyperparameters of a model? - How can we compare the performance of different models in a fair way? - How do we select the right machine learning tool for the task at hand? ## Outline - [Evaluating a Model](11.01-Evaluating-a-Model.ipynb) - [Understanding Cross-Validation, Bootstrapping, and McNemar's Test](11.02-Understanding-Cross-Validation-Bootstrapping-and-McNemar's-Test.ipynb) - [Tuning Hyperparameters with Grid Search](11.03-Tuning-Hyperparameters-with-Grid-Search.ipynb) - [Chaining Algorithms Together to Form a Pipeline](11.04-Chaining-Algorithms-Together-to-Form-a-Pipeline.ipynb) <!--NAVIGATION--> < [Combining Different Models Into a Voting Classifier](10.05-Combining-Different-Models-Into-a-Voting-Classifier.ipynb) | [Contents](../README.md) | [Evaluating a Model](11.01-Evaluating-a-Model.ipynb) >
0.873498
0.877056
``` import pandas as pd import numpy as np import matplotlib.pyplot as plt #read the file df = pd.read_json (r'VZ.json') #print the head df df['t'] = pd.to_datetime(df['t'], unit='s') df = df.rename(columns={'c': 'Close', 'h': 'High', 'l':'Low', 'o': 'Open', 's': 'Status', 't': 'Date', 'v': 'Volume'}) df.head() ``` # Linear Regression ``` #read the file df = pd.read_json (r'VZ.json') #print the head df df['t'] = pd.to_datetime(df['t'], unit='s') X = df[['t']] y = df['c'].values.reshape(-1, 1) print(X.shape, y.shape) data = X.copy() data_binary_encoded = pd.get_dummies(data) data_binary_encoded.head() from sklearn.model_selection import train_test_split X = pd.get_dummies(X) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42) X_train.head() from sklearn.preprocessing import StandardScaler X_scaler = StandardScaler().fit(X_train) y_scaler = StandardScaler().fit(y_train) X_train_scaled = X_scaler.transform(X_train) X_test_scaled = X_scaler.transform(X_test) y_train_scaled = y_scaler.transform(y_train) y_test_scaled = y_scaler.transform(y_test) from sklearn.linear_model import LinearRegression model = LinearRegression() model.fit(X_train_scaled, y_train_scaled) plt.scatter(model.predict(X_train_scaled), model.predict(X_train_scaled) - y_train_scaled, c="blue", label="Training Data") plt.scatter(model.predict(X_test_scaled), model.predict(X_test_scaled) - y_test_scaled, c="orange", label="Testing Data") plt.legend() plt.hlines(y=0, xmin=y_test_scaled.min(), xmax=y_test_scaled.max()) plt.title("Residual Plot") plt.show() predictions = model.predict(X_test_scaled) predictions new_data['mon_fri'] = 0 for i in range(0,len(new_data)): if (new_data['Dayofweek'][i] == 0 or new_data['Dayofweek'][i] == 4): new_data['mon_fri'][i] = 1 else: new_data['mon_fri'][i] = 0 #split into train and validation train = new_data[:987] valid = new_data[987:] x_train = train.drop('Close', axis=1) y_train = train['Close'] x_valid = valid.drop('Close', axis=1) y_valid = valid['Close'] #implement linear regression from sklearn.linear_model import LinearRegression model = LinearRegression() model.fit(x_train,y_train) #make predictions and find the rmse preds = model.predict(X_test_scaled) rms=np.sqrt(np.mean(np.power((np.array(y_test_scaled)-np.array(preds)),2))) rms from sklearn.metrics import mean_squared_error predictions = model.predict(X_test_scaled) MSE = mean_squared_error(y_test_scaled, predictions) r2 = model.score(X_test_scaled, y_test_scaled) print(f"MSE: {MSE}, R2: {r2}") #plot valid['Predictions'] = 0 valid['Predictions'] = preds valid.index = new_data[987:].index train.index = new_data[:987].index plt.plot(train['Close']) plt.plot(valid[['Close', 'Predictions']]) ``` # K-Nearest Neighbours ``` import matplotlib.pyplot as plt from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import accuracy_score #read the file df = pd.read_json (r'VZ.json') #print the head df df['t'] = pd.to_datetime(df['t'], unit='s') df = df.rename(columns={'c': 'Close', 'h': 'High', 'l':'Low', 'o': 'Open', 's': 'Status', 't': 'Date', 'v': 'Volume'}) df.head() # Predictor variables df['Open-Close']= df.Open -df.Close df['High-Low'] = df.High - df.Low df =df.dropna() X= df[['Open-Close', 'High-Low']] X.head() # Target variable Y= np.where(df['Close'].shift(-1)>df['Close'],1,-1) # Splitting the dataset split_percentage = 0.7 split = int(split_percentage*len(df)) X_train = X[:split] Y_train = Y[:split] X_test = X[split:] Y_test = Y[split:] train_scores = [] test_scores = [] for k in range(1, 50, 2): knn = KNeighborsClassifier(n_neighbors=k) knn.fit(X_train, Y_train) train_score = knn.score(X_train, Y_train) test_score = knn.score(X_test, Y_test) train_scores.append(train_score) test_scores.append(test_score) print(f"k: {k}, Train/Test Score: {train_score:.3f}/{test_score:.3f}") plt.plot(range(1, 50, 2), train_scores, marker='o') plt.plot(range(1, 50, 2), test_scores, marker="x") plt.xlabel("k neighbors") plt.ylabel("Testing accuracy Score") plt.show() # Instantiate KNN learning model(k=15) knn = KNeighborsClassifier(n_neighbors=15) # fit the model knn.fit(X_train, Y_train) # Accuracy Score accuracy_train = accuracy_score(Y_train, knn.predict(X_train)) accuracy_test = accuracy_score(Y_test, knn.predict(X_test)) print ('Train_data Accuracy: %.2f' %accuracy_train) print ('Test_data Accuracy: %.2f' %accuracy_test) len(Y_train) pred = knn.predict(X_test) pred pd.DataFrame({"Prediction": pred, 'Actual': Y_test}) # Predicted Signal df['Predicted_Signal'] = knn.predict(X) # SPY Cumulative Returns df['SPY_returns'] = np.log(df['Close']/df['Close'].shift(1)) Cumulative_SPY_returns = df[split:]['SPY_returns'].cumsum()*100 # Cumulative Strategy Returns df['Startegy_returns'] = df['SPY_returns']* df['Predicted_Signal'].shift(1) Cumulative_Strategy_returns = df[split:]['Startegy_returns'].cumsum()*100 # Plot the results to visualize the performance plt.figure(figsize=(10,5)) plt.plot(Cumulative_SPY_returns, color='r',label = 'SPY Returns') plt.plot(Cumulative_Strategy_returns, color='g', label = 'Strategy Returns') plt.legend() plt.show() df ``` What is Sharpe Ratio? Sharpe ratio is a measure for calculating risk-adjusted return. It is the ratio of the excess expected return of investment (over risk-free rate) per unit of volatility or standard deviation. Let us see the formula for Sharpe ratio which will make things much clearer. The sharpe ratio calculation is done in the following manner Sharpe Ratio = (Rx – Rf) / StdDev(x) Where, x is the investment Rx is the average rate of return of x Rf is the risk-free rate of return StdDev(x) is the standard deviation of Rx Once you see the formula, you will understand that we deduct the risk-free rate of return as this helps us in figuring out if the strategy makes sense or not. If the Numerator turned out negative, wouldn’t it be better to invest in a government bond which guarantees you a risk-free rate of return? Some of you would recognise this as the risk-adjusted return. In the denominator, we have the standard deviation of the average return of the investment. It helps us in identifying the volatility as well as the risk associated with the investment. Thus, the Sharpe ratio helps us in identifying which strategy gives better returns in comparison to the volatility. There, that is all when it comes to sharpe ratio calculation. Let’s take an example now to see how the Sharpe ratio calculation helps us. You have devised a strategy and created a portfolio of different stocks. After backtesting, you observe that this portfolio, let’s call it Portfolio A, will give a return of 11%. However, you are concerned with the volatility at 8%. Now, you change certain parameters and pick different financial instruments to create another portfolio, Portfolio B. This portfolio gives an expected return of 8%, but the volatility now drops to 4%. ``` # Calculate Sharpe reatio Std = Cumulative_Strategy_returns.std() Sharpe = (Cumulative_Strategy_returns-Cumulative_SPY_returns)/Std Sharpe = Sharpe.mean() print ('Sharpe ratio: %.2f'%Sharpe ) ``` Tested many neighbours and the lowest sharpe ratio was for 15. # Auto ARIMA ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt from pandas.plotting import lag_plot from pandas import datetime from statsmodels.tsa.arima_model import ARIMA from sklearn.metrics import mean_squared_error #read the file df = pd.read_json (r'VZ.json') #print the head df plt.figure(figsize=(10,10)) lag_plot(df['c'], lag=5) plt.title('Microsoft Autocorrelation plot') size = len(df) train_data, test_data = df[0:int(len(df)*0.8)], df[int(len(df)*0.8):] plt.figure(figsize=(12,7)) plt.title('Microsoft Prices') plt.xlabel('Dates') plt.ylabel('Prices') plt.plot(df['c'], 'blue', label='Training Data') plt.plot(test_data['c'], 'green', label='Testing Data') plt.xticks(np.arange(0,size, 300), df['t'][0:size:300]) plt.legend() def smape_kun(y_true, y_pred): return np.mean((np.abs(y_pred - y_true) * 200/ (np.abs(y_pred) + np.abs(y_true)))) train_ar = train_data['c'].values test_ar = test_data['c'].values history = [x for x in train_ar] print(type(history)) predictions = list() for t in range(len(test_ar)): model = ARIMA(history, order=(5,1,0)) model_fit = model.fit(disp=0) output = model_fit.forecast() yhat = output[0] predictions.append(yhat) obs = test_ar[t] history.append(obs) error = mean_squared_error(test_ar, predictions) print('Testing Mean Squared Error: %.3f' % error) error2 = smape_kun(test_ar, predictions) print('Symmetric mean absolute percentage error: %.3f' % error2) pd.DataFrame({"Prediction": predictions, 'Actual': test_ar}) plt.figure(figsize=(12,7)) plt.plot(df['c'], 'green', color='blue', label='Training Data') plt.plot(test_data.index, predictions, color='green', marker='o', linestyle='dashed', label='Predicted Price') plt.plot(test_data.index, test_data['c'], color='red', label='Actual Price') plt.title('Microsoft Prices Prediction') plt.xlabel('Dates') plt.ylabel('Prices') plt.xticks(np.arange(0,size, 1300), df['t'][0:size:1300]) plt.legend() ``` # Prophet ``` #read the file df = pd.read_json (r'VZ.json') #print the head df df['t'] = pd.to_datetime(df['t'], unit='s') df = df.rename(columns={'c': 'Close', 'h': 'High', 'l':'Low', 'o': 'Open', 's': 'Status', 't': 'Date', 'v': 'Volume'}) df.head() size = len(df) #importing prophet from fbprophet import Prophet #creating dataframe new_data = pd.DataFrame(index=range(0,len(df)),columns=['Date', 'Close']) for i in range(0,len(df)): new_data['Date'][i] = df['Date'][i] new_data['Close'][i] = df['Close'][i] new_data['Date'] = pd.to_datetime(new_data.Date,format='%Y-%m-%d') new_data.index = new_data['Date'] #preparing data new_data.rename(columns={'Close': 'y', 'Date': 'ds'}, inplace=True) new_data[:size] #train and validation train = new_data[:size] valid = new_data[size:] len(valid) #fit the model model = Prophet() model.fit(train) #predictions close_prices = model.make_future_dataframe(periods=size) forecast = model.predict(close_prices) close_prices.tail(2) #rmse forecast_valid = forecast['yhat'][size:] print(forecast_valid.shape, valid['y'].shape) rms=np.sqrt(np.mean(np.power((np.array(new_data['y'])-np.array(forecast_valid)),2))) rms new_data['yhat'] = forecast['yhat'] #plot new_data['Predictions'] = 0 new_data['Predictions'] = forecast_valid.values plt.plot(train['y']) plt.plot(new_data[['y', 'Predictions']]) new_data['Predictions'] pd.DataFrame({"Prediction": new_data['Predictions'], "Actual": new_data['y']}) fig1 =model.plot(forecast) # to view the forecast components fig1 = model.plot_components(forecast) ```
github_jupyter
import pandas as pd import numpy as np import matplotlib.pyplot as plt #read the file df = pd.read_json (r'VZ.json') #print the head df df['t'] = pd.to_datetime(df['t'], unit='s') df = df.rename(columns={'c': 'Close', 'h': 'High', 'l':'Low', 'o': 'Open', 's': 'Status', 't': 'Date', 'v': 'Volume'}) df.head() #read the file df = pd.read_json (r'VZ.json') #print the head df df['t'] = pd.to_datetime(df['t'], unit='s') X = df[['t']] y = df['c'].values.reshape(-1, 1) print(X.shape, y.shape) data = X.copy() data_binary_encoded = pd.get_dummies(data) data_binary_encoded.head() from sklearn.model_selection import train_test_split X = pd.get_dummies(X) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42) X_train.head() from sklearn.preprocessing import StandardScaler X_scaler = StandardScaler().fit(X_train) y_scaler = StandardScaler().fit(y_train) X_train_scaled = X_scaler.transform(X_train) X_test_scaled = X_scaler.transform(X_test) y_train_scaled = y_scaler.transform(y_train) y_test_scaled = y_scaler.transform(y_test) from sklearn.linear_model import LinearRegression model = LinearRegression() model.fit(X_train_scaled, y_train_scaled) plt.scatter(model.predict(X_train_scaled), model.predict(X_train_scaled) - y_train_scaled, c="blue", label="Training Data") plt.scatter(model.predict(X_test_scaled), model.predict(X_test_scaled) - y_test_scaled, c="orange", label="Testing Data") plt.legend() plt.hlines(y=0, xmin=y_test_scaled.min(), xmax=y_test_scaled.max()) plt.title("Residual Plot") plt.show() predictions = model.predict(X_test_scaled) predictions new_data['mon_fri'] = 0 for i in range(0,len(new_data)): if (new_data['Dayofweek'][i] == 0 or new_data['Dayofweek'][i] == 4): new_data['mon_fri'][i] = 1 else: new_data['mon_fri'][i] = 0 #split into train and validation train = new_data[:987] valid = new_data[987:] x_train = train.drop('Close', axis=1) y_train = train['Close'] x_valid = valid.drop('Close', axis=1) y_valid = valid['Close'] #implement linear regression from sklearn.linear_model import LinearRegression model = LinearRegression() model.fit(x_train,y_train) #make predictions and find the rmse preds = model.predict(X_test_scaled) rms=np.sqrt(np.mean(np.power((np.array(y_test_scaled)-np.array(preds)),2))) rms from sklearn.metrics import mean_squared_error predictions = model.predict(X_test_scaled) MSE = mean_squared_error(y_test_scaled, predictions) r2 = model.score(X_test_scaled, y_test_scaled) print(f"MSE: {MSE}, R2: {r2}") #plot valid['Predictions'] = 0 valid['Predictions'] = preds valid.index = new_data[987:].index train.index = new_data[:987].index plt.plot(train['Close']) plt.plot(valid[['Close', 'Predictions']]) import matplotlib.pyplot as plt from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import accuracy_score #read the file df = pd.read_json (r'VZ.json') #print the head df df['t'] = pd.to_datetime(df['t'], unit='s') df = df.rename(columns={'c': 'Close', 'h': 'High', 'l':'Low', 'o': 'Open', 's': 'Status', 't': 'Date', 'v': 'Volume'}) df.head() # Predictor variables df['Open-Close']= df.Open -df.Close df['High-Low'] = df.High - df.Low df =df.dropna() X= df[['Open-Close', 'High-Low']] X.head() # Target variable Y= np.where(df['Close'].shift(-1)>df['Close'],1,-1) # Splitting the dataset split_percentage = 0.7 split = int(split_percentage*len(df)) X_train = X[:split] Y_train = Y[:split] X_test = X[split:] Y_test = Y[split:] train_scores = [] test_scores = [] for k in range(1, 50, 2): knn = KNeighborsClassifier(n_neighbors=k) knn.fit(X_train, Y_train) train_score = knn.score(X_train, Y_train) test_score = knn.score(X_test, Y_test) train_scores.append(train_score) test_scores.append(test_score) print(f"k: {k}, Train/Test Score: {train_score:.3f}/{test_score:.3f}") plt.plot(range(1, 50, 2), train_scores, marker='o') plt.plot(range(1, 50, 2), test_scores, marker="x") plt.xlabel("k neighbors") plt.ylabel("Testing accuracy Score") plt.show() # Instantiate KNN learning model(k=15) knn = KNeighborsClassifier(n_neighbors=15) # fit the model knn.fit(X_train, Y_train) # Accuracy Score accuracy_train = accuracy_score(Y_train, knn.predict(X_train)) accuracy_test = accuracy_score(Y_test, knn.predict(X_test)) print ('Train_data Accuracy: %.2f' %accuracy_train) print ('Test_data Accuracy: %.2f' %accuracy_test) len(Y_train) pred = knn.predict(X_test) pred pd.DataFrame({"Prediction": pred, 'Actual': Y_test}) # Predicted Signal df['Predicted_Signal'] = knn.predict(X) # SPY Cumulative Returns df['SPY_returns'] = np.log(df['Close']/df['Close'].shift(1)) Cumulative_SPY_returns = df[split:]['SPY_returns'].cumsum()*100 # Cumulative Strategy Returns df['Startegy_returns'] = df['SPY_returns']* df['Predicted_Signal'].shift(1) Cumulative_Strategy_returns = df[split:]['Startegy_returns'].cumsum()*100 # Plot the results to visualize the performance plt.figure(figsize=(10,5)) plt.plot(Cumulative_SPY_returns, color='r',label = 'SPY Returns') plt.plot(Cumulative_Strategy_returns, color='g', label = 'Strategy Returns') plt.legend() plt.show() df # Calculate Sharpe reatio Std = Cumulative_Strategy_returns.std() Sharpe = (Cumulative_Strategy_returns-Cumulative_SPY_returns)/Std Sharpe = Sharpe.mean() print ('Sharpe ratio: %.2f'%Sharpe ) import numpy as np import pandas as pd import matplotlib.pyplot as plt from pandas.plotting import lag_plot from pandas import datetime from statsmodels.tsa.arima_model import ARIMA from sklearn.metrics import mean_squared_error #read the file df = pd.read_json (r'VZ.json') #print the head df plt.figure(figsize=(10,10)) lag_plot(df['c'], lag=5) plt.title('Microsoft Autocorrelation plot') size = len(df) train_data, test_data = df[0:int(len(df)*0.8)], df[int(len(df)*0.8):] plt.figure(figsize=(12,7)) plt.title('Microsoft Prices') plt.xlabel('Dates') plt.ylabel('Prices') plt.plot(df['c'], 'blue', label='Training Data') plt.plot(test_data['c'], 'green', label='Testing Data') plt.xticks(np.arange(0,size, 300), df['t'][0:size:300]) plt.legend() def smape_kun(y_true, y_pred): return np.mean((np.abs(y_pred - y_true) * 200/ (np.abs(y_pred) + np.abs(y_true)))) train_ar = train_data['c'].values test_ar = test_data['c'].values history = [x for x in train_ar] print(type(history)) predictions = list() for t in range(len(test_ar)): model = ARIMA(history, order=(5,1,0)) model_fit = model.fit(disp=0) output = model_fit.forecast() yhat = output[0] predictions.append(yhat) obs = test_ar[t] history.append(obs) error = mean_squared_error(test_ar, predictions) print('Testing Mean Squared Error: %.3f' % error) error2 = smape_kun(test_ar, predictions) print('Symmetric mean absolute percentage error: %.3f' % error2) pd.DataFrame({"Prediction": predictions, 'Actual': test_ar}) plt.figure(figsize=(12,7)) plt.plot(df['c'], 'green', color='blue', label='Training Data') plt.plot(test_data.index, predictions, color='green', marker='o', linestyle='dashed', label='Predicted Price') plt.plot(test_data.index, test_data['c'], color='red', label='Actual Price') plt.title('Microsoft Prices Prediction') plt.xlabel('Dates') plt.ylabel('Prices') plt.xticks(np.arange(0,size, 1300), df['t'][0:size:1300]) plt.legend() #read the file df = pd.read_json (r'VZ.json') #print the head df df['t'] = pd.to_datetime(df['t'], unit='s') df = df.rename(columns={'c': 'Close', 'h': 'High', 'l':'Low', 'o': 'Open', 's': 'Status', 't': 'Date', 'v': 'Volume'}) df.head() size = len(df) #importing prophet from fbprophet import Prophet #creating dataframe new_data = pd.DataFrame(index=range(0,len(df)),columns=['Date', 'Close']) for i in range(0,len(df)): new_data['Date'][i] = df['Date'][i] new_data['Close'][i] = df['Close'][i] new_data['Date'] = pd.to_datetime(new_data.Date,format='%Y-%m-%d') new_data.index = new_data['Date'] #preparing data new_data.rename(columns={'Close': 'y', 'Date': 'ds'}, inplace=True) new_data[:size] #train and validation train = new_data[:size] valid = new_data[size:] len(valid) #fit the model model = Prophet() model.fit(train) #predictions close_prices = model.make_future_dataframe(periods=size) forecast = model.predict(close_prices) close_prices.tail(2) #rmse forecast_valid = forecast['yhat'][size:] print(forecast_valid.shape, valid['y'].shape) rms=np.sqrt(np.mean(np.power((np.array(new_data['y'])-np.array(forecast_valid)),2))) rms new_data['yhat'] = forecast['yhat'] #plot new_data['Predictions'] = 0 new_data['Predictions'] = forecast_valid.values plt.plot(train['y']) plt.plot(new_data[['y', 'Predictions']]) new_data['Predictions'] pd.DataFrame({"Prediction": new_data['Predictions'], "Actual": new_data['y']}) fig1 =model.plot(forecast) # to view the forecast components fig1 = model.plot_components(forecast)
0.417509
0.773281
``` import easyocr import onnxruntime import os import string from matplotlib import pyplot as plt import difflib import sys sys.path.append('/home/tandonsa/PycharmProjects/side_project/ocr_mawaqif/') from src.utils import infer_utils # add NLP Models en_model = easyocr.Reader(['en']) ar_model = easyocr.Reader(['ar']) nlp_models = [en_model,ar_model] Model_path= "/home/tandonsa/PycharmProjects/side_project/ocr_mawaqif/src/model/yolov4_1_3_320_320_static.onnx" model = onnxruntime.InferenceSession(Model_path) import logging import numpy as np import cv2 import re import logging as log import string import difflib class Inference_engine: def __init__(self, input_image, detector_model, nlp_model, detector_conf=0.1, nlp_conf=0.4, iou_thresh=0.5): self.input_img = input_image self.input_img_width = self.input_img.shape[1] self.input_img_height = self.input_img.shape[0] # Define Prediction Cofficents self.detector_conf = detector_conf self.iou_thresh = iou_thresh self.nlp_conf = nlp_conf # flag for detection self.success_detection = False self.txt_data = None # Load the model once in the memory self.session = detector_model self.en_reader = nlp_model[0] self.ar_reader = nlp_model[1] def get_licenceplate_info(self, run_detector=False): IN_IMAGE_H = self.session.get_inputs()[0].shape[2] IN_IMAGE_W = self.session.get_inputs()[0].shape[3] if run_detector: print("runnig detector") decoded_img = self.decode_img(self.input_img, shape=(IN_IMAGE_H, IN_IMAGE_W)) if decoded_img is not None: detections = self.detect(decoded_img) boxes = self.post_processing(detections, conf_thresh=self.detector_conf, nms_thresh=self.iou_thresh) self.bounding_cords = self.decode_boxes(boxes) if self.bounding_cords is None: self.txt_data = self.NLP_model(self.input_img.copy(), nlp_confidence=self.nlp_conf) elif not self.check_out_of_bounds(): cropped_alpr = self.input_img[self.bounding_cords[1]-10:self.bounding_cords[3]+20, self.bounding_cords[0]:self.bounding_cords[2]] self.txt_data = self.NLP_model(cropped_alpr.copy(), nlp_confidence=self.nlp_conf) else: self.txt_data = self.NLP_model(self.input_img, nlp_confidence=self.nlp_conf) return self.txt_data def enhance_image(self, crop_image, alpha=1.5, beta=0): gray_image = cv2.cvtColor(crop_image, cv2.COLOR_RGB2GRAY) blur_img = cv2.GaussianBlur(gray_image, (5, 5), 0) adpt_img = cv2.adaptiveThreshold(blur_img, 200, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 7, 3) return adpt_img def check_out_of_bounds(self): out_of_bounds = False if (self.bounding_cords[0] > self.input_img_width) and (self.bounding_cords[2] > self.input_img_width) and ( self.bounding_cords[1] > self.input_img_height) and (self.bounding_cords[3] > self.input_img_height): out_of_bounds = True return out_of_bounds def NLP_model(self, cropped_img, nlp_confidence=0.0): en_meta_data = [] # run NLP model on cropped image results_en = self.en_reader.readtext(cropped_img, allowlist=string.digits + string.ascii_uppercase) for rlt in results_en: en_meta_data.append([rlt[-1], rlt[-2]]) results_ar = self.ar_reader.readtext(cropped_img) nlp_data, raw_data = infer_utils.evaluate_data(en_meta_data, results_ar) nlp_data.sort(key=len) return [nlp_data, raw_data] def detect(self, decoded_image): input_name = self.session.get_inputs()[0].name outputs = self.session.get_outputs() output_names = list(map(lambda output: output.name, outputs)) detections = self.session.run(output_names, {input_name: decoded_image}) return detections def nms_cpu(self, boxes, confs, nms_thresh=0.4, min_mode=False): x1 = boxes[:, 0] y1 = boxes[:, 1] x2 = boxes[:, 2] y2 = boxes[:, 3] areas = (x2 - x1) * (y2 - y1) order = confs.argsort()[::-1] keep = [] while order.size > 0: idx_self = order[0] idx_other = order[1:] keep.append(idx_self) xx1 = np.maximum(x1[idx_self], x1[idx_other]) yy1 = np.maximum(y1[idx_self], y1[idx_other]) xx2 = np.minimum(x2[idx_self], x2[idx_other]) yy2 = np.minimum(y2[idx_self], y2[idx_other]) w = np.maximum(0.0, xx2 - xx1) h = np.maximum(0.0, yy2 - yy1) inter = w * h if min_mode: over = inter / np.minimum(areas[order[0]], areas[order[1:]]) else: over = inter / (areas[order[0]] + areas[order[1:]] - inter) inds = np.where(over <= nms_thresh)[0] order = order[inds + 1] return np.array(keep) def post_processing(self, output, conf_thresh=0.3, nms_thresh=0.5): # [batch, num, 1, 4] box_array = output[0] # [batch, num, num_classes] confs = output[1] if type(box_array).__name__ != 'ndarray': box_array = box_array.cpu().detach().numpy() confs = confs.cpu().detach().numpy() num_classes = confs.shape[2] # [batch, num, 4] box_array = box_array[:, :, 0] # [batch, num, num_classes] --> [batch, num] max_conf = np.max(confs, axis=2) max_id = np.argmax(confs, axis=2) bboxes_batch = [] for i in range(box_array.shape[0]): argwhere = max_conf[i] > conf_thresh l_box_array = box_array[i, argwhere, :] l_max_conf = max_conf[i, argwhere] l_max_id = max_id[i, argwhere] bboxes = [] # nms for each class for j in range(num_classes): cls_argwhere = l_max_id == j ll_box_array = l_box_array[cls_argwhere, :] ll_max_conf = l_max_conf[cls_argwhere] ll_max_id = l_max_id[cls_argwhere] keep = self.nms_cpu(ll_box_array, ll_max_conf, nms_thresh) if (keep.size > 0): ll_box_array = ll_box_array[keep, :] ll_max_conf = ll_max_conf[keep] ll_max_id = ll_max_id[keep] for k in range(ll_box_array.shape[0]): bboxes.append([ll_box_array[k, 0], ll_box_array[k, 1], ll_box_array[k, 2], ll_box_array[k, 3], ll_max_conf[k], ll_max_conf[k], ll_max_id[k]]) bboxes_batch.append(bboxes) return bboxes_batch def decode_boxes(self, boxes): cords = None for i in range(len(boxes[0])): box = boxes[0] x1 = int(box[i][0] * self.input_img_width) y1 = int(box[i][1] * self.input_img_height) x2 = int(box[i][2] * self.input_img_width) y2 = int(box[i][3] * self.input_img_height) cords = (x1, y1, x2, y2) return cords @staticmethod def decode_img(img, shape=(320, 320), channel=3): output_img = None try: resized = cv2.resize(img, shape, interpolation=cv2.INTER_LINEAR) trp_img = np.transpose(resized, (2, 0, 1)).astype(np.float32) output_img = np.expand_dims(trp_img, axis=0) output_img /= 255.0 except IOError as e: log.error('{}! Unable to read image'.format(e)) return output_img test_img_path = '/home/tandonsa/PycharmProjects/side_project/ocr_mawaqif/notebooks/test_imgs' img_path = os.path.join(test_img_path,'10.jpeg') import base64 encodedImage = base64.b64encode(open(img_path, "rb").read()).decode() jpg_original = base64.b64decode(encodedImage) jpg_as_np = np.frombuffer(jpg_original, dtype=np.uint8) input_img = cv2.imdecode(jpg_as_np, flags=1) input_img = cv2.cvtColor(input_img,cv2.COLOR_BGR2RGB) detector = False model_infer = Inference_engine(input_img, model, nlp_models,detector_conf=0.5,nlp_conf=0.4, iou_thresh=0.5) if detector: decoded_img = model_infer.decode_img(input_img) detections = model_infer.detect(decoded_img) boxes = model_infer.post_processing(detections, conf_thresh=0.5,nms_thresh=0.5) cords = model_infer.decode_boxes(boxes) f_image = cv2.rectangle(input_img,(cords[0],cords[1]),(cords[2],cords[3]),(0,255,0),3) crop_img = input_img[cords[1]-20:cords[3]+20,cords[0]-10:cords[2]+10] plt.figure(figsize=(7,17)) plt.imshow(f_image) plt.figure() plt.imshow(crop_img) else: plt.figure(figsize=(7,17)) plt.imshow(input_img) txt_data =model_infer.get_licenceplate_info(run_detector=detector) print("OCR model data:",txt_data[0]) print("raw:",txt_data[1]) import itertools list2d = [['dsdsd'], ['textss'], [''], ['uae']] merged = list(itertools.chain(*list2d)) list(filter(str.strip, merged)) ```
github_jupyter
import easyocr import onnxruntime import os import string from matplotlib import pyplot as plt import difflib import sys sys.path.append('/home/tandonsa/PycharmProjects/side_project/ocr_mawaqif/') from src.utils import infer_utils # add NLP Models en_model = easyocr.Reader(['en']) ar_model = easyocr.Reader(['ar']) nlp_models = [en_model,ar_model] Model_path= "/home/tandonsa/PycharmProjects/side_project/ocr_mawaqif/src/model/yolov4_1_3_320_320_static.onnx" model = onnxruntime.InferenceSession(Model_path) import logging import numpy as np import cv2 import re import logging as log import string import difflib class Inference_engine: def __init__(self, input_image, detector_model, nlp_model, detector_conf=0.1, nlp_conf=0.4, iou_thresh=0.5): self.input_img = input_image self.input_img_width = self.input_img.shape[1] self.input_img_height = self.input_img.shape[0] # Define Prediction Cofficents self.detector_conf = detector_conf self.iou_thresh = iou_thresh self.nlp_conf = nlp_conf # flag for detection self.success_detection = False self.txt_data = None # Load the model once in the memory self.session = detector_model self.en_reader = nlp_model[0] self.ar_reader = nlp_model[1] def get_licenceplate_info(self, run_detector=False): IN_IMAGE_H = self.session.get_inputs()[0].shape[2] IN_IMAGE_W = self.session.get_inputs()[0].shape[3] if run_detector: print("runnig detector") decoded_img = self.decode_img(self.input_img, shape=(IN_IMAGE_H, IN_IMAGE_W)) if decoded_img is not None: detections = self.detect(decoded_img) boxes = self.post_processing(detections, conf_thresh=self.detector_conf, nms_thresh=self.iou_thresh) self.bounding_cords = self.decode_boxes(boxes) if self.bounding_cords is None: self.txt_data = self.NLP_model(self.input_img.copy(), nlp_confidence=self.nlp_conf) elif not self.check_out_of_bounds(): cropped_alpr = self.input_img[self.bounding_cords[1]-10:self.bounding_cords[3]+20, self.bounding_cords[0]:self.bounding_cords[2]] self.txt_data = self.NLP_model(cropped_alpr.copy(), nlp_confidence=self.nlp_conf) else: self.txt_data = self.NLP_model(self.input_img, nlp_confidence=self.nlp_conf) return self.txt_data def enhance_image(self, crop_image, alpha=1.5, beta=0): gray_image = cv2.cvtColor(crop_image, cv2.COLOR_RGB2GRAY) blur_img = cv2.GaussianBlur(gray_image, (5, 5), 0) adpt_img = cv2.adaptiveThreshold(blur_img, 200, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 7, 3) return adpt_img def check_out_of_bounds(self): out_of_bounds = False if (self.bounding_cords[0] > self.input_img_width) and (self.bounding_cords[2] > self.input_img_width) and ( self.bounding_cords[1] > self.input_img_height) and (self.bounding_cords[3] > self.input_img_height): out_of_bounds = True return out_of_bounds def NLP_model(self, cropped_img, nlp_confidence=0.0): en_meta_data = [] # run NLP model on cropped image results_en = self.en_reader.readtext(cropped_img, allowlist=string.digits + string.ascii_uppercase) for rlt in results_en: en_meta_data.append([rlt[-1], rlt[-2]]) results_ar = self.ar_reader.readtext(cropped_img) nlp_data, raw_data = infer_utils.evaluate_data(en_meta_data, results_ar) nlp_data.sort(key=len) return [nlp_data, raw_data] def detect(self, decoded_image): input_name = self.session.get_inputs()[0].name outputs = self.session.get_outputs() output_names = list(map(lambda output: output.name, outputs)) detections = self.session.run(output_names, {input_name: decoded_image}) return detections def nms_cpu(self, boxes, confs, nms_thresh=0.4, min_mode=False): x1 = boxes[:, 0] y1 = boxes[:, 1] x2 = boxes[:, 2] y2 = boxes[:, 3] areas = (x2 - x1) * (y2 - y1) order = confs.argsort()[::-1] keep = [] while order.size > 0: idx_self = order[0] idx_other = order[1:] keep.append(idx_self) xx1 = np.maximum(x1[idx_self], x1[idx_other]) yy1 = np.maximum(y1[idx_self], y1[idx_other]) xx2 = np.minimum(x2[idx_self], x2[idx_other]) yy2 = np.minimum(y2[idx_self], y2[idx_other]) w = np.maximum(0.0, xx2 - xx1) h = np.maximum(0.0, yy2 - yy1) inter = w * h if min_mode: over = inter / np.minimum(areas[order[0]], areas[order[1:]]) else: over = inter / (areas[order[0]] + areas[order[1:]] - inter) inds = np.where(over <= nms_thresh)[0] order = order[inds + 1] return np.array(keep) def post_processing(self, output, conf_thresh=0.3, nms_thresh=0.5): # [batch, num, 1, 4] box_array = output[0] # [batch, num, num_classes] confs = output[1] if type(box_array).__name__ != 'ndarray': box_array = box_array.cpu().detach().numpy() confs = confs.cpu().detach().numpy() num_classes = confs.shape[2] # [batch, num, 4] box_array = box_array[:, :, 0] # [batch, num, num_classes] --> [batch, num] max_conf = np.max(confs, axis=2) max_id = np.argmax(confs, axis=2) bboxes_batch = [] for i in range(box_array.shape[0]): argwhere = max_conf[i] > conf_thresh l_box_array = box_array[i, argwhere, :] l_max_conf = max_conf[i, argwhere] l_max_id = max_id[i, argwhere] bboxes = [] # nms for each class for j in range(num_classes): cls_argwhere = l_max_id == j ll_box_array = l_box_array[cls_argwhere, :] ll_max_conf = l_max_conf[cls_argwhere] ll_max_id = l_max_id[cls_argwhere] keep = self.nms_cpu(ll_box_array, ll_max_conf, nms_thresh) if (keep.size > 0): ll_box_array = ll_box_array[keep, :] ll_max_conf = ll_max_conf[keep] ll_max_id = ll_max_id[keep] for k in range(ll_box_array.shape[0]): bboxes.append([ll_box_array[k, 0], ll_box_array[k, 1], ll_box_array[k, 2], ll_box_array[k, 3], ll_max_conf[k], ll_max_conf[k], ll_max_id[k]]) bboxes_batch.append(bboxes) return bboxes_batch def decode_boxes(self, boxes): cords = None for i in range(len(boxes[0])): box = boxes[0] x1 = int(box[i][0] * self.input_img_width) y1 = int(box[i][1] * self.input_img_height) x2 = int(box[i][2] * self.input_img_width) y2 = int(box[i][3] * self.input_img_height) cords = (x1, y1, x2, y2) return cords @staticmethod def decode_img(img, shape=(320, 320), channel=3): output_img = None try: resized = cv2.resize(img, shape, interpolation=cv2.INTER_LINEAR) trp_img = np.transpose(resized, (2, 0, 1)).astype(np.float32) output_img = np.expand_dims(trp_img, axis=0) output_img /= 255.0 except IOError as e: log.error('{}! Unable to read image'.format(e)) return output_img test_img_path = '/home/tandonsa/PycharmProjects/side_project/ocr_mawaqif/notebooks/test_imgs' img_path = os.path.join(test_img_path,'10.jpeg') import base64 encodedImage = base64.b64encode(open(img_path, "rb").read()).decode() jpg_original = base64.b64decode(encodedImage) jpg_as_np = np.frombuffer(jpg_original, dtype=np.uint8) input_img = cv2.imdecode(jpg_as_np, flags=1) input_img = cv2.cvtColor(input_img,cv2.COLOR_BGR2RGB) detector = False model_infer = Inference_engine(input_img, model, nlp_models,detector_conf=0.5,nlp_conf=0.4, iou_thresh=0.5) if detector: decoded_img = model_infer.decode_img(input_img) detections = model_infer.detect(decoded_img) boxes = model_infer.post_processing(detections, conf_thresh=0.5,nms_thresh=0.5) cords = model_infer.decode_boxes(boxes) f_image = cv2.rectangle(input_img,(cords[0],cords[1]),(cords[2],cords[3]),(0,255,0),3) crop_img = input_img[cords[1]-20:cords[3]+20,cords[0]-10:cords[2]+10] plt.figure(figsize=(7,17)) plt.imshow(f_image) plt.figure() plt.imshow(crop_img) else: plt.figure(figsize=(7,17)) plt.imshow(input_img) txt_data =model_infer.get_licenceplate_info(run_detector=detector) print("OCR model data:",txt_data[0]) print("raw:",txt_data[1]) import itertools list2d = [['dsdsd'], ['textss'], [''], ['uae']] merged = list(itertools.chain(*list2d)) list(filter(str.strip, merged))
0.447702
0.209227
### ***Goal of this notebook:*** #### The purpose of this notebook is to show the different ways implemented to associate cluster catalogs. It is designed to associate the halos in cosmoDC2 and the clusters detected by redMaPPer in cosmoDC2, but can be tuned to work with other catalogues. ### ***Rationale:*** #### Associating detected clusters to true halos (or different type of detected clusters catalogs) is non trivial. Different methods exist and may lead to slightly different results. Here we show different association methods along general statistics. ``` import GCRCatalogs import numpy as np import matplotlib.pyplot as plt from astropy.table import Table from astropy.coordinates import SkyCoord from astropy import units as u from astropy.cosmology import FlatLambdaCDM from cluster_validation.opening_catalogs_functions import * from cluster_validation.association_methods import * from cluster_validation.plotting_functions import * from cluster_validation.association_statistics import * %matplotlib inline plt.rcParams['figure.figsize'] = [9.5, 6] plt.rcParams.update({'font.size': 18}) #plt.rcParams['figure.figsize'] = [10, 8] for big figures ``` ## 0 - Opening and read catalogs #### **Function to open truth and detection catalogs** ``` #function to open truth and detection catalogs RM_cat_name = 'cosmoDC2_v1.1.4_redmapper_v0.2.1py' DC2_cat_name = 'cosmoDC2_v1.1.4' min_richness = 20 min_halo_mass = 3e14 #Msun cluster_data, member_data, truth_data, gc, gc_truth = RM_DC2_cat_open(RM_cat_name,DC2_cat_name,min_richness, min_halo_mass, cluster_only=False) #take only the halo halo_data = truth_data[truth_data['is_central']==True] min_richness = 25 # Get the redMaPPer catalog gc = GCRCatalogs.load_catalog(RM_cat_name) # Select out the cluster and member quantities into different lists quantities = gc.list_all_quantities() cluster_quantities = [q for q in quantities if 'member' not in q] member_quantities = [q for q in quantities if 'member' in q] # Read in the cluster and member data query = GCRCatalogs.GCRQuery('(richness > ' + str(min_richness) +')') cluster_data = Table(gc.get_quantities(cluster_quantities, [query])) member_data = Table(gc.get_quantities(member_quantities)) ``` #### **General catalog properties** ``` print("Number of elements in the truth catalog = ", len(truth_data)) print("Number of halos in the truth catalog = ", len(halo_data)) print("Number of clusters in the detection catalog = ", len(cluster_data)) print("Cluster catalog sky area = ", gc.sky_area, "deg2") print("Truth catalog sky area = ", gc_truth.sky_area, "deg2") #define same cosmological parameters as in the truth catalog (cosmoDC2) cosmo = gc_truth.cosmology #check the cosmological parameters in the two catalogs #print('Cosmo in truth catalog:', gc_truth.cosmology) #print('Cosmo in detection catalog:', gc_truth.cosmology) #gc_truth.halo_mass_def #gc_truth.get_catalog_info() #gc.get_catalog_info() ``` # 1 - basic visualization ``` plt.plot(cluster_data['ra_cen_0'],cluster_data['dec_cen_0'],'b.') plt.plot(truth_data['ra'],truth_data['dec'],'rx',alpha=0.1) plt.xlabel("ra") plt.ylabel("dec"); ``` # 2 - associate Redmapper detections to true DC2 halos **Association method scheme :** - search for RM associations in a given cylinder around each DC2 object (radius $\theta_{max}$ and width $\Delta_z\times(1+z_{object})$) ($\theta_{max}$ can be **fixed** - in Mpc or arcmin - **or scale** with halo mass and richness and $\Delta_z$ can be infinite) - select the **nearest** match in projected distance **or** the one with the **more galaxies in common** - repeat in the other direction (RM>DC2) - return the associations which are bijective ### - 1rst association criteria : nearest within a cylinder with $\Delta_z=\inf, \theta_{max} = 1$ arcmin ``` #criteria delta_zmax = np.inf theta_max = 1. #arcmin theta_max_type = "fixed_angle" method = "nearest" match_num_1w, match_num_2w, ind_bij = \ volume_match(halo_data, cluster_data, delta_zmax, theta_max, theta_max_type, method, cosmo, truth_data, member_data) #truth_to_det_match_numbers, det_to_truth_match_number, bijective_match_indices #statistics print ("number of bijective associations", number_of_associations(ind_bij)) print ("number and fraction of fragmentation", fragmentation(match_num_1w, ind_bij, method="bij")) print ("number and fraction of overmerging", overmerging(match_num_2w, ind_bij, method="bij")) print ("completeness", completeness(halo_data, ind_bij, gc, gc_truth)) print ("purity", purity(cluster_data, ind_bij, gc, gc_truth)) #check plot f,a,b = plot_cluster_and_halo_position(halo_data, cluster_data, match_num_1w, match_num_2w, ind_bij) #plot to check redshift plot_redshift_comparison(halo_data, cluster_data, ind_bij) ``` ### - 2nd association criteria : nearest within a cylinder with $\Delta_z=0.05, \theta_{max} = 1 Mpc$ ``` #criteria delta_zmax = 0.05 theta_max = 1. #Mpc theta_max_type = "fixed_dist" method = "nearest" match_num_1w, match_num_2w, ind_bij = \ volume_match(halo_data, cluster_data, delta_zmax, theta_max, theta_max_type, method, cosmo, truth_data, member_data) #truth_to_det_match_numbers, det_to_truth_match_number, bijective_match_indices #statistics print ("number of bijective associations", number_of_associations(ind_bij)) print ("number and fraction of fragmentation", fragmentation(match_num_1w, ind_bij, method="bij")) print ("number and fraction of overmerging", overmerging(match_num_2w, ind_bij, method="bij")) print ("completeness", completeness(halo_data, ind_bij, gc, gc_truth)) print ("purity", purity(cluster_data, ind_bij, gc, gc_truth)) #check plot f,a,b = plot_cluster_and_halo_position(halo_data, cluster_data, match_num_1w, match_num_2w, ind_bij) ``` ### - 3rd association criteria : nearest within a cylinder with $\Delta_z=0.05, \theta_{max} = R(M_{halo}, \lambda_{cluster})$ ``` #criteria delta_zmax = 0.05 theta_max = 1. #Mpc theta_max_type = "scaled" method = "nearest" match_num_1w, match_num_2w, ind_bij = \ volume_match(halo_data, cluster_data, delta_zmax, theta_max, theta_max_type, method, cosmo, truth_data, member_data) #truth_to_det_match_numbers, det_to_truth_match_number, bijective_match_indices #statistics print ("number of bijective associations", number_of_associations(ind_bij)) print ("number and fraction of fragmentation", fragmentation(match_num_1w, ind_bij, method="bij")) print ("number and fraction of overmerging", overmerging(match_num_2w, ind_bij, method="bij")) print ("completeness", completeness(halo_data, ind_bij, gc, gc_truth)) print ("purity", purity(cluster_data, ind_bij, gc, gc_truth)) #check plot f,a,b = plot_cluster_and_halo_position(halo_data, cluster_data, match_num_1w, match_num_2w, ind_bij) ``` ### - 4rth association criteria : highest common membership within a cylinder with $\Delta_z=0.05, \theta_{max} = 1 Mpc$ ``` #criteria delta_zmax = 0.05 theta_max = 1. #Mpc theta_max_type = "fixed_dist" method = "membership" match_num_1w, match_num_2w, ind_bij = \ volume_match(halo_data, cluster_data, delta_zmax, theta_max, theta_max_type, method, cosmo, truth_data, member_data) #truth_to_det_match_numbers, det_to_truth_match_number, bijective_match_indices #statistics print ("number of bijective associations", number_of_associations(ind_bij)) print ("number and fraction of fragmentation", fragmentation(match_num_1w, ind_bij, method="bij")) print ("number and fraction of overmerging", overmerging(match_num_2w, ind_bij, method="bij")) print ("completeness", completeness(halo_data, ind_bij, gc, gc_truth)) print ("purity", purity(cluster_data, ind_bij, gc, gc_truth)) #check plot f,a,b = plot_cluster_and_halo_position(halo_data, cluster_data, match_num_1w, match_num_2w, ind_bij) ```
github_jupyter
import GCRCatalogs import numpy as np import matplotlib.pyplot as plt from astropy.table import Table from astropy.coordinates import SkyCoord from astropy import units as u from astropy.cosmology import FlatLambdaCDM from cluster_validation.opening_catalogs_functions import * from cluster_validation.association_methods import * from cluster_validation.plotting_functions import * from cluster_validation.association_statistics import * %matplotlib inline plt.rcParams['figure.figsize'] = [9.5, 6] plt.rcParams.update({'font.size': 18}) #plt.rcParams['figure.figsize'] = [10, 8] for big figures #function to open truth and detection catalogs RM_cat_name = 'cosmoDC2_v1.1.4_redmapper_v0.2.1py' DC2_cat_name = 'cosmoDC2_v1.1.4' min_richness = 20 min_halo_mass = 3e14 #Msun cluster_data, member_data, truth_data, gc, gc_truth = RM_DC2_cat_open(RM_cat_name,DC2_cat_name,min_richness, min_halo_mass, cluster_only=False) #take only the halo halo_data = truth_data[truth_data['is_central']==True] min_richness = 25 # Get the redMaPPer catalog gc = GCRCatalogs.load_catalog(RM_cat_name) # Select out the cluster and member quantities into different lists quantities = gc.list_all_quantities() cluster_quantities = [q for q in quantities if 'member' not in q] member_quantities = [q for q in quantities if 'member' in q] # Read in the cluster and member data query = GCRCatalogs.GCRQuery('(richness > ' + str(min_richness) +')') cluster_data = Table(gc.get_quantities(cluster_quantities, [query])) member_data = Table(gc.get_quantities(member_quantities)) print("Number of elements in the truth catalog = ", len(truth_data)) print("Number of halos in the truth catalog = ", len(halo_data)) print("Number of clusters in the detection catalog = ", len(cluster_data)) print("Cluster catalog sky area = ", gc.sky_area, "deg2") print("Truth catalog sky area = ", gc_truth.sky_area, "deg2") #define same cosmological parameters as in the truth catalog (cosmoDC2) cosmo = gc_truth.cosmology #check the cosmological parameters in the two catalogs #print('Cosmo in truth catalog:', gc_truth.cosmology) #print('Cosmo in detection catalog:', gc_truth.cosmology) #gc_truth.halo_mass_def #gc_truth.get_catalog_info() #gc.get_catalog_info() plt.plot(cluster_data['ra_cen_0'],cluster_data['dec_cen_0'],'b.') plt.plot(truth_data['ra'],truth_data['dec'],'rx',alpha=0.1) plt.xlabel("ra") plt.ylabel("dec"); #criteria delta_zmax = np.inf theta_max = 1. #arcmin theta_max_type = "fixed_angle" method = "nearest" match_num_1w, match_num_2w, ind_bij = \ volume_match(halo_data, cluster_data, delta_zmax, theta_max, theta_max_type, method, cosmo, truth_data, member_data) #truth_to_det_match_numbers, det_to_truth_match_number, bijective_match_indices #statistics print ("number of bijective associations", number_of_associations(ind_bij)) print ("number and fraction of fragmentation", fragmentation(match_num_1w, ind_bij, method="bij")) print ("number and fraction of overmerging", overmerging(match_num_2w, ind_bij, method="bij")) print ("completeness", completeness(halo_data, ind_bij, gc, gc_truth)) print ("purity", purity(cluster_data, ind_bij, gc, gc_truth)) #check plot f,a,b = plot_cluster_and_halo_position(halo_data, cluster_data, match_num_1w, match_num_2w, ind_bij) #plot to check redshift plot_redshift_comparison(halo_data, cluster_data, ind_bij) #criteria delta_zmax = 0.05 theta_max = 1. #Mpc theta_max_type = "fixed_dist" method = "nearest" match_num_1w, match_num_2w, ind_bij = \ volume_match(halo_data, cluster_data, delta_zmax, theta_max, theta_max_type, method, cosmo, truth_data, member_data) #truth_to_det_match_numbers, det_to_truth_match_number, bijective_match_indices #statistics print ("number of bijective associations", number_of_associations(ind_bij)) print ("number and fraction of fragmentation", fragmentation(match_num_1w, ind_bij, method="bij")) print ("number and fraction of overmerging", overmerging(match_num_2w, ind_bij, method="bij")) print ("completeness", completeness(halo_data, ind_bij, gc, gc_truth)) print ("purity", purity(cluster_data, ind_bij, gc, gc_truth)) #check plot f,a,b = plot_cluster_and_halo_position(halo_data, cluster_data, match_num_1w, match_num_2w, ind_bij) #criteria delta_zmax = 0.05 theta_max = 1. #Mpc theta_max_type = "scaled" method = "nearest" match_num_1w, match_num_2w, ind_bij = \ volume_match(halo_data, cluster_data, delta_zmax, theta_max, theta_max_type, method, cosmo, truth_data, member_data) #truth_to_det_match_numbers, det_to_truth_match_number, bijective_match_indices #statistics print ("number of bijective associations", number_of_associations(ind_bij)) print ("number and fraction of fragmentation", fragmentation(match_num_1w, ind_bij, method="bij")) print ("number and fraction of overmerging", overmerging(match_num_2w, ind_bij, method="bij")) print ("completeness", completeness(halo_data, ind_bij, gc, gc_truth)) print ("purity", purity(cluster_data, ind_bij, gc, gc_truth)) #check plot f,a,b = plot_cluster_and_halo_position(halo_data, cluster_data, match_num_1w, match_num_2w, ind_bij) #criteria delta_zmax = 0.05 theta_max = 1. #Mpc theta_max_type = "fixed_dist" method = "membership" match_num_1w, match_num_2w, ind_bij = \ volume_match(halo_data, cluster_data, delta_zmax, theta_max, theta_max_type, method, cosmo, truth_data, member_data) #truth_to_det_match_numbers, det_to_truth_match_number, bijective_match_indices #statistics print ("number of bijective associations", number_of_associations(ind_bij)) print ("number and fraction of fragmentation", fragmentation(match_num_1w, ind_bij, method="bij")) print ("number and fraction of overmerging", overmerging(match_num_2w, ind_bij, method="bij")) print ("completeness", completeness(halo_data, ind_bij, gc, gc_truth)) print ("purity", purity(cluster_data, ind_bij, gc, gc_truth)) #check plot f,a,b = plot_cluster_and_halo_position(halo_data, cluster_data, match_num_1w, match_num_2w, ind_bij)
0.441432
0.953232
``` from rfm_deployment.rfm_model_V2_com import * from itertools import product import cx_Oracle import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import calendar import datetime import cairo import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk %matplotlib inline pd.set_option('display.max_columns', 500) inicio = datetime.date(2020, 2, 25) fin = datetime.date(2019, 3, 25) months = -1 fecha_final = add_months(inicio, -2) contador = 1 while fecha_final >= fin : fi_int = datetime_to_integer(inicio) ff_int = datetime_to_integer(fecha_final) print(f'Ciclo--{contador}:') print(f'La fecha de inicio es: {inicio}. La fecha final es: {fecha_final}.' ) fecha_out = str(ff_int) # Fecha límite inferior para el trimestre de interés fecha_in = str(fi_int) # Fecha límite superior para el trimestre de interés label = 'CA' df = pd.read_parquet(f'CA-{fecha_in}--{fecha_out}.parquet') print('=================================================================================================') rfm_model = rfm_scoring(df, fecha_in, fecha_out, label) print('-------------------------------------------------------------------------------------------------') #rfm_corr = rfm_model[['RECENCIA', 'FRECUENCIA', 'MONTO']].corr() #print('La matriz de correlacion es:') #print(rfm_corr.corr()) #print('-------------------------------------------------------------------------------------------------') #bins_R = 90 #bins_F = 100 #bins_M = 100 #range_R = [0,90] #range_F = [0, 10000] #range_M = [0, 10000000] #histogramas(rfm_model['RECENCIA'], rfm_model['FRECUENCIA'], rfm_model['MONTO'], # bins_R, bins_F, bins_M, range_R, range_F, range_M) #EDA... #histogramas(rfm['RECENCIA'], rfm['FRECUENCIA'], rfm['MONTO']) #print('-------------------------------------------------------------------------------------------------') segmentar(rfm_model, fecha_in, fecha_out) rfm_segmentos, dic_cuit, rfm_segmentado = label_segmentos(rfm_model, fecha_in, fecha_out,label) #inicio = add_months(inicio, months) fecha_final = add_months(fecha_final, months) contador += 1 print('=================================================================================================') fecha_out = '20191225' fecha_in = '20200225' label = 'CA' rfm_grafico = pd.read_csv(f'{label}-segment-plot-{fecha_in}--{fecha_out}.csv') df = pd.read_csv(f'{label}-rfm-segmentos-{fecha_in}--{fecha_out}.csv') rfm_prom = df[['RECENCIA', 'FRECUENCIA', 'MONTO', 'Segment']].groupby(['Segment']).median().round(2) rfm_prom = rfm_prom.rename(columns = {'RECENCIA': 'R_MEDIAN', 'FRECUENCIA': 'F_MEDIAN', 'MONTO': 'M_MEDIAN'}) rfm_prom = rfm_prom.reset_index() rfm_x_grafico = pd.merge(rfm_prom, rfm_grafico, on='Segment', how='right') rfm_x_grafico['R_MEDIAN'].fillna('NA', inplace=True) rfm_x_grafico['F_MEDIAN'].fillna('NA', inplace=True) rfm_x_grafico['M_MEDIAN'].fillna('NA', inplace=True) rfm_x_grafico['%'] = rfm_x_grafico['%'].apply(lambda x : str(x)+'%') rfm_x_grafico['cantidad'] = rfm_x_grafico['cantidad'].apply(lambda x : str(x)) rfm_x_grafico['R_MEDIAN'] = rfm_x_grafico['R_MEDIAN'].apply(lambda x : str(x)) rfm_x_grafico['F_MEDIAN'] = rfm_x_grafico['F_MEDIAN'].apply(lambda x : str(x)) rfm_x_grafico['M_MEDIAN'] = rfm_x_grafico['M_MEDIAN'].apply(lambda x : str(x)) rfm_percentaje_dic = dict(zip(rfm_x_grafico.Segment, rfm_x_grafico['%'])) rfm_cantidad_dic = dict(zip(rfm_x_grafico.Segment, rfm_x_grafico.cantidad)) rfm_R_MEDIAN_dic = dict(zip(rfm_x_grafico.Segment, rfm_x_grafico.R_MEDIAN)) rfm_F_MEDIAN_dic = dict(zip(rfm_x_grafico.Segment, rfm_x_grafico.F_MEDIAN)) rfm_M_MEDIAN_dic = dict(zip(rfm_x_grafico.Segment, rfm_x_grafico.M_MEDIAN)) app = RFM_graph() app.porcentajes = rfm_percentaje_dic app.cantidad = rfm_cantidad_dic app.R_MEDIAN = rfm_R_MEDIAN_dic app.F_MEDIAN = rfm_F_MEDIAN_dic app.M_MEDIAN = rfm_M_MEDIAN_dic Gtk.main() df1 = pd.read_parquet(f'CA-20200225--20191225.parquet') df2 = pd.read_parquet(f'CA-20200225--20190725.parquet') fecha_out1 = '20191225' fecha_in1 = '20200225' label = 'CA' rfm1 = rfm_scoring(df1, fecha_in1, fecha_out1, label) fecha_out2 = '20190725' fecha_in2 = '20200225' label = 'CA' rfm2 = rfm_scoring(df2, fecha_in2, fecha_out2, label) data1 = segmentar(rfm1, fecha_in1, fecha_out1) data2 = segmentar(rfm2, fecha_in2, fecha_out2) data1['%'].corr(data2['%'], method='pearson') data1 data2 ```
github_jupyter
from rfm_deployment.rfm_model_V2_com import * from itertools import product import cx_Oracle import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import calendar import datetime import cairo import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk %matplotlib inline pd.set_option('display.max_columns', 500) inicio = datetime.date(2020, 2, 25) fin = datetime.date(2019, 3, 25) months = -1 fecha_final = add_months(inicio, -2) contador = 1 while fecha_final >= fin : fi_int = datetime_to_integer(inicio) ff_int = datetime_to_integer(fecha_final) print(f'Ciclo--{contador}:') print(f'La fecha de inicio es: {inicio}. La fecha final es: {fecha_final}.' ) fecha_out = str(ff_int) # Fecha límite inferior para el trimestre de interés fecha_in = str(fi_int) # Fecha límite superior para el trimestre de interés label = 'CA' df = pd.read_parquet(f'CA-{fecha_in}--{fecha_out}.parquet') print('=================================================================================================') rfm_model = rfm_scoring(df, fecha_in, fecha_out, label) print('-------------------------------------------------------------------------------------------------') #rfm_corr = rfm_model[['RECENCIA', 'FRECUENCIA', 'MONTO']].corr() #print('La matriz de correlacion es:') #print(rfm_corr.corr()) #print('-------------------------------------------------------------------------------------------------') #bins_R = 90 #bins_F = 100 #bins_M = 100 #range_R = [0,90] #range_F = [0, 10000] #range_M = [0, 10000000] #histogramas(rfm_model['RECENCIA'], rfm_model['FRECUENCIA'], rfm_model['MONTO'], # bins_R, bins_F, bins_M, range_R, range_F, range_M) #EDA... #histogramas(rfm['RECENCIA'], rfm['FRECUENCIA'], rfm['MONTO']) #print('-------------------------------------------------------------------------------------------------') segmentar(rfm_model, fecha_in, fecha_out) rfm_segmentos, dic_cuit, rfm_segmentado = label_segmentos(rfm_model, fecha_in, fecha_out,label) #inicio = add_months(inicio, months) fecha_final = add_months(fecha_final, months) contador += 1 print('=================================================================================================') fecha_out = '20191225' fecha_in = '20200225' label = 'CA' rfm_grafico = pd.read_csv(f'{label}-segment-plot-{fecha_in}--{fecha_out}.csv') df = pd.read_csv(f'{label}-rfm-segmentos-{fecha_in}--{fecha_out}.csv') rfm_prom = df[['RECENCIA', 'FRECUENCIA', 'MONTO', 'Segment']].groupby(['Segment']).median().round(2) rfm_prom = rfm_prom.rename(columns = {'RECENCIA': 'R_MEDIAN', 'FRECUENCIA': 'F_MEDIAN', 'MONTO': 'M_MEDIAN'}) rfm_prom = rfm_prom.reset_index() rfm_x_grafico = pd.merge(rfm_prom, rfm_grafico, on='Segment', how='right') rfm_x_grafico['R_MEDIAN'].fillna('NA', inplace=True) rfm_x_grafico['F_MEDIAN'].fillna('NA', inplace=True) rfm_x_grafico['M_MEDIAN'].fillna('NA', inplace=True) rfm_x_grafico['%'] = rfm_x_grafico['%'].apply(lambda x : str(x)+'%') rfm_x_grafico['cantidad'] = rfm_x_grafico['cantidad'].apply(lambda x : str(x)) rfm_x_grafico['R_MEDIAN'] = rfm_x_grafico['R_MEDIAN'].apply(lambda x : str(x)) rfm_x_grafico['F_MEDIAN'] = rfm_x_grafico['F_MEDIAN'].apply(lambda x : str(x)) rfm_x_grafico['M_MEDIAN'] = rfm_x_grafico['M_MEDIAN'].apply(lambda x : str(x)) rfm_percentaje_dic = dict(zip(rfm_x_grafico.Segment, rfm_x_grafico['%'])) rfm_cantidad_dic = dict(zip(rfm_x_grafico.Segment, rfm_x_grafico.cantidad)) rfm_R_MEDIAN_dic = dict(zip(rfm_x_grafico.Segment, rfm_x_grafico.R_MEDIAN)) rfm_F_MEDIAN_dic = dict(zip(rfm_x_grafico.Segment, rfm_x_grafico.F_MEDIAN)) rfm_M_MEDIAN_dic = dict(zip(rfm_x_grafico.Segment, rfm_x_grafico.M_MEDIAN)) app = RFM_graph() app.porcentajes = rfm_percentaje_dic app.cantidad = rfm_cantidad_dic app.R_MEDIAN = rfm_R_MEDIAN_dic app.F_MEDIAN = rfm_F_MEDIAN_dic app.M_MEDIAN = rfm_M_MEDIAN_dic Gtk.main() df1 = pd.read_parquet(f'CA-20200225--20191225.parquet') df2 = pd.read_parquet(f'CA-20200225--20190725.parquet') fecha_out1 = '20191225' fecha_in1 = '20200225' label = 'CA' rfm1 = rfm_scoring(df1, fecha_in1, fecha_out1, label) fecha_out2 = '20190725' fecha_in2 = '20200225' label = 'CA' rfm2 = rfm_scoring(df2, fecha_in2, fecha_out2, label) data1 = segmentar(rfm1, fecha_in1, fecha_out1) data2 = segmentar(rfm2, fecha_in2, fecha_out2) data1['%'].corr(data2['%'], method='pearson') data1 data2
0.118793
0.205575
# Training a CNN in Keras with Real-Time Data Augmentation ## Initial Setup ``` from __future__ import division from PIL import Image import os import numpy as np import matplotlib.pyplot as plt %matplotlib inline %load_ext autoreload %autoreload 2 ``` ## Load Images into a Matrix ``` base_dir = 'square_images128' image_width = 128 image_height = 128 classes = ['daffodil', 'snowdrop', 'lily_valley', 'bluebell', 'crocus', 'iris', 'tigerlily', 'tulip', 'fritillary', 'sunflower', 'daisy', 'colts_foot', 'dandelion', 'cowslip', 'buttercup', 'windflower', 'pansy'] class_dict = { class_name: index for (index, class_name) in enumerate(classes)} EXTENSIONS = [".jpg", ".bmp", ".png", ".pgm", ".tif", ".tiff"] folders = os.listdir(base_dir) folders = [folder for folder in folders if folder != '.DS_Store'] xs = [] ys = [] for folder_name in folders: # We look up the class number based on the name of the folder the image is in. # This maps a folder name like 'daffodil' to a class number like 0. class_index = class_dict[folder_name] file_names = os.listdir(base_dir + '/' + folder_name) #file_names = [name for name in file_names if name != '.DS_Store'] file_names = [name for name in file_names if os.path.splitext(name)[-1].lower() in EXTENSIONS] X = np.empty([len(file_names), image_width, image_height, 3]) y = [] for (index, file_name) in enumerate(file_names): file_path = base_dir + '/' + folder_name + '/' + file_name #print(file_path) I = np.array(Image.open(file_path)) X[index] = I y.append(class_index) X_combined = X y_array = np.array(y) xs.append(X_combined) ys.append(y_array) X_all = np.concatenate(xs) y_all = np.concatenate(ys) print(X_all.shape) print(y_all.shape) # Randomly shuffle the input images and labels (IN THE SAME RANDOM ORDER SO THEY ARE STILL CORRELATED) rng_state = np.random.get_state() np.random.shuffle(X_all) np.random.set_state(rng_state) np.random.shuffle(y_all) # Split the data into training/validation/testing segments from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X_all, y_all, test_size=0.25) """ # 20% of training data reserved for the validation set # Here we're using a fixed validation set, not doing cross-validation percentage_validation = 0.20 num_total = X_train.shape[0] num_validation = int(num_total * percentage_validation) num_training = num_total - num_validation # Our validation set will be num_validation points from the original training set. mask = range(num_training, num_training + num_validation) X_val = X_train[mask] y_val = y_train[mask] # Our training set will be the first num_training points from the original training set. mask = range(num_training) X_train = X_train[mask] y_train = y_train[mask] """ # Normalize the data: subtract the mean image mean_image = np.mean(X_train, axis=0) X_train -= mean_image #X_val -= mean_image X_test -= mean_image # Transpose so that channels come first X_train = X_train.transpose(0, 3, 1, 2).copy() #X_val = X_val.transpose(0, 3, 1, 2).copy() X_test = X_test.transpose(0, 3, 1, 2).copy() print(X_train.shape) #print(X_val.shape) print(X_test.shape) from __future__ import absolute_import from __future__ import print_function from keras.datasets import cifar10 from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation, Flatten from keras.layers.convolutional import Convolution2D, MaxPooling2D from keras.optimizers import SGD, Adadelta, Adagrad from keras.utils import np_utils, generic_utils from six.moves import range ''' Train a (fairly simple) deep CNN on the CIFAR10 small images dataset. GPU run command: THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 python cifar10_cnn.py It gets down to 0.65 test logloss in 25 epochs, and down to 0.55 after 50 epochs. (it's still underfitting at that point, though). Note: the data was pickled with Python 2, and some encoding issues might prevent you from loading it in Python 3. You might have to load it in Python 2, save it in a different format, load it in Python 3 and repickle it. ''' batch_size = 16 num_classes = 17 num_epochs = 30 # input image dimensions img_rows, img_cols = 128, 128 # the images are RGB img_channels = 3 # the data, shuffled and split between train and test sets print('X_train shape:', X_train.shape) print(X_train.shape[0], 'train samples') print(X_test.shape[0], 'test samples') # convert class vectors to binary class matrices Y_train = np_utils.to_categorical(y_train, num_classes) Y_test = np_utils.to_categorical(y_test, num_classes) print(Y_train[0]) model = Sequential() model.add(Convolution2D(32, 3, 3, border_mode='full', input_shape=(img_channels, img_rows, img_cols))) model.add(Activation('relu')) model.add(Convolution2D(32, 3, 3)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Convolution2D(64, 3, 3, border_mode='full')) model.add(Activation('relu')) model.add(Convolution2D(64, 3, 3)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(512)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes)) model.add(Activation('softmax')) # let's train the model using SGD + momentum (how original). adadelta = Adadelta(lr=1.0, rho=0.95, epsilon=1e-6) model.compile(loss='categorical_crossentropy', optimizer=adadelta) X_train = X_train.astype("float32") X_test = X_test.astype("float32") X_train /= 255 X_test /= 255 print("Using real time data augmentation") # this will do preprocessing and realtime data augmentation datagen = ImageDataGenerator( featurewise_center=True, # set input mean to 0 over the dataset samplewise_center=False, # set each sample mean to 0 featurewise_std_normalization=True, # divide inputs by std of the dataset samplewise_std_normalization=False, # divide each input by its std zca_whitening=False, # apply ZCA whitening rotation_range=20, # randomly rotate images in the range (degrees, 0 to 180) width_shift_range=0.2, # randomly shift images horizontally (fraction of total width) height_shift_range=0.2, # randomly shift images vertically (fraction of total height) horizontal_flip=True, # randomly flip images vertical_flip=False) # randomly flip images # compute quantities required for featurewise normalization # (std, mean, and principal components if ZCA whitening is applied) datagen.fit(X_train) for e in range(num_epochs): print('-'*40) print('Epoch', e) print('-'*40) print("Training...") # batch train with realtime data augmentation progbar = generic_utils.Progbar(X_train.shape[0]) for X_batch, Y_batch in datagen.flow(X_train, Y_train): loss = model.train_on_batch(X_batch, Y_batch) progbar.add(X_batch.shape[0], values=[("train loss", loss)]) print("Testing...") # test time! progbar = generic_utils.Progbar(X_test.shape[0]) for X_batch, Y_batch in datagen.flow(X_test, Y_test): score = model.test_on_batch(X_batch, Y_batch) progbar.add(X_batch.shape[0], values=[("test loss", score)]) training_accuracies = history.history['acc'] validation_accuracies = history.history['val_acc'] plt.plot(training_accuracies) plt.plot(validation_accuracies) plt.legend(['Training', 'Validation']) plt.xlabel('Epoch') plt.ylabel('Accuracy') plt.title('Training a CNN on 128x128 Images') ```
github_jupyter
from __future__ import division from PIL import Image import os import numpy as np import matplotlib.pyplot as plt %matplotlib inline %load_ext autoreload %autoreload 2 base_dir = 'square_images128' image_width = 128 image_height = 128 classes = ['daffodil', 'snowdrop', 'lily_valley', 'bluebell', 'crocus', 'iris', 'tigerlily', 'tulip', 'fritillary', 'sunflower', 'daisy', 'colts_foot', 'dandelion', 'cowslip', 'buttercup', 'windflower', 'pansy'] class_dict = { class_name: index for (index, class_name) in enumerate(classes)} EXTENSIONS = [".jpg", ".bmp", ".png", ".pgm", ".tif", ".tiff"] folders = os.listdir(base_dir) folders = [folder for folder in folders if folder != '.DS_Store'] xs = [] ys = [] for folder_name in folders: # We look up the class number based on the name of the folder the image is in. # This maps a folder name like 'daffodil' to a class number like 0. class_index = class_dict[folder_name] file_names = os.listdir(base_dir + '/' + folder_name) #file_names = [name for name in file_names if name != '.DS_Store'] file_names = [name for name in file_names if os.path.splitext(name)[-1].lower() in EXTENSIONS] X = np.empty([len(file_names), image_width, image_height, 3]) y = [] for (index, file_name) in enumerate(file_names): file_path = base_dir + '/' + folder_name + '/' + file_name #print(file_path) I = np.array(Image.open(file_path)) X[index] = I y.append(class_index) X_combined = X y_array = np.array(y) xs.append(X_combined) ys.append(y_array) X_all = np.concatenate(xs) y_all = np.concatenate(ys) print(X_all.shape) print(y_all.shape) # Randomly shuffle the input images and labels (IN THE SAME RANDOM ORDER SO THEY ARE STILL CORRELATED) rng_state = np.random.get_state() np.random.shuffle(X_all) np.random.set_state(rng_state) np.random.shuffle(y_all) # Split the data into training/validation/testing segments from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X_all, y_all, test_size=0.25) """ # 20% of training data reserved for the validation set # Here we're using a fixed validation set, not doing cross-validation percentage_validation = 0.20 num_total = X_train.shape[0] num_validation = int(num_total * percentage_validation) num_training = num_total - num_validation # Our validation set will be num_validation points from the original training set. mask = range(num_training, num_training + num_validation) X_val = X_train[mask] y_val = y_train[mask] # Our training set will be the first num_training points from the original training set. mask = range(num_training) X_train = X_train[mask] y_train = y_train[mask] """ # Normalize the data: subtract the mean image mean_image = np.mean(X_train, axis=0) X_train -= mean_image #X_val -= mean_image X_test -= mean_image # Transpose so that channels come first X_train = X_train.transpose(0, 3, 1, 2).copy() #X_val = X_val.transpose(0, 3, 1, 2).copy() X_test = X_test.transpose(0, 3, 1, 2).copy() print(X_train.shape) #print(X_val.shape) print(X_test.shape) from __future__ import absolute_import from __future__ import print_function from keras.datasets import cifar10 from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation, Flatten from keras.layers.convolutional import Convolution2D, MaxPooling2D from keras.optimizers import SGD, Adadelta, Adagrad from keras.utils import np_utils, generic_utils from six.moves import range ''' Train a (fairly simple) deep CNN on the CIFAR10 small images dataset. GPU run command: THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 python cifar10_cnn.py It gets down to 0.65 test logloss in 25 epochs, and down to 0.55 after 50 epochs. (it's still underfitting at that point, though). Note: the data was pickled with Python 2, and some encoding issues might prevent you from loading it in Python 3. You might have to load it in Python 2, save it in a different format, load it in Python 3 and repickle it. ''' batch_size = 16 num_classes = 17 num_epochs = 30 # input image dimensions img_rows, img_cols = 128, 128 # the images are RGB img_channels = 3 # the data, shuffled and split between train and test sets print('X_train shape:', X_train.shape) print(X_train.shape[0], 'train samples') print(X_test.shape[0], 'test samples') # convert class vectors to binary class matrices Y_train = np_utils.to_categorical(y_train, num_classes) Y_test = np_utils.to_categorical(y_test, num_classes) print(Y_train[0]) model = Sequential() model.add(Convolution2D(32, 3, 3, border_mode='full', input_shape=(img_channels, img_rows, img_cols))) model.add(Activation('relu')) model.add(Convolution2D(32, 3, 3)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Convolution2D(64, 3, 3, border_mode='full')) model.add(Activation('relu')) model.add(Convolution2D(64, 3, 3)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(512)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes)) model.add(Activation('softmax')) # let's train the model using SGD + momentum (how original). adadelta = Adadelta(lr=1.0, rho=0.95, epsilon=1e-6) model.compile(loss='categorical_crossentropy', optimizer=adadelta) X_train = X_train.astype("float32") X_test = X_test.astype("float32") X_train /= 255 X_test /= 255 print("Using real time data augmentation") # this will do preprocessing and realtime data augmentation datagen = ImageDataGenerator( featurewise_center=True, # set input mean to 0 over the dataset samplewise_center=False, # set each sample mean to 0 featurewise_std_normalization=True, # divide inputs by std of the dataset samplewise_std_normalization=False, # divide each input by its std zca_whitening=False, # apply ZCA whitening rotation_range=20, # randomly rotate images in the range (degrees, 0 to 180) width_shift_range=0.2, # randomly shift images horizontally (fraction of total width) height_shift_range=0.2, # randomly shift images vertically (fraction of total height) horizontal_flip=True, # randomly flip images vertical_flip=False) # randomly flip images # compute quantities required for featurewise normalization # (std, mean, and principal components if ZCA whitening is applied) datagen.fit(X_train) for e in range(num_epochs): print('-'*40) print('Epoch', e) print('-'*40) print("Training...") # batch train with realtime data augmentation progbar = generic_utils.Progbar(X_train.shape[0]) for X_batch, Y_batch in datagen.flow(X_train, Y_train): loss = model.train_on_batch(X_batch, Y_batch) progbar.add(X_batch.shape[0], values=[("train loss", loss)]) print("Testing...") # test time! progbar = generic_utils.Progbar(X_test.shape[0]) for X_batch, Y_batch in datagen.flow(X_test, Y_test): score = model.test_on_batch(X_batch, Y_batch) progbar.add(X_batch.shape[0], values=[("test loss", score)]) training_accuracies = history.history['acc'] validation_accuracies = history.history['val_acc'] plt.plot(training_accuracies) plt.plot(validation_accuracies) plt.legend(['Training', 'Validation']) plt.xlabel('Epoch') plt.ylabel('Accuracy') plt.title('Training a CNN on 128x128 Images')
0.593138
0.771413
# A. **Simple Regresi Linier** Teknik ini digunakan untuk menyelesaikan permasalahan hubungan sebab akibat antara 2 variable. 2 variable itu adalah : 1. Variable Faktor Penyebab - biasanya disimbolkan dengan X. Ini disebut `predictor`. 2. Variable Akibat - biasanya disimbolkan dengan Y. Ini disebut `response`. Untuk pembelajaran kali ini kita akan menggunakan dataset `salary.csv`. Isinya adalah perbandingan YearsExperience seorang karyawan dengan Salary yang didapatkannya. Mempersiapkan library yang akan digunakan ## **A. Exploratory Data Analysis ( EDA )** ### **1. Import Libraries** ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns; sns.set() ``` ### **2. Read CSV dan Print Data** ``` data = pd.read_csv('Salary_Data.csv') data ``` ### **3. Melihat Variables Yang Ada** ``` data.keys() ``` ### **4. Melihat bentuk dari dataset** Kolom pertama menyatakan jumlah baris dan kolom kedua menyatakan jumlah variablenya ``` data.shape ``` ### **5. Melihat 5 data awal** Menggunakan fungsi `head()` ``` mydata = pd.DataFrame(data) mydata.head() ``` ### **6. Melihat 5 data akhir** Menggunakan fungsi `tail()` ``` mydata.tail() ``` ### **7. Melihat Info Data** Menggunakan fungsi `info()` kita akan melihat kolom data ( features ), jumlah data, dan tipe data. ``` mydata.info() ``` ## **B. Pre-process Data** ### **1. Split Data Dependent dan Independent** 1. Dependent Variable : variable yang dipengaruhi 2. Independent Variable : variable yang mempengaruhi ``` # slice from the beginning to 'Salary' data.loc[:, :'Salary'] x = data.iloc[:,:-1].values y = data.iloc[:,1].values ``` Jika kodenya diekseskusi akan menghasilkan 2 variabel baru, yaitu **dataset** yang berisi keseluruhan data, x sebagai **independent variable**, dan y sebagai **dependent variable** ### **2. Split Data into Training Set and Test Set** menggunakan library `scikit-learn`. Kode dibawah untuk membagi dataset kita menjadi `training set` sebesar **80%** dan `test set` sebesar **20%**. `XYxy` dideklarasikan untuk nantinya diproses dalam test dan training set ``` #Split data set menjadi Training Set dan Test Set from sklearn. model_selection import train_test_split X_train,X_test,y_train,y_test = train_test_split(x,y,test_size = 0.2,random_state = 0) ``` ## **C. Training Data** Data sudah kita bagi menjadi data uji ( test set ) dan data latih ( training set ). Sekarang waktunya kita melatih data kita dengan classifier/algoritma `LinearRegression` menggunakan library `Sklearn`. ``` from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit (X_train,y_train) ``` ## **D. Predict Data** Tujuan dari memprediksi data adalah prediksi hasil yang akan muncul dari dataset kita. ``` #Memprediksu hasil test set y_pred = regressor.predict(X_test) ``` ## **E. Visualisasi Data** Waktunya melihat hasil visualisasi datanya. ``` #Visualize Data plt.scatter(mydata.YearsExperience,mydata.Salary) plt.xlabel("Years Experience") plt.ylabel("Salary") plt.title("Grafik Nilai Years Experience VS Salary") plt.show() #Visualisasi Hasil Prediksi Pada Training Set #Ukuran Plot plt.figure(figsize=(10,8)) #Biru adalah data observasi plt.scatter(X_train, y_train, color ='blue') #Garis Merah adalah hasil prediction dari ML plt.plot(X_train, regressor.predict(X_train),color='red') #memberi judul dan label plt.title("Grafik Nilai Years Experience VS Salary") plt.xlabel('Years Experience') plt.ylabel('Salary') plt.show() #Visualisasi data pada test set #Ukuran Plot plt.figure(figsize=(10,8)) #Biru adalah data observasi plt.scatter(X_test, y_test, color ='blue') #Garis Merah adalah hasil prediction dari ML plt.plot(X_train, regressor.predict(X_train),color='red') #memberi judul dan label plt.title("Grafik Nilai Years Experience VS Salary") plt.xlabel('Years Experiences') plt.ylabel('Salary') plt.show() ``` ## **F. Uji Coba Model** ``` import ipywidgets as widgets from IPython.display import display textbox = widgets.FloatText(value=7.5, description='Years Experience:',disabled=False) button = widgets.Button(description="Salary") output = widgets.Output() def on_button_clicked(b): # Display the message within the output widget. with output: y_hasil = regressor.predict([[textbox.value]]) print("Years Experiences: %d" % textbox.value) print("Salary: %d" % y_hasil[0]) button.on_click(on_button_clicked) display(textbox, output) display(button, output) ``` ## **References** 1. Kukuh, R. 2018. Simple Linear Regression: Python. Link : https://medium.com/machine-learning-id/simple-linear-regression-python-e541ed030e40 2. Wahyono, T. 2018. Fundamental of Python For Machine Learning. Yogyakarta. Penerbit GAVA MEDIA.
github_jupyter
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns; sns.set() data = pd.read_csv('Salary_Data.csv') data data.keys() data.shape mydata = pd.DataFrame(data) mydata.head() mydata.tail() mydata.info() # slice from the beginning to 'Salary' data.loc[:, :'Salary'] x = data.iloc[:,:-1].values y = data.iloc[:,1].values #Split data set menjadi Training Set dan Test Set from sklearn. model_selection import train_test_split X_train,X_test,y_train,y_test = train_test_split(x,y,test_size = 0.2,random_state = 0) from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit (X_train,y_train) #Memprediksu hasil test set y_pred = regressor.predict(X_test) #Visualize Data plt.scatter(mydata.YearsExperience,mydata.Salary) plt.xlabel("Years Experience") plt.ylabel("Salary") plt.title("Grafik Nilai Years Experience VS Salary") plt.show() #Visualisasi Hasil Prediksi Pada Training Set #Ukuran Plot plt.figure(figsize=(10,8)) #Biru adalah data observasi plt.scatter(X_train, y_train, color ='blue') #Garis Merah adalah hasil prediction dari ML plt.plot(X_train, regressor.predict(X_train),color='red') #memberi judul dan label plt.title("Grafik Nilai Years Experience VS Salary") plt.xlabel('Years Experience') plt.ylabel('Salary') plt.show() #Visualisasi data pada test set #Ukuran Plot plt.figure(figsize=(10,8)) #Biru adalah data observasi plt.scatter(X_test, y_test, color ='blue') #Garis Merah adalah hasil prediction dari ML plt.plot(X_train, regressor.predict(X_train),color='red') #memberi judul dan label plt.title("Grafik Nilai Years Experience VS Salary") plt.xlabel('Years Experiences') plt.ylabel('Salary') plt.show() import ipywidgets as widgets from IPython.display import display textbox = widgets.FloatText(value=7.5, description='Years Experience:',disabled=False) button = widgets.Button(description="Salary") output = widgets.Output() def on_button_clicked(b): # Display the message within the output widget. with output: y_hasil = regressor.predict([[textbox.value]]) print("Years Experiences: %d" % textbox.value) print("Salary: %d" % y_hasil[0]) button.on_click(on_button_clicked) display(textbox, output) display(button, output)
0.501465
0.946843
# Convolutional Layer In this notebook, we visualize four filtered outputs (a.k.a. activation maps) of a convolutional layer. In this example, *we* are defining four filters that are applied to an input image by initializing the **weights** of a convolutional layer, but a trained CNN will learn the values of these weights. <img src='notebook_ims/conv_layer.gif' height=60% width=60% /> ### Import the image ``` import cv2 import matplotlib.pyplot as plt %matplotlib inline # TODO: Feel free to try out your own images here by changing img_path # to a file path to another image on your computer! img_path = 'data/udacity_sdc.png' # load color image bgr_img = cv2.imread(img_path) # convert to grayscale gray_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2GRAY) # normalize, rescale entries to lie in [0,1] gray_img = gray_img.astype("float32")/255 # plot image plt.imshow(gray_img, cmap='gray') plt.show() ``` ### Define and visualize the filters ``` import numpy as np ## TODO: Feel free to modify the numbers here, to try out another filter! filter_vals = np.array([[-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1]]) print('Filter shape: ', filter_vals.shape) # Defining four different filters, # all of which are linear combinations of the `filter_vals` defined above # define four filters filter_1 = filter_vals filter_2 = -filter_1 filter_3 = filter_1.T filter_4 = -filter_3 filters = np.array([filter_1, filter_2, filter_3, filter_4]) # For an example, print out the values of filter 1 print('Filter 1: \n', filter_1) # visualize all four filters fig = plt.figure(figsize=(10, 5)) for i in range(4): ax = fig.add_subplot(1, 4, i+1, xticks=[], yticks=[]) ax.imshow(filters[i], cmap='gray') ax.set_title('Filter %s' % str(i+1)) width, height = filters[i].shape for x in range(width): for y in range(height): ax.annotate(str(filters[i][x][y]), xy=(y,x), horizontalalignment='center', verticalalignment='center', color='white' if filters[i][x][y]<0 else 'black') ``` ## Define a convolutional layer The various layers that make up any neural network are documented, [here](http://pytorch.org/docs/stable/nn.html). For a convolutional neural network, we'll start by defining a: * Convolutional layer Initialize a single convolutional layer so that it contains all your created filters. Note that you are not training this network; you are initializing the weights in a convolutional layer so that you can visualize what happens after a forward pass through this network! #### `__init__` and `forward` To define a neural network in PyTorch, you define the layers of a model in the function `__init__` and define the forward behavior of a network that applyies those initialized layers to an input (`x`) in the function `forward`. In PyTorch we convert all inputs into the Tensor datatype, which is similar to a list data type in Python. Below, I define the structure of a class called `Net` that has a convolutional layer that can contain four 4x4 grayscale filters. ``` import torch import torch.nn as nn import torch.nn.functional as F # define a neural network with a single convolutional layer with four filters class Net(nn.Module): def __init__(self, weight): super(Net, self).__init__() # initializes the weights of the convolutional layer to be the weights of the 4 defined filters k_height, k_width = weight.shape[2:] # assumes there are 4 grayscale filters self.conv = nn.Conv2d(1, 4, kernel_size=(k_height, k_width), bias=False) self.conv.weight = torch.nn.Parameter(weight) def forward(self, x): # calculates the output of a convolutional layer # pre- and post-activation conv_x = self.conv(x) activated_x = F.relu(conv_x) # returns both layers return conv_x, activated_x # instantiate the model and set the weights weight = torch.from_numpy(filters).unsqueeze(1).type(torch.FloatTensor) model = Net(weight) # print out the layer in the network print(model) ``` ### Visualize the output of each filter First, we'll define a helper function, `viz_layer` that takes in a specific layer and number of filters (optional argument), and displays the output of that layer once an image has been passed through. ``` # helper function for visualizing the output of a given layer # default number of filters is 4 def viz_layer(layer, n_filters= 4): fig = plt.figure(figsize=(20, 20)) for i in range(n_filters): ax = fig.add_subplot(1, n_filters, i+1, xticks=[], yticks=[]) # grab layer outputs ax.imshow(np.squeeze(layer[0,i].data.numpy()), cmap='gray') ax.set_title('Output %s' % str(i+1)) ``` Let's look at the output of a convolutional layer, before and after a ReLu activation function is applied. ``` # plot original image plt.imshow(gray_img, cmap='gray') # visualize all filters fig = plt.figure(figsize=(12, 6)) fig.subplots_adjust(left=0, right=1.5, bottom=0.8, top=1, hspace=0.05, wspace=0.05) for i in range(4): ax = fig.add_subplot(1, 4, i+1, xticks=[], yticks=[]) ax.imshow(filters[i], cmap='gray') ax.set_title('Filter %s' % str(i+1)) # convert the image into an input Tensor gray_img_tensor = torch.from_numpy(gray_img).unsqueeze(0).unsqueeze(1) # get the convolutional layer (pre and post activation) conv_layer, activated_layer = model(gray_img_tensor) # visualize the output of a conv layer viz_layer(conv_layer) ``` #### ReLu activation In this model, we've used an activation function that scales the output of the convolutional layer. We've chose a ReLu function to do this, and this function simply turns all negative pixel values in 0's (black). See the equation pictured below for input pixel values, `x`. <img src='notebook_ims/relu_ex.png' height=50% width=50% /> ``` # after a ReLu is applied # visualize the output of an activated conv layer viz_layer(activated_layer) ```
github_jupyter
import cv2 import matplotlib.pyplot as plt %matplotlib inline # TODO: Feel free to try out your own images here by changing img_path # to a file path to another image on your computer! img_path = 'data/udacity_sdc.png' # load color image bgr_img = cv2.imread(img_path) # convert to grayscale gray_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2GRAY) # normalize, rescale entries to lie in [0,1] gray_img = gray_img.astype("float32")/255 # plot image plt.imshow(gray_img, cmap='gray') plt.show() import numpy as np ## TODO: Feel free to modify the numbers here, to try out another filter! filter_vals = np.array([[-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1]]) print('Filter shape: ', filter_vals.shape) # Defining four different filters, # all of which are linear combinations of the `filter_vals` defined above # define four filters filter_1 = filter_vals filter_2 = -filter_1 filter_3 = filter_1.T filter_4 = -filter_3 filters = np.array([filter_1, filter_2, filter_3, filter_4]) # For an example, print out the values of filter 1 print('Filter 1: \n', filter_1) # visualize all four filters fig = plt.figure(figsize=(10, 5)) for i in range(4): ax = fig.add_subplot(1, 4, i+1, xticks=[], yticks=[]) ax.imshow(filters[i], cmap='gray') ax.set_title('Filter %s' % str(i+1)) width, height = filters[i].shape for x in range(width): for y in range(height): ax.annotate(str(filters[i][x][y]), xy=(y,x), horizontalalignment='center', verticalalignment='center', color='white' if filters[i][x][y]<0 else 'black') import torch import torch.nn as nn import torch.nn.functional as F # define a neural network with a single convolutional layer with four filters class Net(nn.Module): def __init__(self, weight): super(Net, self).__init__() # initializes the weights of the convolutional layer to be the weights of the 4 defined filters k_height, k_width = weight.shape[2:] # assumes there are 4 grayscale filters self.conv = nn.Conv2d(1, 4, kernel_size=(k_height, k_width), bias=False) self.conv.weight = torch.nn.Parameter(weight) def forward(self, x): # calculates the output of a convolutional layer # pre- and post-activation conv_x = self.conv(x) activated_x = F.relu(conv_x) # returns both layers return conv_x, activated_x # instantiate the model and set the weights weight = torch.from_numpy(filters).unsqueeze(1).type(torch.FloatTensor) model = Net(weight) # print out the layer in the network print(model) # helper function for visualizing the output of a given layer # default number of filters is 4 def viz_layer(layer, n_filters= 4): fig = plt.figure(figsize=(20, 20)) for i in range(n_filters): ax = fig.add_subplot(1, n_filters, i+1, xticks=[], yticks=[]) # grab layer outputs ax.imshow(np.squeeze(layer[0,i].data.numpy()), cmap='gray') ax.set_title('Output %s' % str(i+1)) # plot original image plt.imshow(gray_img, cmap='gray') # visualize all filters fig = plt.figure(figsize=(12, 6)) fig.subplots_adjust(left=0, right=1.5, bottom=0.8, top=1, hspace=0.05, wspace=0.05) for i in range(4): ax = fig.add_subplot(1, 4, i+1, xticks=[], yticks=[]) ax.imshow(filters[i], cmap='gray') ax.set_title('Filter %s' % str(i+1)) # convert the image into an input Tensor gray_img_tensor = torch.from_numpy(gray_img).unsqueeze(0).unsqueeze(1) # get the convolutional layer (pre and post activation) conv_layer, activated_layer = model(gray_img_tensor) # visualize the output of a conv layer viz_layer(conv_layer) # after a ReLu is applied # visualize the output of an activated conv layer viz_layer(activated_layer)
0.626238
0.987092
# Practical use of HH-suite3 on the command line in Jupyter via MyBinder.org: Basics Run this in sessions launched from [my HH-suite3-binder repo](https://github.com/fomightez/hhsuite3-binder) because the software is already installed. This is the first notebook in my series of notebooks convering use if HH-suite3 software in conjunction with Jupyter and snakemake. Frankly, it just really shows the HH-suite3 items are there and can work on this remote instance; however, these free machines are under-powered for much of real HH-suite3 work. You can use this less powered system downstream for making sense of your HH-suite3 work. For more how you'd take advantage of the Jupyter environment to use HH-suite3 results, see the next notebooks in the series. ----- <div class="alert alert-block alert-warning"> <p>If you haven't used one of these notebooks before, they're basically web pages in which you can write, edit, and run live code. They're meant to encourage experimentation, so don't feel nervous. Just try running a few cells and see what happens!.</p> <p> Some tips: <ul> <li>Code cells have boxes around them. When you hover over them an <i class="fa-step-forward fa"></i> icon appears.</li> <li>To run a code cell either click the <i class="fa-step-forward fa"></i> icon, or click on the cell and then hit <b>Shift+Enter</b>. The <b>Shift+Enter</b> combo will also move you to the next cell, so it's a quick way to work through the notebook.</li> <li>While a cell is running a <b>*</b> appears in the square brackets next to the cell. Once the cell has finished running the asterix will be replaced with a number.</li> <li>In most cases you'll want to start from the top of notebook and work your way down running each cell in turn. Later cells might depend on the results of earlier ones.</li> <li>To edit a code cell, just click on it and type stuff. Remember to run the cell once you've finished editing.</li> </ul> </p> </div> ---- ### General Usage HH-suite3 software is command line software. It is already installed and ready to use here. To run command line software inside a notebook, you preface the commands with an exclamation point. After the exclamation point you write the rest as if you were working on the command line in your typical terminal. This will illustrate printing the usage from a few of the programs that come installed by HH-suite3. Similar things can be found [in the HH-suite3 documentation from the Söding laboratory under 'Summary of command-line parameters'](https://github.com/soedinglab/hh-suite/wiki#summary-of-command-line-parameters) albeit in static form. The HH-suite3 programs seems to print the usage if you just enter the commands with no arguments or options. ``` !hhblits !hhsearch !hhmake ``` The documentation lists a few scripts, such as `hhmakemodel.py` and `hhsuitedb.py `, that you cannot just call the way you call the other software. These are present and to run them you just need to know where they are located and then point at them with the absolute path. Let's locate `hhmakemodel.py` here: (Note that the use of `%bash` cell magic is another way to send commands to the shell and is used here to make multiple lines of commands and avoid changing the working directory more than temporary.) ``` %%bash cd ../../.. find . -type f -name "hhmakemodel.*" ``` Despite the permission errors, we can see the location of the scripts. Now we can use that to run it, like so: (note this required the addition of the pdbx library [provided by the Söding lab](https://github.com/soedinglab/pdbx) using `postBuild` and `apt.txt` for those interested.) ``` %run /srv/conda/envs/notebook/scripts/hhmakemodel.py ``` We see the usage. Similarly for another script in the suite. ``` %run /srv/conda/envs/notebook/scripts/hhsuitedb.py ``` ## Stepping through intial parts of [Example: Comparative protein structure modeling using HHblits and MODELLER](https://github.com/soedinglab/hh-suite/wiki#example-comparative-protein-structure-modeling-using-hhblits-and-modeller) We'll deviate from that somewhat because some steps are difficult to do with the limited resources provided via MyBinder.org. However, overall the approach will be the same, we'll just substitute some of the databases and do the initial query against the Uniclust30 database using the `HHblits` webserver the HH-suite3 authors provide. That section is found under 'Brief tutorial to HHsuite tools' in the [HH-suite3 wiki Table Of Contents](https://github.com/soedinglab/hh-suite/wiki#table-of-contents) ``` s='''>TvLDH MSEAAHVLITGAAGQIGYILSHWIASGELYGDRQVYLHLLDIPPAMNRLTALTMELEDCAFPHLAGFVATTDP KAAFKDIDCAFLVASMPLKPGQVRADLISSNSVIFKNTGEYLSKWAKPSVKVLVIGNPDNTNCEIAMLHAKNL KPENFSSLSMLDQNRAYYEVASKLGVDVKDVHDIIVWGNHGESMVADLTQATFTKEGKTQKVVDVLDHDYVFD TFFKKIGHRAWDILEHRGFTSAASPTKAAIQHMKAWLFGTAPGEVLSMGIPVPEGNPYGIKPGVVFSFPCNVD KEGKIHVVEGFKVNDWLREKLDFTEKDLFHEKEIALNHLAQ''' %store s >query.seq ``` To make things easy, the output file from the first step is already present in this session as `query.a3m`. Below describes two ways you could go about generating it yourself: - 1. To generate ouput as they do in the first in the tutorial without downloading the huge uniclust30 datbase you can use the webserver. Go to https://toolkit.tuebingen.mpg.de/tools/hhblits and paste in the sequence below into the 'Input' window and after pasting, hit 'Submit' in the bottom right. ```text >TvLDH MSEAAHVLITGAAGQIGYILSHWIASGELYGDRQVYLHLLDIPPAMNRLTALTMELEDCAFPHLAGFVATTDP KAAFKDIDCAFLVASMPLKPGQVRADLISSNSVIFKNTGEYLSKWAKPSVKVLVIGNPDNTNCEIAMLHAKNL KPENFSSLSMLDQNRAYYEVASKLGVDVKDVHDIIVWGNHGESMVADLTQATFTKEGKTQKVVDVLDHDYVFD TFFKKIGHRAWDILEHRGFTSAASPTKAAIQHMKAWLFGTAPGEVLSMGIPVPEGNPYGIKPGVVFSFPCNVD KEGKIHVVEGFKVNDWLREKLDFTEKDLFHEKEIALNHLAQ ``` That job will run and at the conclusion, you can collect the alignments, a MSA in a3m format, by clicking on the 'Query MSA' tab and then clicking on 'Download Full A3M'. Name the file as you `query.a3m` to match the tutorial and save the file to your local machine. (The one provided specifically came from using the uniclust30 database from `UniRef30_2020_06`.) - 2. To generate the output using the following command on the command line as they instruct in the tutorial, you'd download the latest uniclust30 database, by going [here](http://wwwuser.gwdg.de/~compbiol/data/hhsuite/databases/hhsuite_dbs/) and selecting `uniclist-latest` to get taken to the current most recent version available from the HH-suite3 authors ```bash hhblits -i query.seq -d databases/uniclust30_2020_06/uniclust30_2020_06 -oa3m query.a3m -cpu 4 -n 1 ``` ``` - 2. ``` ```text >TvLDH MSEAAHVLITGAAGQIGYILSHWIASGELYGDRQVYLHLLDIPPAMNRLTALTMELEDCAFPHLAGFVATTDP KAAFKDIDCAFLVASMPLKPGQVRADLISSNSVIFKNTGEYLSKWAKPSVKVLVIGNPDNTNCEIAMLHAKNL KPENFSSLSMLDQNRAYYEVASKLGVDVKDVHDIIVWGNHGESMVADLTQATFTKEGKTQKVVDVLDHDYVFD TFFKKIGHRAWDILEHRGFTSAASPTKAAIQHMKAWLFGTAPGEVLSMGIPVPEGNPYGIKPGVVFSFPCNVD KEGKIHVVEGFKVNDWLREKLDFTEKDLFHEKEIALNHLAQ ``` That job will run and at the conclusion, you can collect the alignments, a MSA in a3m format, by clicking on the 'Query MSA' tab and then clicking on 'Download Full A3M'. Name the file as you `query.a3m` to match the tutorial and save the file to your local machine. ``` !ls -lah !curl -OL http://wwwuser.gwdg.de/~compbiol/data/hhsuite/databases/hhsuite_dbs/scop70_01Mar17.tgz !tar xzf scop70_01Mar17.tgz !curl -OL http://wwwuser.gwdg.de/~compbiol/data/hhsuite/databases/hhsuite_dbs/scop40_01Mar17.tgz !tar xzf scop40_01Mar17.tgz !curl -OL http://wwwuser.gwdg.de/~compbiol/data/hhsuite/databases/hhsuite_dbs/old-releases/pdb70_06Sep14.tar.gz !tar xzf pdb70_06Sep14.tar.gz %cd ../.. !find . -type f -name "hhmakemodel.*" ``` ----- - [The MPI Bioinformatics Toolkit](https://toolkit.tuebingen.mpg.de/) also offers a web-based interface to HHblits where you can at present query [the Uniclust30 database](https://uniclust.mmseqs.com/). This is useful because that database is large, and so any options available to avoid having to obtain it and unpack it are welcome. The resulting query-template and query alignments can be visualized, downloaded, and forwarded to other tools in the 'Query Template MSA' and 'Query Alignment' tabs. Additionally, that output can then be used on the command line to make additional forms that can be used in searches. For example, under the 'Query Template MSA' and 'Query Alignment' tabs, you can select the `Download Full A3M`. That can then be used to directly make an HHM as shown under the seciton 'Generating a multiple sequence alignment using HHblits' [here](https://github.com/soedinglab/hh-suite/wiki#generating-a-multiple-sequence-alignment-using-hhblits) using `hhmake -i query.a3m -o query.hhm`. (Currently playing with https://toolkit.tuebingen.mpg.de/jobs/Sca190 to explore that.) However, though the MSAS in the `.a3m` format can actually be used by input by `hhblits` (see the `hhblits -i query.a3m -o results.hhr -d databases/pdb70 -cpu 4 -n 1` command under [here](https://github.com/soedinglab/hh-suite/wiki#example-comparative-protein-structure-modeling-using-hhblits-and-modeller)), and so I think the MSAs generated via the [The MPI Bioinformatics Toolkit](https://toolkit.tuebingen.mpg.de/) can be used to query a custom database directly. <==== NEED TO VERIFY ACTUALLY. However, bear in mind that it may **STILL** end up being much more practical to use the command line to go from sequence to a form that can be used to search against a custom database because the command line is able to scale to many more much easier than a web interface. I ALSO NEED TO CHECK WHAT HAPPENS IF YOU PASTE IN A MUTLI-SEQUENCE FASTA TO THE HHBLITS WEB INTERFACE??? ==> you cannot unless it is an alignment in fasta format it seems because you otherwise get a notive from hhpred about sequences need to be equal length. Of course the web interfaces are not as customizable or scaleable as the command line methods to be demonstrated here. ----- ``` import time def executeSomething(): #code here print ('.') time.sleep(480) #60 seconds times 8 minutes while True: executeSomething() ```
github_jupyter
!hhblits !hhsearch !hhmake %%bash cd ../../.. find . -type f -name "hhmakemodel.*" %run /srv/conda/envs/notebook/scripts/hhmakemodel.py %run /srv/conda/envs/notebook/scripts/hhsuitedb.py s='''>TvLDH MSEAAHVLITGAAGQIGYILSHWIASGELYGDRQVYLHLLDIPPAMNRLTALTMELEDCAFPHLAGFVATTDP KAAFKDIDCAFLVASMPLKPGQVRADLISSNSVIFKNTGEYLSKWAKPSVKVLVIGNPDNTNCEIAMLHAKNL KPENFSSLSMLDQNRAYYEVASKLGVDVKDVHDIIVWGNHGESMVADLTQATFTKEGKTQKVVDVLDHDYVFD TFFKKIGHRAWDILEHRGFTSAASPTKAAIQHMKAWLFGTAPGEVLSMGIPVPEGNPYGIKPGVVFSFPCNVD KEGKIHVVEGFKVNDWLREKLDFTEKDLFHEKEIALNHLAQ''' %store s >query.seq >TvLDH MSEAAHVLITGAAGQIGYILSHWIASGELYGDRQVYLHLLDIPPAMNRLTALTMELEDCAFPHLAGFVATTDP KAAFKDIDCAFLVASMPLKPGQVRADLISSNSVIFKNTGEYLSKWAKPSVKVLVIGNPDNTNCEIAMLHAKNL KPENFSSLSMLDQNRAYYEVASKLGVDVKDVHDIIVWGNHGESMVADLTQATFTKEGKTQKVVDVLDHDYVFD TFFKKIGHRAWDILEHRGFTSAASPTKAAIQHMKAWLFGTAPGEVLSMGIPVPEGNPYGIKPGVVFSFPCNVD KEGKIHVVEGFKVNDWLREKLDFTEKDLFHEKEIALNHLAQ hhblits -i query.seq -d databases/uniclust30_2020_06/uniclust30_2020_06 -oa3m query.a3m -cpu 4 -n 1 - 2. >TvLDH MSEAAHVLITGAAGQIGYILSHWIASGELYGDRQVYLHLLDIPPAMNRLTALTMELEDCAFPHLAGFVATTDP KAAFKDIDCAFLVASMPLKPGQVRADLISSNSVIFKNTGEYLSKWAKPSVKVLVIGNPDNTNCEIAMLHAKNL KPENFSSLSMLDQNRAYYEVASKLGVDVKDVHDIIVWGNHGESMVADLTQATFTKEGKTQKVVDVLDHDYVFD TFFKKIGHRAWDILEHRGFTSAASPTKAAIQHMKAWLFGTAPGEVLSMGIPVPEGNPYGIKPGVVFSFPCNVD KEGKIHVVEGFKVNDWLREKLDFTEKDLFHEKEIALNHLAQ !ls -lah !curl -OL http://wwwuser.gwdg.de/~compbiol/data/hhsuite/databases/hhsuite_dbs/scop70_01Mar17.tgz !tar xzf scop70_01Mar17.tgz !curl -OL http://wwwuser.gwdg.de/~compbiol/data/hhsuite/databases/hhsuite_dbs/scop40_01Mar17.tgz !tar xzf scop40_01Mar17.tgz !curl -OL http://wwwuser.gwdg.de/~compbiol/data/hhsuite/databases/hhsuite_dbs/old-releases/pdb70_06Sep14.tar.gz !tar xzf pdb70_06Sep14.tar.gz %cd ../.. !find . -type f -name "hhmakemodel.*" import time def executeSomething(): #code here print ('.') time.sleep(480) #60 seconds times 8 minutes while True: executeSomething()
0.162613
0.913599
# Build the speech model Now that we have created the spectrogram images its time to build the computer vision model. If you are following along with the learning path then you already created a computer vision model in the second module in this path. We will be using the [torchvision](https://pypi.org/project/torchvision/) package to build our vision model. Lets import the packages we need to build the model. ``` from torch.utils.data import DataLoader from torchvision import datasets, transforms import torch import torchaudio import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np import matplotlib.pyplot as plt from torch.utils.data import Dataset, DataLoader from torchvision import datasets, models, transforms import pandas as pd import os ``` ## Load Spectrogram images into a DataLoader for training Here we provide the path to our image data and use the `ImageFolder` helper to load the images into tensors. The labels are created based on the name of the folders. ``` data_path = './data/spectrograms' #looking in subfolder train yes_no_dataset = datasets.ImageFolder( root=data_path, transform=transforms.Compose([transforms.Resize((201,81)), transforms.ToTensor() ]) ) print(yes_no_dataset) print(yes_no_dataset[5][0].size()) ``` ## Split the data for training and testing - Split the data to use 80% to train the model and 20% to test. ``` #split data to test and train #use 80% to train train_size = int(0.8 * len(yes_no_dataset)) test_size = len(yes_no_dataset) - train_size yes_no_train_dataset, yes_no_test_dataset = torch.utils.data.random_split(yes_no_dataset, [train_size, test_size]) print(len(yes_no_train_dataset)) print(len(yes_no_test_dataset)) ``` - Load the data into the `DataLoader` ``` train_dataloader = torch.utils.data.DataLoader( yes_no_train_dataset, batch_size=15, num_workers=2, shuffle=True ) test_dataloader = torch.utils.data.DataLoader( yes_no_test_dataset, batch_size=15, num_workers=2, shuffle=True ) ``` - Lets take a look at what our tensor looks like ``` train_dataloader.dataset[0][0][0][0] ``` - Get GPU for training, else use CPU if GPU is not available ``` device = 'cuda' if torch.cuda.is_available() else 'cpu' print('Using {} device'.format(device)) ``` ## Create the neural network - Create the Convolutional Neural Network and set the device. ``` class CNNet(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(3, 32, kernel_size=5) self.conv2 = nn.Conv2d(32, 64, kernel_size=5) self.conv2_drop = nn.Dropout2d() self.flatten = nn.Flatten() self.fc1 = nn.Linear(51136, 50) self.fc2 = nn.Linear(50, 2) def forward(self, x): x = F.relu(F.max_pool2d(self.conv1(x), 2)) x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2)) #x = x.view(x.size(0), -1) x = self.flatten(x) x = F.relu(self.fc1(x)) x = F.dropout(x, training=self.training) x = F.relu(self.fc2(x)) return F.log_softmax(x,dim=1) model = CNNet().to(device) print(model) ``` ## Create Train and Test functions - Here we will set the cost function, learning_rate, and optimizer. Then set up the train and test functions that we will call next. ``` # cost function used to determine best parameters cost = torch.nn.CrossEntropyLoss() # used to create optimal parameters learning_rate = 0.0001 optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) # Create the training function def train(dataloader, model, loss, optimizer): model.train() size = len(dataloader.dataset) for batch, (X, Y) in enumerate(dataloader): X, Y = X.to(device), Y.to(device) optimizer.zero_grad() pred = model(X) loss = cost(pred, Y) loss.backward() optimizer.step() if batch % 100 == 0: loss, current = loss.item(), batch * len(X) print(f'loss: {loss:>7f} [{current:>5d}/{size:>5d}]') # Create the validation/test function def test(dataloader, model): size = len(dataloader.dataset) model.eval() test_loss, correct = 0, 0 with torch.no_grad(): for batch, (X, Y) in enumerate(dataloader): X, Y = X.to(device), Y.to(device) pred = model(X) test_loss += cost(pred, Y).item() correct += (pred.argmax(1)==Y).type(torch.float).sum().item() test_loss /= size correct /= size print(f'\nTest Error:\nacc: {(100*correct):>0.1f}%, avg loss: {test_loss:>8f}\n') ``` ## Train the model - Now lets set the number of epochs and call our `train` and `test` functions for each epoch. ``` epochs = 15 for t in range(epochs): print(f'Epoch {t+1}\n-------------------------------') train(train_dataloader, model, cost, optimizer) test(test_dataloader, model) print('Done!') ``` ## Test the model Awesome! You should have got somewhere between a 93%-95% accuracy by the 15th epoch. Here we grab a batch from our test data and see how the model performs on the predicted vs the actual result. ``` model.eval() test_loss, correct = 0, 0 with torch.no_grad(): for batch, (X, Y) in enumerate(test_dataloader): X, Y = X.to(device), Y.to(device) pred = model(X) print("Predicted:") print(f"{pred.argmax(1)}") print("Actual:") print(f"{Y}") break ```
github_jupyter
from torch.utils.data import DataLoader from torchvision import datasets, transforms import torch import torchaudio import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np import matplotlib.pyplot as plt from torch.utils.data import Dataset, DataLoader from torchvision import datasets, models, transforms import pandas as pd import os data_path = './data/spectrograms' #looking in subfolder train yes_no_dataset = datasets.ImageFolder( root=data_path, transform=transforms.Compose([transforms.Resize((201,81)), transforms.ToTensor() ]) ) print(yes_no_dataset) print(yes_no_dataset[5][0].size()) #split data to test and train #use 80% to train train_size = int(0.8 * len(yes_no_dataset)) test_size = len(yes_no_dataset) - train_size yes_no_train_dataset, yes_no_test_dataset = torch.utils.data.random_split(yes_no_dataset, [train_size, test_size]) print(len(yes_no_train_dataset)) print(len(yes_no_test_dataset)) train_dataloader = torch.utils.data.DataLoader( yes_no_train_dataset, batch_size=15, num_workers=2, shuffle=True ) test_dataloader = torch.utils.data.DataLoader( yes_no_test_dataset, batch_size=15, num_workers=2, shuffle=True ) train_dataloader.dataset[0][0][0][0] device = 'cuda' if torch.cuda.is_available() else 'cpu' print('Using {} device'.format(device)) class CNNet(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(3, 32, kernel_size=5) self.conv2 = nn.Conv2d(32, 64, kernel_size=5) self.conv2_drop = nn.Dropout2d() self.flatten = nn.Flatten() self.fc1 = nn.Linear(51136, 50) self.fc2 = nn.Linear(50, 2) def forward(self, x): x = F.relu(F.max_pool2d(self.conv1(x), 2)) x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2)) #x = x.view(x.size(0), -1) x = self.flatten(x) x = F.relu(self.fc1(x)) x = F.dropout(x, training=self.training) x = F.relu(self.fc2(x)) return F.log_softmax(x,dim=1) model = CNNet().to(device) print(model) # cost function used to determine best parameters cost = torch.nn.CrossEntropyLoss() # used to create optimal parameters learning_rate = 0.0001 optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) # Create the training function def train(dataloader, model, loss, optimizer): model.train() size = len(dataloader.dataset) for batch, (X, Y) in enumerate(dataloader): X, Y = X.to(device), Y.to(device) optimizer.zero_grad() pred = model(X) loss = cost(pred, Y) loss.backward() optimizer.step() if batch % 100 == 0: loss, current = loss.item(), batch * len(X) print(f'loss: {loss:>7f} [{current:>5d}/{size:>5d}]') # Create the validation/test function def test(dataloader, model): size = len(dataloader.dataset) model.eval() test_loss, correct = 0, 0 with torch.no_grad(): for batch, (X, Y) in enumerate(dataloader): X, Y = X.to(device), Y.to(device) pred = model(X) test_loss += cost(pred, Y).item() correct += (pred.argmax(1)==Y).type(torch.float).sum().item() test_loss /= size correct /= size print(f'\nTest Error:\nacc: {(100*correct):>0.1f}%, avg loss: {test_loss:>8f}\n') epochs = 15 for t in range(epochs): print(f'Epoch {t+1}\n-------------------------------') train(train_dataloader, model, cost, optimizer) test(test_dataloader, model) print('Done!') model.eval() test_loss, correct = 0, 0 with torch.no_grad(): for batch, (X, Y) in enumerate(test_dataloader): X, Y = X.to(device), Y.to(device) pred = model(X) print("Predicted:") print(f"{pred.argmax(1)}") print("Actual:") print(f"{Y}") break
0.884776
0.98191
<div style="display: flex; background-color: #3F579F;"> <h1 style="margin: auto; font-weight: bold; padding: 30px 30px 0px 30px; color:#fff;" align="center">Automatically classify consumer goods - P6</h1> </div> <div style="display: flex; background-color: #3F579F; margin: auto; padding: 5px 30px 0px 30px;" > <h3 style="width: 100%; text-align: center; float: left; font-size: 24px; color:#fff;" align="center">| Notebook - 3D visualization |</h3> </div> <div style="display: flex; background-color: #3F579F; margin: auto; padding: 10px 30px 30px 30px;"> <h4 style="width: 100%; text-align: center; float: left; font-size: 24px; color:#fff;" align="center">Data Scientist course - OpenClassrooms</h4> </div> <div class="alert alert-block alert-info"> <p>This notebook it is only to plot in 3D through Tensorboard, the reductions to 3 components of T-SNE</p> <p>So, we are going to plot only 2 datasets listed below</p> <ul style="list-style-type: square;"> <li><b>tfidf_lemma_price_pca_tsne_3c</b> (NO features from images) - texts (Lemmatization + TF-IDF) and price</li> <li><b>sift_price_bow_stemmed_pca_tsne_3c</b> (WITH features from images) text (Stemmatization + BoW), price and images</li> </ul> </div> <div style="background-color: #506AB9;" > <h2 style="margin: auto; padding: 20px; color:#fff; ">1. Libraries and functions</h2> </div> <div style="background-color: #6D83C5;" > <h3 style="margin: auto; padding: 20px; color:#fff; ">1.1. Libraries and functions</h3> </div> ``` ## General import os import pandas as pd import numpy as np ## TensorFlow import tensorflow as tf from tensorboard.plugins import projector ## Own specific functions from functions import * %load_ext tensorboard # Path to save the embedding and checkpoints generated LOG_DIR = "./logs/projections/" ``` <div style="background-color: #506AB9;" > <h2 style="margin: auto; padding: 20px; color:#fff; ">2. Importing files and Initial analysis</h2> </div> <div style="background-color: #6D83C5;" > <h3 style="margin: auto; padding: 20px; color:#fff; ">2.1. Importing and preparing files</h3> </div> <div class="alert alert-block alert-info"> We are going to load two datesets to plot them in 3D </div> ``` df_text = pd.read_csv(r"datasets\tfidf_lemma_price_pca_tsne_3c.csv", index_col=[0]) df_sift = pd.read_csv(r"datasets\sift_price_tfidf_stemmed_pca_tsne_3c.csv", index_col=[0]) ``` <div style="background-color: #506AB9;" > <h2 style="margin: auto; padding: 20px; color:#fff; ">3. Tensorboard projection</h2> </div> <div style="background-color: #6D83C5;" > <h3 style="margin: auto; padding: 20px; color:#fff; ">3.1. Features from text (Lemmatization + TF-IDF) and price</h3> </div> <div class="alert alert-block alert-info"> <p> In this case, we are going to plot the features from text features, it means that we don't use the descriptors and keypoints from the images</p> </div> ``` df_text.head() ``` <div class="alert alert-block alert-info"> <p> Creating a file with only the features</p> </div> ``` features = df_text[["tsne1", "tsne2", "tsne3"]].copy() features.to_csv(LOG_DIR + "features.txt", sep='\t', index=False, header=False) ``` <div class="alert alert-block alert-info"> <p> Creating a file with only the cluters (labels) as metadata</p> </div> ``` metadata = df_text[["cluster"]].copy() metadata.to_csv(LOG_DIR + "metadata.tsv", sep='\t', index=False, header=False) metadata = os.path.join(LOG_DIR, 'metadata.tsv') ``` <div class="alert alert-block alert-info"> <p>Defining the vectos and weights</p> </div> ``` features_vector = np.loadtxt(LOG_DIR + "features.txt") features_vector weights = tf.Variable(features_vector) weights ``` <div class="alert alert-block alert-info"> <p>Setting up the checkpoints</p> </div> ``` checkpoint = tf.train.Checkpoint(embedding=weights) checkpoint.save(os.path.join(LOG_DIR, "embedding.ckpt")) ``` <div class="alert alert-block alert-info"> <p>Setting up config</p> </div> ``` # Set up config. config = projector.ProjectorConfig() embedding = config.embeddings.add() ``` <div class="alert alert-block alert-info"> <p>Defining embeddings</p> </div> ``` embedding.tensor_name = "embedding/.ATTRIBUTES/VARIABLE_VALUE" embedding.metadata_path = "metadata.tsv" ``` <div class="alert alert-block alert-info"> <p>Initializing the projector based on the setup defined</p> </div> ``` projector.visualize_embeddings(LOG_DIR, config) ``` <div class="alert alert-block alert-info"> <p>Now run tensorboard against on log data we just saved.</p> </div> ``` %tensorboard --logdir {LOG_DIR} ``` <div class="alert alert-block alert-info"> <p>Below, a GIF with the visualization result.</p> </div> ![3D visualization](images/text_analysis/tfidf_lemma_price.gif) <div class="alert alert-block alert-success"> <p><b>Observations / Conclusions</b></p> <p>It is clear the clusters in the plot. Also we can notice the inertia in each cluster</p> </div> <div style="background-color: #6D83C5;" > <h3 style="margin: auto; padding: 20px; color:#fff; ">3.2. Features from images (SIFT), text (Stemmatization + BoW) and price</h3> </div> <div class="alert alert-block alert-info"> <p> In this case, we are going to plot the features from images features, text and price, it means that we use the descriptors and keypoints from the images</p> </div> ``` df_sift.head() ``` <div class="alert alert-block alert-info"> <p> Creating a file with only the features</p> </div> ``` features = df_sift[["tsne1", "tsne2", "tsne3"]].copy() features.to_csv(LOG_DIR + "features.txt", sep='\t', index=False, header=False) ``` <div class="alert alert-block alert-info"> <p> Creating a file with only the cluters (labels) as metadata</p> </div> ``` metadata = df_sift[["cluster"]].copy() metadata.to_csv(LOG_DIR + "metadata.tsv", sep='\t', index=False, header=False) metadata = os.path.join(LOG_DIR, 'metadata.tsv') ``` <div class="alert alert-block alert-info"> <p>Defining the vectos and weights</p> </div> ``` features_vector = np.loadtxt(LOG_DIR + "features.txt") features_vector weights = tf.Variable(features_vector) weights ``` <div class="alert alert-block alert-info"> <p>Setting up the checkpoints</p> </div> ``` checkpoint = tf.train.Checkpoint(embedding=weights) checkpoint.save(os.path.join(LOG_DIR, "embedding.ckpt")) ``` <div class="alert alert-block alert-info"> <p>Setting up config</p> </div> ``` # Set up config. config = projector.ProjectorConfig() embedding = config.embeddings.add() ``` <div class="alert alert-block alert-info"> <p>Defining embeddings</p> </div> ``` embedding.tensor_name = "embedding/.ATTRIBUTES/VARIABLE_VALUE" embedding.metadata_path = "metadata.tsv" ``` <div class="alert alert-block alert-info"> <p>Initializing the projector based on the setup defined</p> </div> ``` projector.visualize_embeddings(LOG_DIR, config) ``` <div class="alert alert-block alert-info"> <p>Now run tensorboard against on log data we just saved.</p> </div> ``` %tensorboard --logdir {LOG_DIR} ``` <div class="alert alert-block alert-info"> <p>Below, a GIF with the visualization result.</p> </div> ![3D visualization](images/text_analysis/sift_price_tfidf_stemmed.gif) <div class="alert alert-block alert-success"> <p><b>Observations / Conclusions</b></p> <p>The clusters are not clear in the plot, they are dispersed</p> </div>
github_jupyter
## General import os import pandas as pd import numpy as np ## TensorFlow import tensorflow as tf from tensorboard.plugins import projector ## Own specific functions from functions import * %load_ext tensorboard # Path to save the embedding and checkpoints generated LOG_DIR = "./logs/projections/" df_text = pd.read_csv(r"datasets\tfidf_lemma_price_pca_tsne_3c.csv", index_col=[0]) df_sift = pd.read_csv(r"datasets\sift_price_tfidf_stemmed_pca_tsne_3c.csv", index_col=[0]) df_text.head() features = df_text[["tsne1", "tsne2", "tsne3"]].copy() features.to_csv(LOG_DIR + "features.txt", sep='\t', index=False, header=False) metadata = df_text[["cluster"]].copy() metadata.to_csv(LOG_DIR + "metadata.tsv", sep='\t', index=False, header=False) metadata = os.path.join(LOG_DIR, 'metadata.tsv') features_vector = np.loadtxt(LOG_DIR + "features.txt") features_vector weights = tf.Variable(features_vector) weights checkpoint = tf.train.Checkpoint(embedding=weights) checkpoint.save(os.path.join(LOG_DIR, "embedding.ckpt")) # Set up config. config = projector.ProjectorConfig() embedding = config.embeddings.add() embedding.tensor_name = "embedding/.ATTRIBUTES/VARIABLE_VALUE" embedding.metadata_path = "metadata.tsv" projector.visualize_embeddings(LOG_DIR, config) %tensorboard --logdir {LOG_DIR} df_sift.head() features = df_sift[["tsne1", "tsne2", "tsne3"]].copy() features.to_csv(LOG_DIR + "features.txt", sep='\t', index=False, header=False) metadata = df_sift[["cluster"]].copy() metadata.to_csv(LOG_DIR + "metadata.tsv", sep='\t', index=False, header=False) metadata = os.path.join(LOG_DIR, 'metadata.tsv') features_vector = np.loadtxt(LOG_DIR + "features.txt") features_vector weights = tf.Variable(features_vector) weights checkpoint = tf.train.Checkpoint(embedding=weights) checkpoint.save(os.path.join(LOG_DIR, "embedding.ckpt")) # Set up config. config = projector.ProjectorConfig() embedding = config.embeddings.add() embedding.tensor_name = "embedding/.ATTRIBUTES/VARIABLE_VALUE" embedding.metadata_path = "metadata.tsv" projector.visualize_embeddings(LOG_DIR, config) %tensorboard --logdir {LOG_DIR}
0.488527
0.875574
# c05-??? *Purpose*: (Apply control charts, Pr modeling techniques) ``` import grama as gr import numpy as np import pandas as pd import time DF = gr.Intention() %matplotlib inline filename_data = "./data/c05-data.csv" ``` # Stang ``` from grama.data import df_stang df_stang.head() ( df_stang >> gr.pt_xbs(group="thick", var="E") ) ``` - The variability is under control - The mean is not under control; in particular the thickest plates have a much lower elasticity # True Model Setup ``` from grama.models import make_plate_buckle md_plate = make_plate_buckle() md_plate ``` ## Data generation Want a dataset to have students practice using control charts; deliberately introduce some out-of-control observations in the dataset. ``` np.random.seed(101) n_batch = 10 mg_standard = gr.marg_mom("norm", mean=0, sd=1) # Base properties; mean and sd differences across operators and plate thicknesses df_base = ( gr.df_make( t=[1/4, 1/8], E_base=[1.0e4, 1.2e4], COV=[0.03, 0.03], ) >> gr.tf_outer(gr.df_make( machine=["A", "B", "C", "D", "E", "F"], eff=[0, 0, 0.06, 0, 0, 0], )) >> gr.tf_mutate(E_mean=DF.E_base * (1 + DF.eff)) ) df_noise = gr.df_make( id_measurement=["g", "h", "i", "j", "k", "l"], noise_sd=[4e2, 8e2, 4e2, 4e2, 4e2, 4e2], ) df_data = gr.df_grid() for i in range(df_base.shape[0]): # Initialize model for true material properties md_tmp = ( gr.Model() >> gr.cp_marginals( E = gr.marg_mom("lognorm", floc=0, mean=df_base.E_mean[i], cov=df_base.COV[i]), mu = gr.marg_mom("lognorm", floc=0, mean=0.32, cov=0.03), ) >> gr.cp_copula_independence() ) # "True" material properties df_true = ( md_tmp >> gr.ev_sample(n=n_batch, df_det="nom", skip=True) >> gr.tf_mutate(t=df_base.t[i], id_machine=df_base.machine[i]) ) # Record values df_data = ( df_data >> gr.tf_bind_rows(df_true) ) # Measured properties n_total = df_data.shape[0] * df_noise.shape[0] df_data = ( df_data >> gr.tf_mutate(id_specimen=DF.index) >> gr.tf_outer(df_noise) >> gr.tf_mutate(z=mg_standard.r(n_total), z2=mg_standard.r(n_total)) >> gr.tf_mutate( E=DF.E + DF.noise_sd * DF.z, mu=DF.mu + 0.005 * DF.z2, ) >> gr.tf_drop("z", "z2", "noise_sd") ) ## Write data to disk df_data.to_csv(filename_data, index=False) ## Printout df_data ( df_data >> gr.tf_arrange(DF.id_specimen) >> gr.tf_mutate(id=DF.index) >> gr.ggplot(gr.aes("id", "E")) + gr.geom_point() ) ( df_data >> gr.tf_arrange(DF.id_specimen) >> gr.tf_mutate(id=DF.index) >> gr.ggplot(gr.aes("id", "mu")) + gr.geom_point() ) ( df_data >> gr.tf_group_by(DF.t) >> gr.tf_summarize( E_mean=gr.mean(DF.E), E_sd=gr.sd(DF.E), ) >> gr.tf_mutate(E_cov=DF.E_sd/DF.E_mean) ) ``` # Data Analysis ## Real vs Error ``` df_real = ( df_data >> gr.tf_group_by(DF.t, DF.id_specimen, DF.id_machine) >> gr.tf_summarize( E=gr.mean(DF.E), mu=gr.mean(DF.mu), ) >> gr.tf_ungroup() >> gr.tf_arrange(DF.id_machine) ) df_real ``` ## Xbar and S charts ### 1/4 Plates ``` ( df_real >> gr.tf_filter(DF.t == 1/4) >> gr.pt_xbs(group="id_machine", var="E") ) ( df_data >> gr.tf_filter(DF.t == 1/4) >> gr.pt_xbs(group="id_measurement", var="E") ) ``` ### 1/8 Plates ``` ( df_real >> gr.tf_filter(DF.t == 1/8) >> gr.pt_xbs(group="id_machine", var="E") ) ( df_data >> gr.tf_filter(DF.t == 1/8) >> gr.pt_xbs(group="id_measurement", var="E") ) ```
github_jupyter
import grama as gr import numpy as np import pandas as pd import time DF = gr.Intention() %matplotlib inline filename_data = "./data/c05-data.csv" from grama.data import df_stang df_stang.head() ( df_stang >> gr.pt_xbs(group="thick", var="E") ) from grama.models import make_plate_buckle md_plate = make_plate_buckle() md_plate np.random.seed(101) n_batch = 10 mg_standard = gr.marg_mom("norm", mean=0, sd=1) # Base properties; mean and sd differences across operators and plate thicknesses df_base = ( gr.df_make( t=[1/4, 1/8], E_base=[1.0e4, 1.2e4], COV=[0.03, 0.03], ) >> gr.tf_outer(gr.df_make( machine=["A", "B", "C", "D", "E", "F"], eff=[0, 0, 0.06, 0, 0, 0], )) >> gr.tf_mutate(E_mean=DF.E_base * (1 + DF.eff)) ) df_noise = gr.df_make( id_measurement=["g", "h", "i", "j", "k", "l"], noise_sd=[4e2, 8e2, 4e2, 4e2, 4e2, 4e2], ) df_data = gr.df_grid() for i in range(df_base.shape[0]): # Initialize model for true material properties md_tmp = ( gr.Model() >> gr.cp_marginals( E = gr.marg_mom("lognorm", floc=0, mean=df_base.E_mean[i], cov=df_base.COV[i]), mu = gr.marg_mom("lognorm", floc=0, mean=0.32, cov=0.03), ) >> gr.cp_copula_independence() ) # "True" material properties df_true = ( md_tmp >> gr.ev_sample(n=n_batch, df_det="nom", skip=True) >> gr.tf_mutate(t=df_base.t[i], id_machine=df_base.machine[i]) ) # Record values df_data = ( df_data >> gr.tf_bind_rows(df_true) ) # Measured properties n_total = df_data.shape[0] * df_noise.shape[0] df_data = ( df_data >> gr.tf_mutate(id_specimen=DF.index) >> gr.tf_outer(df_noise) >> gr.tf_mutate(z=mg_standard.r(n_total), z2=mg_standard.r(n_total)) >> gr.tf_mutate( E=DF.E + DF.noise_sd * DF.z, mu=DF.mu + 0.005 * DF.z2, ) >> gr.tf_drop("z", "z2", "noise_sd") ) ## Write data to disk df_data.to_csv(filename_data, index=False) ## Printout df_data ( df_data >> gr.tf_arrange(DF.id_specimen) >> gr.tf_mutate(id=DF.index) >> gr.ggplot(gr.aes("id", "E")) + gr.geom_point() ) ( df_data >> gr.tf_arrange(DF.id_specimen) >> gr.tf_mutate(id=DF.index) >> gr.ggplot(gr.aes("id", "mu")) + gr.geom_point() ) ( df_data >> gr.tf_group_by(DF.t) >> gr.tf_summarize( E_mean=gr.mean(DF.E), E_sd=gr.sd(DF.E), ) >> gr.tf_mutate(E_cov=DF.E_sd/DF.E_mean) ) df_real = ( df_data >> gr.tf_group_by(DF.t, DF.id_specimen, DF.id_machine) >> gr.tf_summarize( E=gr.mean(DF.E), mu=gr.mean(DF.mu), ) >> gr.tf_ungroup() >> gr.tf_arrange(DF.id_machine) ) df_real ( df_real >> gr.tf_filter(DF.t == 1/4) >> gr.pt_xbs(group="id_machine", var="E") ) ( df_data >> gr.tf_filter(DF.t == 1/4) >> gr.pt_xbs(group="id_measurement", var="E") ) ( df_real >> gr.tf_filter(DF.t == 1/8) >> gr.pt_xbs(group="id_machine", var="E") ) ( df_data >> gr.tf_filter(DF.t == 1/8) >> gr.pt_xbs(group="id_measurement", var="E") )
0.445771
0.820937
<a href="https://colab.research.google.com/github/Abhishek1236/computer-vision-models/blob/main/Alexnet_practice.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` #importing the libraries import keras from keras.models import Sequential from keras.layers import Dense, Activation, Dropout, Flatten,\ Conv2D, MaxPooling2D from keras.layers.normalization import BatchNormalization import numpy as np import tflearn.datasets.oxflower17 as oxflower17 import tensorflow as tf np.random.seed(1000) !pip install -r requirements.txt !pip install tflearn #preparing the data x, y = oxflower17.load_data(one_hot=True) #Model class Alexnet: def __init__(self,batch_size,epoch,validation_split,x,y): self.batch_size = batch_size self.epoch = epoch self.validation_split = validation_split self.x = x self.y = y def forward(): model = Sequential() model.add(Conv2D(96,input_shape=(224,224,3),kernel_size=(11,11),strides=(4,4),padding='valid'))# first conv model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(3,3),strides=(2,2),padding='valid')) model.add(BatchNormalization()) model.add(Conv2D(256,kernel_size=(5,5),padding='same'))# second conv model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(3,3),strides=(1,1))) model.add(BatchNormalization()) model.add(Conv2D(384,kernel_size=(3,3),padding="same",strides=(1,1)))#third conv model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(3,3),padding='valid')) model.add(BatchNormalization()) model.add(Conv2D(256,kernel_size=(3,3),padding='valid')) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(3,3),strides=(2,2),padding='valid')) model.add(BatchNormalization()) model.add(Flatten()) model.add(Dense(4096)) model.add(Activation('relu')) model.add(Dense(4096)) model.add(Activation('relu')) model.add(Dense(17)) model.add(Activation('softmax')) return model def training(x,y,batch_size,epochs,validation_split,model): model.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['accuracy']) model.fit(x,y, batch_size=batch_size, epochs=epochs, verbose=1,validation_split=validation_split, shuffle=True) return model #printing the summary of the model model = Alexnet.forward() model.summary() trained_model = Alexnet.training(x = x,y = y,batch_size=64,epochs= 25,validation_split=0.25,model=model) #saving to disk trained_model.save('Alexnet.h5') ```
github_jupyter
#importing the libraries import keras from keras.models import Sequential from keras.layers import Dense, Activation, Dropout, Flatten,\ Conv2D, MaxPooling2D from keras.layers.normalization import BatchNormalization import numpy as np import tflearn.datasets.oxflower17 as oxflower17 import tensorflow as tf np.random.seed(1000) !pip install -r requirements.txt !pip install tflearn #preparing the data x, y = oxflower17.load_data(one_hot=True) #Model class Alexnet: def __init__(self,batch_size,epoch,validation_split,x,y): self.batch_size = batch_size self.epoch = epoch self.validation_split = validation_split self.x = x self.y = y def forward(): model = Sequential() model.add(Conv2D(96,input_shape=(224,224,3),kernel_size=(11,11),strides=(4,4),padding='valid'))# first conv model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(3,3),strides=(2,2),padding='valid')) model.add(BatchNormalization()) model.add(Conv2D(256,kernel_size=(5,5),padding='same'))# second conv model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(3,3),strides=(1,1))) model.add(BatchNormalization()) model.add(Conv2D(384,kernel_size=(3,3),padding="same",strides=(1,1)))#third conv model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(3,3),padding='valid')) model.add(BatchNormalization()) model.add(Conv2D(256,kernel_size=(3,3),padding='valid')) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(3,3),strides=(2,2),padding='valid')) model.add(BatchNormalization()) model.add(Flatten()) model.add(Dense(4096)) model.add(Activation('relu')) model.add(Dense(4096)) model.add(Activation('relu')) model.add(Dense(17)) model.add(Activation('softmax')) return model def training(x,y,batch_size,epochs,validation_split,model): model.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['accuracy']) model.fit(x,y, batch_size=batch_size, epochs=epochs, verbose=1,validation_split=validation_split, shuffle=True) return model #printing the summary of the model model = Alexnet.forward() model.summary() trained_model = Alexnet.training(x = x,y = y,batch_size=64,epochs= 25,validation_split=0.25,model=model) #saving to disk trained_model.save('Alexnet.h5')
0.759047
0.831759
# Time normalization of data > Marcos Duarte > Laboratory of Biomechanics and Motor Control ([http://demotu.org/](http://demotu.org/)) > Federal University of ABC, Brazil Time normalization is usually employed for the temporal alignment of cyclic data obtained from different trials with different duration (number of points). The most simple and common procedure for time normalization used in Biomechanics and Motor Control is known as the normalization to percent cycle (although it might not be the most adequate procedure in certain cases ([Helwig et al., 2011](http://www.sciencedirect.com/science/article/pii/S0021929010005038)). In the percent cycle, a fixed number (typically a temporal base from 0 to 100%) of new equally spaced data is created based on the old data with a mathematical procedure known as interpolation. **Interpolation** is the estimation of new data points within the range of known data points. This is different from **extrapolation**, the estimation of data points outside the range of known data points. Time normalization of data using interpolation is a simple procedure and it doesn't matter if the original data have more or less data points than desired. The Python function `tnorma.py` from Python module `tnorma` implements the normalization to percent cycle procedure for time normalization. The function signature is: ```python yn, tn, indie = tnorma(y, axis=0, step=1, k=3, smooth=0, mask=None, nan_at_ext='delete', show=False, ax=None) ``` Let's see now how to perform interpolation and time normalization; first let's import the necessary Python libraries and configure the environment: ## Installation ```bash pip install tnorma ``` Or ```bash conda install -c duartexyz tnorma ``` ``` # Import the necessary libraries import numpy as np %matplotlib inline import matplotlib.pyplot as plt ``` For instance, consider the data shown next. The time normalization of these data to represent a cycle from 0 to 100%, with a step of 1% (101 data points) is: ``` y = [5, 4, 10, 8, 1, 10, 2, 7, 1, 3] print("y data:") y t = np.linspace(0, 100, len(y)) # time vector for the original data tn = np.linspace(0, 100, 101) # new time vector for the new time-normalized data yn = np.interp(tn, t, y) # new time-normalized data print("y data interpolated to 101 points:") yn ``` The key is the Numpy `interp` function, from its help: >interp(x, xp, fp, left=None, right=None) >One-dimensional linear interpolation. >Returns the one-dimensional piecewise linear interpolant to a function with given values at discrete data-points. A plot of the data will show what we have done: ``` plt.figure(figsize=(9, 5)) plt.plot(t, y, 'bo-', lw=2, label='original data') plt.plot(tn, yn, '.-', color=[1, 0, 0, .5], lw=2, label='time normalized') plt.legend(loc='best', framealpha=.5) plt.xlabel('Cycle [%]') plt.show() ``` The function `tnorma.py` implements this kind of normalization with option for a different interpolation than the linear one used, deal with missing points in the data (if these missing points are not at the extremities of the data because the interpolation function can not extrapolate data), other things. Let's see the `tnorma.py` examples: ``` from tnorma import tnorma >>> # Default options: cubic spline interpolation passing through >>> # each datum, 101 points, and no plot >>> y = [5, 4, 10, 8, 1, 10, 2, 7, 1, 3] >>> tnorma(y) >>> # Linear interpolation passing through each datum >>> yn, tn, indie = tnorma(y, k=1, smooth=0, mask=None, show=True) >>> # Cubic spline interpolation with smoothing >>> yn, tn, indie = tnorma(y, k=3, smooth=1, mask=None, show=True) >>> # Cubic spline interpolation with smoothing and 50 points >>> x = np.linspace(-3, 3, 60) >>> y = np.exp(-x**2) + np.random.randn(60)/10 >>> yn, tn, indie = tnorma(y, step=-50, k=3, smooth=1, show=True) >>> # Deal with missing data (use NaN as mask) >>> x = np.linspace(-3, 3, 100) >>> y = np.exp(-x**2) + np.random.randn(100)/10 >>> y[:10] = np.NaN # first ten points are missing >>> y[30: 41] = np.NaN # make other 10 missing points >>> yn, tn, indie = tnorma(y, step=-50, k=3, smooth=1, show=True) >>> # Deal with missing data at the extremities replacing by first/last not-NaN >>> x = np.linspace(-3, 3, 100) >>> y = np.exp(-x**2) + np.random.randn(100)/10 >>> y[0:10] = np.NaN # first ten points are missing >>> y[-10:] = np.NaN # last ten points are missing >>> yn, tn, indie = tnorma(y, step=-50, k=3, smooth=1, nan_at_ext='replace', show=True) >>> # Deal with missing data at the extremities replacing by first/last not-NaN >>> x = np.linspace(-3, 3, 100) >>> y = np.exp(-x**2) + np.random.randn(100)/10 >>> y[0:10] = np.NaN # first ten points are missing >>> y[-10:] = np.NaN # last ten points are missing >>> yn, tn, indie = tnorma(y, step=-50, k=1, smooth=0, nan_at_ext='replace', show=True) >>> # Deal with 2-D array >>> x = np.linspace(-3, 3, 100) >>> y = np.exp(-x**2) + np.random.randn(100)/10 >>> y = np.vstack((y-1, y[::-1])).T >>> yn, tn, indie = tnorma(y, step=-50, k=3, smooth=1, show=True) ```
github_jupyter
yn, tn, indie = tnorma(y, axis=0, step=1, k=3, smooth=0, mask=None, nan_at_ext='delete', show=False, ax=None) pip install tnorma conda install -c duartexyz tnorma # Import the necessary libraries import numpy as np %matplotlib inline import matplotlib.pyplot as plt y = [5, 4, 10, 8, 1, 10, 2, 7, 1, 3] print("y data:") y t = np.linspace(0, 100, len(y)) # time vector for the original data tn = np.linspace(0, 100, 101) # new time vector for the new time-normalized data yn = np.interp(tn, t, y) # new time-normalized data print("y data interpolated to 101 points:") yn plt.figure(figsize=(9, 5)) plt.plot(t, y, 'bo-', lw=2, label='original data') plt.plot(tn, yn, '.-', color=[1, 0, 0, .5], lw=2, label='time normalized') plt.legend(loc='best', framealpha=.5) plt.xlabel('Cycle [%]') plt.show() from tnorma import tnorma >>> # Default options: cubic spline interpolation passing through >>> # each datum, 101 points, and no plot >>> y = [5, 4, 10, 8, 1, 10, 2, 7, 1, 3] >>> tnorma(y) >>> # Linear interpolation passing through each datum >>> yn, tn, indie = tnorma(y, k=1, smooth=0, mask=None, show=True) >>> # Cubic spline interpolation with smoothing >>> yn, tn, indie = tnorma(y, k=3, smooth=1, mask=None, show=True) >>> # Cubic spline interpolation with smoothing and 50 points >>> x = np.linspace(-3, 3, 60) >>> y = np.exp(-x**2) + np.random.randn(60)/10 >>> yn, tn, indie = tnorma(y, step=-50, k=3, smooth=1, show=True) >>> # Deal with missing data (use NaN as mask) >>> x = np.linspace(-3, 3, 100) >>> y = np.exp(-x**2) + np.random.randn(100)/10 >>> y[:10] = np.NaN # first ten points are missing >>> y[30: 41] = np.NaN # make other 10 missing points >>> yn, tn, indie = tnorma(y, step=-50, k=3, smooth=1, show=True) >>> # Deal with missing data at the extremities replacing by first/last not-NaN >>> x = np.linspace(-3, 3, 100) >>> y = np.exp(-x**2) + np.random.randn(100)/10 >>> y[0:10] = np.NaN # first ten points are missing >>> y[-10:] = np.NaN # last ten points are missing >>> yn, tn, indie = tnorma(y, step=-50, k=3, smooth=1, nan_at_ext='replace', show=True) >>> # Deal with missing data at the extremities replacing by first/last not-NaN >>> x = np.linspace(-3, 3, 100) >>> y = np.exp(-x**2) + np.random.randn(100)/10 >>> y[0:10] = np.NaN # first ten points are missing >>> y[-10:] = np.NaN # last ten points are missing >>> yn, tn, indie = tnorma(y, step=-50, k=1, smooth=0, nan_at_ext='replace', show=True) >>> # Deal with 2-D array >>> x = np.linspace(-3, 3, 100) >>> y = np.exp(-x**2) + np.random.randn(100)/10 >>> y = np.vstack((y-1, y[::-1])).T >>> yn, tn, indie = tnorma(y, step=-50, k=3, smooth=1, show=True)
0.667906
0.988154
### SET DATA Structure ``` st = set() print(type(st)) # creating a simple set st= {'pumar','kris','krish','bara','bara'} print(type(st)) print(st) # eliminated the duplicate values # add elemets to the set st.add('Gommu') print(st) # remove element from the set st.remove('Gommu') print(st) # Adding more than one or more values in the set simultanously st.update(['gommu','danda','lol']) # given within list print(st) # Set will not allow duplicate entries st1={'kris','gomu','gomu','bench'} print(st1) # Write a program to eliminate the repeated entries from the given list and keep single copy of each element in list ls =[11,12,13,14,15,16,11,12,13] s =set(ls) print(s) # returns set of non repeated integers ls1 =list(s) ls1 # returns list of non repeated integers # mixed type s = {'hello',23,3.14,-14,14,14} # set allows mixed data type values too print(s) ``` ### Lambda Functions - Functions without names - Simple functions where the task to be carried out is small - can take arguemens ``` # simple example of Lamba function x = lambda a : a+10 print(x(10)) # lamba functions with two arguements # a and b are the arguements for lambda function # a*b is the body of lambda function (expression) x = lambda a,b : a*b print(x(10,20)) print(x(4,5)) print(x(1,2)) ``` ### Filter functions ``` # Fliter () --> filter function filters the unwanted list elements form the list ls =[1,2,3,4,5,6,7,8,9,10] filtered_list = list(filter(lambda x : (x%2 !=0) ,ls)) print('filered list: ',filtered_list) print('boolean list: ',['True' if x%2 ==0 else x+1 for x in filtered_list]) # extract the words from astring(line) those having length as 3 st= input() ls = st.split(' ') ls1 = list(filter(lambda x : (len(x)==3),ls)) print(ls1) # extract the words from a string (line) whihc are starting with 'h' st1 = input() ls = st1.split(' ') ls2 = list(filter(lambda a :(a[0:1]=='h'),ls)) print(ls2) #Alternate method st1 = input() ls = st1.split(' ') ls2 = list(filter(lambda a :(a.startswith('h')),ls)) print(ls2) ``` ### MAP function ``` # Lambda function with map() --> match one list with another list # to call lambda function , instead of for loop, map() is used ls = [1,2,3,4,5,6,7,8,9,10] ls1 = list(map(lambda x: x*2,ls)) # old list is modified using map() --> now realtionship between ls and ls1 were defined inside the lambda function print(ls1) # new list is created # Compute variance of list of elemets a = int(input('no.of list elements :')) ls=[] for i in range (a): n= int(input('list elemets: ')) ls.append(n) print(ls) l = len(ls) q=sum(ls)/l print('mean' ,q) ls1 = list(map(lambda x : (x*x)-(q*q),ls)) s=sum(ls1)/l print('Variance' , s) #Alteranate method ls = [5,7,8,9,22,34,35,36,37] avg =sum(ls)/len(ls) dev =list(map(lambda x : (x-avg)**2,ls)) var =sum(dev)/len(ls) var import numpy as np n = np.array(ls) np.var(n) ``` ### Reduce Function - from functools import reduce ``` from functools import reduce ld = [5,3,6,7,8,12] ld1 = reduce((lambda x,y :x+y) , ld) print(ld1) ls = ['hi','how','are','you'] ls1 =reduce((lambda x,y :x+y), ls) print(ls1) txt = 'India is a great country. karnataka is one of the states' words =txt.split(' ') words.sort(key=len, reverse =True) print(words) # Assignment n = input() ls=[int(x) for x in (n.split())] ct = 0 ls1=[] for ct in ls: ls1.append((ls[ct],ls.count(ct))) ct+=1 st = set((ls1)) print(st) ``` ### Exception handling - Sematic error - syntatic error - runtime error ( exception) ``` # example of exception handling a = int(input()) while True: b =int(input()) try: c= a/b break except: print('division by zero is not possible') print('division :',c) ``` ### File Handling ``` # Example of file handling try: f=open('C:/Users/Administrator/Desktop/python/Python/myfile','r') print('file opened succesfully') except: print('file cannot be opened') exit() for i in f: print(i, end ='') f.close() # Assignment try : f=open('myfile','r') l_c=0 c_c=0 w_c=0 except: print('error') for i in f: print(i,end="") # 1 count number of lines in a file l_c+=1 # 2 count number of words in a file ls=i.split(' ') w_c+=len(ls) # 3. count number of characters in afile c_c+=len(i) print('total no.of words: ',w_c) print('line count:',l_c) print('no.of characters in string:',c_c) f.close() # 4 . print only the lines which are statring with a specified word, taken thorugh keyboard file = input('enter file name: ') word = input() try : f=open(file) except: print('error') for line in f: if line.startswith(word): print(line) f.close() # Example to write and overwrite the data into a file try: fout=open('myfile1','w') print('file opened') except: print('file cannot open') exit() for i in range(2): line = input('enter a line: ') fout.write(line + '\n') print('file writed successfully') fout.close() # usage of read() function. this will read whole file as a single string and # stroe it into a variable of the program try: f = open('myfile','r') except: print('file cannot be opened') exit() s = f.read() # this method is avoided in real-life cause it consume lot of RAM print(len(s)) print('the file contents are:',s) print('the first 20 characters of file are:',s[:20]) f.close() # write a program to copy contents of one file into another file try : f =open('myfile','r') except: print('file cannot open') f1 =open('new.txt','w') for line in f: f1.write(line) f.close() f1.close() ```
github_jupyter
st = set() print(type(st)) # creating a simple set st= {'pumar','kris','krish','bara','bara'} print(type(st)) print(st) # eliminated the duplicate values # add elemets to the set st.add('Gommu') print(st) # remove element from the set st.remove('Gommu') print(st) # Adding more than one or more values in the set simultanously st.update(['gommu','danda','lol']) # given within list print(st) # Set will not allow duplicate entries st1={'kris','gomu','gomu','bench'} print(st1) # Write a program to eliminate the repeated entries from the given list and keep single copy of each element in list ls =[11,12,13,14,15,16,11,12,13] s =set(ls) print(s) # returns set of non repeated integers ls1 =list(s) ls1 # returns list of non repeated integers # mixed type s = {'hello',23,3.14,-14,14,14} # set allows mixed data type values too print(s) # simple example of Lamba function x = lambda a : a+10 print(x(10)) # lamba functions with two arguements # a and b are the arguements for lambda function # a*b is the body of lambda function (expression) x = lambda a,b : a*b print(x(10,20)) print(x(4,5)) print(x(1,2)) # Fliter () --> filter function filters the unwanted list elements form the list ls =[1,2,3,4,5,6,7,8,9,10] filtered_list = list(filter(lambda x : (x%2 !=0) ,ls)) print('filered list: ',filtered_list) print('boolean list: ',['True' if x%2 ==0 else x+1 for x in filtered_list]) # extract the words from astring(line) those having length as 3 st= input() ls = st.split(' ') ls1 = list(filter(lambda x : (len(x)==3),ls)) print(ls1) # extract the words from a string (line) whihc are starting with 'h' st1 = input() ls = st1.split(' ') ls2 = list(filter(lambda a :(a[0:1]=='h'),ls)) print(ls2) #Alternate method st1 = input() ls = st1.split(' ') ls2 = list(filter(lambda a :(a.startswith('h')),ls)) print(ls2) # Lambda function with map() --> match one list with another list # to call lambda function , instead of for loop, map() is used ls = [1,2,3,4,5,6,7,8,9,10] ls1 = list(map(lambda x: x*2,ls)) # old list is modified using map() --> now realtionship between ls and ls1 were defined inside the lambda function print(ls1) # new list is created # Compute variance of list of elemets a = int(input('no.of list elements :')) ls=[] for i in range (a): n= int(input('list elemets: ')) ls.append(n) print(ls) l = len(ls) q=sum(ls)/l print('mean' ,q) ls1 = list(map(lambda x : (x*x)-(q*q),ls)) s=sum(ls1)/l print('Variance' , s) #Alteranate method ls = [5,7,8,9,22,34,35,36,37] avg =sum(ls)/len(ls) dev =list(map(lambda x : (x-avg)**2,ls)) var =sum(dev)/len(ls) var import numpy as np n = np.array(ls) np.var(n) from functools import reduce ld = [5,3,6,7,8,12] ld1 = reduce((lambda x,y :x+y) , ld) print(ld1) ls = ['hi','how','are','you'] ls1 =reduce((lambda x,y :x+y), ls) print(ls1) txt = 'India is a great country. karnataka is one of the states' words =txt.split(' ') words.sort(key=len, reverse =True) print(words) # Assignment n = input() ls=[int(x) for x in (n.split())] ct = 0 ls1=[] for ct in ls: ls1.append((ls[ct],ls.count(ct))) ct+=1 st = set((ls1)) print(st) # example of exception handling a = int(input()) while True: b =int(input()) try: c= a/b break except: print('division by zero is not possible') print('division :',c) # Example of file handling try: f=open('C:/Users/Administrator/Desktop/python/Python/myfile','r') print('file opened succesfully') except: print('file cannot be opened') exit() for i in f: print(i, end ='') f.close() # Assignment try : f=open('myfile','r') l_c=0 c_c=0 w_c=0 except: print('error') for i in f: print(i,end="") # 1 count number of lines in a file l_c+=1 # 2 count number of words in a file ls=i.split(' ') w_c+=len(ls) # 3. count number of characters in afile c_c+=len(i) print('total no.of words: ',w_c) print('line count:',l_c) print('no.of characters in string:',c_c) f.close() # 4 . print only the lines which are statring with a specified word, taken thorugh keyboard file = input('enter file name: ') word = input() try : f=open(file) except: print('error') for line in f: if line.startswith(word): print(line) f.close() # Example to write and overwrite the data into a file try: fout=open('myfile1','w') print('file opened') except: print('file cannot open') exit() for i in range(2): line = input('enter a line: ') fout.write(line + '\n') print('file writed successfully') fout.close() # usage of read() function. this will read whole file as a single string and # stroe it into a variable of the program try: f = open('myfile','r') except: print('file cannot be opened') exit() s = f.read() # this method is avoided in real-life cause it consume lot of RAM print(len(s)) print('the file contents are:',s) print('the first 20 characters of file are:',s[:20]) f.close() # write a program to copy contents of one file into another file try : f =open('myfile','r') except: print('file cannot open') f1 =open('new.txt','w') for line in f: f1.write(line) f.close() f1.close()
0.429669
0.800185
``` %run data.py ``` ### Read the zipcode data. ``` zipcode_data = fetchData(nyc_zcta_url) zipcode_data.head(10) zipcode_old_df = spark.createDataFrame(zipcode_data) zipcode_df = zipcode_old_df.select(zipcode_old_df.MODZCTA.cast("integer").alias("zipcode"), zipcode_old_df["Positive"], zipcode_old_df["Total"]) zipcode_df = zipcode_df.filter(zipcode_df["zipcode"] != 0) ``` ### Read the income data. ``` results_df = fetch_nycOpenData(nyc_income, 100, 10000) results_df.head(10) #remove null and nan value. df = pandas_to_spark(results_df) df = df.filter(df["postcode"].isNotNull()) df = df.filter(df["postcode"] != "NaN") #convert string to integer. new_df = df.select(df["building_id"], df["postcode"], df.extremely_low_income_units.cast('integer').alias('extremely_low_income_units'), df.very_low_income_units.cast('integer').alias('very_low_income_units'), df.low_income_units.cast('integer').alias('low_income_units'), df.middle_income_units.cast('integer').alias('middle_income_units'), df.moderate_income_units.cast('integer').alias('moderate_income_units'), df.other_income_units.cast('integer').alias('other_income_units') ) new_df.show() new_df.createOrReplaceTempView("new_df") #group by zipcode and sum low_income_units, middle_income_units and moderate_income_units. income_old_df = spark.sql("SELECT postcode as zipcode, \ sum(extremely_low_income_units) as extremely_low_income_units, \ sum(very_low_income_units) as very_low_income_units, \ sum(low_income_units) as low_income_units, \ sum(middle_income_units) as middle_income_units, \ sum(moderate_income_units) as moderate_income_units, \ sum(other_income_units) as other_income_units \ FROM new_df GROUP BY postcode ORDER BY postcode") #set low_income_units = extremely_low_income_units + very_low_income_units + low_income_units income_old_df.createOrReplaceTempView("income_old_df") income_df = spark.sql("SELECT zipcode, \ (extremely_low_income_units + very_low_income_units + low_income_units) as low_income_units, \ middle_income_units, \ moderate_income_units \ FROM income_old_df") income_df.show() #label every zipcode: low, middle or moderate. income_df = income_df.withColumn("income", f.when((f.col("low_income_units") >= f.col("middle_income_units")) & \ (f.col("low_income_units") >= f.col("moderate_income_units")), "low")\ .when((f.col("middle_income_units") >= f.col("low_income_units")) & \ (f.col("middle_income_units") >= f.col("moderate_income_units")), "middle")\ .when((f.col("moderate_income_units") >= f.col("low_income_units")) & \ (f.col("moderate_income_units") >= f.col("middle_income_units")), "moderate")) income_df.show() zipcode_df.createOrReplaceTempView("zipcode_df") income_df.createOrReplaceTempView("income_df") # join two table on zipcode. join_df = spark.sql("SELECT * FROM zipcode_df NATURAL JOIN income_df") join_df.createOrReplaceTempView("join_df") # sum positive number for three groups: low, middle and moderate. final_df = spark.sql("SELECT income, sum(Positive) as cases FROM join_df GROUP BY income ORDER BY cases") data = final_df.toPandas() data.head(10) import seaborn as sns cm = sns.light_palette("#ff7000", as_cmap = True) data.style.background_gradient(cmap = cm) ```
github_jupyter
%run data.py zipcode_data = fetchData(nyc_zcta_url) zipcode_data.head(10) zipcode_old_df = spark.createDataFrame(zipcode_data) zipcode_df = zipcode_old_df.select(zipcode_old_df.MODZCTA.cast("integer").alias("zipcode"), zipcode_old_df["Positive"], zipcode_old_df["Total"]) zipcode_df = zipcode_df.filter(zipcode_df["zipcode"] != 0) results_df = fetch_nycOpenData(nyc_income, 100, 10000) results_df.head(10) #remove null and nan value. df = pandas_to_spark(results_df) df = df.filter(df["postcode"].isNotNull()) df = df.filter(df["postcode"] != "NaN") #convert string to integer. new_df = df.select(df["building_id"], df["postcode"], df.extremely_low_income_units.cast('integer').alias('extremely_low_income_units'), df.very_low_income_units.cast('integer').alias('very_low_income_units'), df.low_income_units.cast('integer').alias('low_income_units'), df.middle_income_units.cast('integer').alias('middle_income_units'), df.moderate_income_units.cast('integer').alias('moderate_income_units'), df.other_income_units.cast('integer').alias('other_income_units') ) new_df.show() new_df.createOrReplaceTempView("new_df") #group by zipcode and sum low_income_units, middle_income_units and moderate_income_units. income_old_df = spark.sql("SELECT postcode as zipcode, \ sum(extremely_low_income_units) as extremely_low_income_units, \ sum(very_low_income_units) as very_low_income_units, \ sum(low_income_units) as low_income_units, \ sum(middle_income_units) as middle_income_units, \ sum(moderate_income_units) as moderate_income_units, \ sum(other_income_units) as other_income_units \ FROM new_df GROUP BY postcode ORDER BY postcode") #set low_income_units = extremely_low_income_units + very_low_income_units + low_income_units income_old_df.createOrReplaceTempView("income_old_df") income_df = spark.sql("SELECT zipcode, \ (extremely_low_income_units + very_low_income_units + low_income_units) as low_income_units, \ middle_income_units, \ moderate_income_units \ FROM income_old_df") income_df.show() #label every zipcode: low, middle or moderate. income_df = income_df.withColumn("income", f.when((f.col("low_income_units") >= f.col("middle_income_units")) & \ (f.col("low_income_units") >= f.col("moderate_income_units")), "low")\ .when((f.col("middle_income_units") >= f.col("low_income_units")) & \ (f.col("middle_income_units") >= f.col("moderate_income_units")), "middle")\ .when((f.col("moderate_income_units") >= f.col("low_income_units")) & \ (f.col("moderate_income_units") >= f.col("middle_income_units")), "moderate")) income_df.show() zipcode_df.createOrReplaceTempView("zipcode_df") income_df.createOrReplaceTempView("income_df") # join two table on zipcode. join_df = spark.sql("SELECT * FROM zipcode_df NATURAL JOIN income_df") join_df.createOrReplaceTempView("join_df") # sum positive number for three groups: low, middle and moderate. final_df = spark.sql("SELECT income, sum(Positive) as cases FROM join_df GROUP BY income ORDER BY cases") data = final_df.toPandas() data.head(10) import seaborn as sns cm = sns.light_palette("#ff7000", as_cmap = True) data.style.background_gradient(cmap = cm)
0.379608
0.766031
<a href="https://colab.research.google.com/github/BandaruDheeraj/TTSModel/blob/main/waveglow.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ### This notebook requires a GPU runtime to run. ### Please select the menu option "Runtime" -> "Change runtime type", select "Hardware Accelerator" -> "GPU" and click "SAVE" ---------------------------------------------------------------------- # WaveGlow *Author: NVIDIA* **WaveGlow model for generating speech from mel spectrograms (generated by Tacotron2)** <img src="https://pytorch.org/assets/images/waveglow_diagram.png" alt="alt" width="50%"/> ### Model Description The Tacotron 2 and WaveGlow model form a text-to-speech system that enables user to synthesise a natural sounding speech from raw transcripts without any additional prosody information. The Tacotron 2 model (also available via torch.hub) produces mel spectrograms from input text using encoder-decoder architecture. WaveGlow is a flow-based model that consumes the mel spectrograms to generate speech. ### Example In the example below: - pretrained Tacotron2 and Waveglow models are loaded from torch.hub - Tacotron2 generates mel spectrogram given tensor represantation of an input text ("Hello world, I missed you so much") - Waveglow generates sound given the mel spectrogram - the output sound is saved in an 'audio.wav' file To run the example you need some extra python packages installed. These are needed for preprocessing the text and audio, as well as for display and input / output. ``` %%bash pip install numpy scipy librosa unidecode inflect librosa apt-get update apt-get install -y libsndfile1 ``` Load the WaveGlow model pre-trained on [LJ Speech dataset](https://keithito.com/LJ-Speech-Dataset/) ``` import torch waveglow = torch.hub.load('NVIDIA/DeepLearningExamples:torchhub', 'nvidia_waveglow', model_math='fp32') ``` Prepare the WaveGlow model for inference ``` waveglow = waveglow.remove_weightnorm(waveglow) waveglow = waveglow.to('cuda') waveglow.eval() ``` Load a pretrained Tacotron2 model ``` tacotron2 = torch.hub.load('NVIDIA/DeepLearningExamples:torchhub', 'nvidia_tacotron2', model_math='fp32') tacotron2 = tacotron2.to('cuda') tacotron2.eval() ``` Now, let's make the model say: ``` text = "hello world, I missed you so much" ``` Format the input using utility methods ``` utils = torch.hub.load('NVIDIA/DeepLearningExamples:torchhub', 'nvidia_tts_utils') sequences, lengths = utils.prepare_input_sequence([text]) ``` Run the chained models ``` with torch.no_grad(): mel, _, _ = tacotron2.infer(sequences, lengths) audio = waveglow.infer(mel) audio_numpy = audio[0].data.cpu().numpy() rate = 22050 ``` You can write it to a file and listen to it ``` from scipy.io.wavfile import write write("audio.wav", rate, audio_numpy) ``` Alternatively, play it right away in a notebook with IPython widgets ``` from IPython.display import Audio Audio(audio_numpy, rate=rate) ``` ### Details For detailed information on model input and output, training recipies, inference and performance visit: [github](https://github.com/NVIDIA/DeepLearningExamples/tree/master/PyTorch/SpeechSynthesis/Tacotron2) and/or [NGC](https://ngc.nvidia.com/catalog/resources/nvidia:tacotron_2_and_waveglow_for_pytorch) ### References - [Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions](https://arxiv.org/abs/1712.05884) - [WaveGlow: A Flow-based Generative Network for Speech Synthesis](https://arxiv.org/abs/1811.00002) - [Tacotron2 and WaveGlow on NGC](https://ngc.nvidia.com/catalog/resources/nvidia:tacotron_2_and_waveglow_for_pytorch) - [Tacotron2 and Waveglow on github](https://github.com/NVIDIA/DeepLearningExamples/tree/master/PyTorch/SpeechSynthesis/Tacotron2)
github_jupyter
%%bash pip install numpy scipy librosa unidecode inflect librosa apt-get update apt-get install -y libsndfile1 import torch waveglow = torch.hub.load('NVIDIA/DeepLearningExamples:torchhub', 'nvidia_waveglow', model_math='fp32') waveglow = waveglow.remove_weightnorm(waveglow) waveglow = waveglow.to('cuda') waveglow.eval() tacotron2 = torch.hub.load('NVIDIA/DeepLearningExamples:torchhub', 'nvidia_tacotron2', model_math='fp32') tacotron2 = tacotron2.to('cuda') tacotron2.eval() text = "hello world, I missed you so much" utils = torch.hub.load('NVIDIA/DeepLearningExamples:torchhub', 'nvidia_tts_utils') sequences, lengths = utils.prepare_input_sequence([text]) with torch.no_grad(): mel, _, _ = tacotron2.infer(sequences, lengths) audio = waveglow.infer(mel) audio_numpy = audio[0].data.cpu().numpy() rate = 22050 from scipy.io.wavfile import write write("audio.wav", rate, audio_numpy) from IPython.display import Audio Audio(audio_numpy, rate=rate)
0.580114
0.982237
#1. Install Dependencies First install the libraries needed to execute recipes, this only needs to be done once, then click play. ``` !pip install git+https://github.com/google/starthinker ``` #2. Get Cloud Project ID To run this recipe [requires a Google Cloud Project](https://github.com/google/starthinker/blob/master/tutorials/cloud_project.md), this only needs to be done once, then click play. ``` CLOUD_PROJECT = 'PASTE PROJECT ID HERE' print("Cloud Project Set To: %s" % CLOUD_PROJECT) ``` #3. Get Client Credentials To read and write to various endpoints requires [downloading client credentials](https://github.com/google/starthinker/blob/master/tutorials/cloud_client_installed.md), this only needs to be done once, then click play. ``` CLIENT_CREDENTIALS = 'PASTE CREDENTIALS HERE' print("Client Credentials Set To: %s" % CLIENT_CREDENTIALS) ``` #4. Enter Storage To Table Parameters Move using bucket and path prefix. 1. Specify a bucket and path prefix, * suffix is NOT required. 1. Every time the job runs it will overwrite the table. Modify the values below for your use case, can be done multiple times, then click play. ``` FIELDS = { 'auth_read': 'user', # Credentials used for reading data. 'bucket': '', # Google cloud bucket. 'auth_write': 'service', # Credentials used for writing data. 'path': '', # Path prefix to read from, no * required. 'dataset': '', # Existing BigQuery dataset. 'table': '', # Table to create from this query. 'schema': '[]', # Schema provided in JSON list format or empty list. } print("Parameters Set To: %s" % FIELDS) ``` #5. Execute Storage To Table This does NOT need to be modified unles you are changing the recipe, click play. ``` from starthinker.util.project import project from starthinker.script.parse import json_set_fields, json_expand_includes USER_CREDENTIALS = '/content/user.json' TASKS = [ { 'bigquery': { 'auth': 'user', 'from': { 'bucket': {'field': {'name': 'bucket','kind': 'string','order': 1,'default': '','description': 'Google cloud bucket.'}}, 'path': {'field': {'name': 'path','kind': 'string','order': 2,'default': '','description': 'Path prefix to read from, no * required.'}} }, 'to': { 'auth': 'user', 'dataset': {'field': {'name': 'dataset','kind': 'string','order': 3,'default': '','description': 'Existing BigQuery dataset.'}}, 'table': {'field': {'name': 'table','kind': 'string','order': 4,'default': '','description': 'Table to create from this query.'}} }, 'schema': {'field': {'name': 'schema','kind': 'json','order': 5,'default': '[]','description': 'Schema provided in JSON list format or empty list.'}} } } ] json_set_fields(TASKS, FIELDS) json_expand_includes(TASKS) project.initialize(_recipe={ 'tasks':TASKS }, _project=CLOUD_PROJECT, _user=USER_CREDENTIALS, _client=CLIENT_CREDENTIALS, _verbose=True) project.execute() ```
github_jupyter
!pip install git+https://github.com/google/starthinker CLOUD_PROJECT = 'PASTE PROJECT ID HERE' print("Cloud Project Set To: %s" % CLOUD_PROJECT) CLIENT_CREDENTIALS = 'PASTE CREDENTIALS HERE' print("Client Credentials Set To: %s" % CLIENT_CREDENTIALS) FIELDS = { 'auth_read': 'user', # Credentials used for reading data. 'bucket': '', # Google cloud bucket. 'auth_write': 'service', # Credentials used for writing data. 'path': '', # Path prefix to read from, no * required. 'dataset': '', # Existing BigQuery dataset. 'table': '', # Table to create from this query. 'schema': '[]', # Schema provided in JSON list format or empty list. } print("Parameters Set To: %s" % FIELDS) from starthinker.util.project import project from starthinker.script.parse import json_set_fields, json_expand_includes USER_CREDENTIALS = '/content/user.json' TASKS = [ { 'bigquery': { 'auth': 'user', 'from': { 'bucket': {'field': {'name': 'bucket','kind': 'string','order': 1,'default': '','description': 'Google cloud bucket.'}}, 'path': {'field': {'name': 'path','kind': 'string','order': 2,'default': '','description': 'Path prefix to read from, no * required.'}} }, 'to': { 'auth': 'user', 'dataset': {'field': {'name': 'dataset','kind': 'string','order': 3,'default': '','description': 'Existing BigQuery dataset.'}}, 'table': {'field': {'name': 'table','kind': 'string','order': 4,'default': '','description': 'Table to create from this query.'}} }, 'schema': {'field': {'name': 'schema','kind': 'json','order': 5,'default': '[]','description': 'Schema provided in JSON list format or empty list.'}} } } ] json_set_fields(TASKS, FIELDS) json_expand_includes(TASKS) project.initialize(_recipe={ 'tasks':TASKS }, _project=CLOUD_PROJECT, _user=USER_CREDENTIALS, _client=CLIENT_CREDENTIALS, _verbose=True) project.execute()
0.371935
0.715349
# Developing an AI application Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications. In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using [this dataset](http://www.robots.ox.ac.uk/~vgg/data/flowers/102/index.html) of 102 flower categories, you can see a few examples below. <img src='assets/Flowers.png' width=500px> The project is broken down into multiple steps: * Load and preprocess the image dataset * Train the image classifier on your dataset * Use the trained classifier to predict image content We'll lead you through each part which you'll implement in Python. When you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new. First up is importing the packages you'll need. It's good practice to keep all the imports at the beginning of your code. As you work through this notebook and find you need to import a package, make sure to add the import up here. ``` # Imports here import torch from torch import nn from torch import optim import torch.nn.functional as F from torchvision import datasets, transforms, models import numpy as np from PIL import Image ``` ## Load the data Here you'll use `torchvision` to load the data ([documentation](http://pytorch.org/docs/0.3.0/torchvision/index.html)). The data should be included alongside this notebook, otherwise you can [download it here](https://s3.amazonaws.com/content.udacity-data.com/nd089/flower_data.tar.gz). The dataset is split into three parts, training, validation, and testing. For the training, you'll want to apply transformations such as random scaling, cropping, and flipping. This will help the network generalize leading to better performance. You'll also need to make sure the input data is resized to 224x224 pixels as required by the pre-trained networks. The validation and testing sets are used to measure the model's performance on data it hasn't seen yet. For this you don't want any scaling or rotation transformations, but you'll need to resize then crop the images to the appropriate size. The pre-trained networks you'll use were trained on the ImageNet dataset where each color channel was normalized separately. For all three sets you'll need to normalize the means and standard deviations of the images to what the network expects. For the means, it's `[0.485, 0.456, 0.406]` and for the standard deviations `[0.229, 0.224, 0.225]`, calculated from the ImageNet images. These values will shift each color channel to be centered at 0 and range from -1 to 1. ``` data_dir = 'flowers' train_dir = data_dir + '/train' valid_dir = data_dir + '/valid' test_dir = data_dir + '/test' # TODO: Define your transforms for the training, validation, and testing sets data_transforms = transforms.Compose([transforms.Resize(225), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) train_transforms = transforms.Compose([transforms.RandomRotation(30), transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) test_transforms = transforms.Compose([transforms.Resize(225), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) # TODO: Load the datasets with ImageFolder image_datasets = datasets.ImageFolder(data_dir, transform=data_transforms) train_datasets = datasets.ImageFolder(train_dir, transform=train_transforms) test_datasets = datasets.ImageFolder(test_dir, transform=test_transforms) # TODO: Using the image datasets and the trainforms, define the dataloaders dataloader = torch.utils.data.DataLoader(image_datasets, batch_size=256, shuffle=True) trainloader = torch.utils.data.DataLoader(train_datasets, batch_size=256, shuffle=True) testloader = torch.utils.data.DataLoader(test_datasets, batch_size=256) ``` ### Label mapping You'll also need to load in a mapping from category label to category name. You can find this in the file `cat_to_name.json`. It's a JSON object which you can read in with the [`json` module](https://docs.python.org/2/library/json.html). This will give you a dictionary mapping the integer encoded categories to the actual names of the flowers. ``` import json with open('cat_to_name.json', 'r') as f: cat_to_name = json.load(f) ``` # Building and training the classifier Now that the data is ready, it's time to build and train the classifier. As usual, you should use one of the pretrained models from `torchvision.models` to get the image features. Build and train a new feed-forward classifier using those features. We're going to leave this part up to you. Refer to [the rubric](https://review.udacity.com/#!/rubrics/1663/view) for guidance on successfully completing this section. Things you'll need to do: * Load a [pre-trained network](http://pytorch.org/docs/master/torchvision/models.html) (If you need a starting point, the VGG networks work great and are straightforward to use) * Define a new, untrained feed-forward network as a classifier, using ReLU activations and dropout * Train the classifier layers using backpropagation using the pre-trained network to get the features * Track the loss and accuracy on the validation set to determine the best hyperparameters We've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal! When training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right. Make sure to try different hyperparameters (learning rate, units in the classifier, epochs, etc) to find the best model. Save those hyperparameters to use as default values in the next part of the project. One last important tip if you're using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to GPU Workspaces about Keeping Your Session Active. You'll want to include code from the workspace_utils.py module. **Note for Workspace users:** If your network is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. Typically this happens with wide dense layers after the convolutional layers. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with `ls -lh`), you should reduce the size of your hidden layers and train again. ``` #Use GPU, if turned on device = torch.device("cuda" if torch.cuda.is_available() else "cpu") #Load model model = models.vgg19(pretrained=True) #Freeze parameters for param in model.parameters(): param.requires_grad = False model #Create new classifier for VRR19 model classifier = nn.Sequential(nn.Linear(25088, 2048), nn.ReLU(), nn.Dropout(p=0.2), nn.Linear(2048, 102), nn.LogSoftmax(dim=1)) model.classifier = classifier criterion = nn.NLLLoss() optimizer = optim.Adam(model.classifier.parameters(), lr=0.001) model.to(device); #train the new classifier epochs = 7 steps = 0 running_loss = 0 print_every = 5 for epoch in range(epochs): for images, labels in trainloader: steps += 1 images, labels = images.to(device), labels.to(device) optimizer.zero_grad() logps = model.forward(images) loss = criterion(logps, labels) loss.backward() optimizer.step() running_loss += loss.item() if steps % print_every == 0: model.eval() test_loss = 0 accuracy = 0 with torch.no_grad(): for images, labels in testloader: images, labels = images.to(device), labels.to(device) logps = model(images) loss = criterion(logps, labels) test_loss += loss.item() ps = torch.exp(logps) top_ps, top_class = ps.topk(1, dim=1) equality = top_class == labels.view(*top_class.shape) accuracy += torch.mean(equality.type(torch.FloatTensor)).item() print(f"Epoch {epoch+1}/{epochs}.. " f"Train loss: {running_loss/print_every:.3f}.. " f"Test loss: {test_loss/len(testloader):.3f}.. " f"Test accuracy: {accuracy/len(testloader):.3f}") running_loss = 0 model.train() ``` ## Testing your network It's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. Run the test images through the network and measure the accuracy, the same way you did validation. You should be able to reach around 70% accuracy on the test set if the model has been trained well. ``` #Testing the model, same as test above, but with another dataset model.eval() test_loss = 0 accuracy = 0 with torch.no_grad(): for images, labels in dataloader: images, labels = images.to(device), labels.to(device) logps = model(images) loss = criterion(logps, labels) test_loss += loss.item() ps = torch.exp(logps) top_ps, top_class = ps.topk(1, dim=1) equality = top_class == labels.view(*top_class.shape) accuracy += torch.mean(equality.type(torch.FloatTensor)).item() print(f"Test loss: {test_loss/len(dataloader):.3f}.. " f"Test accuracy: {accuracy/len(dataloader):.3f}") running_loss = 0 ``` ## Save the checkpoint Now that your network is trained, save the model so you can load it later for making predictions. You probably want to save other things such as the mapping of classes to indices which you get from one of the image datasets: `image_datasets['train'].class_to_idx`. You can attach this to the model as an attribute which makes inference easier later on. ```model.class_to_idx = image_datasets['train'].class_to_idx``` Remember that you'll want to completely rebuild the model later so you can use it for inference. Make sure to include any information you need in the checkpoint. If you want to load the model and keep training, you'll want to save the number of epochs as well as the optimizer state, `optimizer.state_dict`. You'll likely want to use this trained model in the next part of the project, so best to save it now. ``` # TODO: Save the checkpoint model.class_to_idx = train_datasets.class_to_idx checkpoint = {'input_size': 25088, 'output_size': 102, 'learning_rate': 0.001, 'epochs': 7, 'model': models.vgg19(pretrained=True), 'classifier': model.classifier, 'optimizer': optimizer.state_dict(), 'state_dict': model.state_dict(), 'class_to_idx': model.class_to_idx} torch.save(checkpoint, 'checkpoint.pth') ``` ## Loading the checkpoint At this point it's good to write a function that can load a checkpoint and rebuild the model. That way you can come back to this project and keep working on it without having to retrain the network. ``` # TODO: Write a function that loads a checkpoint and rebuilds the model def load_checkpoint(filepath): checkpoint = torch.load(filepath) input_size = checkpoint['input_size'] output_size = checkpoint['output_size'] epochs = checkpoint['epochs'] learning_rate = checkpoint['learning_rate'] model = checkpoint['model'] model.classifier = checkpoint['classifier'] optimizer.load_state_dict(checkpoint['optimizer']) model.load_state_dict(checkpoint['state_dict']) return model model = load_checkpoint('checkpoint.pth') print(model) ``` # Inference for classification Now you'll write a function to use a trained network for inference. That is, you'll pass an image into the network and predict the class of the flower in the image. Write a function called `predict` that takes an image and a model, then returns the top $K$ most likely classes along with the probabilities. It should look like ```python probs, classes = predict(image_path, model) print(probs) print(classes) > [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339] > ['70', '3', '45', '62', '55'] ``` First you'll need to handle processing the input image such that it can be used in your network. ## Image Preprocessing You'll want to use `PIL` to load the image ([documentation](https://pillow.readthedocs.io/en/latest/reference/Image.html)). It's best to write a function that preprocesses the image so it can be used as input for the model. This function should process the images in the same manner used for training. First, resize the images where the shortest side is 256 pixels, keeping the aspect ratio. This can be done with the [`thumbnail`](http://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.thumbnail) or [`resize`](http://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.thumbnail) methods. Then you'll need to crop out the center 224x224 portion of the image. Color channels of images are typically encoded as integers 0-255, but the model expected floats 0-1. You'll need to convert the values. It's easiest with a Numpy array, which you can get from a PIL image like so `np_image = np.array(pil_image)`. As before, the network expects the images to be normalized in a specific way. For the means, it's `[0.485, 0.456, 0.406]` and for the standard deviations `[0.229, 0.224, 0.225]`. You'll want to subtract the means from each color channel, then divide by the standard deviation. And finally, PyTorch expects the color channel to be the first dimension but it's the third dimension in the PIL image and Numpy array. You can reorder dimensions using [`ndarray.transpose`](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ndarray.transpose.html). The color channel needs to be first and retain the order of the other two dimensions. ``` def process_image(image): picture = Image.open(image) picture = picture.resize((256, 256)) (left, upper, right, lower) = (16, 16, 240, 240) cropped_picture = picture.crop((left, upper, right, lower)) np_picture = np.array(cropped_picture) np_picture = np_picture / 255 mean = np.array([0.485, 0.456, 0.406]) std_dev = np.array([0.229, 0.224, 0.225]) std_picture = (np_picture - mean)/std_dev std_picture = np.transpose(std_picture, (2, 0, 1)) return std_picture img='flowers/test/1/image_06743.jpg' processed_image = (process_image(img)) # TODO: Process a PIL image for use in a PyTorch model ``` To check your work, the function below converts a PyTorch tensor and displays it in the notebook. If your `process_image` function works, running the output through this function should return the original image (except for the cropped out portions). ``` def imshow(image, ax=None, title=None): """Imshow for Tensor.""" if ax is None: fig, ax = plt.subplots() # PyTorch tensors assume the color channel is the first dimension # but matplotlib assumes is the third dimension image = image.numpy().transpose((1, 2, 0)) # Undo preprocessing mean = np.array([0.485, 0.456, 0.406]) std = np.array([0.229, 0.224, 0.225]) image = std * image + mean # Image needs to be clipped between 0 and 1 or it looks like noise when displayed image = np.clip(image, 0, 1) ax.imshow(image) return ax ``` ## Class Prediction Once you can get images in the correct format, it's time to write a function for making predictions with your model. A common practice is to predict the top 5 or so (usually called top-$K$) most probable classes. You'll want to calculate the class probabilities then find the $K$ largest values. To get the top $K$ largest values in a tensor use [`x.topk(k)`](http://pytorch.org/docs/master/torch.html#torch.topk). This method returns both the highest `k` probabilities and the indices of those probabilities corresponding to the classes. You need to convert from these indices to the actual class labels using `class_to_idx` which hopefully you added to the model or from an `ImageFolder` you used to load the data ([see here](#Save-the-checkpoint)). Make sure to invert the dictionary so you get a mapping from index to class as well. Again, this method should take a path to an image and a model checkpoint, then return the probabilities and classes. ```python probs, classes = predict(image_path, model) print(probs) print(classes) > [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339] > ['70', '3', '45', '62', '55'] ``` ``` def predict(image_path, model, topk=5): ''' Predict the class (or classes) of an image using a trained deep learning model. ''' # TODO: Implement the code to predict the class from an image file ``` ## Sanity Checking Now that you can use a trained model for predictions, check to make sure it makes sense. Even if the testing accuracy is high, it's always good to check that there aren't obvious bugs. Use `matplotlib` to plot the probabilities for the top 5 classes as a bar graph, along with the input image. It should look like this: <img src='assets/inference_example.png' width=300px> You can convert from the class integer encoding to actual flower names with the `cat_to_name.json` file (should have been loaded earlier in the notebook). To show a PyTorch tensor as an image, use the `imshow` function defined above. ``` # TODO: Display an image along with the top 5 classes ```
github_jupyter
# Imports here import torch from torch import nn from torch import optim import torch.nn.functional as F from torchvision import datasets, transforms, models import numpy as np from PIL import Image data_dir = 'flowers' train_dir = data_dir + '/train' valid_dir = data_dir + '/valid' test_dir = data_dir + '/test' # TODO: Define your transforms for the training, validation, and testing sets data_transforms = transforms.Compose([transforms.Resize(225), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) train_transforms = transforms.Compose([transforms.RandomRotation(30), transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) test_transforms = transforms.Compose([transforms.Resize(225), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) # TODO: Load the datasets with ImageFolder image_datasets = datasets.ImageFolder(data_dir, transform=data_transforms) train_datasets = datasets.ImageFolder(train_dir, transform=train_transforms) test_datasets = datasets.ImageFolder(test_dir, transform=test_transforms) # TODO: Using the image datasets and the trainforms, define the dataloaders dataloader = torch.utils.data.DataLoader(image_datasets, batch_size=256, shuffle=True) trainloader = torch.utils.data.DataLoader(train_datasets, batch_size=256, shuffle=True) testloader = torch.utils.data.DataLoader(test_datasets, batch_size=256) import json with open('cat_to_name.json', 'r') as f: cat_to_name = json.load(f) #Use GPU, if turned on device = torch.device("cuda" if torch.cuda.is_available() else "cpu") #Load model model = models.vgg19(pretrained=True) #Freeze parameters for param in model.parameters(): param.requires_grad = False model #Create new classifier for VRR19 model classifier = nn.Sequential(nn.Linear(25088, 2048), nn.ReLU(), nn.Dropout(p=0.2), nn.Linear(2048, 102), nn.LogSoftmax(dim=1)) model.classifier = classifier criterion = nn.NLLLoss() optimizer = optim.Adam(model.classifier.parameters(), lr=0.001) model.to(device); #train the new classifier epochs = 7 steps = 0 running_loss = 0 print_every = 5 for epoch in range(epochs): for images, labels in trainloader: steps += 1 images, labels = images.to(device), labels.to(device) optimizer.zero_grad() logps = model.forward(images) loss = criterion(logps, labels) loss.backward() optimizer.step() running_loss += loss.item() if steps % print_every == 0: model.eval() test_loss = 0 accuracy = 0 with torch.no_grad(): for images, labels in testloader: images, labels = images.to(device), labels.to(device) logps = model(images) loss = criterion(logps, labels) test_loss += loss.item() ps = torch.exp(logps) top_ps, top_class = ps.topk(1, dim=1) equality = top_class == labels.view(*top_class.shape) accuracy += torch.mean(equality.type(torch.FloatTensor)).item() print(f"Epoch {epoch+1}/{epochs}.. " f"Train loss: {running_loss/print_every:.3f}.. " f"Test loss: {test_loss/len(testloader):.3f}.. " f"Test accuracy: {accuracy/len(testloader):.3f}") running_loss = 0 model.train() #Testing the model, same as test above, but with another dataset model.eval() test_loss = 0 accuracy = 0 with torch.no_grad(): for images, labels in dataloader: images, labels = images.to(device), labels.to(device) logps = model(images) loss = criterion(logps, labels) test_loss += loss.item() ps = torch.exp(logps) top_ps, top_class = ps.topk(1, dim=1) equality = top_class == labels.view(*top_class.shape) accuracy += torch.mean(equality.type(torch.FloatTensor)).item() print(f"Test loss: {test_loss/len(dataloader):.3f}.. " f"Test accuracy: {accuracy/len(dataloader):.3f}") running_loss = 0 Remember that you'll want to completely rebuild the model later so you can use it for inference. Make sure to include any information you need in the checkpoint. If you want to load the model and keep training, you'll want to save the number of epochs as well as the optimizer state, `optimizer.state_dict`. You'll likely want to use this trained model in the next part of the project, so best to save it now. ## Loading the checkpoint At this point it's good to write a function that can load a checkpoint and rebuild the model. That way you can come back to this project and keep working on it without having to retrain the network. # Inference for classification Now you'll write a function to use a trained network for inference. That is, you'll pass an image into the network and predict the class of the flower in the image. Write a function called `predict` that takes an image and a model, then returns the top $K$ most likely classes along with the probabilities. It should look like First you'll need to handle processing the input image such that it can be used in your network. ## Image Preprocessing You'll want to use `PIL` to load the image ([documentation](https://pillow.readthedocs.io/en/latest/reference/Image.html)). It's best to write a function that preprocesses the image so it can be used as input for the model. This function should process the images in the same manner used for training. First, resize the images where the shortest side is 256 pixels, keeping the aspect ratio. This can be done with the [`thumbnail`](http://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.thumbnail) or [`resize`](http://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.thumbnail) methods. Then you'll need to crop out the center 224x224 portion of the image. Color channels of images are typically encoded as integers 0-255, but the model expected floats 0-1. You'll need to convert the values. It's easiest with a Numpy array, which you can get from a PIL image like so `np_image = np.array(pil_image)`. As before, the network expects the images to be normalized in a specific way. For the means, it's `[0.485, 0.456, 0.406]` and for the standard deviations `[0.229, 0.224, 0.225]`. You'll want to subtract the means from each color channel, then divide by the standard deviation. And finally, PyTorch expects the color channel to be the first dimension but it's the third dimension in the PIL image and Numpy array. You can reorder dimensions using [`ndarray.transpose`](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ndarray.transpose.html). The color channel needs to be first and retain the order of the other two dimensions. To check your work, the function below converts a PyTorch tensor and displays it in the notebook. If your `process_image` function works, running the output through this function should return the original image (except for the cropped out portions). ## Class Prediction Once you can get images in the correct format, it's time to write a function for making predictions with your model. A common practice is to predict the top 5 or so (usually called top-$K$) most probable classes. You'll want to calculate the class probabilities then find the $K$ largest values. To get the top $K$ largest values in a tensor use [`x.topk(k)`](http://pytorch.org/docs/master/torch.html#torch.topk). This method returns both the highest `k` probabilities and the indices of those probabilities corresponding to the classes. You need to convert from these indices to the actual class labels using `class_to_idx` which hopefully you added to the model or from an `ImageFolder` you used to load the data ([see here](#Save-the-checkpoint)). Make sure to invert the dictionary so you get a mapping from index to class as well. Again, this method should take a path to an image and a model checkpoint, then return the probabilities and classes. ## Sanity Checking Now that you can use a trained model for predictions, check to make sure it makes sense. Even if the testing accuracy is high, it's always good to check that there aren't obvious bugs. Use `matplotlib` to plot the probabilities for the top 5 classes as a bar graph, along with the input image. It should look like this: <img src='assets/inference_example.png' width=300px> You can convert from the class integer encoding to actual flower names with the `cat_to_name.json` file (should have been loaded earlier in the notebook). To show a PyTorch tensor as an image, use the `imshow` function defined above.
0.665628
0.969957
![MLU Logo](../data/MLU_Logo.png) # <a name="0">Machine Learning Accelerator - Natural Language Processing - Lecture 3</a> ## Neural Networks with PyTorch In this notebook, we will build, train and validate a Neural Network using PyTorch. 1. <a href="#1">Implementing a neural network with PyTorch</a> 2. <a href="#2">Loss Functions</a> 3. <a href="#3">Training</a> 4. <a href="#4">Example - Binary Classification</a> 5. <a href="#5">Natural Language Processing Context</a> ## 1. <a name="1">Implementing a neural network with PyTorch</a> (<a href="#0">Go to top</a>) Let's implement a simple neural network with two hidden layers of size 64 and 128 using the sequential mode (Adding things in sequence). We will have 3 inputs, 2 hidden layers and 1 output layer. Some drop-outs attached to the hidden layers. ``` import torch from torch import nn net = nn.Sequential( nn.Linear(in_features=3, # Input size of 3 is expected out_features=64), # Linear layer-1 with 64 units nn.Tanh(), # Tanh activation is applied nn.Dropout(p=.4), # Apply random 40% drop-out to layer_1 nn.Linear(64, 64), # Linear layer-2 with 64 units nn.Tanh(), # Tanh activation is applied nn.Dropout(p=.3), # Apply random 30% drop-out to layer_2 nn.Linear(64,1)) # Output layer with single unit print(net) ``` We can initialize the weights of the network with 'initialize()' function. We prefer to use the following: ``` def xavier_init_weights(m): if type(m) == nn.Linear: torch.nn.init.xavier_uniform_(m.weight) net.apply(xavier_init_weights) ``` Let's look at our layers and dropouts on them. We can easily access them wth net[layer_index] ``` print(net[0]) print(net[1]) print(net[2]) print(net[3]) print(net[4]) ``` ## 2. <a name="2">Loss Functions</a> (<a href="#0">Go to top</a>) We can select [loss functions](https://d2l.ai/chapter_linear-networks/linear-regression.html#loss-function) according to our problem. A full list of supported `Loss` functions in PyTorch are available [here](https://pytorch.org/docs/stable/nn.html#loss-functions). Let's go over some popular loss functions and see how to call a built-in loss function: __Binary Cross-entropy Loss:__ A common used loss function for binary classification. ```python loss = nn.BCELoss() ``` __Categorical Cross-entropy Loss:__ A common used loss function for multi-class classification. ```python loss = nn.CrossEntropyLoss() ``` __MSE Loss:__ One of the most common loss functions for regression problems. ```python loss = nn.MSELoss() ``` __L1 Loss:__ This is similar to L2 loss. It measures the abolsute difference between target values (y) and predictions (p). $$ \mathrm{L1 loss} = \frac{1}{2} \sum_{examples}|y - p| $$ In pytorch, we can use it with `L1Loss`: ```python loss = nn.L1Loss() ``` ## 3. <a name="3">Training</a> (<a href="#0">Go to top</a>) `torch.optim` module provides necessary optimization algorithms for neural networks. We can use the following `Optimizers` to train a network using [Stochastic Gradient Descent (SGD)](https://d2l.ai/chapter_optimization/sgd.html) method and learning rate of 0.001. ```python from torch import optim optimizer = optim.SGD(net.parameters(), lr=0.001) ``` ## 4. <a name="4">Example - Binary Classification</a> (<a href="#0">Go to top</a>) Let's train a neural network on a random dataset. We have two classes and will learn to classify them. ``` from sklearn.datasets import make_circles X, y = make_circles(n_samples=750, shuffle=True, random_state=42, noise=0.05, factor=0.3) ``` Let's plot the dataset ``` %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns def plot_dataset(X, y, title): # Activate Seaborn visualization sns.set() # Plot both classes: Class1->Blue, Class2->Red plt.scatter(X[y==1, 0], X[y==1, 1], c='blue', label="class 1") plt.scatter(X[y==0, 0], X[y==0, 1], c='red', label="class 2") plt.legend(loc='upper right') plt.xlabel('x1') plt.ylabel('x2') plt.xlim(-2, 2) plt.ylim(-2, 2) plt.title(title) plt.show() plot_dataset(X, y, title="Dataset") ``` Importing the necessary libraries ``` import time import mxnet as mx from mxnet import gluon, autograd import mxnet.ndarray as nd from mxnet.gluon.loss import SigmoidBinaryCrossEntropyLoss import time from torch.nn import BCELoss ``` We are creating the network below. We will have two hidden layers. Since the data seems easily seperable, we can have a small network (2 hidden layers) with 10 units at each layer. ``` net = nn.Sequential(nn.Linear(in_features=2, out_features=10), nn.ReLU(), nn.Linear(10, 10), nn.ReLU(), nn.Linear(10, 1), nn.Sigmoid()) ``` Let's define the training parameters ``` batch_size = 4 # How many samples to use for each weight update epochs = 50 # Total number of iterations learning_rate = 0.01 # Learning rate device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") epochs = 50 # Total number of iterations lr = 0.01 # Learning rate # Define the loss. As we used sigmoid in the last layer, we use `nn.BCELoss`. # Otherwise we could have made use of `nn.BCEWithLogitsLoss`. loss = BCELoss(reduction='none') # Define the optimizer, SGD with learning rate optimizer = torch.optim.SGD(net.parameters(), lr=lr) # Split the dataset into two parts: 80%-20% split X_train, X_val = X[0:int(len(X)*0.8), :], X[int(len(X)*0.8):, :] y_train, y_val = y[:int(len(X)*0.8)], y[int(len(X)*0.8):] # Use PyTorch DataLoaders to load the data in batches train_dataset = torch.utils.data.TensorDataset(torch.tensor(X_train, dtype=torch.float32), torch.tensor(y_train, dtype=torch.float32)) train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size) # Move validation dataset on CPU/GPU device X_val = torch.tensor(X_val, dtype=torch.float32).to(device) y_val = torch.tensor(y_val, dtype=torch.float32).to(device) ``` Let's start the training process. We will have training and validation sets and print our losses at each step. ``` train_losses = [] val_losses = [] for epoch in range(epochs): start = time.time() training_loss = 0 # Build a training loop, to train the network for idx, (data, target) in enumerate(train_loader): # zero the parameter gradients optimizer.zero_grad() data = data.to(device) target = target.to(device).view(-1, 1) output = net(data) L = loss(output, target).sum() training_loss += L.item() L.backward() optimizer.step() # Get validation predictions val_predictions = net(X_val) # Calculate the validation loss val_loss = torch.sum(loss(val_predictions, y_val.view(-1, 1))).item() # Take the average losses training_loss = training_loss / len(y_train) val_loss = val_loss / len(y_val) train_losses.append(training_loss) val_losses.append(val_loss) end = time.time() print("Epoch %s. Train_loss %f Validation_loss %f Seconds %f" % \ (epoch, training_loss, val_loss, end-start)) ``` Let's see the training and validation loss plots below. Losses go down as the training process continues as expected. ``` %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns plt.plot(train_losses, label="Training Loss") plt.plot(val_losses, label="Validation Loss") plt.title("Loss values") plt.xlabel("Epoch") plt.ylabel("Loss") plt.legend() plt.show() ``` ## 5. <a name="5">Natural Language Processing Context</a> (<a href="#0">Go to top</a>) If we want to use the same type of architecture for text classification, we need to apply some feature extraction methods first. For example: We can get TF-IDF vectors of text fields. After that, we can use neural networks on those features. We will also look at __more advanced neural network architrectures__ such as __Recurrent Neural Networks (RNNs)__, __Long Short-Term Memory networks (LSTMs)__ and __Transformers__.
github_jupyter
import torch from torch import nn net = nn.Sequential( nn.Linear(in_features=3, # Input size of 3 is expected out_features=64), # Linear layer-1 with 64 units nn.Tanh(), # Tanh activation is applied nn.Dropout(p=.4), # Apply random 40% drop-out to layer_1 nn.Linear(64, 64), # Linear layer-2 with 64 units nn.Tanh(), # Tanh activation is applied nn.Dropout(p=.3), # Apply random 30% drop-out to layer_2 nn.Linear(64,1)) # Output layer with single unit print(net) def xavier_init_weights(m): if type(m) == nn.Linear: torch.nn.init.xavier_uniform_(m.weight) net.apply(xavier_init_weights) print(net[0]) print(net[1]) print(net[2]) print(net[3]) print(net[4]) loss = nn.BCELoss() loss = nn.CrossEntropyLoss() loss = nn.MSELoss() loss = nn.L1Loss() from torch import optim optimizer = optim.SGD(net.parameters(), lr=0.001) from sklearn.datasets import make_circles X, y = make_circles(n_samples=750, shuffle=True, random_state=42, noise=0.05, factor=0.3) %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns def plot_dataset(X, y, title): # Activate Seaborn visualization sns.set() # Plot both classes: Class1->Blue, Class2->Red plt.scatter(X[y==1, 0], X[y==1, 1], c='blue', label="class 1") plt.scatter(X[y==0, 0], X[y==0, 1], c='red', label="class 2") plt.legend(loc='upper right') plt.xlabel('x1') plt.ylabel('x2') plt.xlim(-2, 2) plt.ylim(-2, 2) plt.title(title) plt.show() plot_dataset(X, y, title="Dataset") import time import mxnet as mx from mxnet import gluon, autograd import mxnet.ndarray as nd from mxnet.gluon.loss import SigmoidBinaryCrossEntropyLoss import time from torch.nn import BCELoss net = nn.Sequential(nn.Linear(in_features=2, out_features=10), nn.ReLU(), nn.Linear(10, 10), nn.ReLU(), nn.Linear(10, 1), nn.Sigmoid()) batch_size = 4 # How many samples to use for each weight update epochs = 50 # Total number of iterations learning_rate = 0.01 # Learning rate device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") epochs = 50 # Total number of iterations lr = 0.01 # Learning rate # Define the loss. As we used sigmoid in the last layer, we use `nn.BCELoss`. # Otherwise we could have made use of `nn.BCEWithLogitsLoss`. loss = BCELoss(reduction='none') # Define the optimizer, SGD with learning rate optimizer = torch.optim.SGD(net.parameters(), lr=lr) # Split the dataset into two parts: 80%-20% split X_train, X_val = X[0:int(len(X)*0.8), :], X[int(len(X)*0.8):, :] y_train, y_val = y[:int(len(X)*0.8)], y[int(len(X)*0.8):] # Use PyTorch DataLoaders to load the data in batches train_dataset = torch.utils.data.TensorDataset(torch.tensor(X_train, dtype=torch.float32), torch.tensor(y_train, dtype=torch.float32)) train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size) # Move validation dataset on CPU/GPU device X_val = torch.tensor(X_val, dtype=torch.float32).to(device) y_val = torch.tensor(y_val, dtype=torch.float32).to(device) train_losses = [] val_losses = [] for epoch in range(epochs): start = time.time() training_loss = 0 # Build a training loop, to train the network for idx, (data, target) in enumerate(train_loader): # zero the parameter gradients optimizer.zero_grad() data = data.to(device) target = target.to(device).view(-1, 1) output = net(data) L = loss(output, target).sum() training_loss += L.item() L.backward() optimizer.step() # Get validation predictions val_predictions = net(X_val) # Calculate the validation loss val_loss = torch.sum(loss(val_predictions, y_val.view(-1, 1))).item() # Take the average losses training_loss = training_loss / len(y_train) val_loss = val_loss / len(y_val) train_losses.append(training_loss) val_losses.append(val_loss) end = time.time() print("Epoch %s. Train_loss %f Validation_loss %f Seconds %f" % \ (epoch, training_loss, val_loss, end-start)) %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns plt.plot(train_losses, label="Training Loss") plt.plot(val_losses, label="Validation Loss") plt.title("Loss values") plt.xlabel("Epoch") plt.ylabel("Loss") plt.legend() plt.show()
0.919004
0.987935
### Note * Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps. ``` # Dependencies and Setup import pandas as pd # File to Load (Remember to Change These) file_to_load = "Resources/purchase_data.csv" # Read Purchasing File and store into Pandas data frame purchase_df = pd.read_csv(file_to_load) purchase_df age_df = pd.read_csv(file_to_load) purchase_df ``` ## Player Count * Display the total number of players ``` #locates the three columns from the main df number_of_uniqueplayers = purchase_df.loc[:,["SN","Gender","Age"]] #drops any duplicate rows number_of_uniqueplayers = number_of_uniqueplayers.drop_duplicates() number_of_players = len(number_of_uniqueplayers) #creates data frame for number of players players_count_summary=pd.DataFrame({"Number of Players":[number_of_players]}) players_count_summary ``` ## Purchasing Analysis (Total) * Run basic calculations to obtain number of unique items, average price, etc. * Create a summary data frame to hold the results * Optional: give the displayed data cleaner formatting * Display the summary data frame ``` #finds the unique item ids number_of_uniqueitems = purchase_df["Item ID"].unique() #counts how many unique items number_of_items = len(number_of_uniqueitems) number_of_purchases = purchase_df["Price"].count() #sums the purchases total_of_purchases = purchase_df["Price"].sum() #finds the number of purchases number_of_purchases = len(purchase_df["Item ID"]) average_price = purchase_df["Price"].mean() #formats the price average_price = "${:,.2f}".format(average_price) summary= pd.DataFrame({"Number of Purchases":[number_of_purchases], "Number of Items":number_of_items, "Average Price":[average_price], "Total Revenue":[total_of_purchases]}) summary["Total Revenue"]=summary["Total Revenue"].map("${:,.2f}".format) summary ``` ## Gender Demographics * Percentage and Count of Male Players * Percentage and Count of Female Players * Percentage and Count of Other / Non-Disclosed ``` #counting the number of each genders gender_demographic = number_of_uniqueplayers['Gender'].value_counts() #calculating the percentage gender_demographic_pct = (gender_demographic/number_of_players) gender_demographic_pct gender_summary= pd.DataFrame({"Total Count":gender_demographic, "Percentage":gender_demographic_pct}) gender_summary["Percentage"]=gender_summary["Percentage"].map("{:,.2%}".format) gender_summary ``` ## Purchasing Analysis (Gender) * Run basic calculations to obtain purchase count, avg. purchase price, avg. purchase total per person etc. by gender * Create a summary data frame to hold the results * Optional: give the displayed data cleaner formatting * Display the summary data frame ``` #calculating spend by gender gender_total_purchase = purchase_df.groupby("Gender").sum()["Price"] #average price gender_average_price = purchase_df.groupby("Gender").mean()["Price"] gender_count = purchase_df.groupby("Gender").count()["Price"] total_purchase_per_person = gender_total_purchase/gender_summary["Total Count"] gender_purchase_summary= pd.DataFrame({"Purchase Count":gender_count, "Average Purchase Price":gender_average_price, "Total Purchase Value":gender_total_purchase, "Avg Total Purchase per Person":total_purchase_per_person}) gender_purchase_summary["Average Purchase Price"]=gender_purchase_summary["Average Purchase Price"].map("${:,.2f}".format) gender_purchase_summary["Total Purchase Value"]=gender_purchase_summary["Total Purchase Value"].map("${:,.2f}".format) gender_purchase_summary["Avg Total Purchase per Person"]=gender_purchase_summary["Avg Total Purchase per Person"].map("${:,.2f}".format) gender_purchase_summary ``` ## Age Demographics * Establish bins for ages * Categorize the existing players using the age bins. Hint: use pd.cut() * Calculate the numbers and percentages by age group * Create a summary data frame to hold the results * Optional: round the percentage column to two decimal points * Display Age Demographics Table ``` #setting the bins bins = [0,9,14,19,24,29,34,39,1500] group_names =["<10","10-14","15-19","20-24","25-29","30-34","35-39","40+"] number_of_uniqueplayers["Total Count"] = pd.cut(number_of_uniqueplayers["Age"], bins, labels=group_names) age_count = number_of_uniqueplayers['Total Count'].value_counts() age_count_pct = age_count/number_of_players age_count_summary= pd.DataFrame({"Total Count":age_count, "Percentage of Players":age_count_pct }) age_count_summary["Percentage of Players"]=age_count_summary["Percentage of Players"].map("{:,.2%}".format) age_count_summary ``` ## Purchasing Analysis (Age) * Bin the purchase_data data frame by age * Run basic calculations to obtain purchase count, avg. purchase price, avg. purchase total per person etc. in the table below * Create a summary data frame to hold the results * Optional: give the displayed data cleaner formatting * Display the summary data frame ``` bins = [0,9,14,19,24,29,34,39,1500] group_names =["<10","10-14","15-19","20-24","25-29","30-34","35-39","40+"] purchase_df["Age Group"] = pd.cut(purchase_df["Age"], bins, labels=group_names) age_purchase_count = purchase_df.groupby("Age Group").count()["Price"] age_group = purchase_df.groupby("Age Group") age_total_purchase = purchase_df.groupby("Age Group").sum()["Price"] age_average_price = purchase_df.groupby("Age Group").mean()["Price"] age_avg_purchase = age_total_purchase/age_count_summary["Total Count"] age_spending_summary= pd.DataFrame({"Purchase Count":age_purchase_count, "Average Purchase Price":age_average_price, "Total Purchase Value":age_total_purchase, "Avg Total Purchase per Person":age_avg_purchase}) age_spending_summary["Average Purchase Price"]=age_spending_summary["Average Purchase Price"].map("${:,.2f}".format) age_spending_summary["Total Purchase Value"]=age_spending_summary["Total Purchase Value"].map("${:,.2f}".format) age_spending_summary["Avg Total Purchase per Person"]=age_spending_summary["Avg Total Purchase per Person"].map("${:,.2f}".format) age_spending_summary ``` ## Top Spenders * Run basic calculations to obtain the results in the table below * Create a summary data frame to hold the results * Sort the total purchase value column in descending order * Optional: give the displayed data cleaner formatting * Display a preview of the summary data frame ``` #made the date frame to the only needed columns reduced_purchase_df = purchase_df.loc[:, ["SN", "Price", "Item Name"]] sn_purchase_count = reduced_purchase_df.groupby("SN").count()["Item Name"] sn_purchase_total =reduced_purchase_df.groupby("SN").sum()["Price"] sn_avg_price = sn_purchase_total/sn_purchase_count sn_df= pd.DataFrame({"Purchase Count":sn_purchase_count, "Average Purchase Price":sn_avg_price, "Total Purchase Value":sn_purchase_total}) sn_sorted_df= sn_df.sort_values(['Total Purchase Value'], ascending=[False]) sn_sorted_df["Average Purchase Price"]=sn_sorted_df["Average Purchase Price"].map("${:,.2f}".format) sn_sorted_df["Total Purchase Value"]=sn_sorted_df["Total Purchase Value"].map("${:,.2f}".format) sn_sorted_df.head() ``` ## Most Popular Items * Retrieve the Item ID, Item Name, and Item Price columns * Group by Item ID and Item Name. Perform calculations to obtain purchase count, item price, and total purchase value * Create a summary data frame to hold the results * Sort the purchase count column in descending order * Optional: give the displayed data cleaner formatting * Display a preview of the summary data frame ``` reduced_item_df = purchase_df.loc[:, ["Item ID", "Item Name", "Price"]] item_purchase_count = reduced_item_df.groupby(["Item Name","Item ID"]).count()["Price"] item_purchase_total =reduced_item_df.groupby(["Item Name","Item ID"]).sum()["Price"] item_price = item_purchase_total/item_purchase_count item_df= pd.DataFrame({"Purchase Count":item_purchase_count, "Item Price":item_price, "Total Purchase Value":item_purchase_total}) item_sorted_df= item_df.sort_values(['Purchase Count'], ascending=[False]) item_sorted_df["Item Price"]=item_sorted_df["Item Price"].map("${:,.2f}".format) item_sorted_df["Total Purchase Value"]=item_sorted_df["Total Purchase Value"].map("${:,.2f}".format) item_sorted_df ``` ## Most Profitable Items * Sort the above table by total purchase value in descending order * Optional: give the displayed data cleaner formatting * Display a preview of the data frame ``` item_value_sorted_df =item_df.sort_values(['Total Purchase Value'], ascending=[False]) item_value_sorted_df["Item Price"]=item_value_sorted_df["Item Price"].map("${:,.2f}".format) item_value_sorted_df["Total Purchase Value"]=item_value_sorted_df["Total Purchase Value"].map("${:,.2f}".format) item_value_sorted_df print("The three trends I noticed were, over 84% of the players were male, 58% of the players are in their 20s, and Even though males were 84% of the players they were only 82% of the spend") ```
github_jupyter
# Dependencies and Setup import pandas as pd # File to Load (Remember to Change These) file_to_load = "Resources/purchase_data.csv" # Read Purchasing File and store into Pandas data frame purchase_df = pd.read_csv(file_to_load) purchase_df age_df = pd.read_csv(file_to_load) purchase_df #locates the three columns from the main df number_of_uniqueplayers = purchase_df.loc[:,["SN","Gender","Age"]] #drops any duplicate rows number_of_uniqueplayers = number_of_uniqueplayers.drop_duplicates() number_of_players = len(number_of_uniqueplayers) #creates data frame for number of players players_count_summary=pd.DataFrame({"Number of Players":[number_of_players]}) players_count_summary #finds the unique item ids number_of_uniqueitems = purchase_df["Item ID"].unique() #counts how many unique items number_of_items = len(number_of_uniqueitems) number_of_purchases = purchase_df["Price"].count() #sums the purchases total_of_purchases = purchase_df["Price"].sum() #finds the number of purchases number_of_purchases = len(purchase_df["Item ID"]) average_price = purchase_df["Price"].mean() #formats the price average_price = "${:,.2f}".format(average_price) summary= pd.DataFrame({"Number of Purchases":[number_of_purchases], "Number of Items":number_of_items, "Average Price":[average_price], "Total Revenue":[total_of_purchases]}) summary["Total Revenue"]=summary["Total Revenue"].map("${:,.2f}".format) summary #counting the number of each genders gender_demographic = number_of_uniqueplayers['Gender'].value_counts() #calculating the percentage gender_demographic_pct = (gender_demographic/number_of_players) gender_demographic_pct gender_summary= pd.DataFrame({"Total Count":gender_demographic, "Percentage":gender_demographic_pct}) gender_summary["Percentage"]=gender_summary["Percentage"].map("{:,.2%}".format) gender_summary #calculating spend by gender gender_total_purchase = purchase_df.groupby("Gender").sum()["Price"] #average price gender_average_price = purchase_df.groupby("Gender").mean()["Price"] gender_count = purchase_df.groupby("Gender").count()["Price"] total_purchase_per_person = gender_total_purchase/gender_summary["Total Count"] gender_purchase_summary= pd.DataFrame({"Purchase Count":gender_count, "Average Purchase Price":gender_average_price, "Total Purchase Value":gender_total_purchase, "Avg Total Purchase per Person":total_purchase_per_person}) gender_purchase_summary["Average Purchase Price"]=gender_purchase_summary["Average Purchase Price"].map("${:,.2f}".format) gender_purchase_summary["Total Purchase Value"]=gender_purchase_summary["Total Purchase Value"].map("${:,.2f}".format) gender_purchase_summary["Avg Total Purchase per Person"]=gender_purchase_summary["Avg Total Purchase per Person"].map("${:,.2f}".format) gender_purchase_summary #setting the bins bins = [0,9,14,19,24,29,34,39,1500] group_names =["<10","10-14","15-19","20-24","25-29","30-34","35-39","40+"] number_of_uniqueplayers["Total Count"] = pd.cut(number_of_uniqueplayers["Age"], bins, labels=group_names) age_count = number_of_uniqueplayers['Total Count'].value_counts() age_count_pct = age_count/number_of_players age_count_summary= pd.DataFrame({"Total Count":age_count, "Percentage of Players":age_count_pct }) age_count_summary["Percentage of Players"]=age_count_summary["Percentage of Players"].map("{:,.2%}".format) age_count_summary bins = [0,9,14,19,24,29,34,39,1500] group_names =["<10","10-14","15-19","20-24","25-29","30-34","35-39","40+"] purchase_df["Age Group"] = pd.cut(purchase_df["Age"], bins, labels=group_names) age_purchase_count = purchase_df.groupby("Age Group").count()["Price"] age_group = purchase_df.groupby("Age Group") age_total_purchase = purchase_df.groupby("Age Group").sum()["Price"] age_average_price = purchase_df.groupby("Age Group").mean()["Price"] age_avg_purchase = age_total_purchase/age_count_summary["Total Count"] age_spending_summary= pd.DataFrame({"Purchase Count":age_purchase_count, "Average Purchase Price":age_average_price, "Total Purchase Value":age_total_purchase, "Avg Total Purchase per Person":age_avg_purchase}) age_spending_summary["Average Purchase Price"]=age_spending_summary["Average Purchase Price"].map("${:,.2f}".format) age_spending_summary["Total Purchase Value"]=age_spending_summary["Total Purchase Value"].map("${:,.2f}".format) age_spending_summary["Avg Total Purchase per Person"]=age_spending_summary["Avg Total Purchase per Person"].map("${:,.2f}".format) age_spending_summary #made the date frame to the only needed columns reduced_purchase_df = purchase_df.loc[:, ["SN", "Price", "Item Name"]] sn_purchase_count = reduced_purchase_df.groupby("SN").count()["Item Name"] sn_purchase_total =reduced_purchase_df.groupby("SN").sum()["Price"] sn_avg_price = sn_purchase_total/sn_purchase_count sn_df= pd.DataFrame({"Purchase Count":sn_purchase_count, "Average Purchase Price":sn_avg_price, "Total Purchase Value":sn_purchase_total}) sn_sorted_df= sn_df.sort_values(['Total Purchase Value'], ascending=[False]) sn_sorted_df["Average Purchase Price"]=sn_sorted_df["Average Purchase Price"].map("${:,.2f}".format) sn_sorted_df["Total Purchase Value"]=sn_sorted_df["Total Purchase Value"].map("${:,.2f}".format) sn_sorted_df.head() reduced_item_df = purchase_df.loc[:, ["Item ID", "Item Name", "Price"]] item_purchase_count = reduced_item_df.groupby(["Item Name","Item ID"]).count()["Price"] item_purchase_total =reduced_item_df.groupby(["Item Name","Item ID"]).sum()["Price"] item_price = item_purchase_total/item_purchase_count item_df= pd.DataFrame({"Purchase Count":item_purchase_count, "Item Price":item_price, "Total Purchase Value":item_purchase_total}) item_sorted_df= item_df.sort_values(['Purchase Count'], ascending=[False]) item_sorted_df["Item Price"]=item_sorted_df["Item Price"].map("${:,.2f}".format) item_sorted_df["Total Purchase Value"]=item_sorted_df["Total Purchase Value"].map("${:,.2f}".format) item_sorted_df item_value_sorted_df =item_df.sort_values(['Total Purchase Value'], ascending=[False]) item_value_sorted_df["Item Price"]=item_value_sorted_df["Item Price"].map("${:,.2f}".format) item_value_sorted_df["Total Purchase Value"]=item_value_sorted_df["Total Purchase Value"].map("${:,.2f}".format) item_value_sorted_df print("The three trends I noticed were, over 84% of the players were male, 58% of the players are in their 20s, and Even though males were 84% of the players they were only 82% of the spend")
0.48438
0.832849
# Fashion MNIST mit Neuronalen Netzen In diesem Arbeitsblatt wollen wir uns erneut den Fashion MNIST Datensatz vornehmen, den wir schon aus dem 7. Arbeitsblatt kennen. Dort haben wir das Problem mit Multinomialer Logistischer Regression gelöst. Hier wollen wir ein Multi-Layer Perceptron einsetzen, also ein recht einfaches, mehrschichtiges (und voll-vermaschtes) Neuronale Netz. Wir werden später sehen, dass sich eine andere Form von Neuronalen Netzen, die sogenannten Faltungsnetze (oder *Convolutional Neural Networks*, CNN) besser für solche Aufgaben eignen. Zunächst importieren wir den Datensatz aus Tensorflow und passen die Daten an. ``` import tensorflow as tf #Datensatz aus Keras laden (X_train, y_train), (X_test, y_test) = tf.keras.datasets.fashion_mnist.load_data() #Pixelwerte nach [0,1] skalieren X_train = X_train / 255.0 X_test = X_test / 255.0 # Mache aus den 2D Bildern 1D Vektoren X_train = X_train.reshape(-1,28*28,1)[:,:,0] X_test = X_test.reshape(-1,28*28,1)[:,:,0] ``` Der MLPClassifier aus **Scikit-learn**kann für binäre, Multi-Klassen und Multi-Label Klassifizierung verwendet werden. Die Aktivierungsfunktion der Ausgabeschicht wird basierend auf dem Typ von `y` ausgewählt: - **Multi-Klassen**: Es sind verschiedene Klassen möglich, von denen eine wahr ist. `y` kann kann einen Wert annehmen (`y` ist ein Integer) $\rightarrow$ *Softmax* - **Multi-Label oder binär**: Es sind verschiedene Klassen möglich, von denen mehrere wahr sein können (`y` ist ein Vektor von "Einzel-Wahrscheinlichkeiten") $\rightarrow$ *Sigmoidfunktion* - **Regression**: `y` ist ein Wert aus $\mathbb{R}$ $\rightarrow$ *Identitätsfunktion* ($f(x)=x$) Der MLPClassifier vervwendet als Trainings-Algorithmus *Stochastic Gradient Descent* (SGD), *Adam* oder *L-BFGS*. SGD kennen wir bereits. Adam ist eine Weiterentwicklung von SGD, bei der für einzelne Attribute die Lernrate entsprechend optimiert wird. Dass kann dabei helfen, für jedes Merkmal die *passende* Schrittweite zu finden. L-BFGS ist ebenfalls ein itteratives Lösungsverfahren und gehört zur Klasse der sogenannten *Quasi-Newton-Verfahren*. Anders als SGD-basierte verfahren benötigt L-BFGS in jedem Iterationsschritt alle Daten, konvergiert aber in vielen Fällen trozdem recht schnell zum Minimum. Da das Trainieren eines MLP Modells schon recht zeitaufwändig ist, verwenden wir in der folgenden Code-Zelle das Modul *Pickle*, um das Modell in eine Datei zu speichern. Achten Sie darauf, die Datei zu löschen, wenn Sie das Modell erneut trainieren möchten. ``` from sklearn.neural_network import MLPClassifier import os, pickle modelname = "model.pickle" if os.path.isfile(modelname): clf = pickle.load(open(modelname, "rb")) else: clf = MLPClassifier(solver='lbfgs', hidden_layer_sizes=(128,), random_state=1) %time clf.fit(X_train, y_train) pickle.dump(clf, open(modelname, "wb")) clf.score(X_test, y_test) # Zum Löschen der Modell-Datei folgende Zeite un-kommentieren: #!rm model.pickle ``` ## Fashion MNIST mit Keras Nun Wollen wir statt Scikit-learn Tensorflow mit Keras verwenden, um ein MLP für Fashion MNIST zu trainieren. Zuerst verwenden wir die **Sequential API**: ``` from tensorflow import keras #Datensatz aus Keras laden (X_train, y_train), (X_test, y_test) = tf.keras.datasets.fashion_mnist.load_data() #Pixelwerte nach [0,1] skalieren X_train = X_train / 255.0 X_test = X_test / 255.0 #Modell definieren model = keras.Sequential() model.add(keras.layers.Flatten(input_shape=(28, 28))) model.add(keras.layers.Dense(128, activation=tf.nn.relu)) model.add(keras.layers.Dense(10, activation=tf.nn.softmax)) #Modell erzeugen model.compile('sgd','sparse_categorical_crossentropy',['accuracy']) #Modell trainieren model.fit(X_train, y_train, epochs=10) #Trainiertes Modell auswerten test_loss, test_acc = model.evaluate (X_test, y_test) print('Test accuracy:', test_acc) model.summary() ``` Und nun die **Functional API**: ``` #Datensatz aus Keras laden (X_train, y_train), (X_test, y_test) = tf.keras.datasets.fashion_mnist.load_data() #Pixelwerte nach [0,1] skalieren X_train = X_train / 255.0 X_test = X_test / 255.0 #Funktionale abhängigkeiten inputs = keras.Input(shape=(28, 28)) finputs = keras.layers.Flatten()(inputs) l1 = keras.layers.Dense(128, activation=tf.nn.relu)(finputs) outputs = keras.layers.Dense(10, activation=tf.nn.softmax)(l1) #Modell definieren model = keras.Model(inputs, outputs) #Modell erzeugen model.compile('sgd','sparse_categorical_crossentropy',['accuracy']) #Modell trainieren model.fit(X_train, y_train, epochs=5) #Trainiertes Modell auswerten test_loss, test_acc = model.evaluate (X_test, y_test) print('Test accuracy:', test_acc) ``` ### Referenzen [1] Tensorflow.org, *Basic classification: Classify images of clothing*, tensorflow.org/tutorials/keras/classification, 2021
github_jupyter
import tensorflow as tf #Datensatz aus Keras laden (X_train, y_train), (X_test, y_test) = tf.keras.datasets.fashion_mnist.load_data() #Pixelwerte nach [0,1] skalieren X_train = X_train / 255.0 X_test = X_test / 255.0 # Mache aus den 2D Bildern 1D Vektoren X_train = X_train.reshape(-1,28*28,1)[:,:,0] X_test = X_test.reshape(-1,28*28,1)[:,:,0] from sklearn.neural_network import MLPClassifier import os, pickle modelname = "model.pickle" if os.path.isfile(modelname): clf = pickle.load(open(modelname, "rb")) else: clf = MLPClassifier(solver='lbfgs', hidden_layer_sizes=(128,), random_state=1) %time clf.fit(X_train, y_train) pickle.dump(clf, open(modelname, "wb")) clf.score(X_test, y_test) # Zum Löschen der Modell-Datei folgende Zeite un-kommentieren: #!rm model.pickle from tensorflow import keras #Datensatz aus Keras laden (X_train, y_train), (X_test, y_test) = tf.keras.datasets.fashion_mnist.load_data() #Pixelwerte nach [0,1] skalieren X_train = X_train / 255.0 X_test = X_test / 255.0 #Modell definieren model = keras.Sequential() model.add(keras.layers.Flatten(input_shape=(28, 28))) model.add(keras.layers.Dense(128, activation=tf.nn.relu)) model.add(keras.layers.Dense(10, activation=tf.nn.softmax)) #Modell erzeugen model.compile('sgd','sparse_categorical_crossentropy',['accuracy']) #Modell trainieren model.fit(X_train, y_train, epochs=10) #Trainiertes Modell auswerten test_loss, test_acc = model.evaluate (X_test, y_test) print('Test accuracy:', test_acc) model.summary() #Datensatz aus Keras laden (X_train, y_train), (X_test, y_test) = tf.keras.datasets.fashion_mnist.load_data() #Pixelwerte nach [0,1] skalieren X_train = X_train / 255.0 X_test = X_test / 255.0 #Funktionale abhängigkeiten inputs = keras.Input(shape=(28, 28)) finputs = keras.layers.Flatten()(inputs) l1 = keras.layers.Dense(128, activation=tf.nn.relu)(finputs) outputs = keras.layers.Dense(10, activation=tf.nn.softmax)(l1) #Modell definieren model = keras.Model(inputs, outputs) #Modell erzeugen model.compile('sgd','sparse_categorical_crossentropy',['accuracy']) #Modell trainieren model.fit(X_train, y_train, epochs=5) #Trainiertes Modell auswerten test_loss, test_acc = model.evaluate (X_test, y_test) print('Test accuracy:', test_acc)
0.680772
0.92617
# Why Fugue Does NOT Want To Be Another Pandas-Like Framework Fugue fully utilizes Pandas for computing tasks, but **Fugue is NOT a Pandas-like computing framework, and it never wants to be.** In this article we are going to explain the reason for this critical design decision. ## Benchmarking PySpark Pandas (Koalas) This is an example modified from a real piece of Pandas user code. Assume we have Pandas dataframes generated by this code: ```python def gen(n): np.random.seed(0) return pd.DataFrame(dict( a=np.random.choice(["aa","abcd","xyzzzz","tttfs"],n), b=np.random.randint(0,100,n), c=np.random.choice(["aa","abcd","xyzzzz","tttfs"],n), d=np.random.randint(0,10000,n), )) ``` The output has four columns with string and integer types. Here is the user's code: ```python df.sort_values(["a", "b", "c", "d"]).drop_duplicates(subset=["a", "b"], keep="last") ``` Based on the code, the user want to firstly partition the dataframe by `a` and `b`, and in each group, the user wants to sort by `c` and `d` and then to get the last record of each group. ### Configuration and Datasets * **Databricks runtime version:** 10.1 (Scala 2.12 Spark 3.2..0) * **Cluster:** 1 i3.xlarge driver instance and 8 i3.xlarge worker instances And we will use 4 different datasets: 1 million, 10 million, 20 million, and 30 million ```python g1 = gen(1 * 1000 * 1000) df1 = spark.createDataFrame(g1).cache() df1.count() pdf1 = df1.to_pandas_on_spark() g10 = gen(10 * 1000 * 1000) df10 = spark.createDataFrame(g10).cache() df10.count() pdf10 = df10.to_pandas_on_spark() g20 = gen(20 * 1000 * 1000) df20 = spark.createDataFrame(g20).cache() df20.count() pdf20 = df20.to_pandas_on_spark() g30 = gen(30 * 1000 * 1000) df30 = spark.createDataFrame(g30).cache() df30.count() pdf30 = df30.to_pandas_on_spark() ``` ### Comparison 1 Let's firstly follow the user's original logic, and we will discuss the alternative solution later. In this [Databrick's article](https://databricks.com/blog/2021/10/04/pandas-api-on-upcoming-apache-spark-3-2.html) the author claimed that Pandas users will be able to scale their workloads with one simple line change in the Spark 3.2 release. So we will first convert the Pandas dataframe to the Spark Pandas dataframe (and without any other change) to verify the result. On the other hand, in traditional Spark, a [window function solution](https://stackoverflow.com/a/33878701) is typical. So we will also add the window function solution to the comparison. To force the full execution of the statement and also to verify result consistency, at the end of each execution we will compute the sum of column `d` and print. Based on the output, the 3 solutions all have consistent result, meaning they have no correctness issue, now let's take a look at their speed: ![Sort Dedup vs Window](../../images/pandas_like_1.png) * With a 32 core Spark cluster, both Spark solutions are significantly faster than the single core Pandas solution * The window function solution is 30% to 50% faster than the Spark Pandas solution On a local machine, a global sort is a very popular technique that is often seen in Pandas code. And in certain scenarios it outperforms other methods. However the global sort operation in distributed computing is difficult and expensive. The performance depends on each specific computing framework's implementation. Spark Pandas has done an amazing job, but even so, it is still significantly slower than a window function. Rethinking about the problem we want to solve, a global sort on the entire dataset is not necessary. If convenience is the only thing important, then switching the Pandas backend to Spark Pandas may make sense. However the whole point of moving to Spark is to be more scalable and performant. Moving to window function that will sort inside each partition isn't overly complicated, but the performance advantage is significant. ### Comparison 2 In the second comparison, we simplify the original problem to not consider column `c`. We only need to remove `c` in `sort_values` to accommodate the change ```python df.sort_values(["a", "b", "d"]).drop_duplicates(subset=["a", "b"], keep="last") ``` Again, it's intuitive and convenient and Spark Pandas can inherit this change too. However, this new problem actually means we want to group by `a` and `b` and get the max value of `d`. It can be a simple aggregation in big data. So in this comparison, we add the simple Spark aggregation approach. ![Sort Dedup vs Window vs Aggregation](../../images/pandas_like_2.png) * The previous performance pattern stays the same * Spark aggregation takes ~1 sec regardless of data size So now, do you want to just remove column `c` for simplicity or do you want to rewrite the logic for performance? ### Comparison 3 Let's go back to the original logic where we still have 4 columns. By understanding the intention, we can have an alternative Pandas solution: ```python df.groupby(["a", "b"]).apply(lambda df:df.sort_values(["c", "d"], ascending=[False, False]).head(1)) ``` When testing on the 1 million dataset, the original logic takes `1.43 sec` while this new logic takes `2.2 sec`. This is probably one of the reasons the user chose the sort & dedup approach. On a small local dataset, a global sort seems to be faster. In this section, we are going to compare groupby-apply with sort-dedup on all datasets. In addition, this fits nicely with [Pandas UDF](https://databricks.com/blog/2017/10/30/introducing-vectorized-udfs-for-pyspark.html) scenarios, so we will also compare with the Pandas UDF approach. To avoid duplication, we extract the lambda function: ```python def largest(df:pd.DataFrame) -> pd.DataFrame: return df.sort_values(["c","d"], ascending=[False, False]).head(1) ``` Unfortunately, the first issue we encounter is that Spark Pandas can't take this function ```python g1.groupby(["a", "b"]).apply(largest) # g1 is a pandas dataframe, it works df1.groupby(["a", "b"]).applyInPandas(largest, schema="a string,b long,c string,d long") # Pandas UDF works pdf1.groupby(["a", "b"]).apply(largest) # pdf1 is a spark pandas dataframe, it doesn't work ``` So for Spark Pandas we will need to use: ```python pdf1.groupby(["a", "b"]).apply(lambda df: largest(df)) ``` This breaks the claim that with an import change everything works out of the box. Now let's see the performance chart: ![Sort Dedup vs Group Apply vs Pandas UDF](../../images/pandas_like_3.png) * For Pandas, when data size increases, groupby-apply has more performance advantage over sort-dedup * For Spark Pandas, groupby-apply is even slower than Pandas * Pandas UDF is the fastest Spark solution for this problem ### Summary of Comparisons With the 3 comparisons we find out: * The convenience is at the cost of performance * Simply switching backend doesn't always work (not 100% consistent) * Simply switching backend can cause unexpected performance issues * Big data problems require different ways of thinking, users must learn and change their mindset ## Example Issues of PySpark Pandas (Koalas) The promise of PySpark Pandas (Koalas) is that you only need to change [the import line of code](https://databricks.com/blog/2021/10/04/pandas-api-on-upcoming-apache-spark-3-2.html) to bring your code from Pandas to Spark. This promise is, of course, too good to be true. In this section we will show some common operations that don't behave as expected. Some of these might be fixable, but some of them are also inherent to the differences of Pandas and Spark. From here on, we'll use the word Koalas to refer to PySpark Pandas to easily distinguish it from Pandas. ### Setup First, we set-up Koalas and Pandas DataFrames. They will take the same input and we can check the `head()` of the Koalas DataFrame. ``` import pandas as pd import pyspark.pandas as ps df = pd.DataFrame({"a": [None, None, 1, 1, 2, 2], "b": [1, 2, 3, 4, 5, 6]}) kdf = ps.DataFrame({"a": [None, None, 1, 1, 2, 2], "b": [1, 2, 3, 4, 5, 6]}) kdf.head() ``` ### Operation 1 - Reset Index The first operation we'll look at is resetting an index. Note that Spark does not have any such concept. In order to provide a consistent experience to Pandas, the Koalas DataFrame is a Spark DataFrame that has an index added to it. Because it isn't a Spark DataFrame, you need to convert it to a Spark DataFrame to take advantage of Spark code. So let's look at a simple operation, `groupby-max`. First, we do it with Pandas. Note `NULL` values drop by default in Pandas while they are kept in Spark. This is expected. ``` df.groupby("a").max("b") ``` For some reason though, the same syntax does not work in Koalas. This is a minor issue, but shows that the APIs will not always match. ``` import traceback try: kdf.groupby("a").max("b") except: traceback.print_exc() ``` So we tweak the syntax a bit and it works. This operation is consistent with Pandas. ``` kdf.groupby("a").max() ``` In Pandas, it is very common operation to `reset_index()`. So we add it to the Koalas expression. ``` kdf.groupby("a").max().reset_index() ``` Spark has a lot of warning messages. This one though can not be easily ignored. It says we did not define a partitioning scheme, so all of the data is being collected to a single machine and then the index is added. This is very expensive and likely to crash for big data. It also defeats the purpose of using a Spark backend. The default `reset_index()` behavior is actually very harmful, and likely to hurt performance compared to if you just used Pandas. This is because there is an overhead to move data round in order to add the index. Pandas relies on the index a lot, while Spark has no concept of index. Thus, a design decision has to be made whether or not to be consistent with Pandas or Spark. Koalas chooses to be consistent with Pandas. We'll look at one more example with the index. Operation 2 - iloc All of the data in Pandas lives in a single machine. Because of this, indexing it is trivial. What is the index? It is a global sort of the data. When we do `reset_index()`, we number the data from starting from 0 to the last record. Once we do this, we can use the `iloc` operation, or look up by index and we are guaranteed order. A simple Pandas example is below. Everything is as expected. ``` df = pd.DataFrame({"a": [None, None, 1, 1, 2, 2], "b": [1, 2, 3, 4, 5, 6]}) res = [] for i in range(10): res.append(df) t = pd.concat(res, axis=0) t = t.groupby("b").min().reset_index() t.iloc[0:5] ``` Notice how doing `iloc` in Pandas gives the values for `b` from 1 to 5 in order. Let's compare this operation in Koalas. For the Koalas version of this operation, you may get consistent records if you run this locally. But when run distributedly on a cluster, you will see inconsistent behavior. Below is a screen shot of a run on Databricks. ![Databricks Koalas](../../images/databricks_koalas_iloc.png) The `iloc` values give us a different order of records. This is because order is not guaranteed in Spark, and it's expensive to keep a global location index across multiple machines. This can cause inaccurate results even if code successfully runs. ## Joining For joining, Pandas joins `NULL` with `NULL` while Spark does not. Let's see who Koalas is consistent with. Recall for `groupby` it was consistent with Pandas. ``` df2 = pd.DataFrame({"a": [None, 1, 2], "c": [1, 2, 3]}) df.merge(df2, on="a") ``` We run the same operation on Koalas below. ``` kdf2 = ps.DataFrame({"a": [None, 1, 2], "c": [1, 2, 3]}) kdf.merge(kdf2, on="a") ``` We can see the `NULL` values are dropped. This means that for join, Koalas is actually closer to the Spark behavior than Pandas. There is a consistency issue. ## Mixed Types in Columns One of the things acceptable in Pandas is having columns that contain different data types. The reason it's hard to execute this behavior in Spark is because Spark operates on different machines, and in order to guaratee consistent behavior across partitions, schema needs to be explicit. Related to this, inferring schema is also a very expensive operation in Spark, and can even be inaccurate if partitions contain different types. In the snippet below, we'll see that Koalas is consistent with Spark in being unable to have mixed type columns. ``` mixed_df = pd.DataFrame({"a": [None, "test", 1], "b": [1, 2, 3]}) try: ps.from_pandas(mixed_df) except: traceback.print_exc() ``` ## Inconsistent Operation Behavior Some of the same API can have slightly different behavior. Take the following `assign()` statement. We create two columns `c` and `c_diff`. ``` df.assign(c=df['a'] * df["b"], c_diff=lambda x: x['c'].diff()) ``` The same operation will actually fail in Koalas. ``` try: kdf.assign(c=df['a'] * df["b"], c_diff=lambda x: x['c'].diff()) except: traceback.print_exc() ``` This fails because the Pandas implementation can create `c_diff` after `c`, but for Koalas, they are created at the same time and `c_diff` can't reference `c`. The error does not make this immediately clear. There are a lot of caveats to watch out for when using Koalas. ## Conclusion We have shown some inconsistencies between Pandas and Koalas. Some of these are because Pandas was inherent not made for distribute compute. Some operations are harder to carry over, or in some cases, they don't make sense like `iloc`. These issues are not fixable because they are ingrained in the Pandas mindset. This is why Fugue deviates away from being another Pandas-like interface. Fugue considers Spark first, and then extends to local development rather than the other way around. Ultimately, changing one line in the import to bring code to Spark is an unrealistic expectation. There are a lot of tradeoffs to consider, and in order to support a Pandas interface, there needs to be tradeoffs in consistency and performance. If Koalas, is neither consistent with Pandas or Spark, how does it help?
github_jupyter
def gen(n): np.random.seed(0) return pd.DataFrame(dict( a=np.random.choice(["aa","abcd","xyzzzz","tttfs"],n), b=np.random.randint(0,100,n), c=np.random.choice(["aa","abcd","xyzzzz","tttfs"],n), d=np.random.randint(0,10000,n), )) df.sort_values(["a", "b", "c", "d"]).drop_duplicates(subset=["a", "b"], keep="last") g1 = gen(1 * 1000 * 1000) df1 = spark.createDataFrame(g1).cache() df1.count() pdf1 = df1.to_pandas_on_spark() g10 = gen(10 * 1000 * 1000) df10 = spark.createDataFrame(g10).cache() df10.count() pdf10 = df10.to_pandas_on_spark() g20 = gen(20 * 1000 * 1000) df20 = spark.createDataFrame(g20).cache() df20.count() pdf20 = df20.to_pandas_on_spark() g30 = gen(30 * 1000 * 1000) df30 = spark.createDataFrame(g30).cache() df30.count() pdf30 = df30.to_pandas_on_spark() df.sort_values(["a", "b", "d"]).drop_duplicates(subset=["a", "b"], keep="last") df.groupby(["a", "b"]).apply(lambda df:df.sort_values(["c", "d"], ascending=[False, False]).head(1)) def largest(df:pd.DataFrame) -> pd.DataFrame: return df.sort_values(["c","d"], ascending=[False, False]).head(1) g1.groupby(["a", "b"]).apply(largest) # g1 is a pandas dataframe, it works df1.groupby(["a", "b"]).applyInPandas(largest, schema="a string,b long,c string,d long") # Pandas UDF works pdf1.groupby(["a", "b"]).apply(largest) # pdf1 is a spark pandas dataframe, it doesn't work pdf1.groupby(["a", "b"]).apply(lambda df: largest(df)) import pandas as pd import pyspark.pandas as ps df = pd.DataFrame({"a": [None, None, 1, 1, 2, 2], "b": [1, 2, 3, 4, 5, 6]}) kdf = ps.DataFrame({"a": [None, None, 1, 1, 2, 2], "b": [1, 2, 3, 4, 5, 6]}) kdf.head() df.groupby("a").max("b") import traceback try: kdf.groupby("a").max("b") except: traceback.print_exc() kdf.groupby("a").max() kdf.groupby("a").max().reset_index() df = pd.DataFrame({"a": [None, None, 1, 1, 2, 2], "b": [1, 2, 3, 4, 5, 6]}) res = [] for i in range(10): res.append(df) t = pd.concat(res, axis=0) t = t.groupby("b").min().reset_index() t.iloc[0:5] df2 = pd.DataFrame({"a": [None, 1, 2], "c": [1, 2, 3]}) df.merge(df2, on="a") kdf2 = ps.DataFrame({"a": [None, 1, 2], "c": [1, 2, 3]}) kdf.merge(kdf2, on="a") mixed_df = pd.DataFrame({"a": [None, "test", 1], "b": [1, 2, 3]}) try: ps.from_pandas(mixed_df) except: traceback.print_exc() df.assign(c=df['a'] * df["b"], c_diff=lambda x: x['c'].diff()) try: kdf.assign(c=df['a'] * df["b"], c_diff=lambda x: x['c'].diff()) except: traceback.print_exc()
0.202325
0.965446
# Amazon SageMaker Multi-Model Endpoints using XGBoost With [Amazon SageMaker multi-model endpoints](https://docs.aws.amazon.com/sagemaker/latest/dg/multi-model-endpoints.html), customers can create an endpoint that seamlessly hosts up to thousands of models. These endpoints are well suited to use cases where any one of a large number of models, which can be served from a common inference container to save inference costs, needs to be invokable on-demand and where it is acceptable for infrequently invoked models to incur some additional latency. For applications which require consistently low inference latency, an endpoint deploying a single model is still the best choice. At a high level, Amazon SageMaker manages the loading and unloading of models for a multi-model endpoint, as they are needed. When an invocation request is made for a particular model, Amazon SageMaker routes the request to an instance assigned to that model, downloads the model artifacts from S3 onto that instance, and initiates loading of the model into the memory of the container. As soon as the loading is complete, Amazon SageMaker performs the requested invocation and returns the result. If the model is already loaded in memory on the selected instance, the downloading and loading steps are skipped and the invocation is performed immediately. To demonstrate how multi-model endpoints are created and used, this notebook provides an example using a set of XGBoost models that each predict housing prices for a single location. This domain is used as a simple example to easily experiment with multi-model endpoints. The Amazon SageMaker multi-model endpoint capability is designed to work across with Mxnet, PyTorch and Scikit-Learn machine learning frameworks (TensorFlow coming soon), SageMaker XGBoost, KNN, and Linear Learner algorithms. In addition, Amazon SageMaker multi-model endpoints are also designed to work with cases where you bring your own container that integrates with the multi-model server library. An example of this can be found [here](https://github.com/awslabs/amazon-sagemaker-examples/tree/master/advanced_functionality/multi_model_bring_your_own) and documentation [here.](https://docs.aws.amazon.com/sagemaker/latest/dg/build-multi-model-build-container.html) ### Contents 1. [Generate synthetic data for housing models](#Generate-synthetic-data-for-housing-models) 1. [Train multiple house value prediction models](#Train-multiple-house-value-prediction-models) 1. [Create the Amazon SageMaker MultiDataModel entity](#Create-the-Amazon-SageMaker-MultiDataModel-entity) 1. [Create the Multi-Model Endpoint](#Create-the-multi-model-endpoint) 1. [Deploy the Multi-Model Endpoint](#deploy-the-multi-model-endpoint) 1. [Get Predictions from the endpoint](#Get-predictions-from-the-endpoint) 1. [Additional Information](#Additional-information) 1. [Clean up](#Clean-up) # Generate synthetic data The code below contains helper functions to generate synthetic data in the form of a `1x7` numpy array representing the features of a house. The first entry in the array is the randomly generated price of a house. The remaining entries are the features (i.e. number of bedroom, square feet, number of bathrooms, etc.). These functions will be used to generate synthetic data for training, validation, and testing. It will also allow us to submit synthetic payloads for inference to test our multi-model endpoint. ``` import numpy as np import pandas as pd import time NUM_HOUSES_PER_LOCATION = 1000 LOCATIONS = ['NewYork_NY', 'LosAngeles_CA', 'Chicago_IL', 'Houston_TX', 'Dallas_TX', 'Phoenix_AZ', 'Philadelphia_PA', 'SanAntonio_TX', 'SanDiego_CA', 'SanFrancisco_CA'] PARALLEL_TRAINING_JOBS = 4 # len(LOCATIONS) if your account limits can handle it MAX_YEAR = 2019 def gen_price(house): _base_price = int(house['SQUARE_FEET'] * 150) _price = int(_base_price + (10000 * house['NUM_BEDROOMS']) + \ (15000 * house['NUM_BATHROOMS']) + \ (15000 * house['LOT_ACRES']) + \ (15000 * house['GARAGE_SPACES']) - \ (5000 * (MAX_YEAR - house['YEAR_BUILT']))) return _price def gen_random_house(): _house = {'SQUARE_FEET': int(np.random.normal(3000, 750)), 'NUM_BEDROOMS': np.random.randint(2, 7), 'NUM_BATHROOMS': np.random.randint(2, 7) / 2, 'LOT_ACRES': round(np.random.normal(1.0, 0.25), 2), 'GARAGE_SPACES': np.random.randint(0, 4), 'YEAR_BUILT': min(MAX_YEAR, int(np.random.normal(1995, 10)))} _price = gen_price(_house) return [_price, _house['YEAR_BUILT'], _house['SQUARE_FEET'], _house['NUM_BEDROOMS'], _house['NUM_BATHROOMS'], _house['LOT_ACRES'], _house['GARAGE_SPACES']] def gen_houses(num_houses): _house_list = [] for i in range(num_houses): _house_list.append(gen_random_house()) _df = pd.DataFrame(_house_list, columns=['PRICE', 'YEAR_BUILT', 'SQUARE_FEET', 'NUM_BEDROOMS', 'NUM_BATHROOMS','LOT_ACRES', 'GARAGE_SPACES']) return _df ``` # Train multiple house value prediction models In the follow section, we are setting up the code to train a house price prediction model for each of 4 different cities. As such, we will launch multiple training jobs asynchronously, using the XGBoost algorithm. In this notebook, we will be using the AWS Managed XGBoost Image for both training and inference - this image provides native support for launching multi-model endpoints. ``` import sagemaker from sagemaker import get_execution_role from sagemaker.amazon.amazon_estimator import get_image_uri import boto3 from sklearn.model_selection import train_test_split s3 = boto3.resource('s3') sagemaker_session = sagemaker.Session() role = get_execution_role() BUCKET = sagemaker_session.default_bucket() # This is references the AWS managed XGBoost container XGBOOST_IMAGE = get_image_uri(boto3.Session().region_name, 'xgboost', repo_version='1.0-1') DATA_PREFIX = 'XGBOOST_BOSTON_HOUSING' MULTI_MODEL_ARTIFACTS = 'multi_model_artifacts' TRAIN_INSTANCE_TYPE = 'ml.m4.xlarge' ENDPOINT_INSTANCE_TYPE = 'ml.m4.xlarge' ENDPOINT_NAME = 'mme-xgboost-housing' MODEL_NAME = ENDPOINT_NAME ``` ### Split a given dataset into train, validation, and test The code below will generate 3 sets of data. 1 set to train, 1 set for validation and 1 for testing. ``` SEED = 7 SPLIT_RATIOS = [0.6, 0.3, 0.1] def split_data(df): # split data into train and test sets seed = SEED val_size = SPLIT_RATIOS[1] test_size = SPLIT_RATIOS[2] num_samples = df.shape[0] X1 = df.values[:num_samples, 1:] # keep only the features, skip the target, all rows Y1 = df.values[:num_samples, :1] # keep only the target, all rows # Use split ratios to divide up into train/val/test X_train, X_val, y_train, y_val = \ train_test_split(X1, Y1, test_size=(test_size + val_size), random_state=seed) # Of the remaining non-training samples, give proper ratio to validation and to test X_test, X_test, y_test, y_test = \ train_test_split(X_val, y_val, test_size=(test_size / (test_size + val_size)), random_state=seed) # reassemble the datasets with target in first column and features after that _train = np.concatenate([y_train, X_train], axis=1) _val = np.concatenate([y_val, X_val], axis=1) _test = np.concatenate([y_test, X_test], axis=1) return _train, _val, _test ``` ### Launch a single training job for a given housing location There is nothing specific to multi-model endpoints in terms of the models it will host. They are trained in the same way as all other SageMaker models. Here we are using the XGBoost estimator and not waiting for the job to complete. ``` def launch_training_job(location): # clear out old versions of the data s3_bucket = s3.Bucket(BUCKET) full_input_prefix = f'{DATA_PREFIX}/model_prep/{location}' s3_bucket.objects.filter(Prefix=full_input_prefix + '/').delete() # upload the entire set of data for all three channels local_folder = f'data/{location}' inputs = sagemaker_session.upload_data(path=local_folder, key_prefix=full_input_prefix) print(f'Training data uploaded: {inputs}') _job = 'xgb-{}'.format(location.replace('_', '-')) full_output_prefix = f'{DATA_PREFIX}/model_artifacts/{location}' s3_output_path = f's3://{BUCKET}/{full_output_prefix}' xgb = sagemaker.estimator.Estimator(XGBOOST_IMAGE, role, train_instance_count=1, train_instance_type=TRAIN_INSTANCE_TYPE, output_path=s3_output_path, base_job_name=_job, sagemaker_session=sagemaker_session) xgb.set_hyperparameters(max_depth=5, eta=0.2, gamma=4, min_child_weight=6, subsample=0.8, silent=0, early_stopping_rounds=5, objective='reg:linear', num_round=25) DISTRIBUTION_MODE = 'FullyReplicated' train_input = sagemaker.s3_input(s3_data=inputs+'/train', distribution=DISTRIBUTION_MODE, content_type='csv') val_input = sagemaker.s3_input(s3_data=inputs+'/val', distribution=DISTRIBUTION_MODE, content_type='csv') remote_inputs = {'train': train_input, 'validation': val_input} xgb.fit(remote_inputs, wait=False) # Return the estimator object return xgb ``` ### Kick off a model training job for each housing location ``` def save_data_locally(location, train, val, test): os.makedirs(f'data/{location}/train') np.savetxt( f'data/{location}/train/{location}_train.csv', train, delimiter=',', fmt='%.2f') os.makedirs(f'data/{location}/val') np.savetxt(f'data/{location}/val/{location}_val.csv', val, delimiter=',', fmt='%.2f') os.makedirs(f'data/{location}/test') np.savetxt(f'data/{location}/test/{location}_test.csv', test, delimiter=',', fmt='%.2f') import shutil import os estimators = [] shutil.rmtree('data', ignore_errors=True) for loc in LOCATIONS[:PARALLEL_TRAINING_JOBS]: _houses = gen_houses(NUM_HOUSES_PER_LOCATION) _train, _val, _test = split_data(_houses) save_data_locally(loc, _train, _val, _test) estimator = launch_training_job(loc) estimators.append(estimator) print() print(f'{len(estimators)} training jobs launched: {[x.latest_training_job.job_name for x in estimators]}') ``` ### Wait for all model training to finish ``` def wait_for_training_job_to_complete(estimator): job = estimator.latest_training_job.job_name print(f'Waiting for job: {job}') status = estimator.latest_training_job.describe()['TrainingJobStatus'] while status == 'InProgress': time.sleep(45) status = estimator.latest_training_job.describe()['TrainingJobStatus'] if status == 'InProgress': print(f'{job} job status: {status}') print(f'DONE. Status for {job} is {status}\n') for est in estimators: wait_for_training_job_to_complete(est) ``` # Create the multi-model endpoint with the SageMaker SDK ### Create a SageMaker Model from one of the Estimators ``` estimator = estimators[0] model = estimator.create_model(role=role, image=XGBOOST_IMAGE) ``` ### Create the Amazon SageMaker MultiDataModel entity We create the multi-model endpoint using the [```MultiDataModel```](https://sagemaker.readthedocs.io/en/stable/api/inference/multi_data_model.html) class. You can create a MultiDataModel by directly passing in a `sagemaker.model.Model` object - in which case, the Endpoint will inherit information about the image to use, as well as any environmental variables, network isolation, etc., once the MultiDataModel is deployed. In addition, a MultiDataModel can also be created without explictly passing a `sagemaker.model.Model` object. Please refer to the documentation for additional details. ``` from sagemaker.multidatamodel import MultiDataModel # This is where our MME will read models from on S3. model_data_prefix = f's3://{BUCKET}/{DATA_PREFIX}/{MULTI_MODEL_ARTIFACTS}/' mme = MultiDataModel(name=MODEL_NAME, model_data_prefix=model_data_prefix, model=model,# passing our model - passes container image needed for the endpoint sagemaker_session=sagemaker_session) ``` # Deploy the Multi Model Endpoint You need to consider the appropriate instance type and number of instances for the projected prediction workload across all the models you plan to host behind your multi-model endpoint. The number and size of the individual models will also drive memory requirements. ``` predictor = mme.deploy(initial_instance_count=1, instance_type=ENDPOINT_INSTANCE_TYPE, endpoint_name=ENDPOINT_NAME) ``` ### Our endpoint has launched! Let's look at what models are available to the endpoint! By 'available', what we mean is, what model artfiacts are currently stored under the S3 prefix we defined when setting up the `MultiDataModel` above i.e. `model_data_prefix`. Currently, since we have no artifacts (i.e. `tar.gz` files) stored under our defined S3 prefix, our endpoint, will have no models 'available' to serve inference requests. We will demonstrate how to make models 'available' to our endpoint below. ``` # No models visible! list(mme.list_models()) ``` ### Lets deploy model artifacts to be found by the endpoint We are now using the `.add_model()` method of the `MultiDataModel` to copy over our model artifacts from where they were initially stored, during training, to where our endpoint will source model artifacts for inference requests. `model_data_source` refers to the location of our model artifact (i.e. where it was deposited on S3 after training completed) `model_data_path` is the **relative** path to the S3 prefix we specified above (i.e. `model_data_prefix`) where our endpoint will source models for inference requests. Since this is a **relative** path, we can simply pass the name of what we wish to call the model artifact at inference time (i.e. `Chicago_IL.tar.gz`) ### Dynamically deploying additional models It is also important to note, that we can always use the `.add_model()` method, as shown below, to dynamically deploy more models to the endpoint, to serve up inference requests as needed. ``` for est in estimators: artifact_path = est.latest_training_job.describe()['ModelArtifacts']['S3ModelArtifacts'] model_name = artifact_path.split('/')[-4]+'.tar.gz' # This is copying over the model artifact to the S3 location for the MME. mme.add_model(model_data_source=artifact_path, model_data_path=model_name) ``` ## We have added the 4 model artifacts from our training jobs! We can see that the S3 prefix we specified when setting up `MultiDataModel` now has 4 model artifacts. As such, the endpoint can now serve up inference requests for these models. ``` list(mme.list_models()) ``` # Get predictions from the endpoint Recall that ```mme.deploy()``` returns a [RealTimePredictor](https://github.com/aws/sagemaker-python-sdk/blob/master/src/sagemaker/predictor.py#L35) that we saved in a variable called ```predictor```. We will use ```predictor``` to submit requests to the endpoint. XGBoost supports ```text/csv``` for the content type and accept type. For more information on XGBoost Input/Output Interface, please see [here.](https://docs.aws.amazon.com/sagemaker/latest/dg/xgboost.html#InputOutput-XGBoost) Since the default RealTimePredictor does not have a serializer or deserializer set for requests, we will also set these. This will allow us to submit a python list for inference, and get back a float response. ``` from sagemaker.predictor import csv_serializer, json_deserializer from sagemaker.content_types import CONTENT_TYPE_CSV predictor.serializer = csv_serializer predictor.deserializer = json_deserializer predictor.content_type = CONTENT_TYPE_CSV predictor.accept = CONTENT_TYPE_CSV ``` ### Invoking models on a multi-model endpoint Notice the higher latencies on the first invocation of any given model. This is due to the time it takes SageMaker to download the model to the Endpoint instance and then load the model into the inference container. Subsequent invocations of the same model take advantage of the model already being loaded into the inference container. ``` start_time = time.time() predicted_value = predictor.predict(data=gen_random_house()[1:], target_model='Chicago_IL.tar.gz') duration = time.time() - start_time print('${:,.2f}, took {:,d} ms\n'.format(predicted_value, int(duration * 1000))) start_time = time.time() #Invoke endpoint predicted_value = predictor.predict(data=gen_random_house()[1:], target_model='Chicago_IL.tar.gz') duration = time.time() - start_time print('${:,.2f}, took {:,d} ms\n'.format(predicted_value, int(duration * 1000))) start_time = time.time() #Invoke endpoint predicted_value = predictor.predict(data=gen_random_house()[1:], target_model='Houston_TX.tar.gz') duration = time.time() - start_time print('${:,.2f}, took {:,d} ms\n'.format(predicted_value, int(duration * 1000))) start_time = time.time() #Invoke endpoint predicted_value = predictor.predict(data=gen_random_house()[1:], target_model='Houston_TX.tar.gz') duration = time.time() - start_time print('${:,.2f}, took {:,d} ms\n'.format(predicted_value, int(duration * 1000))) ``` ### Updating a model To update a model, you would follow the same approach as above and add it as a new model. For example, if you have retrained the `NewYork_NY.tar.gz` model and wanted to start invoking it, you would upload the updated model artifacts behind the S3 prefix with a new name such as `NewYork_NY_v2.tar.gz`, and then change the `target_model` field to invoke `NewYork_NY_v2.tar.gz` instead of `NewYork_NY.tar.gz`. You do not want to overwrite the model artifacts in Amazon S3, because the old version of the model might still be loaded in the containers or on the storage volume of the instances on the endpoint. Invocations to the new model could then invoke the old version of the model. Alternatively, you could stop the endpoint and re-deploy a fresh set of models. ## Using Boto APIs to invoke the endpoint While developing interactively within a Jupyter notebook, since `.deploy()` returns a `RealTimePredictor` it is a more seamless experience to start invoking your endpoint using the SageMaker SDK. You have more fine grained control over the serialization and deserialization protocols to shape your request and response payloads to/from the endpoint. This is great for iterative experimentation within a notebook. Furthermore, should you have an application that has access to the SageMaker SDK, you can always import `RealTimePredictor` and attach it to an existing endpoint - this allows you to stick to using the high level SDK if preferable. Additional documentation on `RealTimePredictor` can be found [here.](https://sagemaker.readthedocs.io/en/stable/api/inference/predictors.html?highlight=RealTimePredictor#sagemaker.predictor.RealTimePredictor) The lower level Boto3 SDK may be preferable if you are attempting to invoke the endpoint as a part of a broader architecture. Imagine an API gateway frontend that uses a Lambda Proxy in order to transform request payloads before hitting a SageMaker Endpoint - in this example, Lambda does not have access to the SageMaker Python SDK, and as such, Boto3 can still allow you to interact with your endpoint and serve inference requests. Boto3 allows for quick injection of ML intelligence via SageMaker Endpoints into existing applications with minimal/no refactoring to existing code. Boto3 will submit your requests as a binary payload, while still allowing you to supply your desired `Content-Type` and `Accept` headers with serialization being handled by the inference container in the SageMaker Endpoint. Additional documentation on `.invoke_endpoint()` can be found [here.](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker-runtime.html) ``` import boto3 import json runtime_sm_client = boto3.client(service_name='sagemaker-runtime') def predict_one_house_value(features, model_name): print(f'Using model {model_name} to predict price of this house: {features}') # Notice how we alter the list into a string as the payload body = ','.join(map(str, features)) + '\n' start_time = time.time() response = runtime_sm_client.invoke_endpoint( EndpointName=ENDPOINT_NAME, ContentType='text/csv', TargetModel=model_name, Body=body) predicted_value = json.loads(response['Body'].read())[0] duration = time.time() - start_time print('${:,.2f}, took {:,d} ms\n'.format(predicted_value, int(duration * 1000))) predict_one_house_value(gen_random_house()[1:], 'Chicago_IL.tar.gz') ``` ## Clean up Here, to be sure we are not billed for endpoints we are no longer using, we clean up. ``` predictor.delete_endpoint() predictor.delete_model() ```
github_jupyter
import numpy as np import pandas as pd import time NUM_HOUSES_PER_LOCATION = 1000 LOCATIONS = ['NewYork_NY', 'LosAngeles_CA', 'Chicago_IL', 'Houston_TX', 'Dallas_TX', 'Phoenix_AZ', 'Philadelphia_PA', 'SanAntonio_TX', 'SanDiego_CA', 'SanFrancisco_CA'] PARALLEL_TRAINING_JOBS = 4 # len(LOCATIONS) if your account limits can handle it MAX_YEAR = 2019 def gen_price(house): _base_price = int(house['SQUARE_FEET'] * 150) _price = int(_base_price + (10000 * house['NUM_BEDROOMS']) + \ (15000 * house['NUM_BATHROOMS']) + \ (15000 * house['LOT_ACRES']) + \ (15000 * house['GARAGE_SPACES']) - \ (5000 * (MAX_YEAR - house['YEAR_BUILT']))) return _price def gen_random_house(): _house = {'SQUARE_FEET': int(np.random.normal(3000, 750)), 'NUM_BEDROOMS': np.random.randint(2, 7), 'NUM_BATHROOMS': np.random.randint(2, 7) / 2, 'LOT_ACRES': round(np.random.normal(1.0, 0.25), 2), 'GARAGE_SPACES': np.random.randint(0, 4), 'YEAR_BUILT': min(MAX_YEAR, int(np.random.normal(1995, 10)))} _price = gen_price(_house) return [_price, _house['YEAR_BUILT'], _house['SQUARE_FEET'], _house['NUM_BEDROOMS'], _house['NUM_BATHROOMS'], _house['LOT_ACRES'], _house['GARAGE_SPACES']] def gen_houses(num_houses): _house_list = [] for i in range(num_houses): _house_list.append(gen_random_house()) _df = pd.DataFrame(_house_list, columns=['PRICE', 'YEAR_BUILT', 'SQUARE_FEET', 'NUM_BEDROOMS', 'NUM_BATHROOMS','LOT_ACRES', 'GARAGE_SPACES']) return _df import sagemaker from sagemaker import get_execution_role from sagemaker.amazon.amazon_estimator import get_image_uri import boto3 from sklearn.model_selection import train_test_split s3 = boto3.resource('s3') sagemaker_session = sagemaker.Session() role = get_execution_role() BUCKET = sagemaker_session.default_bucket() # This is references the AWS managed XGBoost container XGBOOST_IMAGE = get_image_uri(boto3.Session().region_name, 'xgboost', repo_version='1.0-1') DATA_PREFIX = 'XGBOOST_BOSTON_HOUSING' MULTI_MODEL_ARTIFACTS = 'multi_model_artifacts' TRAIN_INSTANCE_TYPE = 'ml.m4.xlarge' ENDPOINT_INSTANCE_TYPE = 'ml.m4.xlarge' ENDPOINT_NAME = 'mme-xgboost-housing' MODEL_NAME = ENDPOINT_NAME SEED = 7 SPLIT_RATIOS = [0.6, 0.3, 0.1] def split_data(df): # split data into train and test sets seed = SEED val_size = SPLIT_RATIOS[1] test_size = SPLIT_RATIOS[2] num_samples = df.shape[0] X1 = df.values[:num_samples, 1:] # keep only the features, skip the target, all rows Y1 = df.values[:num_samples, :1] # keep only the target, all rows # Use split ratios to divide up into train/val/test X_train, X_val, y_train, y_val = \ train_test_split(X1, Y1, test_size=(test_size + val_size), random_state=seed) # Of the remaining non-training samples, give proper ratio to validation and to test X_test, X_test, y_test, y_test = \ train_test_split(X_val, y_val, test_size=(test_size / (test_size + val_size)), random_state=seed) # reassemble the datasets with target in first column and features after that _train = np.concatenate([y_train, X_train], axis=1) _val = np.concatenate([y_val, X_val], axis=1) _test = np.concatenate([y_test, X_test], axis=1) return _train, _val, _test def launch_training_job(location): # clear out old versions of the data s3_bucket = s3.Bucket(BUCKET) full_input_prefix = f'{DATA_PREFIX}/model_prep/{location}' s3_bucket.objects.filter(Prefix=full_input_prefix + '/').delete() # upload the entire set of data for all three channels local_folder = f'data/{location}' inputs = sagemaker_session.upload_data(path=local_folder, key_prefix=full_input_prefix) print(f'Training data uploaded: {inputs}') _job = 'xgb-{}'.format(location.replace('_', '-')) full_output_prefix = f'{DATA_PREFIX}/model_artifacts/{location}' s3_output_path = f's3://{BUCKET}/{full_output_prefix}' xgb = sagemaker.estimator.Estimator(XGBOOST_IMAGE, role, train_instance_count=1, train_instance_type=TRAIN_INSTANCE_TYPE, output_path=s3_output_path, base_job_name=_job, sagemaker_session=sagemaker_session) xgb.set_hyperparameters(max_depth=5, eta=0.2, gamma=4, min_child_weight=6, subsample=0.8, silent=0, early_stopping_rounds=5, objective='reg:linear', num_round=25) DISTRIBUTION_MODE = 'FullyReplicated' train_input = sagemaker.s3_input(s3_data=inputs+'/train', distribution=DISTRIBUTION_MODE, content_type='csv') val_input = sagemaker.s3_input(s3_data=inputs+'/val', distribution=DISTRIBUTION_MODE, content_type='csv') remote_inputs = {'train': train_input, 'validation': val_input} xgb.fit(remote_inputs, wait=False) # Return the estimator object return xgb def save_data_locally(location, train, val, test): os.makedirs(f'data/{location}/train') np.savetxt( f'data/{location}/train/{location}_train.csv', train, delimiter=',', fmt='%.2f') os.makedirs(f'data/{location}/val') np.savetxt(f'data/{location}/val/{location}_val.csv', val, delimiter=',', fmt='%.2f') os.makedirs(f'data/{location}/test') np.savetxt(f'data/{location}/test/{location}_test.csv', test, delimiter=',', fmt='%.2f') import shutil import os estimators = [] shutil.rmtree('data', ignore_errors=True) for loc in LOCATIONS[:PARALLEL_TRAINING_JOBS]: _houses = gen_houses(NUM_HOUSES_PER_LOCATION) _train, _val, _test = split_data(_houses) save_data_locally(loc, _train, _val, _test) estimator = launch_training_job(loc) estimators.append(estimator) print() print(f'{len(estimators)} training jobs launched: {[x.latest_training_job.job_name for x in estimators]}') def wait_for_training_job_to_complete(estimator): job = estimator.latest_training_job.job_name print(f'Waiting for job: {job}') status = estimator.latest_training_job.describe()['TrainingJobStatus'] while status == 'InProgress': time.sleep(45) status = estimator.latest_training_job.describe()['TrainingJobStatus'] if status == 'InProgress': print(f'{job} job status: {status}') print(f'DONE. Status for {job} is {status}\n') for est in estimators: wait_for_training_job_to_complete(est) estimator = estimators[0] model = estimator.create_model(role=role, image=XGBOOST_IMAGE) from sagemaker.multidatamodel import MultiDataModel # This is where our MME will read models from on S3. model_data_prefix = f's3://{BUCKET}/{DATA_PREFIX}/{MULTI_MODEL_ARTIFACTS}/' mme = MultiDataModel(name=MODEL_NAME, model_data_prefix=model_data_prefix, model=model,# passing our model - passes container image needed for the endpoint sagemaker_session=sagemaker_session) predictor = mme.deploy(initial_instance_count=1, instance_type=ENDPOINT_INSTANCE_TYPE, endpoint_name=ENDPOINT_NAME) # No models visible! list(mme.list_models()) for est in estimators: artifact_path = est.latest_training_job.describe()['ModelArtifacts']['S3ModelArtifacts'] model_name = artifact_path.split('/')[-4]+'.tar.gz' # This is copying over the model artifact to the S3 location for the MME. mme.add_model(model_data_source=artifact_path, model_data_path=model_name) list(mme.list_models()) from sagemaker.predictor import csv_serializer, json_deserializer from sagemaker.content_types import CONTENT_TYPE_CSV predictor.serializer = csv_serializer predictor.deserializer = json_deserializer predictor.content_type = CONTENT_TYPE_CSV predictor.accept = CONTENT_TYPE_CSV start_time = time.time() predicted_value = predictor.predict(data=gen_random_house()[1:], target_model='Chicago_IL.tar.gz') duration = time.time() - start_time print('${:,.2f}, took {:,d} ms\n'.format(predicted_value, int(duration * 1000))) start_time = time.time() #Invoke endpoint predicted_value = predictor.predict(data=gen_random_house()[1:], target_model='Chicago_IL.tar.gz') duration = time.time() - start_time print('${:,.2f}, took {:,d} ms\n'.format(predicted_value, int(duration * 1000))) start_time = time.time() #Invoke endpoint predicted_value = predictor.predict(data=gen_random_house()[1:], target_model='Houston_TX.tar.gz') duration = time.time() - start_time print('${:,.2f}, took {:,d} ms\n'.format(predicted_value, int(duration * 1000))) start_time = time.time() #Invoke endpoint predicted_value = predictor.predict(data=gen_random_house()[1:], target_model='Houston_TX.tar.gz') duration = time.time() - start_time print('${:,.2f}, took {:,d} ms\n'.format(predicted_value, int(duration * 1000))) import boto3 import json runtime_sm_client = boto3.client(service_name='sagemaker-runtime') def predict_one_house_value(features, model_name): print(f'Using model {model_name} to predict price of this house: {features}') # Notice how we alter the list into a string as the payload body = ','.join(map(str, features)) + '\n' start_time = time.time() response = runtime_sm_client.invoke_endpoint( EndpointName=ENDPOINT_NAME, ContentType='text/csv', TargetModel=model_name, Body=body) predicted_value = json.loads(response['Body'].read())[0] duration = time.time() - start_time print('${:,.2f}, took {:,d} ms\n'.format(predicted_value, int(duration * 1000))) predict_one_house_value(gen_random_house()[1:], 'Chicago_IL.tar.gz') predictor.delete_endpoint() predictor.delete_model()
0.42477
0.956063
# Train a gesture recognition model for microcontroller use This notebook demonstrates how to train a 20kb gesture recognition model for [TensorFlow Lite for Microcontrollers](https://tensorflow.org/lite/microcontrollers/overview). It will produce the same model used in the [magic_wand](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/lite/experimental/micro/examples/magic_wand) example application. The model is designed to be used with [Google Colaboratory](https://colab.research.google.com). <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://colab.research.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/lite/experimental/micro/examples/magic_wand/train/train_magic_wand_model.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/experimental/micro/examples/magic_wand/train/train_magic_wand_model.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a> </td> </table> Training is much faster using GPU acceleration. Before you proceed, ensure you are using a GPU runtime by going to **Runtime -> Change runtime type** and selecting **GPU**. Training will take around 5 minutes on a GPU runtime. ## Configure dependencies Run the following cell to ensure the correct version of TensorFlow is used. ``` %tensorflow_version 2.x ``` We'll also clone the TensorFlow repository, which contains the training scripts, and copy them into our workspace. ``` # Clone the repository from GitHub !git clone --depth 1 -q https://github.com/tensorflow/tensorflow # Copy the training scripts into our workspace !cp -r tensorflow/tensorflow/lite/experimental/micro/examples/magic_wand/train train ``` ## Prepare the data Next, we'll download the data and extract it into the expected location within the training scripts' directory. ``` # Download the data we will use to train the model !wget http://download.tensorflow.org/models/tflite/magic_wand/data.tar.gz # Extract the data into the train directory !tar xvzf data.tar.gz -C train 1>/dev/null ``` We'll then run the scripts that split the data into training, validation, and test sets. ``` # The scripts must be run from within the train directory %cd train # Prepare the data !python data_prepare.py # Split the data by person !python data_split_person.py ``` ## Load TensorBoard Now, we set up TensorBoard so that we can graph our accuracy and loss as training proceeds. ``` # Load TensorBoard %load_ext tensorboard %tensorboard --logdir logs/scalars ``` ## Begin training The following cell will begin the training process. Training will take around 5 minutes on a GPU runtime. You'll see the metrics in TensorBoard after a few epochs. ``` !python train.py --model CNN --person true ``` ## Create a C source file The `train.py` script writes a quantized model, `model_quantized.tflite`, to the training scripts' directory. In the following cell, we convert this model into a C++ source file we can use with TensorFlow Lite for Microcontrollers. ``` # Install xxd if it is not available !apt-get -qq install xxd # Save the file as a C source file !xxd -i model_quantized.tflite > /content/model_quantized.cc # Print the source file !cat /content/model_quantized.cc ```
github_jupyter
%tensorflow_version 2.x # Clone the repository from GitHub !git clone --depth 1 -q https://github.com/tensorflow/tensorflow # Copy the training scripts into our workspace !cp -r tensorflow/tensorflow/lite/experimental/micro/examples/magic_wand/train train # Download the data we will use to train the model !wget http://download.tensorflow.org/models/tflite/magic_wand/data.tar.gz # Extract the data into the train directory !tar xvzf data.tar.gz -C train 1>/dev/null # The scripts must be run from within the train directory %cd train # Prepare the data !python data_prepare.py # Split the data by person !python data_split_person.py # Load TensorBoard %load_ext tensorboard %tensorboard --logdir logs/scalars !python train.py --model CNN --person true # Install xxd if it is not available !apt-get -qq install xxd # Save the file as a C source file !xxd -i model_quantized.tflite > /content/model_quantized.cc # Print the source file !cat /content/model_quantized.cc
0.657098
0.987508
# Project summary In this project, I used machine learning to predicting the operating conditions of a waterpoint using data from the Tanzanian Ministry of Water. The algorithm used was Random Forest for multiclassification between three outcomes: "Functional", "Functional needs repair", and "Nonfunctional". # Data import and cleaning ## Importing libraries and seperating DataFrames ``` #Importing external libraries import math import numpy as np import pandas as pd import re import matplotlib.pyplot as plt import seaborn as sns from collections import OrderedDict from scipy.stats import chi2_contingency from scipy.stats import chi2 import statsmodels.api as sm from statsmodels.formula.api import ols from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import GridSearchCV, RandomizedSearchCV, KFold import xgboost as xgb #Importing classes and functions from external files: from model_classes import ModelSwitcher, DataPreprocessor from cleaning_functions import * from feature_engineering import * from visualization_functions import * #Configuring options %matplotlib inline pd.set_option('display.max_columns', 50) df_outcomes = pd.read_csv("DATASETS/0bf8bc6e-30d0-4c50-956a-603fc693d966.csv") test_set = pd.read_csv("DATASETS/702ddfc5-68cd-4d1d-a0de-f5f566f76d91.csv") df = pd.read_csv("DATASETS/4910797b-ee55-40a7-8668-10efd5c1b960.csv") target_col = "status_group" ``` Merging the test set with the set for evaluation before data cleaning optimizes the process by being able to see the a greater scope of possible values from the start. ``` df_c = pd.concat([df,test_set], axis=0).copy() ``` Created a seperate dataframe for EDA which combines the training set and their respective values. ``` df_j = pd.merge(df, df_outcomes, how="left", on="id") ``` ## Dealing with missing data I stored parameters for the imputer functions to process all all of the missing data within OrderedDicts which will be fitted/transformed in bulk through the use of loops. The functtions also create a dummy variable for missing continuous values to preserve as much information as possible. Some of the data is explored in a state before it was cleaned in the EDA section. ``` impute_dict = OrderedDict([("construction_year",[0, "median", None]), ("population",[0, "median", None]), ("amount_tsh",[0, "constant", .01]), ("subvillage",[np.nan, "constant", "Unknown"]), ("public_meeting",[np.nan, "most_frequent", None]), ("scheme_name",[np.nan, "constant", "Unknown"]), ("permit",[np.nan, "most_frequent", None]), ]) impute_cat_dict = {"funder":["0", "Unknown"], "installer":["0", "Unknown"], "scheme_management":["None", "Unknown"], } imputes = get_imputer_objs(df_j, impute_dict) df_c = impute_vals(df_c, impute_dict, imputes) df_j = impute_vals(df_j, impute_dict, imputes) df_c=impute_mult_categorical(df_c, impute_cat_dict) df_j=impute_mult_categorical(df_j, impute_cat_dict) df_c = main_data_cleaning(df_c) df_j = main_data_cleaning(df_j) ``` # EDA ### Evaluating total static head "Amount TSH" is a provided feature that measures the "Total Static Head" of a well. Its exact units were not provided but is based on the height of water reserves. The actual measurements vary widely between rows with a range from 0 to hundreds of thousands. The datapoints were heavily skewed to the right, so taking their log was valuable for subsequent visualizations. ``` f, ax = plt.subplots(figsize=(14, 11)) non_zero_tsh = df_j[df_j["amount_tsh"]!= 0]["amount_tsh"] logged_tsh = non_zero_tsh.map(lambda x: math.log(x)) sns.distplot(logged_tsh) ``` After zero, the smallest measured value of total standing head is .2. For the purpose of not breaking the log transformation and maintaining the negative scale, I have imputed values that are based off of that minimum but reduced by a factor of 20 to keep maintain that relationship while capturing the fact that it was measured at zero in a dummy variable. ### Evaluating any affect of population size I began by exploring the relationship between the size of the population and the condition of the well. It was another variable with an exponential relationship, so I took its log. ``` df_j["logged_pop"] = df_j["population"].map(lambda x: 0 if x<= 0 else math.log(x, 30)) f, ax = plt.subplots(figsize=(14, 11)) sns.distplot(df_j["logged_pop"]) sns.scatterplot(x="logged_pop", y=target_col, data=df_j) ``` It appears that the population values can be subset into two distinct groups. Half of which are registered with no population, while the other half follow an approximate normal distribute when a heavy log transformation is applied, ``` df_non_zero_pop = df_j[df_j["logged_pop"] != 0] df_non_zero_pop[["logged_pop", target_col]].groupby(target_col).mean() ``` To help gauge whether this would be a useful feature for the model or just noise, I examined the three different outcomes and the means of the logged population values for each. The effect size seemed significant enough but to see if statistically it met the needs of a 95% confidence interval, I tested the values with ANOVA. ``` #ANOVA test comparing the logged population size between the outcomes formula = 'logged_pop ~ C(status_group)' lm = ols(formula, df_non_zero_pop).fit() table = sm.stats.anova_lm(lm, typ=2) print("ANOVA for all outcomes") print(table) ``` A P value that small was likely a result between the difference in population between the whether a well currently worked or not(distinctions between how they weren't working was much less). A non linear relationship prevents it from being useful in any logistic regression, however that is not required for ensemble methods like random foresst. It is interesting to note the relationship. Perhaps there is a small sampling bias that is introduced where larger populations bring non functional wells to attention more or heavier use is affecting the degradation. ``` #Grabs the respective counts of well functionality in the provided data. totals = df_j[["logged_pop", target_col]].groupby(target_col).count()["logged_pop"] #Dataframe only the wells that have zeros input for population. df_zero_pop = df_j[df_j["logged_pop"] == 0] #Returns proportions for missing population data depending on the status of the well. print(totals.index) df_zero_pop[["logged_pop", target_col]].groupby(target_col).count()["logged_pop"]/totals.values ``` The proportions of zeros in population data vary among the different outcomes in the sample. In order to preserve that information, when imputing median, I created a dummy variable that indicates a zero value while preserving the rest of the continuous entries. While the histogram indicates that there remains a disproportionatly large block of nonzero population sizes at very small values, doing the same process to would likely destroy information for the model. ### TSH VS Years old To better see the relationship that "total static head" has, I plotted it along with the age of the well (Created as a feature in the next section). The information captured in population was added as a scalar, since it can indicate the magnitude of people affected should any watersource not be functional. Using the logged values helps condense the graph to see the relationships. Generally the graph behaves as expected with age being a liability and "total static head" having a somewhat positive effect in predicting functionality. However, there are a nonfunctional few values on the zero "total static head" line that come as a slight surprise. Taking a closer look at the calculation of "years old", they appear to have negative ages. It seems that some wells in this dataset might be unfinished and undergoing active instruction. ``` df_j["logged_tsh"] = df_j["amount_tsh"].map(lambda x: math.log(x)) sns.set_style("darkgrid") sns.set(font_scale=1.5) f, ax = plt.subplots(figsize=(16, 14)) functional_pal = {"functional":"springgreen", "functional needs repair":"orange", "non functional":"red"} sns.scatterplot(x="years_old", y="logged_tsh", hue=target_col, size="logged_pop", sizes=(10, 500), alpha=.2, palette=functional_pal, data = df_j) lgnd = ["Well status:", "Functional", "Non functional", "Needs repair", "Population:", "0", "200", "27k", "4.5M"] ax.legend(lgnd) ax.set_ylabel('Total Standing Head') ax.set_xlabel('Years Old') ticks = list(np.arange(-5,15,2.5)) tick_labels = unlog_plot(ticks, math.e) tick_labels.insert(1, "0") ax.set(yticklabels=tick_labels) plt.show() ``` ### Correlation heatmap There were not a lot of continuous variables provided and it shows. Each of these variables more or less stood on their own with not much correlation between any of them. The biggest relationship was between longitude and latitude, and while they should be independant, there is a possibility for certain combinations to appear more frequently to indicate areas where more people are settled or the fact that a missing value for one means a missing value for the other. ``` cont_features = ["gps_height", "longitude", "latitude", "num_private", "check-period", "years_old", "logged_tsh", "logged_pop"] trimmed_heatmap(df_c, cont_features) ``` # Feature Engineering/Selection The features that I chose to add came from date of the inspection and the year the well was built. The obvious choice was to use the two datapoints to get the age of the well. However I was also surprised at the impact of the time of year the inspection was. To place it on a continuous scale, I took the cosine of the day divided by the amount of days in a year. I chose cosine, because in Tanzania, the summer season is at it's peak in January, so it seemed logical to start at the biggesst values to reflect that. ``` # df_j["month_checked"] = df_j["date_recorded"].map(lambda x: x.month) df_j = add_features(df_j) df_j ``` It is not surprise to see that the average age of the well has an inverse relationship with it's functionality ``` df_j[[target_col, "years_old"]].groupby(target_col).mean() ``` These small but statitistically significant differences between the period when the well was checked for functionality actually ends up being one of the most used features in the random forest model! ``` print(df_j["seasonal_period"].max()) df_j[[target_col, "seasonal_period"]].groupby(target_col).mean() ``` # Missing longitude, latitude, and GPS height The lowest hanging fruit in improving the accuracy of this model is imputing missing values for GPS height which in turn requires missing values from latitude and longitude. The best way to do so would be to use external data as these values exist and the approximation of the exact location in this manner will be much more accurate than any internal imputations. For the sake of the contest, no external data is permitted, so the next best way would be to do a deep dive and first fill in specific approximations for the longitude/latitude via the extensive categorical location data in this dataset. It would require attempting to see if unique values can be gleaned using the more specific "ward" and "lga" columns, followed by the more general "region columns" if not successful. Then when the longitude/latitude information is free from missing values, gps height can be imputed using knn regression since elevations will almost certainly be correlated with surrounding GPS coordinates. As the scope of this is more time intensive, I have passed over it for the sake of expediency. ``` df_j[df_j["longitude"]==0].head() sns.distplot(df_j["latitude"]) sns.distplot(df_j["longitude"]) sns.distplot(df_j["gps_height"]) df_j[(df_j["gps_height"]<0)] df_j[(df_j["longitude"]>39.812912) & (df_j["longitude"]<40.112912)& (df_j["latitude"]<-7.889986)& (df_j["latitude"]>-8.133632)] ``` # The model In order to simplify the transformations, class balancing, splitting and dummy variables, I have abstracted away the process using a DataPreprocessor object. The different variable types/columns can complicate the process, so in order to strike the best balance of simplicity and functionality, columns dictionaries are passed in as arguments. ``` target_col = "status_group" categorical = { "nominal_features":["funder", "installer", "wpt_name", "basin", "subvillage", "region", "region_code", "lga", "ward", "public_meeting", "scheme_management", "scheme_name", "permit", "extraction_type", "extraction_type_group", "extraction_type_class", "management", "management_group", "payment", "payment_type", "water_quality", "quality_group", "source", "source_type", "source_class", "waterpoint_type", "waterpoint_type_group" ], "impute_dummies":extract_column_names(df1, "^missing_") } # Overwriting the first categorical dictionary to remove columns without losing original selection. categorical = { "nominal_features":["basin", "region", "region_code", "public_meeting", "scheme_management", "permit", "extraction_type", "extraction_type_group", "extraction_type_class", "management", "management_group", "payment", "payment_type", "water_quality", "quality_group", "source", "source_type", "source_class", "waterpoint_type", "waterpoint_type_group" ], "impute_dummies":extract_column_names(df1, "^missing_") } continuous = {"untransformed":["gps_height", "longitude", "latitude", "num_private", "check-period", "years_old"], "transformed": {"logged": {"population":30, "amount_tsh":None} }} # There are a siginificant amount of arguments to customize the training/test data. # See the py file that contains the object for what is happening here. data = DataPreprocessor(df1, target_col, categorical, continuous, True, True, True, True) data.data_preprocessing(balance_class="upsample", scale_type="minmax", poly_degree=False) data.X_train ``` I began with an unconfigured Random Forest model, but was able to vastly improve the accuracy with a grid search. ``` forest = RandomForestClassifier(n_estimators=200, max_depth=5, criterion='gini', n_jobs=-1, random_state=101) forest.fit(data.X_train, data.y_train) evaluate_model(forest, data.X_test, data.y_test) param_dist = {'n_estimators':[100,500,900], 'criterion':["gini", "entropy"], 'max_depth':[3,8,13], 'min_samples_split':[2,7,12], 'min_samples_leaf':[1,9,17], "min_impurity_decrease":[0,.1, .2] } param_dist = {'n_estimators':[501,900,1300], 'criterion':["entropy"], 'max_depth':[8,13,18], 'min_samples_split':[2,4,6], 'min_samples_leaf':[1,5,9], "min_impurity_decrease":[0,.05, .09] } g_forest = GridSearchCV(estimator=forest, param_grid=param_dist, scoring='accuracy', n_jobs=-1, verbose=1, iid=False, cv=5) g_forest.fit(data.X_train, data.y_train) g_forest.best_params_ g_forest.best_params_ evaluate_model(g_forest, data.X_test, data.y_test) evaluate_model(g_forest, data.X_test, data.y_test) forest = RandomForestClassifier(**g_forest.best_params_) forest.fit(data.X_train, data.y_train) evaluate_model(forest, data.X_test, data.y_test) ``` The findings of what features were used the most in the most effective random forest model were surprising. Longitude, Latitude, and GPS height show that there may be something to be gained, by having a thorough look at the missing values. "Check-period" was a custom feature that I did not expect to see in the top three. It indicates there must be some seasonal aspect involved that is affecting the results when a well is assessed for functionality. There are a lot of dummy variables which seems to increase friction in the model selection process. None of the ones used seemed expendable, but perhaps a detailed imputation of latitude/longitude can eliminate the usefullness of some of the categorical regional data. ``` f, ax = plt.subplots(figsize=(14, 12)) sns.set(font_scale=1) importance = pd.DataFrame(forest.feature_importances_, index=data.X_train.columns).reset_index() importance.columns = pd.Index(["Feature", "Importance"]) sns.barplot(y="Feature", x="Importance", data=importance.sort_values("Importance", ascending=False).iloc[0:12]) ```
github_jupyter
#Importing external libraries import math import numpy as np import pandas as pd import re import matplotlib.pyplot as plt import seaborn as sns from collections import OrderedDict from scipy.stats import chi2_contingency from scipy.stats import chi2 import statsmodels.api as sm from statsmodels.formula.api import ols from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import GridSearchCV, RandomizedSearchCV, KFold import xgboost as xgb #Importing classes and functions from external files: from model_classes import ModelSwitcher, DataPreprocessor from cleaning_functions import * from feature_engineering import * from visualization_functions import * #Configuring options %matplotlib inline pd.set_option('display.max_columns', 50) df_outcomes = pd.read_csv("DATASETS/0bf8bc6e-30d0-4c50-956a-603fc693d966.csv") test_set = pd.read_csv("DATASETS/702ddfc5-68cd-4d1d-a0de-f5f566f76d91.csv") df = pd.read_csv("DATASETS/4910797b-ee55-40a7-8668-10efd5c1b960.csv") target_col = "status_group" df_c = pd.concat([df,test_set], axis=0).copy() df_j = pd.merge(df, df_outcomes, how="left", on="id") impute_dict = OrderedDict([("construction_year",[0, "median", None]), ("population",[0, "median", None]), ("amount_tsh",[0, "constant", .01]), ("subvillage",[np.nan, "constant", "Unknown"]), ("public_meeting",[np.nan, "most_frequent", None]), ("scheme_name",[np.nan, "constant", "Unknown"]), ("permit",[np.nan, "most_frequent", None]), ]) impute_cat_dict = {"funder":["0", "Unknown"], "installer":["0", "Unknown"], "scheme_management":["None", "Unknown"], } imputes = get_imputer_objs(df_j, impute_dict) df_c = impute_vals(df_c, impute_dict, imputes) df_j = impute_vals(df_j, impute_dict, imputes) df_c=impute_mult_categorical(df_c, impute_cat_dict) df_j=impute_mult_categorical(df_j, impute_cat_dict) df_c = main_data_cleaning(df_c) df_j = main_data_cleaning(df_j) f, ax = plt.subplots(figsize=(14, 11)) non_zero_tsh = df_j[df_j["amount_tsh"]!= 0]["amount_tsh"] logged_tsh = non_zero_tsh.map(lambda x: math.log(x)) sns.distplot(logged_tsh) df_j["logged_pop"] = df_j["population"].map(lambda x: 0 if x<= 0 else math.log(x, 30)) f, ax = plt.subplots(figsize=(14, 11)) sns.distplot(df_j["logged_pop"]) sns.scatterplot(x="logged_pop", y=target_col, data=df_j) df_non_zero_pop = df_j[df_j["logged_pop"] != 0] df_non_zero_pop[["logged_pop", target_col]].groupby(target_col).mean() #ANOVA test comparing the logged population size between the outcomes formula = 'logged_pop ~ C(status_group)' lm = ols(formula, df_non_zero_pop).fit() table = sm.stats.anova_lm(lm, typ=2) print("ANOVA for all outcomes") print(table) #Grabs the respective counts of well functionality in the provided data. totals = df_j[["logged_pop", target_col]].groupby(target_col).count()["logged_pop"] #Dataframe only the wells that have zeros input for population. df_zero_pop = df_j[df_j["logged_pop"] == 0] #Returns proportions for missing population data depending on the status of the well. print(totals.index) df_zero_pop[["logged_pop", target_col]].groupby(target_col).count()["logged_pop"]/totals.values df_j["logged_tsh"] = df_j["amount_tsh"].map(lambda x: math.log(x)) sns.set_style("darkgrid") sns.set(font_scale=1.5) f, ax = plt.subplots(figsize=(16, 14)) functional_pal = {"functional":"springgreen", "functional needs repair":"orange", "non functional":"red"} sns.scatterplot(x="years_old", y="logged_tsh", hue=target_col, size="logged_pop", sizes=(10, 500), alpha=.2, palette=functional_pal, data = df_j) lgnd = ["Well status:", "Functional", "Non functional", "Needs repair", "Population:", "0", "200", "27k", "4.5M"] ax.legend(lgnd) ax.set_ylabel('Total Standing Head') ax.set_xlabel('Years Old') ticks = list(np.arange(-5,15,2.5)) tick_labels = unlog_plot(ticks, math.e) tick_labels.insert(1, "0") ax.set(yticklabels=tick_labels) plt.show() cont_features = ["gps_height", "longitude", "latitude", "num_private", "check-period", "years_old", "logged_tsh", "logged_pop"] trimmed_heatmap(df_c, cont_features) # df_j["month_checked"] = df_j["date_recorded"].map(lambda x: x.month) df_j = add_features(df_j) df_j df_j[[target_col, "years_old"]].groupby(target_col).mean() print(df_j["seasonal_period"].max()) df_j[[target_col, "seasonal_period"]].groupby(target_col).mean() df_j[df_j["longitude"]==0].head() sns.distplot(df_j["latitude"]) sns.distplot(df_j["longitude"]) sns.distplot(df_j["gps_height"]) df_j[(df_j["gps_height"]<0)] df_j[(df_j["longitude"]>39.812912) & (df_j["longitude"]<40.112912)& (df_j["latitude"]<-7.889986)& (df_j["latitude"]>-8.133632)] target_col = "status_group" categorical = { "nominal_features":["funder", "installer", "wpt_name", "basin", "subvillage", "region", "region_code", "lga", "ward", "public_meeting", "scheme_management", "scheme_name", "permit", "extraction_type", "extraction_type_group", "extraction_type_class", "management", "management_group", "payment", "payment_type", "water_quality", "quality_group", "source", "source_type", "source_class", "waterpoint_type", "waterpoint_type_group" ], "impute_dummies":extract_column_names(df1, "^missing_") } # Overwriting the first categorical dictionary to remove columns without losing original selection. categorical = { "nominal_features":["basin", "region", "region_code", "public_meeting", "scheme_management", "permit", "extraction_type", "extraction_type_group", "extraction_type_class", "management", "management_group", "payment", "payment_type", "water_quality", "quality_group", "source", "source_type", "source_class", "waterpoint_type", "waterpoint_type_group" ], "impute_dummies":extract_column_names(df1, "^missing_") } continuous = {"untransformed":["gps_height", "longitude", "latitude", "num_private", "check-period", "years_old"], "transformed": {"logged": {"population":30, "amount_tsh":None} }} # There are a siginificant amount of arguments to customize the training/test data. # See the py file that contains the object for what is happening here. data = DataPreprocessor(df1, target_col, categorical, continuous, True, True, True, True) data.data_preprocessing(balance_class="upsample", scale_type="minmax", poly_degree=False) data.X_train forest = RandomForestClassifier(n_estimators=200, max_depth=5, criterion='gini', n_jobs=-1, random_state=101) forest.fit(data.X_train, data.y_train) evaluate_model(forest, data.X_test, data.y_test) param_dist = {'n_estimators':[100,500,900], 'criterion':["gini", "entropy"], 'max_depth':[3,8,13], 'min_samples_split':[2,7,12], 'min_samples_leaf':[1,9,17], "min_impurity_decrease":[0,.1, .2] } param_dist = {'n_estimators':[501,900,1300], 'criterion':["entropy"], 'max_depth':[8,13,18], 'min_samples_split':[2,4,6], 'min_samples_leaf':[1,5,9], "min_impurity_decrease":[0,.05, .09] } g_forest = GridSearchCV(estimator=forest, param_grid=param_dist, scoring='accuracy', n_jobs=-1, verbose=1, iid=False, cv=5) g_forest.fit(data.X_train, data.y_train) g_forest.best_params_ g_forest.best_params_ evaluate_model(g_forest, data.X_test, data.y_test) evaluate_model(g_forest, data.X_test, data.y_test) forest = RandomForestClassifier(**g_forest.best_params_) forest.fit(data.X_train, data.y_train) evaluate_model(forest, data.X_test, data.y_test) f, ax = plt.subplots(figsize=(14, 12)) sns.set(font_scale=1) importance = pd.DataFrame(forest.feature_importances_, index=data.X_train.columns).reset_index() importance.columns = pd.Index(["Feature", "Importance"]) sns.barplot(y="Feature", x="Importance", data=importance.sort_values("Importance", ascending=False).iloc[0:12])
0.398406
0.927429
# Concluding Thoughts Congratulations! You've made it! If you have worked through all of the notebooks to this point, then you have joined the small, but growing group of people that are able to harness the power of deep learning to solve real problems. You may not feel that way yet—in fact you probably don't. We have seen again and again that students that complete the fast.ai courses dramatically underestimate how effective they are as deep learning practitioners. We've also seen that these people are often underestimated by others with a classic academic background. So if you are to rise above your own expectations and the expectations of others, what you do next, after closing this book, is even more important than what you've done to get to this point. The most important thing is to keep the momentum going. In fact, as you know from your study of optimizers, momentum is something that can build upon itself! So think about what you can do now to maintain and accelerate your deep learning journey. <<do_next>> can give you a few ideas. <img alt="What to do next" width="550" caption="What to do next" id="do_next" src="images/att_00053.png"> We've talked a lot in this book about the value of writing, whether it be code or prose. But perhaps you haven't quite written as much as you had hoped so far. That's okay! Now is a great chance to turn that around. You have a lot to say, at this point. Perhaps you have tried some experiments on a dataset that other people don't seem to have looked at in quite the same way. Tell the world about it! Or perhaps thinking about trying out some ideas that occurred to you while you were reading—now is a great time to turn those ideas into code. If you'd like to share your ideas, one fairly low-key place to do so is the [fast.ai forums](https://forums.fast.ai/). You will find that the community there is very supportive and helpful, so please do drop by and let us know what you've been up to. Or see if you can answer a few questions for those folks who are earlier in their journey than you. And if you do have some successes, big or small, in your deep learning journey, be sure to let us know! It's especially helpful if you post about them on the forums, because learning about the successes of other students can be extremely motivating. Perhaps the most important approach for many people to stay connected with their learning journey is to build a community around it. For instance, you could try to set up a small deep learning meetup in your local neighborhood, or a study group, or even offer to do a talk at a local meetup about what you've learned so far or some particular aspect that interested you. It's okay that you are not the world's leading expert just yet—the important thing to remember is that you now know about plenty of stuff that other people don't, so they are very likely to appreciate your perspective. Another community event which many people find useful is a regular book club or paper reading club. You might find that there are some in your neighbourhood already, and if not you could try to get one started yourself. Even if there is just one other person doing it with you, it will help give you the support and encouragement to get going. If you are not in a geography where it's easy to get together with like-minded folks in person, drop by the forums, because there are always people starting up virtual study groups. These generally involve a bunch of folks getting together over video chat once a week or so to discuss some deep learning topic. Hopefully, by this point, you have a few little projects that you've put together and experiments that you've run. Our recommendation for the next step is to pick one of these and make it as good as you can. Really polish it up into the best piece of work that you can—something you are really proud of. This will force you to go much deeper into a topic, which will really test your understanding and give you the opportunity to see what you can do when you really put your mind to it. Also, you may want to take a look at the fast.ai free online course that covers the same material as this book. Sometimes, seeing the same material in two different ways can really help to crystallize the ideas. In fact, human learning researchers have found that one of the best ways to learn material is to see the same thing from different angles, described in different ways. Your final mission, should you choose to accept it, is to take this book and give it to somebody that you know—and get somebody else starte on their own deep learning journey!
github_jupyter
# Concluding Thoughts Congratulations! You've made it! If you have worked through all of the notebooks to this point, then you have joined the small, but growing group of people that are able to harness the power of deep learning to solve real problems. You may not feel that way yet—in fact you probably don't. We have seen again and again that students that complete the fast.ai courses dramatically underestimate how effective they are as deep learning practitioners. We've also seen that these people are often underestimated by others with a classic academic background. So if you are to rise above your own expectations and the expectations of others, what you do next, after closing this book, is even more important than what you've done to get to this point. The most important thing is to keep the momentum going. In fact, as you know from your study of optimizers, momentum is something that can build upon itself! So think about what you can do now to maintain and accelerate your deep learning journey. <<do_next>> can give you a few ideas. <img alt="What to do next" width="550" caption="What to do next" id="do_next" src="images/att_00053.png"> We've talked a lot in this book about the value of writing, whether it be code or prose. But perhaps you haven't quite written as much as you had hoped so far. That's okay! Now is a great chance to turn that around. You have a lot to say, at this point. Perhaps you have tried some experiments on a dataset that other people don't seem to have looked at in quite the same way. Tell the world about it! Or perhaps thinking about trying out some ideas that occurred to you while you were reading—now is a great time to turn those ideas into code. If you'd like to share your ideas, one fairly low-key place to do so is the [fast.ai forums](https://forums.fast.ai/). You will find that the community there is very supportive and helpful, so please do drop by and let us know what you've been up to. Or see if you can answer a few questions for those folks who are earlier in their journey than you. And if you do have some successes, big or small, in your deep learning journey, be sure to let us know! It's especially helpful if you post about them on the forums, because learning about the successes of other students can be extremely motivating. Perhaps the most important approach for many people to stay connected with their learning journey is to build a community around it. For instance, you could try to set up a small deep learning meetup in your local neighborhood, or a study group, or even offer to do a talk at a local meetup about what you've learned so far or some particular aspect that interested you. It's okay that you are not the world's leading expert just yet—the important thing to remember is that you now know about plenty of stuff that other people don't, so they are very likely to appreciate your perspective. Another community event which many people find useful is a regular book club or paper reading club. You might find that there are some in your neighbourhood already, and if not you could try to get one started yourself. Even if there is just one other person doing it with you, it will help give you the support and encouragement to get going. If you are not in a geography where it's easy to get together with like-minded folks in person, drop by the forums, because there are always people starting up virtual study groups. These generally involve a bunch of folks getting together over video chat once a week or so to discuss some deep learning topic. Hopefully, by this point, you have a few little projects that you've put together and experiments that you've run. Our recommendation for the next step is to pick one of these and make it as good as you can. Really polish it up into the best piece of work that you can—something you are really proud of. This will force you to go much deeper into a topic, which will really test your understanding and give you the opportunity to see what you can do when you really put your mind to it. Also, you may want to take a look at the fast.ai free online course that covers the same material as this book. Sometimes, seeing the same material in two different ways can really help to crystallize the ideas. In fact, human learning researchers have found that one of the best ways to learn material is to see the same thing from different angles, described in different ways. Your final mission, should you choose to accept it, is to take this book and give it to somebody that you know—and get somebody else starte on their own deep learning journey!
0.368633
0.620507
# What's New - Internal ## Summary This new edition of `made-with-gs-quant` is tailored exclusively for our internal users and showcases some of the latest features of the internal gs-quant toolkit. In this notebook we find solutions for some the most popular questions we get such as: + How do I generate an FX dual binary pricing grid in gs_quant? + How do I load the trade that my client did with us? + How do I price this rates structure live? The content of this notebook is split into: 1. [Let's get started with gs-quant](#1---Let's-get-started-with-gs-quant) 2. [TDAPI package](#2---TDAPI-package) 3. [Load trade from SecDb](#3---Load-trade-from-SecDb) 4. [Live Pricing](#4---Live-Pricing) ### 1 - Let's get started with gs-quant Upon installing the `gs-quant` and `gs-quant[internal]` packages ([see here](https://gitlab.gs.com/marquee/analytics/gs_quant_internal#internal-users) for instructions), start your session using your kerberos entitlements directly (no need to register an app). ``` from gs_quant.session import GsSession GsSession.use() ``` ### 2 - TDAPI package On top of the [externalised instruments](https://developer.gs.com/docs/gsquant/guides/Pricing-and-Risk/instruments/) supported in gs-quant, TDAPI enables you to directly leverage a wider range of instruments from SecDb, considerably widening the available universe for pricing and risk analytics. To see which instruments are supported, simply import the package and type `tdapi.[tab]`. ``` import gs_quant_internal.tdapi as tdapi from IPython.display import Image Image(filename='images/tdapi_package.png') ``` In this notebook we showcase the use of the TDAPI package using the example of Dual FX Binary Options. Let's consider 2 months options with payoff of $10M if strike 1 < EURUSD and GBPUSD < strike 2. These options are composed of 2 nested legs built as below. ``` from gs_quant.markets.portfolio import Portfolio def FXDualBinaryOption(pair_1, pair_2, strikes_1, strikes_2, expiry, size): portfolio = Portfolio() for strike_1 in strikes_1: for strike_2 in strikes_2: over, under = pair_1.split('/') leg_1 = tdapi.FXMultiCrossBinaryChildBuilder(over=over, under=under, strike=strike_1) over, under = pair_2.split('/') leg_2 = tdapi.FXMultiCrossBinaryChildBuilder(over=over, under=under, strike=strike_2, striketype='Binary Put') dual = tdapi.FXMultiCrossBinaryBuilder(expiry=expiry, size=size, legs=(leg_1, leg_2), premium=0) portfolio.append(dual) return portfolio ``` For assistance while building the instrument, `shif+tab` on the instrument name displays the list of parameters. ``` from IPython.display import Image Image(filename='images/instrument_help.png') ``` For each leg we consider a range of 9 possible strikes varying around the current spot rate of the associated currency pair. We build a portfolio of 81 options (9 USD/EUR strikes x 9 USD/GBP strikes) and compute the price for each option as a percentage of the payoff. Please note that the code uses internal SecDB notation for FX crosses (e.g. USD/EUR). ``` eur_strikes = ["s{:+}%".format(x) for x in range(-4, 5)] gbp_strikes = ["s{:+}%".format(x) for x in range(-4, 5)] dual_options = FXDualBinaryOption('USD/EUR', 'USD/GBP', eur_strikes, gbp_strikes, '2m', 10e6) from gs_quant.markets import PricingContext import pandas as pd with PricingContext(): dual_prices = dual_options.dollar_price() prices = pd.DataFrame(index=eur_strikes, columns=gbp_strikes) for dual in dual_options: prices.loc[dual.legs[0].strike][dual.legs[1].strike] = dual_prices[dual] / 10e6 ``` We can now visualise the price repartition of the options on the strike grid. ``` import seaborn as sns import numpy as np import matplotlib.pyplot as plt plt.subplots(figsize=(14, 8)) ax = sns.heatmap(prices.apply(pd.to_numeric), annot=True, fmt='.2%', cmap='YlGn') ax.set(ylabel='USD/EUR Strikes', xlabel='USD/GBP Strikes', title='Option prices depending on Strike') ax.xaxis.tick_top() ``` By looking at prices as a % of premium, we can assimilate this grid of binary prices to the discounted value of the risk neutral probability of both crosses being in the money in two months time. This begs the question of how correlated they are and what premium we are saving from the correlation effect of USD/EUR and USD/GBP for the various different events. Let's investigate by building a similar price grid for the individual binary options represented by the two legs. ``` def FXBinaryOptionPrice(pair, strike, expiry, size, optiontype='Call'): over, under = pair.split('/') with PricingContext(): option = tdapi.FXBinaryBuilder(over=over, under=under, strike=strike, expiry=expiry, size=size, premium=0, optiontype=optiontype) price = option.dollar_price() return price.result() indep_prices = pd.DataFrame(index=eur_strikes, columns=gbp_strikes) for dual in dual_options: eurusd_price = FXBinaryOptionPrice('USD/EUR', dual.legs[0].strike, expiry='2m', size=10e6) gbpusd_price = FXBinaryOptionPrice('USD/GBP', dual.legs[1].strike, expiry='2m', size=10e6, optiontype='Put') indep_prices.loc[dual.legs[0].strike][dual.legs[1].strike] = eurusd_price/10e6 * gbpusd_price/10e6 plt.subplots(figsize=(14, 8)) ax = sns.heatmap(indep_prices.apply(pd.to_numeric)-prices.apply(pd.to_numeric), annot=True, fmt='.2%', cmap='YlGn') ax.set(ylabel='USD/EUR Strikes', xlabel='USD/GBP Strikes', title='Option price probabilities assuming independance of xccy pairs') ax.xaxis.tick_top() ``` By comparing the prices of the individual binary options in the above table to that of the dual binary option, you can see an approximation for the premium saved (or cost) from the correlation factor of the events. ## 3 - Load trade from SecDb Going one step further into leveraging the resources of SecDb, as an internal users you are now able to load real SecDb trades or portfolio of trades referenced by their SecDb ETI or Book ID. With this feature you can now run concrete risk analysis your own book. With `from_book()` you can easily create a portfolio from your existing SecDb book: ``` portfolio = Portfolio.from_book('my Book ID') # replace with your secDb book ID e.g. '76037320' ``` Your gs-quant portfolio now contains instruments based on your SecDb book leaves: ``` portfolio.as_dict()['instruments'][:5] ``` You can use all the gs-quant functionalities to price and calculate any of the available risk measures on your own portfolio: ``` from gs_quant.risk import DollarPrice, IRDeltaParallel results = portfolio.calc((DollarPrice, IRDeltaParallel)) ``` To view risk results, you may directly reference the SecDb leaf: ``` results[portfolio['my leaf name']] # replace with your SecDb leaf e.g. 'LTAABBCS3333PGQGCZ7A' ``` Or view book level results: ``` results[DollarPrice].aggregate() ``` For trades involving supported instruments, `from.eti()` creates a gs-quant portfolio directly from the existing SecDb trade referenced by the ETI number: ``` portfolio = Portfolio.from_eti('my ETI number') # Replace with your ETI trade number ``` With `from_book` and `from_eti`, you can now fully leverage the gs-quant risk package on your own SecDb books! **Please note that all portfolio types are not yet handled.** Should you experience any issue, reach-out to the `gs-quant` distro. For more examples of what you can do with Portfolios, refer to the [examples folder](https://nbviewer.jupyter.org/github/goldmansachs/gs-quant/tree/master/gs_quant/examples/) and [previous made_with_gs_quant notebooks](https://nbviewer.jupyter.org/github/goldmansachs/gs-quant/tree/master/gs_quant/made_with_gs_quant/) of `made_with_gs_quant`. ### 4 - Live Pricing Finally, another powerful new feature brought to our internal users is the ability to get live prices. Re-using the dual option portfolio built in the first section, let's compare our portfolio price under yesterday's market data at close and live pricing environments. Here we use a PricingContext with batch to group the requests together and avoid timeouts. ``` from gs_quant.markets import LiveMarket live_pricing = PricingContext(market=LiveMarket('LDN'), market_data_location='LDN') close_pricing = PricingContext(is_batch=True, is_async=True) with live_pricing: prices_live = dual_options.dollar_price() with close_pricing: prices_close = dual_options.dollar_price() print('{:,.0f}'.format(prices_live.aggregate())) print('{:,.0f}'.format(prices_close.aggregate())) ``` `LiveMarket` accesses the latest market data available for the specified market location. This means you can now use gs-quant to compute real-time prices and intra-day risk on your portfolio. This closes this first internal edition of `made_with_gs_quant` please continue sharing your feedback on to make `gs-quant` even more useful to you, and look out for the next editions of `What's New` in `made_with_gs_quant`. Happy hacking!
github_jupyter
from gs_quant.session import GsSession GsSession.use() import gs_quant_internal.tdapi as tdapi from IPython.display import Image Image(filename='images/tdapi_package.png') from gs_quant.markets.portfolio import Portfolio def FXDualBinaryOption(pair_1, pair_2, strikes_1, strikes_2, expiry, size): portfolio = Portfolio() for strike_1 in strikes_1: for strike_2 in strikes_2: over, under = pair_1.split('/') leg_1 = tdapi.FXMultiCrossBinaryChildBuilder(over=over, under=under, strike=strike_1) over, under = pair_2.split('/') leg_2 = tdapi.FXMultiCrossBinaryChildBuilder(over=over, under=under, strike=strike_2, striketype='Binary Put') dual = tdapi.FXMultiCrossBinaryBuilder(expiry=expiry, size=size, legs=(leg_1, leg_2), premium=0) portfolio.append(dual) return portfolio from IPython.display import Image Image(filename='images/instrument_help.png') eur_strikes = ["s{:+}%".format(x) for x in range(-4, 5)] gbp_strikes = ["s{:+}%".format(x) for x in range(-4, 5)] dual_options = FXDualBinaryOption('USD/EUR', 'USD/GBP', eur_strikes, gbp_strikes, '2m', 10e6) from gs_quant.markets import PricingContext import pandas as pd with PricingContext(): dual_prices = dual_options.dollar_price() prices = pd.DataFrame(index=eur_strikes, columns=gbp_strikes) for dual in dual_options: prices.loc[dual.legs[0].strike][dual.legs[1].strike] = dual_prices[dual] / 10e6 import seaborn as sns import numpy as np import matplotlib.pyplot as plt plt.subplots(figsize=(14, 8)) ax = sns.heatmap(prices.apply(pd.to_numeric), annot=True, fmt='.2%', cmap='YlGn') ax.set(ylabel='USD/EUR Strikes', xlabel='USD/GBP Strikes', title='Option prices depending on Strike') ax.xaxis.tick_top() def FXBinaryOptionPrice(pair, strike, expiry, size, optiontype='Call'): over, under = pair.split('/') with PricingContext(): option = tdapi.FXBinaryBuilder(over=over, under=under, strike=strike, expiry=expiry, size=size, premium=0, optiontype=optiontype) price = option.dollar_price() return price.result() indep_prices = pd.DataFrame(index=eur_strikes, columns=gbp_strikes) for dual in dual_options: eurusd_price = FXBinaryOptionPrice('USD/EUR', dual.legs[0].strike, expiry='2m', size=10e6) gbpusd_price = FXBinaryOptionPrice('USD/GBP', dual.legs[1].strike, expiry='2m', size=10e6, optiontype='Put') indep_prices.loc[dual.legs[0].strike][dual.legs[1].strike] = eurusd_price/10e6 * gbpusd_price/10e6 plt.subplots(figsize=(14, 8)) ax = sns.heatmap(indep_prices.apply(pd.to_numeric)-prices.apply(pd.to_numeric), annot=True, fmt='.2%', cmap='YlGn') ax.set(ylabel='USD/EUR Strikes', xlabel='USD/GBP Strikes', title='Option price probabilities assuming independance of xccy pairs') ax.xaxis.tick_top() portfolio = Portfolio.from_book('my Book ID') # replace with your secDb book ID e.g. '76037320' portfolio.as_dict()['instruments'][:5] from gs_quant.risk import DollarPrice, IRDeltaParallel results = portfolio.calc((DollarPrice, IRDeltaParallel)) results[portfolio['my leaf name']] # replace with your SecDb leaf e.g. 'LTAABBCS3333PGQGCZ7A' results[DollarPrice].aggregate() portfolio = Portfolio.from_eti('my ETI number') # Replace with your ETI trade number from gs_quant.markets import LiveMarket live_pricing = PricingContext(market=LiveMarket('LDN'), market_data_location='LDN') close_pricing = PricingContext(is_batch=True, is_async=True) with live_pricing: prices_live = dual_options.dollar_price() with close_pricing: prices_close = dual_options.dollar_price() print('{:,.0f}'.format(prices_live.aggregate())) print('{:,.0f}'.format(prices_close.aggregate()))
0.441191
0.949763
<a href="https://colab.research.google.com/github/ayulockin/LossLandscape/blob/master/Visualizing_Function_Space_Similarity_SmallCNN.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Setups, Imports and Installations ``` ## This is so that I can save my models. from google.colab import drive drive.mount('gdrive') %%capture !pip install wandb import tensorflow as tf from tensorflow import keras from tensorflow.keras.datasets import cifar10 from tensorflow.keras.applications import resnet50 import os os.environ["TF_DETERMINISTIC_OPS"] = "1" import numpy as np from numpy.linalg import norm import pandas as pd import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D %matplotlib inline import seaborn as sns sns.set() from tqdm.notebook import tqdm_notebook from sklearn.manifold import TSNE import wandb from wandb.keras import WandbCallback wandb.login() ``` # Get Trained Models (For now I am using models trained from SmallCNN.) ``` ROOT_PATH = 'gdrive/My Drive/LossLandscape/' ## SmallCNN model checkpoint for each epoch(total 40 epochs) MODEL_PATH = ROOT_PATH+'SmallCNN_CheckpointID_1/' ## SmallCNN models with different initialization(total 10 models) INDEPENDENT_MODEL_PATH = ROOT_PATH+'SmallIndependentSolutions/' ## SmallCNN models with different initialization(total 3 models) with all checkpoints saved INDEPENDENT_MODEL_PATH_tsne = ROOT_PATH+'SmallIndependentSolutions_tsne/' same_model_ckpts = os.listdir(MODEL_PATH) independent_models = os.listdir(INDEPENDENT_MODEL_PATH) independent_models_tsne = os.listdir(INDEPENDENT_MODEL_PATH_tsne) print(len(same_model_ckpts)) print(len(independent_models)) print(len(independent_models_tsne)) # https://stackoverflow.com/a/2669120/7636462 import re def sorted_nicely(l): """ Sort the given iterable in the way that humans expect.""" convert = lambda text: int(text) if text.isdigit() else text alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] return sorted(l, key = alphanum_key) same_model_ckpts = sorted_nicely(same_model_ckpts) same_model_ckpts[:5] independent_models = sorted_nicely(independent_models) independent_models[:5] ``` # Get Dataset and Prepare #### CIFAR-10 ``` (x_train, y_train), (x_test, y_test) = cifar10.load_data() y_train = y_train.flatten() y_test = y_test.flatten() CLASS_NAMES = ("airplane", "automobile", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck") print(x_train.shape, y_train.shape, x_test.shape, y_test.shape) ``` #### Dataloader ``` AUTO = tf.data.experimental.AUTOTUNE BATCH_SIZE = 128 IMG_SHAPE = 32 testloader = tf.data.Dataset.from_tensor_slices((x_test, y_test)) def preprocess_image(image, label): img = tf.cast(image, tf.float32) img = img/255. return img, label testloader = ( testloader .map(preprocess_image, num_parallel_calls=AUTO) .batch(BATCH_SIZE) .prefetch(AUTO) ) ``` # Similarity of Functions Within Initialized Trajectories ## Disagreement of predictions (Refer figure 2(b) from paper) ``` # Given model and test data, return true_labels and predictions. def evaluate(test_dataloader, model): true_labels = [] pred_labels = [] for imgs, labels in iter(test_dataloader): preds = model.predict(imgs) true_labels.extend(labels) pred_labels.extend(np.argmax(preds, axis=1)) return np.array(true_labels), np.array(pred_labels) predictions = [] for i in tqdm_notebook(range(40)): # load model model = tf.keras.models.load_model(MODEL_PATH+same_model_ckpts[i]) # get predictions for model _, preds = evaluate(testloader, model) predictions.append(preds) empty_arr = np.zeros(shape=(40,40)) for i in tqdm_notebook(range(40)): preds1 = predictions[i] for j in range(i, 40): preds2 = predictions[j] # compute dissimilarity dissimilarity_score = 1-np.sum(np.equal(preds1, preds2))/10000 empty_arr[i][j] = dissimilarity_score if i is not j: empty_arr[j][i] = dissimilarity_score dissimilarity_coeff = empty_arr[::-1] plt.figure(figsize=(9,8)) sns.heatmap(dissimilarity_coeff, cmap='RdBu_r'); plt.xticks([5,10,15,20,25,30,35],[5,10,15,20,25,30,35]); plt.yticks([5,10,15,20,25,30,35],[35,30,25,20,15,10,5]); plt.savefig('prediction_disagreement.png') ``` ## Cosine Similarity of weights (Refer figure 2(a) from paper) ``` # Get the weights of the input model. def get_model_weights(model): model_weights = [] # iterate through model layers. for layer in model.layers: # grab weights of that layer weights = layer.get_weights() # list # check if layer got triainable weights if len(weights)==0: continue # discard biases term, wrap with ndarray, flatten weights model_weights.extend(np.array(weights[0]).flatten()) return np.array(model_weights) weights_of_models = [] for i in tqdm_notebook(range(40)): # load model model = tf.keras.models.load_model(MODEL_PATH+same_model_ckpts[i]) # get predictions for model weights = get_model_weights(model) weights_of_models.append(weights) empty_arr = np.zeros(shape=(40,40)) for i in tqdm_notebook(range(40)): weights1 = weights_of_models[i] for j in range(i, 40): weights2 = weights_of_models[j] # compute cosine similarity of weights cos_sim = np.dot(weights1, weights2)/(norm(weights1)*norm(weights2)) empty_arr[i][j] = cos_sim if i is not j: empty_arr[j][i] = cos_sim cos_sim_coeff = empty_arr[::-1] plt.figure(figsize=(9,8)) sns.heatmap(cos_sim_coeff, cmap='RdBu_r'); plt.xticks([5,10,15,20,25,30,35],[5,10,15,20,25,30,35]); plt.yticks([5,10,15,20,25,30,35],[35,30,25,20,15,10,5]); plt.savefig('functional_similarity.png') wandb.init(entity='authors', project='loss-landscape', id='smallcnn_same_model_investigations') wandb.log({'prediction_disagreement': wandb.Image('prediction_disagreement.png')}) wandb.log({'functional_similarity': wandb.Image('functional_similarity.png')}) ``` # Similarity of Functions Across Randomly Initialized Trajectories ## Disagreement of predictions (Refer figure 3(a) from paper) ``` predictions = [] for i in tqdm_notebook(range(10)): # load model model = tf.keras.models.load_model(INDEPENDENT_MODEL_PATH+independent_models[i]) # get predictions for model _, preds = evaluate(testloader, model) predictions.append(preds) empty_arr = np.zeros(shape=(10,10)) for i in tqdm_notebook(range(10)): preds1 = predictions[i] for j in range(i, 10): preds2 = predictions[j] # compute dissimilarity dissimilarity_score = 1-np.sum(np.equal(preds1, preds2))/10000 empty_arr[i][j] = dissimilarity_score if i is not j: empty_arr[j][i] = dissimilarity_score dissimilarity_coeff = empty_arr[::-1] plt.figure(figsize=(9,8)) sns.heatmap(dissimilarity_coeff, cmap='RdBu_r'); plt.xticks([0,2,4,6,8],[0,2,4,6,8]); plt.yticks([0,2,4,6,8],[8,6,4,2,1]); plt.savefig('independent_prediction_disagreement.png') ``` ## Cosine Similarity of weights (Refer figure 3(a) from paper) ``` # Get the weights of the input model. def get_model_weights(model): model_weights = [] # iterate through model layers. for layer in model.layers: # grab weights of that layer weights = layer.get_weights() # list # check if layer got triainable weights if len(weights)==0: continue # discard biases term, wrap with ndarray, flatten weights model_weights.extend(np.array(weights[0]).flatten()) return np.array(model_weights) weights_of_models = [] for i in tqdm_notebook(range(10)): # load model model = tf.keras.models.load_model(INDEPENDENT_MODEL_PATH+independent_models[i]) # get predictions for model weights = get_model_weights(model) weights_of_models.append(weights) empty_arr = np.zeros(shape=(10,10)) for i in tqdm_notebook(range(10)): weights1 = weights_of_models[i] for j in range(i, 10): weights2 = weights_of_models[j] # compute cosine similarity of weights cos_sim = np.dot(weights1, weights2)/(norm(weights1)*norm(weights2)) empty_arr[i][j] = cos_sim if i is not j: empty_arr[j][i] = cos_sim cos_sim_coeff = empty_arr[::-1] plt.figure(figsize=(9,8)) sns.heatmap(cos_sim_coeff, cmap='RdBu_r'); plt.xticks([0,2,4,6,8],[0,2,4,6,8]); plt.yticks([0,2,4,6,8],[8,6,4,2,1]); plt.savefig('independent_functional_similarity.png') wandb.init(entity='authors', project='loss-landscape', id='smallcnn_independent_model_investigations') wandb.log({'independent_prediction_disagreement': wandb.Image('independent_prediction_disagreement.png')}) wandb.log({'independent_functional_similarity': wandb.Image('independent_functional_similarity.png')}) ``` # Investigating Load Landscape ``` NUM_EXAMPLES = 1024 NUM_CLASSES = 10 test_tsne_ds = testloader.unbatch().take(NUM_EXAMPLES).batch(BATCH_SIZE) # Given model and test data, return true_labels and predictions. def evaluate_tsne(test_dataloader, model): true_labels = [] pred_labels = [] for imgs, labels in iter(test_dataloader): preds = model.predict(imgs) true_labels.extend(labels) pred_labels.extend(preds) ## change here return np.array(true_labels), np.array(pred_labels) NUM_TRAJECTORIES = 3 predictions_for_tsne = [] for i in tqdm_notebook(range(NUM_TRAJECTORIES)): subdir = independent_models_tsne[i] model_files = os.listdir(INDEPENDENT_MODEL_PATH_tsne+subdir) model_files = sorted_nicely(model_files) predictions = [] for model_file in model_files: if model_file=='small_cnn_checkpoint_5.h5': # this check is because this model checkpoint didn't serialize properly. continue model = tf.keras.models.load_model(INDEPENDENT_MODEL_PATH_tsne+subdir+'/'+model_file) _, preds = evaluate_tsne(test_tsne_ds, model) predictions.append(preds) predictions = np.array(predictions) print(predictions.shape) predictions_for_tsne.append(predictions) # convert list to array predictions_for_tsne = np.array(predictions_for_tsne) print('[INFO] shape of predictions tensor: ', predictions_for_tsne.shape) # reshape the tensor reshaped_predictions_for_tsne = predictions_for_tsne.reshape([-1, NUM_EXAMPLES*NUM_CLASSES]) print('[INFO] shape of reshaped tensor: ', reshaped_predictions_for_tsne.shape) # initialize tsne object tsne = TSNE(n_components=2) # compute tsne prediction_embed = tsne.fit_transform(reshaped_predictions_for_tsne) print('[INFO] Shape of embedded tensor: ', prediction_embed.shape) # reshape trajectory_embed = prediction_embed.reshape([NUM_TRAJECTORIES, -1, 2]) print('[INFO] Shape of reshaped tensor: ', trajectory_embed.shape) # Plot plt.figure(constrained_layout=True, figsize=(6,6)) colors_list=['r', 'b', 'g'] labels_list = ['traj_{}'.format(i) for i in range(NUM_TRAJECTORIES)] for i in range(NUM_TRAJECTORIES): plt.plot(trajectory_embed[i,:,0],trajectory_embed[i,:,1],color = colors_list[i], alpha = 0.8,linestyle = "", marker = "o") plt.plot(trajectory_embed[i,:,0],trajectory_embed[i,:,1],color = colors_list[i], alpha = 0.3,linestyle = "-", marker = "") plt.plot(trajectory_embed[i,0,0],trajectory_embed[i,0,1],color = colors_list[i], alpha = 1.0,linestyle = "", marker = "*") plt.savefig('loss_landscape_2d.png') wandb.init(entity='authors', project='loss-landscape', id='small_cnn_trajectory_investigation') wandb.log({'loss_landscape_2d': wandb.Image('loss_landscape_2d.png')}) ```
github_jupyter
## This is so that I can save my models. from google.colab import drive drive.mount('gdrive') %%capture !pip install wandb import tensorflow as tf from tensorflow import keras from tensorflow.keras.datasets import cifar10 from tensorflow.keras.applications import resnet50 import os os.environ["TF_DETERMINISTIC_OPS"] = "1" import numpy as np from numpy.linalg import norm import pandas as pd import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D %matplotlib inline import seaborn as sns sns.set() from tqdm.notebook import tqdm_notebook from sklearn.manifold import TSNE import wandb from wandb.keras import WandbCallback wandb.login() ROOT_PATH = 'gdrive/My Drive/LossLandscape/' ## SmallCNN model checkpoint for each epoch(total 40 epochs) MODEL_PATH = ROOT_PATH+'SmallCNN_CheckpointID_1/' ## SmallCNN models with different initialization(total 10 models) INDEPENDENT_MODEL_PATH = ROOT_PATH+'SmallIndependentSolutions/' ## SmallCNN models with different initialization(total 3 models) with all checkpoints saved INDEPENDENT_MODEL_PATH_tsne = ROOT_PATH+'SmallIndependentSolutions_tsne/' same_model_ckpts = os.listdir(MODEL_PATH) independent_models = os.listdir(INDEPENDENT_MODEL_PATH) independent_models_tsne = os.listdir(INDEPENDENT_MODEL_PATH_tsne) print(len(same_model_ckpts)) print(len(independent_models)) print(len(independent_models_tsne)) # https://stackoverflow.com/a/2669120/7636462 import re def sorted_nicely(l): """ Sort the given iterable in the way that humans expect.""" convert = lambda text: int(text) if text.isdigit() else text alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] return sorted(l, key = alphanum_key) same_model_ckpts = sorted_nicely(same_model_ckpts) same_model_ckpts[:5] independent_models = sorted_nicely(independent_models) independent_models[:5] (x_train, y_train), (x_test, y_test) = cifar10.load_data() y_train = y_train.flatten() y_test = y_test.flatten() CLASS_NAMES = ("airplane", "automobile", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck") print(x_train.shape, y_train.shape, x_test.shape, y_test.shape) AUTO = tf.data.experimental.AUTOTUNE BATCH_SIZE = 128 IMG_SHAPE = 32 testloader = tf.data.Dataset.from_tensor_slices((x_test, y_test)) def preprocess_image(image, label): img = tf.cast(image, tf.float32) img = img/255. return img, label testloader = ( testloader .map(preprocess_image, num_parallel_calls=AUTO) .batch(BATCH_SIZE) .prefetch(AUTO) ) # Given model and test data, return true_labels and predictions. def evaluate(test_dataloader, model): true_labels = [] pred_labels = [] for imgs, labels in iter(test_dataloader): preds = model.predict(imgs) true_labels.extend(labels) pred_labels.extend(np.argmax(preds, axis=1)) return np.array(true_labels), np.array(pred_labels) predictions = [] for i in tqdm_notebook(range(40)): # load model model = tf.keras.models.load_model(MODEL_PATH+same_model_ckpts[i]) # get predictions for model _, preds = evaluate(testloader, model) predictions.append(preds) empty_arr = np.zeros(shape=(40,40)) for i in tqdm_notebook(range(40)): preds1 = predictions[i] for j in range(i, 40): preds2 = predictions[j] # compute dissimilarity dissimilarity_score = 1-np.sum(np.equal(preds1, preds2))/10000 empty_arr[i][j] = dissimilarity_score if i is not j: empty_arr[j][i] = dissimilarity_score dissimilarity_coeff = empty_arr[::-1] plt.figure(figsize=(9,8)) sns.heatmap(dissimilarity_coeff, cmap='RdBu_r'); plt.xticks([5,10,15,20,25,30,35],[5,10,15,20,25,30,35]); plt.yticks([5,10,15,20,25,30,35],[35,30,25,20,15,10,5]); plt.savefig('prediction_disagreement.png') # Get the weights of the input model. def get_model_weights(model): model_weights = [] # iterate through model layers. for layer in model.layers: # grab weights of that layer weights = layer.get_weights() # list # check if layer got triainable weights if len(weights)==0: continue # discard biases term, wrap with ndarray, flatten weights model_weights.extend(np.array(weights[0]).flatten()) return np.array(model_weights) weights_of_models = [] for i in tqdm_notebook(range(40)): # load model model = tf.keras.models.load_model(MODEL_PATH+same_model_ckpts[i]) # get predictions for model weights = get_model_weights(model) weights_of_models.append(weights) empty_arr = np.zeros(shape=(40,40)) for i in tqdm_notebook(range(40)): weights1 = weights_of_models[i] for j in range(i, 40): weights2 = weights_of_models[j] # compute cosine similarity of weights cos_sim = np.dot(weights1, weights2)/(norm(weights1)*norm(weights2)) empty_arr[i][j] = cos_sim if i is not j: empty_arr[j][i] = cos_sim cos_sim_coeff = empty_arr[::-1] plt.figure(figsize=(9,8)) sns.heatmap(cos_sim_coeff, cmap='RdBu_r'); plt.xticks([5,10,15,20,25,30,35],[5,10,15,20,25,30,35]); plt.yticks([5,10,15,20,25,30,35],[35,30,25,20,15,10,5]); plt.savefig('functional_similarity.png') wandb.init(entity='authors', project='loss-landscape', id='smallcnn_same_model_investigations') wandb.log({'prediction_disagreement': wandb.Image('prediction_disagreement.png')}) wandb.log({'functional_similarity': wandb.Image('functional_similarity.png')}) predictions = [] for i in tqdm_notebook(range(10)): # load model model = tf.keras.models.load_model(INDEPENDENT_MODEL_PATH+independent_models[i]) # get predictions for model _, preds = evaluate(testloader, model) predictions.append(preds) empty_arr = np.zeros(shape=(10,10)) for i in tqdm_notebook(range(10)): preds1 = predictions[i] for j in range(i, 10): preds2 = predictions[j] # compute dissimilarity dissimilarity_score = 1-np.sum(np.equal(preds1, preds2))/10000 empty_arr[i][j] = dissimilarity_score if i is not j: empty_arr[j][i] = dissimilarity_score dissimilarity_coeff = empty_arr[::-1] plt.figure(figsize=(9,8)) sns.heatmap(dissimilarity_coeff, cmap='RdBu_r'); plt.xticks([0,2,4,6,8],[0,2,4,6,8]); plt.yticks([0,2,4,6,8],[8,6,4,2,1]); plt.savefig('independent_prediction_disagreement.png') # Get the weights of the input model. def get_model_weights(model): model_weights = [] # iterate through model layers. for layer in model.layers: # grab weights of that layer weights = layer.get_weights() # list # check if layer got triainable weights if len(weights)==0: continue # discard biases term, wrap with ndarray, flatten weights model_weights.extend(np.array(weights[0]).flatten()) return np.array(model_weights) weights_of_models = [] for i in tqdm_notebook(range(10)): # load model model = tf.keras.models.load_model(INDEPENDENT_MODEL_PATH+independent_models[i]) # get predictions for model weights = get_model_weights(model) weights_of_models.append(weights) empty_arr = np.zeros(shape=(10,10)) for i in tqdm_notebook(range(10)): weights1 = weights_of_models[i] for j in range(i, 10): weights2 = weights_of_models[j] # compute cosine similarity of weights cos_sim = np.dot(weights1, weights2)/(norm(weights1)*norm(weights2)) empty_arr[i][j] = cos_sim if i is not j: empty_arr[j][i] = cos_sim cos_sim_coeff = empty_arr[::-1] plt.figure(figsize=(9,8)) sns.heatmap(cos_sim_coeff, cmap='RdBu_r'); plt.xticks([0,2,4,6,8],[0,2,4,6,8]); plt.yticks([0,2,4,6,8],[8,6,4,2,1]); plt.savefig('independent_functional_similarity.png') wandb.init(entity='authors', project='loss-landscape', id='smallcnn_independent_model_investigations') wandb.log({'independent_prediction_disagreement': wandb.Image('independent_prediction_disagreement.png')}) wandb.log({'independent_functional_similarity': wandb.Image('independent_functional_similarity.png')}) NUM_EXAMPLES = 1024 NUM_CLASSES = 10 test_tsne_ds = testloader.unbatch().take(NUM_EXAMPLES).batch(BATCH_SIZE) # Given model and test data, return true_labels and predictions. def evaluate_tsne(test_dataloader, model): true_labels = [] pred_labels = [] for imgs, labels in iter(test_dataloader): preds = model.predict(imgs) true_labels.extend(labels) pred_labels.extend(preds) ## change here return np.array(true_labels), np.array(pred_labels) NUM_TRAJECTORIES = 3 predictions_for_tsne = [] for i in tqdm_notebook(range(NUM_TRAJECTORIES)): subdir = independent_models_tsne[i] model_files = os.listdir(INDEPENDENT_MODEL_PATH_tsne+subdir) model_files = sorted_nicely(model_files) predictions = [] for model_file in model_files: if model_file=='small_cnn_checkpoint_5.h5': # this check is because this model checkpoint didn't serialize properly. continue model = tf.keras.models.load_model(INDEPENDENT_MODEL_PATH_tsne+subdir+'/'+model_file) _, preds = evaluate_tsne(test_tsne_ds, model) predictions.append(preds) predictions = np.array(predictions) print(predictions.shape) predictions_for_tsne.append(predictions) # convert list to array predictions_for_tsne = np.array(predictions_for_tsne) print('[INFO] shape of predictions tensor: ', predictions_for_tsne.shape) # reshape the tensor reshaped_predictions_for_tsne = predictions_for_tsne.reshape([-1, NUM_EXAMPLES*NUM_CLASSES]) print('[INFO] shape of reshaped tensor: ', reshaped_predictions_for_tsne.shape) # initialize tsne object tsne = TSNE(n_components=2) # compute tsne prediction_embed = tsne.fit_transform(reshaped_predictions_for_tsne) print('[INFO] Shape of embedded tensor: ', prediction_embed.shape) # reshape trajectory_embed = prediction_embed.reshape([NUM_TRAJECTORIES, -1, 2]) print('[INFO] Shape of reshaped tensor: ', trajectory_embed.shape) # Plot plt.figure(constrained_layout=True, figsize=(6,6)) colors_list=['r', 'b', 'g'] labels_list = ['traj_{}'.format(i) for i in range(NUM_TRAJECTORIES)] for i in range(NUM_TRAJECTORIES): plt.plot(trajectory_embed[i,:,0],trajectory_embed[i,:,1],color = colors_list[i], alpha = 0.8,linestyle = "", marker = "o") plt.plot(trajectory_embed[i,:,0],trajectory_embed[i,:,1],color = colors_list[i], alpha = 0.3,linestyle = "-", marker = "") plt.plot(trajectory_embed[i,0,0],trajectory_embed[i,0,1],color = colors_list[i], alpha = 1.0,linestyle = "", marker = "*") plt.savefig('loss_landscape_2d.png') wandb.init(entity='authors', project='loss-landscape', id='small_cnn_trajectory_investigation') wandb.log({'loss_landscape_2d': wandb.Image('loss_landscape_2d.png')})
0.602763
0.850096
# Star with toruses This is an example of a synthesized three dimensional volume that is not easy to visualize using only two dimenaional projections. The calculation to generate the volume array is not optimized and it takes a while to complete. ``` import numpy as np from numpy.linalg import norm def vec(*args): return np.array(args, dtype=np.float) def normalize(V, epsilon=1e-12): nm = norm(V) if nm < epsilon: return vec(1, 0, 0) # whatever return (1.0 / nm) * V def point_segment_distance(P, segment, epsilon=1e-4): A = segment[0] B = segment[1] V = B - A nV2 = V.dot(V) if (nV2 < epsilon): #print("degenerate segment") return norm(B - P) lmd = V.dot(P - A) / nV2 if 0 < lmd and lmd < 1: #print("project onto line segment") Pprojection = A + lmd * V return norm(P - Pprojection) # otherwise distance to closer end point #print("closest end point") dA = norm(P - A) dB = norm(P - B) return min(dA, dB) def circle_distance(P, center, radius, normal): plane_distance = normal.dot(P - center) vertical_offset = plane_distance * normal plane_projection = P - vertical_offset direction_from_center = normalize(plane_projection - center) circle_nearest_point = center + radius * direction_from_center distance = norm(P - circle_nearest_point) return distance circle_distance(vec(1,1,1), vec(0,1,1), 2, normalize(vec(-1,2,-1))) # tetrahedral vertices vertices = vec([1,1,1], [-1,-1,1], [1,-1,-1], [-1,1,-1], ) normals = [] origin = vec(0,0,0) radius = 0.9 for v in vertices: normals.append(normalize(v)) def inverse_distance_sum(P, epsilon=0.1): total = 0.0 for (i, v) in enumerate(vertices): dsegment = point_segment_distance(P, [origin, v]) total += 1.0 / (dsegment + epsilon) normal = normals[i] dcircle = circle_distance(P, v, radius, normal) total += 1.0 / (dcircle + epsilon) return total for L in ([0,0,0], [-1, -1, -2], [1, -1, 1], [2,2,2], [1,1,1], [0,0,1]): print(L) P = vec(*L) print(" ", inverse_distance_sum(P)) # This computation takes a while (it has not been optimized.) N = 20 N2 = 2 * N N4 = 4 * N invN = 1.0 / N A = np.zeros((N4, N4, N4), dtype=np.float) def shifti(i): return (i - N2) * invN for i in range(N4): for j in range(N4): for k in range(N4): P = shifti(vec(i,j,k)) A[i, j, k] = inverse_distance_sum(P) from feedWebGL2 import volume H = A.mean() A.shape, H volume.widen_notebook() W = volume.Volume32() W W.load_3d_numpy_array(A, threshold=H, sorted=False) #W.load_3d_numpy_array(A, threshold=H, sorted=True, method="diagonal") x = W.build(1500) # Create a web folder containing the visualization if False: target_folder = "../docs/torus_html" from feedWebGL2 import html_generator html_generator.generate_volume_html(A, target_folder, force=False, width=1500) ```
github_jupyter
import numpy as np from numpy.linalg import norm def vec(*args): return np.array(args, dtype=np.float) def normalize(V, epsilon=1e-12): nm = norm(V) if nm < epsilon: return vec(1, 0, 0) # whatever return (1.0 / nm) * V def point_segment_distance(P, segment, epsilon=1e-4): A = segment[0] B = segment[1] V = B - A nV2 = V.dot(V) if (nV2 < epsilon): #print("degenerate segment") return norm(B - P) lmd = V.dot(P - A) / nV2 if 0 < lmd and lmd < 1: #print("project onto line segment") Pprojection = A + lmd * V return norm(P - Pprojection) # otherwise distance to closer end point #print("closest end point") dA = norm(P - A) dB = norm(P - B) return min(dA, dB) def circle_distance(P, center, radius, normal): plane_distance = normal.dot(P - center) vertical_offset = plane_distance * normal plane_projection = P - vertical_offset direction_from_center = normalize(plane_projection - center) circle_nearest_point = center + radius * direction_from_center distance = norm(P - circle_nearest_point) return distance circle_distance(vec(1,1,1), vec(0,1,1), 2, normalize(vec(-1,2,-1))) # tetrahedral vertices vertices = vec([1,1,1], [-1,-1,1], [1,-1,-1], [-1,1,-1], ) normals = [] origin = vec(0,0,0) radius = 0.9 for v in vertices: normals.append(normalize(v)) def inverse_distance_sum(P, epsilon=0.1): total = 0.0 for (i, v) in enumerate(vertices): dsegment = point_segment_distance(P, [origin, v]) total += 1.0 / (dsegment + epsilon) normal = normals[i] dcircle = circle_distance(P, v, radius, normal) total += 1.0 / (dcircle + epsilon) return total for L in ([0,0,0], [-1, -1, -2], [1, -1, 1], [2,2,2], [1,1,1], [0,0,1]): print(L) P = vec(*L) print(" ", inverse_distance_sum(P)) # This computation takes a while (it has not been optimized.) N = 20 N2 = 2 * N N4 = 4 * N invN = 1.0 / N A = np.zeros((N4, N4, N4), dtype=np.float) def shifti(i): return (i - N2) * invN for i in range(N4): for j in range(N4): for k in range(N4): P = shifti(vec(i,j,k)) A[i, j, k] = inverse_distance_sum(P) from feedWebGL2 import volume H = A.mean() A.shape, H volume.widen_notebook() W = volume.Volume32() W W.load_3d_numpy_array(A, threshold=H, sorted=False) #W.load_3d_numpy_array(A, threshold=H, sorted=True, method="diagonal") x = W.build(1500) # Create a web folder containing the visualization if False: target_folder = "../docs/torus_html" from feedWebGL2 import html_generator html_generator.generate_volume_html(A, target_folder, force=False, width=1500)
0.452778
0.93337
``` # Load dependencies import numpy as np import pandas as pd pd.options.display.float_format = '{:,.1e}'.format import sys sys.path.insert(0, '../../statistics_helper') from CI_helper import * from excel_utils import * ``` # Estimating the total biomass of terrestrial deep subsurface archaea and bacteria We use our best estimates for the total biomass of terrestrial deep subsurface prokaryotes and the fraction of archaea and bacteria out of the total population of terrestrial deep subsurface prokaryotes to estimate the total biomass of terrestrial deep subsurface bacteria and archaea. ``` results = pd.read_excel('terrestrial_deep_subsurface_prok_biomass_estimate.xlsx') results ``` We multiply all the relevant parameters to arrive at our best estimate for the biomass of terrestrial deep subsurface archaea and bacteria, and propagate the uncertainties associated with each parameter to calculate the uncertainty associated with the estimate for the total biomass. ``` # Calculate the total biomass of marine archaea and bacteria total_arch_biomass = results['Value'][0]*results['Value'][1] total_bac_biomass = results['Value'][0]*results['Value'][2] print('Our best estimate for the total biomass of terrestrial deep subsurface archaea is %.0f Gt C' %(total_arch_biomass/1e15)) print('Our best estimate for the total biomass of terrestrial deep subsurface bacteria is %.0f Gt C' %(total_bac_biomass/1e15)) # Propagate the uncertainty associated with each parameter to the final estimate arch_biomass_uncertainty = CI_prod_prop(results['Uncertainty'][:2]) bac_biomass_uncertainty = CI_prod_prop(results.iloc[[0,2]]['Uncertainty']) print('The uncertainty associated with the estimate for the biomass of archaea is %.1f-fold' %arch_biomass_uncertainty) print('The uncertainty associated with the estimate for the biomass of bacteria is %.1f-fold' %bac_biomass_uncertainty) # Feed bacteria results to Table 1 & Fig. 1 update_results(sheet='Table1 & Fig1', row=('Bacteria','Terrestrial deep subsurface'), col=['Biomass [Gt C]', 'Uncertainty'], values=[total_bac_biomass/1e15,bac_biomass_uncertainty], path='../../results.xlsx') # Feed archaea results to Table 1 & Fig. 1 update_results(sheet='Table1 & Fig1', row=('Archaea','Terrestrial deep subsurface'), col=['Biomass [Gt C]', 'Uncertainty'], values=[total_arch_biomass/1e15,arch_biomass_uncertainty], path='../../results.xlsx') # Feed bacteria results to Table S1 update_results(sheet='Table S1', row=('Bacteria','Terrestrial deep subsurface'), col=['Number of individuals'], values= results['Value'][0]*results['Value'][2]/results['Value'][3], path='../../results.xlsx') # Feed archaea results to Table S1 update_results(sheet='Table S1', row=('Archaea','Terrestrial deep subsurface'), col=['Number of individuals'], values= results['Value'][0]*results['Value'][1]/results['Value'][3], path='../../results.xlsx') ```
github_jupyter
# Load dependencies import numpy as np import pandas as pd pd.options.display.float_format = '{:,.1e}'.format import sys sys.path.insert(0, '../../statistics_helper') from CI_helper import * from excel_utils import * results = pd.read_excel('terrestrial_deep_subsurface_prok_biomass_estimate.xlsx') results # Calculate the total biomass of marine archaea and bacteria total_arch_biomass = results['Value'][0]*results['Value'][1] total_bac_biomass = results['Value'][0]*results['Value'][2] print('Our best estimate for the total biomass of terrestrial deep subsurface archaea is %.0f Gt C' %(total_arch_biomass/1e15)) print('Our best estimate for the total biomass of terrestrial deep subsurface bacteria is %.0f Gt C' %(total_bac_biomass/1e15)) # Propagate the uncertainty associated with each parameter to the final estimate arch_biomass_uncertainty = CI_prod_prop(results['Uncertainty'][:2]) bac_biomass_uncertainty = CI_prod_prop(results.iloc[[0,2]]['Uncertainty']) print('The uncertainty associated with the estimate for the biomass of archaea is %.1f-fold' %arch_biomass_uncertainty) print('The uncertainty associated with the estimate for the biomass of bacteria is %.1f-fold' %bac_biomass_uncertainty) # Feed bacteria results to Table 1 & Fig. 1 update_results(sheet='Table1 & Fig1', row=('Bacteria','Terrestrial deep subsurface'), col=['Biomass [Gt C]', 'Uncertainty'], values=[total_bac_biomass/1e15,bac_biomass_uncertainty], path='../../results.xlsx') # Feed archaea results to Table 1 & Fig. 1 update_results(sheet='Table1 & Fig1', row=('Archaea','Terrestrial deep subsurface'), col=['Biomass [Gt C]', 'Uncertainty'], values=[total_arch_biomass/1e15,arch_biomass_uncertainty], path='../../results.xlsx') # Feed bacteria results to Table S1 update_results(sheet='Table S1', row=('Bacteria','Terrestrial deep subsurface'), col=['Number of individuals'], values= results['Value'][0]*results['Value'][2]/results['Value'][3], path='../../results.xlsx') # Feed archaea results to Table S1 update_results(sheet='Table S1', row=('Archaea','Terrestrial deep subsurface'), col=['Number of individuals'], values= results['Value'][0]*results['Value'][1]/results['Value'][3], path='../../results.xlsx')
0.49585
0.839603
``` %matplotlib inline ``` 파이프라인 병렬화로 트랜스포머 모델 학습시키기 ============================================== **Author**: `Pritam Damania <https://github.com/pritamdamania87>`_ **번역**: `백선희 <https://github.com/spongebob03>`_ 이 튜토리얼은 파이프라인(pipeline) 병렬화(parallelism)를 사용하여 여러 GPU에 걸친 거대한 트랜스포머(transformer) 모델을 어떻게 학습시키는지 보여줍니다. `NN.TRANSFORMER 와 TORCHTEXT 로 시퀀스-투-시퀀스(SEQUENCE-TO-SEQUENCE) 모델링하기 <https://tutorials.pytorch.kr/beginner/transformer_tutorial.html>`__ 튜토리얼의 확장판이며 파이프라인 병렬화가 어떻게 트랜스포머 모델 학습에 쓰이는지 증명하기 위해 이전 튜토리얼에서의 모델 규모를 증가시켰습니다. 선수과목(Prerequisites): * `Pipeline Parallelism <https://pytorch.org/docs/stable/pipeline.html>`__ * `NN.TRANSFORMER 와 TORCHTEXT 로 시퀀스-투-시퀀스(SEQUENCE-TO-SEQUENCE) 모델링하기 <https://tutorials.pytorch.kr/beginner/transformer_tutorial.html>`__ 모델 정의하기 ------------- 이번 튜토리얼에서는, 트랜스포머 모델을 두 개의 GPU에 걸쳐서 나누고 파이프라인 병렬화로 학습시켜 보겠습니다. 모델은 바로 `NN.TRANSFORMER 와 TORCHTEXT 로 시퀀스-투-시퀀스(SEQUENCE-TO-SEQUENCE) 모델링하기 <https://tutorials.pytorch.kr/beginner/transformer_tutorial.html>`__ 튜토리얼과 똑같은 모델이지만 두 단계로 나뉩니다. 대부분 파라미터(parameter)들은 `nn.TransformerEncoder <https://pytorch.org/docs/stable/generated/torch.nn.TransformerEncoder.html>`__ 계층(layer)에 포함됩니다. `nn.TransformerEncoder <https://pytorch.org/docs/stable/generated/torch.nn.TransformerEncoder.html>`__ 는 `nn.TransformerEncoderLayer <https://pytorch.org/docs/stable/generated/torch.nn.TransformerEncoderLayer.html>`__ 의 ``nlayers`` 로 구성되어 있습니다. 결과적으로, 우리는 ``nn.TransformerEncoder`` 에 중점을 두고 있으며, ``nn.TransformerEncoderLayer`` 의 절반은 한 GPU에 두고 나머지 절반은 다른 GPU에 있도록 모델을 분할합니다. 이를 위해서 ``Encoder`` 와 ``Decoder`` 섹션을 분리된 모듈로 빼낸 다음, 원본 트랜스포머 모듈을 나타내는 nn.Sequential을 빌드 합니다. ``` import sys import math import torch import torch.nn as nn import torch.nn.functional as F import tempfile from torch.nn import TransformerEncoder, TransformerEncoderLayer if sys.platform == 'win32': print('Windows platform is not supported for pipeline parallelism') sys.exit(0) if torch.cuda.device_count() < 2: print('Need at least two GPU devices for this tutorial') sys.exit(0) class Encoder(nn.Module): def __init__(self, ntoken, ninp, dropout=0.5): super(Encoder, self).__init__() self.pos_encoder = PositionalEncoding(ninp, dropout) self.encoder = nn.Embedding(ntoken, ninp) self.ninp = ninp self.init_weights() def init_weights(self): initrange = 0.1 self.encoder.weight.data.uniform_(-initrange, initrange) def forward(self, src): # 인코더로 (S, N) 포맷이 필요합니다. src = src.t() src = self.encoder(src) * math.sqrt(self.ninp) return self.pos_encoder(src) class Decoder(nn.Module): def __init__(self, ntoken, ninp): super(Decoder, self).__init__() self.decoder = nn.Linear(ninp, ntoken) self.init_weights() def init_weights(self): initrange = 0.1 self.decoder.bias.data.zero_() self.decoder.weight.data.uniform_(-initrange, initrange) def forward(self, inp): # 파이프라인 결과물을 위해 먼저 배치 차원 필요합니다. return self.decoder(inp).permute(1, 0, 2) ``` ``PositionalEncoding`` 모듈은 시퀀스 안에서 토큰의 상대적인 또는 절대적인 포지션에 대한 정보를 주입합니다. 포지셔널 인코딩은 임베딩과 합칠 수 있도록 똑같은 차원을 가집니다. 여기서 다른 주기(frequency)의 ``sine`` 과 ``cosine`` 함수를 사용합니다. ``` class PositionalEncoding(nn.Module): def __init__(self, d_model, dropout=0.1, max_len=5000): super(PositionalEncoding, self).__init__() self.dropout = nn.Dropout(p=dropout) pe = torch.zeros(max_len, d_model) position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model)) pe[:, 0::2] = torch.sin(position * div_term) pe[:, 1::2] = torch.cos(position * div_term) pe = pe.unsqueeze(0).transpose(0, 1) self.register_buffer('pe', pe) def forward(self, x): x = x + self.pe[:x.size(0), :] return self.dropout(x) ``` 데이터 로드하고 배치 만들기 --------------------------- 학습 프로세스는 ``torchtext`` 의 Wikitext-2 데이터셋을 사용합니다. 단어 오브젝트는 훈련 데이터셋으로 만들어지고, 토큰을 텐서(tensor)로 수치화하는데 사용됩니다. 시퀀스 데이터로부터 시작하여, ``batchify()`` 함수는 데이터셋을 열(column)들로 정리하고, ``batch_size`` 사이즈의 배치들로 나눈 후에 남은 모든 토큰을 버립니다. 예를 들어, 알파벳을 시퀀스(총 길이 26)로 생각하고 배치 사이즈를 4라고 한다면, 알파벳을 길이가 6인 4개의 시퀀스로 나눌 수 있습니다: \begin{align}\begin{bmatrix} \text{A} & \text{B} & \text{C} & \ldots & \text{X} & \text{Y} & \text{Z} \end{bmatrix} \Rightarrow \begin{bmatrix} \begin{bmatrix}\text{A} \\ \text{B} \\ \text{C} \\ \text{D} \\ \text{E} \\ \text{F}\end{bmatrix} & \begin{bmatrix}\text{G} \\ \text{H} \\ \text{I} \\ \text{J} \\ \text{K} \\ \text{L}\end{bmatrix} & \begin{bmatrix}\text{M} \\ \text{N} \\ \text{O} \\ \text{P} \\ \text{Q} \\ \text{R}\end{bmatrix} & \begin{bmatrix}\text{S} \\ \text{T} \\ \text{U} \\ \text{V} \\ \text{W} \\ \text{X}\end{bmatrix} \end{bmatrix}\end{align} 이 열들은 모델에 의해서 독립적으로 취급되며, 이는 ``G`` 와 ``F`` 의 의존성이 학습될 수 없다는 것을 의미하지만, 더 효율적인 배치 프로세싱(batch processing)을 허용합니다. ``` import torch from torchtext.datasets import WikiText2 from torchtext.data.utils import get_tokenizer from torchtext.vocab import build_vocab_from_iterator train_iter = WikiText2(split='train') tokenizer = get_tokenizer('basic_english') vocab = build_vocab_from_iterator(map(tokenizer, train_iter), specials=["<unk>"]) vocab.set_default_index(vocab["<unk>"]) def data_process(raw_text_iter): data = [torch.tensor(vocab(tokenizer(item)), dtype=torch.long) for item in raw_text_iter] return torch.cat(tuple(filter(lambda t: t.numel() > 0, data))) train_iter, val_iter, test_iter = WikiText2() train_data = data_process(train_iter) val_data = data_process(val_iter) test_data = data_process(test_iter) device = torch.device("cuda") def batchify(data, bsz): # 데이터셋을 bsz 파트들로 나눕니다. nbatch = data.size(0) // bsz # 깔끔하게 나누어 떨어지지 않는 추가적인 부분(나머지)은 잘라냅니다. data = data.narrow(0, 0, nbatch * bsz) # 데이터를 bsz 배치들로 동일하게 나눕니다. data = data.view(bsz, -1).t().contiguous() return data.to(device) batch_size = 20 eval_batch_size = 10 train_data = batchify(train_data, batch_size) val_data = batchify(val_data, eval_batch_size) test_data = batchify(test_data, eval_batch_size) ``` 입력과 타겟 시퀀스를 생성하기 위한 함수들 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``get_batch()`` 함수는 트랜스포머 모델을 위한 입력과 타겟 시퀀스를 생성합니다. 이 함수는 소스 데이터를 ``bptt`` 길이를 가진 덩어리로 세분화합니다. 언어 모델링 과제를 위해서, 모델은 다음 단어인 ``Target`` 이 필요합니다. 에를 들어 ``bptt`` 의 값이 2라면, ``i`` = 0 일 때 다음의 2 개 변수(Variable)를 얻을 수 있습니다: ![](../_static/img/transformer_input_target.png) 변수 덩어리는 트랜스포머 모델의 ``S`` 차원과 일치하는 0 차원에 해당합니다. 배치 차원 ``N`` 은 1 차원에 해당합니다. ``` bptt = 25 def get_batch(source, i): seq_len = min(bptt, len(source) - 1 - i) data = source[i:i+seq_len] target = source[i+1:i+1+seq_len].view(-1) # 파이프라인 병렬화를 위해 먼저 배치 차원이 필요합니다. return data.t(), target ``` 모델 규모와 파이프 초기화 ------------------------- 파이프라인 병렬화를 활용한 대형 트랜스포머 모델 학습을 증명하기 위해서 트랜스포머 계층 규모를 적절히 확장시킵니다. 4096차원의 임베딩 벡터, 4096의 은닉 사이즈, 16개의 어텐션 헤드(attention head)와 총 12 개의 트랜스포머 계층 (``nn.TransformerEncoderLayer``)를 사용합니다. 이는 최대 **1.4억** 개의 파라미터를 갖는 모델을 생성합니다. Pipe는 `RRef <https://pytorch.org/docs/stable/rpc.html#rref>`__ 를 통해 `RPC 프레임워크 <https://pytorch.org/docs/stable/rpc.html>`__ 에 의존하는데 이는 향후 호스트 파이프라인을 교차 확장할 수 있도록 하기 때문에 RPC 프레임워크를 초기화해야 합니다. 이때 RPC 프레임워크는 오직 하나의 하나의 worker로 초기화를 해야 하는데, 여러 GPU를 다루기 위해 프로세스 하나만 사용하고 있기 때문입니다. 그런 다음 파이프라인은 한 GPU에 8개의 트랜스포머와 다른 GPU에 8개의 트랜스포머 레이어로 초기화됩니다. <div class="alert alert-info"><h4>Note</h4><p>효율성을 위해 ``Pipe`` 에 전달된 ``nn.Sequential`` 이 오직 두 개의 요소(2개의 GPU)로만 구성되도록 합니다. 이렇게 하면 Pipe가 두 개의 파티션에서만 작동하고 파티션 간 오버헤드를 피할 수 있습니다.</p></div> ``` ntokens = len(vocab) # 단어 사전(어휘집)의 크기 emsize = 4096 # 임베딩 차원 nhid = 4096 # nn.TransformerEncoder 에서 순전파(feedforward) 신경망 모델의 차원 nlayers = 12 # nn.TransformerEncoder 내부의 nn.TransformerEncoderLayer 개수 nhead = 16 # multiheadattention 모델의 헤드 개수 dropout = 0.2 # dropout 값 from torch.distributed import rpc tmpfile = tempfile.NamedTemporaryFile() rpc.init_rpc( name="worker", rank=0, world_size=1, rpc_backend_options=rpc.TensorPipeRpcBackendOptions( init_method="file://{}".format(tmpfile.name), # _transports와 _channels를 지정하는 것이 해결 방법이며 # PyTorch 버전 >= 1.8.1 에서는 _transports와 _channels를 # 지정하지 않아도 됩니다. _transports=["ibv", "uv"], _channels=["cuda_ipc", "cuda_basic"], ) ) num_gpus = 2 partition_len = ((nlayers - 1) // num_gpus) + 1 # 처음에 인코더를 추가합니다. tmp_list = [Encoder(ntokens, emsize, dropout).cuda(0)] module_list = [] # 필요한 모든 트랜스포머 블록들을 추가합니다. for i in range(nlayers): transformer_block = TransformerEncoderLayer(emsize, nhead, nhid, dropout) if i != 0 and i % (partition_len) == 0: module_list.append(nn.Sequential(*tmp_list)) tmp_list = [] device = i // (partition_len) tmp_list.append(transformer_block.to(device)) # 마지막에 디코더를 추가합니다. tmp_list.append(Decoder(ntokens, emsize).cuda(num_gpus - 1)) module_list.append(nn.Sequential(*tmp_list)) from torch.distributed.pipeline.sync import Pipe # 파이프라인을 빌드합니다. chunks = 8 model = Pipe(torch.nn.Sequential(*module_list), chunks = chunks) def get_total_params(module: torch.nn.Module): total_params = 0 for param in module.parameters(): total_params += param.numel() return total_params print ('Total parameters in model: {:,}'.format(get_total_params(model))) ``` 모델 실행하기 ------------- 손실(loss)을 추적하기 위해 `CrossEntropyLoss <https://pytorch.org/docs/master/nn.html?highlight=crossentropyloss#torch.nn.CrossEntropyLoss>`__ 가 적용되며, 옵티마이저(optimizer)로서 `SGD <https://pytorch.org/docs/master/optim.html?highlight=sgd#torch.optim.SGD>`__ 는 확률적 경사하강법(stochastic gradient descent method)을 구현합니다. 초기 학습률(learning rate)은 5.0로 설정됩니다. `StepLR <https://pytorch.org/docs/master/optim.html?highlight=steplr#torch.optim.lr_scheduler.StepLR>`__ 는 에폭(epoch)에 따라서 학습률을 조절하는 데 사용됩니다. 학습하는 동안, 기울기 폭발(gradient exploding)을 방지하기 위해 모든 기울기를 함께 조정(scale)하는 함수 `nn.utils.clip_grad_norm\_ <https://pytorch.org/docs/master/nn.html?highlight=nn%20utils%20clip_grad_norm#torch.nn.utils.clip_grad_norm_>`__ 을 이용합니다. ``` criterion = nn.CrossEntropyLoss() lr = 5.0 # 학습률 optimizer = torch.optim.SGD(model.parameters(), lr=lr) scheduler = torch.optim.lr_scheduler.StepLR(optimizer, 1.0, gamma=0.95) import time def train(): model.train() # 훈련 모드로 전환 total_loss = 0. start_time = time.time() ntokens = len(vocab) # 스크립트 실행 시간을 짧게 유지하기 위해서 50 배치만 학습합니다. nbatches = min(50 * bptt, train_data.size(0) - 1) for batch, i in enumerate(range(0, nbatches, bptt)): data, targets = get_batch(train_data, i) optimizer.zero_grad() # Pipe는 단일 호스트 내에 있고 # forward 메서드로 반환된 ``RRef`` 프로세스는 이 노드에 국한되어 있기 때문에 # ``RRef.local_value()`` 를 통해 간단히 찾을 수 있습니다. output = model(data).local_value() # 타겟을 파이프라인 출력이 있는 # 장치로 옮겨야합니다. loss = criterion(output.view(-1, ntokens), targets.cuda(1)) loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), 0.5) optimizer.step() total_loss += loss.item() log_interval = 10 if batch % log_interval == 0 and batch > 0: cur_loss = total_loss / log_interval elapsed = time.time() - start_time print('| epoch {:3d} | {:5d}/{:5d} batches | ' 'lr {:02.2f} | ms/batch {:5.2f} | ' 'loss {:5.2f} | ppl {:8.2f}'.format( epoch, batch, nbatches // bptt, scheduler.get_lr()[0], elapsed * 1000 / log_interval, cur_loss, math.exp(cur_loss))) total_loss = 0 start_time = time.time() def evaluate(eval_model, data_source): eval_model.eval() # 평가 모드로 전환 total_loss = 0. ntokens = len(vocab) # 스크립트 실행 시간을 짧게 유지하기 위해 50 배치만 평가합니다. nbatches = min(50 * bptt, data_source.size(0) - 1) with torch.no_grad(): for i in range(0, nbatches, bptt): data, targets = get_batch(data_source, i) output = eval_model(data).local_value() output_flat = output.view(-1, ntokens) # 타겟을 파이프라인 출력이 있는 # 장치로 옮겨야합니다. total_loss += len(data) * criterion(output_flat, targets.cuda(1)).item() return total_loss / (len(data_source) - 1) ``` 에폭을 반복합니다. 만약 검증 오차(validation loss)가 지금까지 관찰한 것 중 최적이라면 모델을 저장합니다. 각 에폭 이후에 학습률을 조절합니다. ``` best_val_loss = float("inf") epochs = 3 # 에폭 수 best_model = None for epoch in range(1, epochs + 1): epoch_start_time = time.time() train() val_loss = evaluate(model, val_data) print('-' * 89) print('| end of epoch {:3d} | time: {:5.2f}s | valid loss {:5.2f} | ' 'valid ppl {:8.2f}'.format(epoch, (time.time() - epoch_start_time), val_loss, math.exp(val_loss))) print('-' * 89) if val_loss < best_val_loss: best_val_loss = val_loss best_model = model scheduler.step() ``` 평가 데이터셋으로 모델 평가하기 ------------------------------- 평가 데이터셋에서의 결과를 확인하기 위해 최고의 모델을 적용합니다. ``` test_loss = evaluate(best_model, test_data) print('=' * 89) print('| End of training | test loss {:5.2f} | test ppl {:8.2f}'.format( test_loss, math.exp(test_loss))) print('=' * 89) ```
github_jupyter
%matplotlib inline import sys import math import torch import torch.nn as nn import torch.nn.functional as F import tempfile from torch.nn import TransformerEncoder, TransformerEncoderLayer if sys.platform == 'win32': print('Windows platform is not supported for pipeline parallelism') sys.exit(0) if torch.cuda.device_count() < 2: print('Need at least two GPU devices for this tutorial') sys.exit(0) class Encoder(nn.Module): def __init__(self, ntoken, ninp, dropout=0.5): super(Encoder, self).__init__() self.pos_encoder = PositionalEncoding(ninp, dropout) self.encoder = nn.Embedding(ntoken, ninp) self.ninp = ninp self.init_weights() def init_weights(self): initrange = 0.1 self.encoder.weight.data.uniform_(-initrange, initrange) def forward(self, src): # 인코더로 (S, N) 포맷이 필요합니다. src = src.t() src = self.encoder(src) * math.sqrt(self.ninp) return self.pos_encoder(src) class Decoder(nn.Module): def __init__(self, ntoken, ninp): super(Decoder, self).__init__() self.decoder = nn.Linear(ninp, ntoken) self.init_weights() def init_weights(self): initrange = 0.1 self.decoder.bias.data.zero_() self.decoder.weight.data.uniform_(-initrange, initrange) def forward(self, inp): # 파이프라인 결과물을 위해 먼저 배치 차원 필요합니다. return self.decoder(inp).permute(1, 0, 2) class PositionalEncoding(nn.Module): def __init__(self, d_model, dropout=0.1, max_len=5000): super(PositionalEncoding, self).__init__() self.dropout = nn.Dropout(p=dropout) pe = torch.zeros(max_len, d_model) position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model)) pe[:, 0::2] = torch.sin(position * div_term) pe[:, 1::2] = torch.cos(position * div_term) pe = pe.unsqueeze(0).transpose(0, 1) self.register_buffer('pe', pe) def forward(self, x): x = x + self.pe[:x.size(0), :] return self.dropout(x) import torch from torchtext.datasets import WikiText2 from torchtext.data.utils import get_tokenizer from torchtext.vocab import build_vocab_from_iterator train_iter = WikiText2(split='train') tokenizer = get_tokenizer('basic_english') vocab = build_vocab_from_iterator(map(tokenizer, train_iter), specials=["<unk>"]) vocab.set_default_index(vocab["<unk>"]) def data_process(raw_text_iter): data = [torch.tensor(vocab(tokenizer(item)), dtype=torch.long) for item in raw_text_iter] return torch.cat(tuple(filter(lambda t: t.numel() > 0, data))) train_iter, val_iter, test_iter = WikiText2() train_data = data_process(train_iter) val_data = data_process(val_iter) test_data = data_process(test_iter) device = torch.device("cuda") def batchify(data, bsz): # 데이터셋을 bsz 파트들로 나눕니다. nbatch = data.size(0) // bsz # 깔끔하게 나누어 떨어지지 않는 추가적인 부분(나머지)은 잘라냅니다. data = data.narrow(0, 0, nbatch * bsz) # 데이터를 bsz 배치들로 동일하게 나눕니다. data = data.view(bsz, -1).t().contiguous() return data.to(device) batch_size = 20 eval_batch_size = 10 train_data = batchify(train_data, batch_size) val_data = batchify(val_data, eval_batch_size) test_data = batchify(test_data, eval_batch_size) bptt = 25 def get_batch(source, i): seq_len = min(bptt, len(source) - 1 - i) data = source[i:i+seq_len] target = source[i+1:i+1+seq_len].view(-1) # 파이프라인 병렬화를 위해 먼저 배치 차원이 필요합니다. return data.t(), target ntokens = len(vocab) # 단어 사전(어휘집)의 크기 emsize = 4096 # 임베딩 차원 nhid = 4096 # nn.TransformerEncoder 에서 순전파(feedforward) 신경망 모델의 차원 nlayers = 12 # nn.TransformerEncoder 내부의 nn.TransformerEncoderLayer 개수 nhead = 16 # multiheadattention 모델의 헤드 개수 dropout = 0.2 # dropout 값 from torch.distributed import rpc tmpfile = tempfile.NamedTemporaryFile() rpc.init_rpc( name="worker", rank=0, world_size=1, rpc_backend_options=rpc.TensorPipeRpcBackendOptions( init_method="file://{}".format(tmpfile.name), # _transports와 _channels를 지정하는 것이 해결 방법이며 # PyTorch 버전 >= 1.8.1 에서는 _transports와 _channels를 # 지정하지 않아도 됩니다. _transports=["ibv", "uv"], _channels=["cuda_ipc", "cuda_basic"], ) ) num_gpus = 2 partition_len = ((nlayers - 1) // num_gpus) + 1 # 처음에 인코더를 추가합니다. tmp_list = [Encoder(ntokens, emsize, dropout).cuda(0)] module_list = [] # 필요한 모든 트랜스포머 블록들을 추가합니다. for i in range(nlayers): transformer_block = TransformerEncoderLayer(emsize, nhead, nhid, dropout) if i != 0 and i % (partition_len) == 0: module_list.append(nn.Sequential(*tmp_list)) tmp_list = [] device = i // (partition_len) tmp_list.append(transformer_block.to(device)) # 마지막에 디코더를 추가합니다. tmp_list.append(Decoder(ntokens, emsize).cuda(num_gpus - 1)) module_list.append(nn.Sequential(*tmp_list)) from torch.distributed.pipeline.sync import Pipe # 파이프라인을 빌드합니다. chunks = 8 model = Pipe(torch.nn.Sequential(*module_list), chunks = chunks) def get_total_params(module: torch.nn.Module): total_params = 0 for param in module.parameters(): total_params += param.numel() return total_params print ('Total parameters in model: {:,}'.format(get_total_params(model))) criterion = nn.CrossEntropyLoss() lr = 5.0 # 학습률 optimizer = torch.optim.SGD(model.parameters(), lr=lr) scheduler = torch.optim.lr_scheduler.StepLR(optimizer, 1.0, gamma=0.95) import time def train(): model.train() # 훈련 모드로 전환 total_loss = 0. start_time = time.time() ntokens = len(vocab) # 스크립트 실행 시간을 짧게 유지하기 위해서 50 배치만 학습합니다. nbatches = min(50 * bptt, train_data.size(0) - 1) for batch, i in enumerate(range(0, nbatches, bptt)): data, targets = get_batch(train_data, i) optimizer.zero_grad() # Pipe는 단일 호스트 내에 있고 # forward 메서드로 반환된 ``RRef`` 프로세스는 이 노드에 국한되어 있기 때문에 # ``RRef.local_value()`` 를 통해 간단히 찾을 수 있습니다. output = model(data).local_value() # 타겟을 파이프라인 출력이 있는 # 장치로 옮겨야합니다. loss = criterion(output.view(-1, ntokens), targets.cuda(1)) loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), 0.5) optimizer.step() total_loss += loss.item() log_interval = 10 if batch % log_interval == 0 and batch > 0: cur_loss = total_loss / log_interval elapsed = time.time() - start_time print('| epoch {:3d} | {:5d}/{:5d} batches | ' 'lr {:02.2f} | ms/batch {:5.2f} | ' 'loss {:5.2f} | ppl {:8.2f}'.format( epoch, batch, nbatches // bptt, scheduler.get_lr()[0], elapsed * 1000 / log_interval, cur_loss, math.exp(cur_loss))) total_loss = 0 start_time = time.time() def evaluate(eval_model, data_source): eval_model.eval() # 평가 모드로 전환 total_loss = 0. ntokens = len(vocab) # 스크립트 실행 시간을 짧게 유지하기 위해 50 배치만 평가합니다. nbatches = min(50 * bptt, data_source.size(0) - 1) with torch.no_grad(): for i in range(0, nbatches, bptt): data, targets = get_batch(data_source, i) output = eval_model(data).local_value() output_flat = output.view(-1, ntokens) # 타겟을 파이프라인 출력이 있는 # 장치로 옮겨야합니다. total_loss += len(data) * criterion(output_flat, targets.cuda(1)).item() return total_loss / (len(data_source) - 1) best_val_loss = float("inf") epochs = 3 # 에폭 수 best_model = None for epoch in range(1, epochs + 1): epoch_start_time = time.time() train() val_loss = evaluate(model, val_data) print('-' * 89) print('| end of epoch {:3d} | time: {:5.2f}s | valid loss {:5.2f} | ' 'valid ppl {:8.2f}'.format(epoch, (time.time() - epoch_start_time), val_loss, math.exp(val_loss))) print('-' * 89) if val_loss < best_val_loss: best_val_loss = val_loss best_model = model scheduler.step() test_loss = evaluate(best_model, test_data) print('=' * 89) print('| End of training | test loss {:5.2f} | test ppl {:8.2f}'.format( test_loss, math.exp(test_loss))) print('=' * 89)
0.611962
0.958402
# Tutorial: topic modeling to analyze the EGC conference EGC is a French-speaking conference on knowledge discovery in databases (KDD). In this notebook we show how to use TOM for inferring latent topics that pervade the corpus of articles published at EGC between 2004 and 2015 using non-negative matrix factorization. Based on the discovered topics we use TOM to shed light on interesting facts on the topical structure of the EGC society. ## Loading and vectorizing the corpus We prune words which absolute frequency in the corpus is less than 4, as well as words which relative frequency is higher than 80%, with the aim to only keep the most significant ones. Eventually, we build the vector space representation of these articles with $tf \cdot idf$ weighting. It is a $n \times m$ matrix denoted by $A$, where each line represents an article, with $n = 817$ (i.e. the number of articles) and $m = 1738$ (i.e. the number of words). ``` from tom_lib.structure.corpus import Corpus from tom_lib.visualization.visualization import Visualization corpus = Corpus(source_file_path='input/egc_lemmatized.csv', language='french', vectorization='tfidf', max_relative_frequency=0.8, min_absolute_frequency=4) print('corpus size:', corpus.size) print('vocabulary size:', len(corpus.vocabulary)) ``` ## Estimating the optimal number of topics ($k$) Non-negative matrix factorization approximates $A$, the document-term matrix, in the following way: $$ A \approx HW $$ where $H$ is a $n \times k$ matrix that describes the documents in terms of topics, and $W$ is a $k \times m$ matrix that describes topics in terms of words. More precisely, the coefficient $h_{i,j}$ defines the importance of topic $j$ in article $i$, and the coefficient $w_{i,j}$ defines the importance of word $j$ in topic $i$. Determining an appropriate value of $k$ is critical to ensure a pertinent analysis of the EGC anthology. If $k$ is too small, then the discovered topics will be too vague; if $k$ is too large, then the discovered topics will be too narrow and may be redundant. To help us with this task, we compute two metrics implemented in TOM : the stability metric proposed by Greene et al. (2014) and the spectral metric proposed by Arun et al. (2010). ``` from tom_lib.nlp.topic_model import NonNegativeMatrixFactorization topic_model = NonNegativeMatrixFactorization(corpus) ``` ### Weighted Jaccard average stability The figure below shows this metric for a number of topics varying between 5 and 50 (higher is better). ``` from bokeh.io import show, output_notebook from bokeh.plotting import figure output_notebook() p = figure(plot_height=250) p.line(range(10, 51), topic_model.greene_metric(min_num_topics=10, step=1, max_num_topics=50, top_n_words=10, tao=10), line_width=2) show(p) ``` ### Symmetric Kullback-Liebler divergence The figure below shows this metric for a number of topics varying between 5 and 50 (lower is better). ``` p = figure(plot_height=250) p.line(range(10, 51), topic_model.arun_metric(min_num_topics=10, max_num_topics=50, iterations=10), line_width=2) show(p) ``` Guided by the two metrics described previously, we manually evaluate the quality of the topics identified with $k$ varying between 15 and 20. Eventually, we judge that the best results are achieved with NMF for $k=15$. ``` k = 15 topic_model.infer_topics(num_topics=k) ``` ## Results ### Description of the discovered topics The table below lists the most relevant words for each of the 15 topics discovered from the articles with NMF. They reveal that the people who form the EGC society are interested in a wide variety of both theoretical and applied issues. For instance, topics 11 and 12 are related to theoretical issues: topic 11 covers papers about model and variable selection, and topic 12 covers papers that propose new or improved learning algorithms. On the other hand, topics 0 and 6 are related to applied issues: topic 13 covers papers about social network analysis, and topic 6 covers papers about Web usage mining. ``` import pandas as pd pd.set_option('display.max_colwidth', 500) d = {'Most relevant words': [', '.join([word for word, weight in topic_model.top_words(i, 10)]) for i in range(k)]} df = pd.DataFrame(data=d) df.head(k) ``` In the following, we leverage the discovered topics to highlight interesting particularities about the EGC society. To be able to analyze the topics, supplemented with information about the related papers, we partition the papers into 15 non-overlapping clusters, i.e. a cluster per topic. Each article $i \in [0;1-n]$ is assigned to the cluster $j$ that corresponds to the topic with the highest weight $w_{ij}$: \begin{equation} \text{cluster}_i = \underset{j}{\mathrm{argmax}}(w_{i,j}) \label{eq:cluster} \end{equation} ### Global topic proportions ``` p = figure(x_range=[str(_) for _ in range(k)], plot_height=350, x_axis_label='topic', y_axis_label='proportion') p.vbar(x=[str(_) for _ in range(k)], top=topic_model.topics_frequency(), width=0.7) show(p) ``` ### Shifting attention, evolving interests Here we focus on topics topics 12 (social network analysis and mining) and 3 (association rule mining). The following figures describe these topics in terms of their respective top 10 words and top 3 documents. ``` def plot_top_words(topic_id): words = [word for word, weight in topic_model.top_words(topic_id, 10)] weights = [weight for word, weight in topic_model.top_words(topic_id, 10)] p = figure(x_range=words, plot_height=300, plot_width=800, x_axis_label='word', y_axis_label='weight') p.vbar(x=words, top=weights, width=0.7) show(p) def top_documents_df(topic_id): top_docs = topic_model.top_documents(topic_id, 3) d = {'Article title': [corpus.title(doc_id) for doc_id, weight in top_docs], 'Year': [int(corpus.date(doc_id)) for doc_id, weight in top_docs]} df = pd.DataFrame(data=d) return df ``` #### Topic #12 ##### Top 10 words ``` plot_top_words(12) ``` ##### Top 3 articles ``` top_documents_df(12).head() ``` #### Topic #3 ##### Top 10 words ``` plot_top_words(3) ``` ##### Top 3 articles ``` top_documents_df(3).head() ``` #### Evolution of the frequencies of topics 3 and 12 The figure below shows the frequency of topics 12 (social network analysis and mining) and 3 (association rule mining) per year, from 2004 until 2015. The frequency of a topic for a given year is defined as the proportion of articles, among those published this year, that belong to the corresponding cluster. This figure reveals two opposite trends: topic 12 is emerging and topic 3 is fading over time. While there was apparently no article about social network analysis in 2004, in 2013, 12% of the articles presented at the conference were related to this topic. In contrast, papers related to association rule mining were the most frequent in 2006 (12%), but their frequency dropped down to as low as 0.2% in 2014. This illustrates how the attention of the members of the EGC society is shifting between topics through time. This goes on to show that the EGC society is evolving and is enlarging its scope to incorporate works about novel issues. ``` p = figure(plot_height=250, x_axis_label='year', y_axis_label='topic frequency') p.line(range(2004, 2015), [topic_model.topic_frequency(3, date=i) for i in range(2004, 2015)], line_width=2, line_color='blue', legend='topic #3') p.line(range(2004, 2015), [topic_model.topic_frequency(12, date=i) for i in range(2004, 2015)], line_width=2, line_color='red', legend='topic #12') show(p) ```
github_jupyter
from tom_lib.structure.corpus import Corpus from tom_lib.visualization.visualization import Visualization corpus = Corpus(source_file_path='input/egc_lemmatized.csv', language='french', vectorization='tfidf', max_relative_frequency=0.8, min_absolute_frequency=4) print('corpus size:', corpus.size) print('vocabulary size:', len(corpus.vocabulary)) from tom_lib.nlp.topic_model import NonNegativeMatrixFactorization topic_model = NonNegativeMatrixFactorization(corpus) from bokeh.io import show, output_notebook from bokeh.plotting import figure output_notebook() p = figure(plot_height=250) p.line(range(10, 51), topic_model.greene_metric(min_num_topics=10, step=1, max_num_topics=50, top_n_words=10, tao=10), line_width=2) show(p) p = figure(plot_height=250) p.line(range(10, 51), topic_model.arun_metric(min_num_topics=10, max_num_topics=50, iterations=10), line_width=2) show(p) k = 15 topic_model.infer_topics(num_topics=k) import pandas as pd pd.set_option('display.max_colwidth', 500) d = {'Most relevant words': [', '.join([word for word, weight in topic_model.top_words(i, 10)]) for i in range(k)]} df = pd.DataFrame(data=d) df.head(k) p = figure(x_range=[str(_) for _ in range(k)], plot_height=350, x_axis_label='topic', y_axis_label='proportion') p.vbar(x=[str(_) for _ in range(k)], top=topic_model.topics_frequency(), width=0.7) show(p) def plot_top_words(topic_id): words = [word for word, weight in topic_model.top_words(topic_id, 10)] weights = [weight for word, weight in topic_model.top_words(topic_id, 10)] p = figure(x_range=words, plot_height=300, plot_width=800, x_axis_label='word', y_axis_label='weight') p.vbar(x=words, top=weights, width=0.7) show(p) def top_documents_df(topic_id): top_docs = topic_model.top_documents(topic_id, 3) d = {'Article title': [corpus.title(doc_id) for doc_id, weight in top_docs], 'Year': [int(corpus.date(doc_id)) for doc_id, weight in top_docs]} df = pd.DataFrame(data=d) return df plot_top_words(12) top_documents_df(12).head() plot_top_words(3) top_documents_df(3).head() p = figure(plot_height=250, x_axis_label='year', y_axis_label='topic frequency') p.line(range(2004, 2015), [topic_model.topic_frequency(3, date=i) for i in range(2004, 2015)], line_width=2, line_color='blue', legend='topic #3') p.line(range(2004, 2015), [topic_model.topic_frequency(12, date=i) for i in range(2004, 2015)], line_width=2, line_color='red', legend='topic #12') show(p)
0.590307
0.983375
<a href="https://colab.research.google.com/github/Lilchoto3/DS-Unit-2-Linear-Models/blob/master/module3-ridge-regression/LS_DS_213.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Lambda School Data Science *Unit 2, Sprint 1, Module 3* --- # Ridge Regression - Do one-hot encoding of categorical features - Do univariate feature selection - Use scikit-learn to fit Ridge Regression models ### Setup You can work locally (follow the [local setup instructions](https://lambdaschool.github.io/ds/unit2/local/)) or on Colab (run the code cell below). Libraries: - category_encoders - matplotlib - numpy - pandas - scikit-learn ``` %%capture import sys # If you're on Colab: if 'google.colab' in sys.modules: DATA_PATH = 'https://raw.githubusercontent.com/LambdaSchool/DS-Unit-2-Applied-Modeling/master/data/' !pip install category_encoders==2.* # If you're working locally: else: DATA_PATH = '../data/' ``` # Do one-hot encoding of categorical features ## Overview First, let's load the NYC apartment rental listing data: ``` import numpy as np import pandas as pd # Read New York City apartment rental listing data df = pd.read_csv(DATA_PATH+'apartments/renthop-nyc.csv') assert df.shape == (49352, 34) # Remove the most extreme 1% prices, # the most extreme .1% latitudes, & # the most extreme .1% longitudes df = df[(df['price'] >= np.percentile(df['price'], 0.5)) & (df['price'] <= np.percentile(df['price'], 99.5)) & (df['latitude'] >= np.percentile(df['latitude'], 0.05)) & (df['latitude'] < np.percentile(df['latitude'], 99.95)) & (df['longitude'] >= np.percentile(df['longitude'], 0.05)) & (df['longitude'] <= np.percentile(df['longitude'], 99.95))] # Do train/test split # Use data from April & May 2016 to train # Use data from June 2016 to test df['created'] = pd.to_datetime(df['created'], infer_datetime_format=True) cutoff = pd.to_datetime('2016-06-01') train = df[df.created < cutoff] test = df[df.created >= cutoff] ``` Some columns are numeric: ``` # TODO train.describe() ``` Some columns are _not_ numeric: ``` # TODO train.describe(include='object') ``` Let's look at the relationship between `interest_level` and `price`: ``` # TODO train['interest_level'].value_counts() train.groupby('interest_level')['price'].mean() ``` Interest Level seems like a useful, predictive feature. But it's a string — and our scikit-learn models expect all inputs to be numbers. So, we can "one-hot encode" the feature. To go from this: | interest_level | |----------------| | high | | medium | | low | To this: | interest_level_high | interest_level_medium | interest_level_low | |---------------------|-----------------------|--------------------| | 1 | 0 | 0 | | 0 | 1 | 0 | | 0 | 0 | 1 | "One-hot encoding" adds a dimension for each unique value of each categorical feature. So, it may not be a good choice for "high cardinality" categoricals that have dozens, hundreds, or thousands of unique values. [Cardinality](https://simple.wikipedia.org/wiki/Cardinality) means the number of unique values that a feature has: > In mathematics, the cardinality of a set means the number of its elements. For example, the set A = {2, 4, 6} contains 3 elements, and therefore A has a cardinality of 3. ## Follow Along The other non-numeric columns have high cardinality. So let's exclude them from our features for now. ``` # TODO target = 'price' high_cardinality = ['display_address','street_address','description','created'] features = train.columns.drop([target] + high_cardinality) ``` Here's what `X_train` looks like **before** encoding: ``` # TODO X_train = train[features] y_train = train[target] X_test = test[features] y_test = test[target] ``` Use [OneHotEncoder](https://contrib.scikit-learn.org/categorical-encoding/onehot.html) from the [category_encoders](https://github.com/scikit-learn-contrib/categorical-encoding) library to encode any non-numeric features. (In this case, it's just `interest_level`.) - Use the **`fit_transform`** method on the **train** set - Use the **`transform`** method on **validation / test** sets ``` # TODO df.shape, X_train.shape, X_test.shape ``` Here's what it looks like **after:** ``` # TODO import category_encoders as ce encoder = ce.OneHotEncoder(use_cat_names=True) X_train = encoder.fit_transform(X_train) X_train.head() X_train[['interest_level_high','interest_level_medium','interest_level_low']].head() X_test = encoder.transform(X_test) X_test.head() ``` ## Challenge In your assignment, you will do one-hot encoding of categorical features with feasible cardinality, using the category_encoders library. # Do univariate feature selection ## Overview The previous assignment quoted Wikipedia on [Feature Engineering](https://en.wikipedia.org/wiki/Feature_engineering): > "Some machine learning projects succeed and some fail. What makes the difference? Easily the most important factor is the features used." — Pedro Domingos, ["A Few Useful Things to Know about Machine Learning"](https://homes.cs.washington.edu/~pedrod/papers/cacm12.pdf) > "Coming up with features is difficult, time-consuming, requires expert knowledge. 'Applied machine learning' is basically feature engineering." — Andrew Ng, [Machine Learning and AI via Brain simulations](https://forum.stanford.edu/events/2011/2011slides/plenary/2011plenaryNg.pdf) > Feature engineering is the process of using domain knowledge of the data to create features that make machine learning algorithms work. Pedro Domingos says, "the most important factor is the **features used**." This includes not just **Feature Engineering** (making new features, representing features in new ways) but also **Feature Selection** (choosing which features to include and which to exclude). There are _many_ specific tools and techniques for feature selection. - Today we'll try [scikit-learn's `SelectKBest` transformer](https://scikit-learn.org/stable/modules/feature_selection.html#univariate-feature-selection), for "univariate, forward selection." - Later we'll try another technique, ["permutation importance"](https://www.kaggle.com/dansbecker/permutation-importance) - If you want to explore even more options, here are some good resources! - [scikit-learn's User Guide for Feature Selection](https://scikit-learn.org/stable/modules/feature_selection.html) - [mlxtend](http://rasbt.github.io/mlxtend/) library - scikit-learn-contrib libraries: [boruta_py](https://github.com/scikit-learn-contrib/boruta_py) & [stability-selection](https://github.com/scikit-learn-contrib/stability-selection) - [_Feature Engineering and Selection_](http://www.feat.engineering/) by Kuhn & Johnson. My general recommendation is: > Predictive accuracy on test sets is the criterion for how good the model is. — Leo Breiman, ["Statistical Modeling: The Two Cultures"](https://projecteuclid.org/download/pdf_1/euclid.ss/1009213726) First, let's engineer a few more features to select from. This is a partial example solution from the previous assignment. ``` def engineer_features(X): # Avoid SettingWithCopyWarning X = X.copy() # How many total perks does each apartment have? perk_cols = ['elevator', 'cats_allowed', 'hardwood_floors', 'dogs_allowed', 'doorman', 'dishwasher', 'no_fee', 'laundry_in_building', 'fitness_center', 'pre-war', 'laundry_in_unit', 'roof_deck', 'outdoor_space', 'dining_room', 'high_speed_internet', 'balcony', 'swimming_pool', 'new_construction', 'exclusive', 'terrace', 'loft', 'garden_patio', 'common_outdoor_space', 'wheelchair_access'] X['perk_count'] = X[perk_cols].sum(axis=1) # Are cats or dogs allowed? X['cats_or_dogs'] = (X['cats_allowed']==1) | (X['dogs_allowed']==1) # Are cats and dogs allowed? X['cats_and_dogs'] = (X['cats_allowed']==1) & (X['dogs_allowed']==1) # Total number of rooms (beds + baths) X['rooms'] = X['bedrooms'] + X['bathrooms'] return X X_train = engineer_features(X_train) X_test = engineer_features(X_test) ``` ### Could we try every possible feature combination? The number of [combinations](https://en.wikipedia.org/wiki/Combination) is shocking! ``` # How many features do we have currently? features = X_train.columns n = len(features) n # How many ways to choose 1 to n features? from math import factorial def n_choose_k(n, k): return factorial(n)/(factorial(k)*factorial(n-k)) combinations = sum(n_choose_k(n,k) for k in range(1,n+1)) print(f'{combinations:,.0f}') ``` We can't try every possible combination, but we can try some. For example, we can use univariate statistical tests to measure the correlation between each feature and the target, and select the k best features. ## Follow Along Refer to the [Scikit-Learn User Guide on Univariate Feature Selection](https://scikit-learn.org/stable/modules/feature_selection.html#univariate-feature-selection). ``` # TODO: Select the 15 features that best correlate with the target # (15 is an arbitrary starting point here) from sklearn.feature_selection import SelectKBest, f_regression selector = SelectKBest(score_func=f_regression, k=15) # SelectKBest has a similar API to what we've seen before. # IMPORTANT! # .fit_transform on the train set # .transform on test set X_train_selected = selector.fit_transform(X_train, y_train) X_train_selected.shape # TODO: Which features were selected? selected_mask = selector.get_support() all_names = X_train.columns selected_names = all_names[selected_mask] unselected_names = all_names[~selected_mask] print('Features Selected:') for name in selected_names: print(name) print() print('Features not selected:') for name in unselected_names: print(name) # TODO: How many features should be selected? # You can try a range of values for k, # then choose the model with the best score. # If multiple models "tie" for the best score, # choose the simplest model. # You decide what counts as a tie! from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_absolute_error for k in range(1, len(X_train.columns)+1): print(f'{k} features') selector = SelectKBest(score_func=f_regression, k=k) X_train_selected = selector.fit_transform(X_train, y_train) X_test_selected = selector.transform(X_test) model = LinearRegression() model.fit(X_train_selected, y_train) y_pred = model.predict(X_test_selected) mae = mean_absolute_error(y_test, y_pred) print(f'Test Mean Absolute Error: ${mae:,.0f} \n') ``` ## Challenge In your assignment, you will do feature selection with SelectKBest. You'll go back to our other New York City real estate dataset. Instead of predicting apartment rents, you'll predict property sales prices. But not just for condos in Tribeca. Instead, you'll predict property sales prices for One Family Dwellings, where the sale price was more than 100 thousand and less than 2 million. If you run the above code cell with your assignment dataset, you will probably get some shocking results like these: ``` 1 features Test MAE: $183,641 2 features Test MAE: $182,569 3 features Test MAE: $182,569 4 features Test MAE: $183,441 5 features Test MAE: $186,532 6 features Test MAE: $176,121 7 features Test MAE: $177,001 8 features Test MAE: $176,707 9 features Test MAE: $170,969 10 features Test MAE: $170,977 11 features Test MAE: $170,507 12 features Test MAE: $162,301 13 features Test MAE: $163,559 14 features Test MAE: $162,562 15 features Test MAE: $162,550 16 features Test MAE: $162,678 17 features Test MAE: $162,419 18 features Test MAE: $162,177 19 features Test MAE: $162,177 20 features Test MAE: $157,893 21 features Test MAE: $157,966 22 features Test MAE: $157,966 23 features Test MAE: $157,966 24 features Test MAE: $157,630 25 features Test MAE: $157,580 26 features Test MAE: $25,968,990,575,776,280 27 features Test MAE: $157,550 28 features Test MAE: $87,300,193,986,380,608 29 features Test MAE: $158,491 30 features Test MAE: $17,529,140,644,990,770 31 features Test MAE: $24,191,458,933,688,856 32 features Test MAE: $15,214,122,471,992,104 33 features Test MAE: $15,539,731,847,001,626 34 features Test MAE: $26,823,915,969,200,480 35 features Test MAE: $3,813,290,272,870,121 36 features Test MAE: $157,900 37 features Test MAE: $157,900 38 features Test MAE: $158,911 39 features Test MAE: $9,101,846,282,581,472 40 features Test MAE: $1,424,168,120,777,820 41 features Test MAE: $158,261 42 features Test MAE: $158,261 43 features Test MAE: $4,784,333,158,313,152 44 features Test MAE: $1,329,759,264,341,476 45 features Test MAE: $158,451 46 features Test MAE: $158,450 47 features Test MAE: $158,450 48 features Test MAE: $1,331,383,815,682,658 49 features Test MAE: $1,504,319,420,789,134 50 features Test MAE: $2,285,927,437,866,492 ``` Why did the error blow up with 26 features? We can look at the coefficients of the selected features: ``` BLOCK -97,035 ZIP_CODE -152,985 COMMERCIAL_UNITS -4,115,324,664,197,034,496 TOTAL_UNITS -2,872,516,607,892,124,160 GROSS_SQUARE_FEET 123,739 BOROUGH_3 146,876 BOROUGH_4 197,262 BOROUGH_2 -55,917 BOROUGH_5 -84,107 NEIGHBORHOOD_OTHER 56,036 NEIGHBORHOOD_FLUSHING-NORTH 63,394 NEIGHBORHOOD_FOREST HILLS 46,411 NEIGHBORHOOD_BOROUGH PARK 29,915 TAX_CLASS_AT_PRESENT_1D -545,831,543,721,722,112 BUILDING_CLASS_AT_PRESENT_A5 -1,673 BUILDING_CLASS_AT_PRESENT_A3 5,516,361,218,128,626 BUILDING_CLASS_AT_PRESENT_S1 1,735,885,668,110,473,216 BUILDING_CLASS_AT_PRESENT_A6 -25,974,113,243,185,788 BUILDING_CLASS_AT_PRESENT_A8 -760,608,646,332,801,664 BUILDING_CLASS_AT_PRESENT_S0 941,854,072,479,442,176 BUILDING_CLASS_AT_TIME_OF_SALE_A5 -24,599 BUILDING_CLASS_AT_TIME_OF_SALE_A3 -5,516,361,218,111,506 BUILDING_CLASS_AT_TIME_OF_SALE_S1 4,253,055,231,847,939,072 BUILDING_CLASS_AT_TIME_OF_SALE_A6 25,974,113,243,176,404 BUILDING_CLASS_AT_TIME_OF_SALE_A8 -541,733,439,448,260,800 BUILDING_CLASS_AT_TIME_OF_SALE_S0 990,851,394,820,416,512 ``` These were the coefficients that minimized the sum of squared errors in the training set. But this model has become too complex, with extreme coefficients that can lead to extreme predictions on new unseen data. This linear model needs _regularization._ Ridge Regression to the rescue! # Use scikit-learn to fit Ridge Regression models ## Overview Josh Starmer explains in his [StatQuest video on Ridge Regression:](https://youtu.be/Q81RR3yKn30?t=222) > The main idea behind **Ridge Regression** is to find a new line that _doesn't_ fit the training data as well. In other words, we introduce a small amount of **bias** into how the new line is fit to the data. But in return for that small amount of bias we get a significant drop in **variance.** In other words, by starting with a slightly worse fit Ridge regression can provide better long-term predictions. BAM!!! ### OLS vs Mean Baseline vs Ridge Let's see look at some examples. First, here's a famous, tiny dataset — [Anscombe's quartet](https://en.wikipedia.org/wiki/Anscombe%27s_quartet), dataset III: ``` import seaborn as sns anscombe = sns.load_dataset('anscombe').query('dataset=="III"') anscombe.plot.scatter('x', 'y'); ``` We'll compare: - Ordinary Least Squares Linear Regression - Mean Baseline - Ridge Regression #### OLS ``` %matplotlib inline # Plot data ax = anscombe.plot.scatter('x', 'y') # Fit linear model ols = LinearRegression() ols.fit(anscombe[['x']], anscombe['y']) # Get linear equation m = ols.coef_[0].round(2) b = ols.intercept_.round(2) title = f'Linear Regression \n y = {m}x + {b}' # Get predictions anscombe['y_pred'] = ols.predict(anscombe[['x']]) # Plot predictions anscombe.plot('x', 'y_pred', ax=ax, title=title); ``` #### Mean Baseline ``` # Plot data ax = anscombe.plot.scatter('x', 'y') # Mean baseline mean = anscombe['y'].mean() anscombe['y_pred'] = mean title = f'Mean Baseline \n y = 0x + {mean:.2f}' # Plot "predictions" anscombe.plot('x', 'y_pred', ax=ax, title=title); ``` #### Ridge Regression With increasing regularization: ``` import matplotlib.pyplot as plt from sklearn.linear_model import Ridge def ridge_anscombe(alpha): """ Fit & plot a ridge regression model, with Anscombe Quartet dataset III. alpha : positive float, regularization strength """ # Load data anscombe = sns.load_dataset('anscombe').query('dataset=="III"') # Plot data ax = anscombe.plot.scatter('x', 'y') # Fit linear model ridge = Ridge(alpha=alpha, normalize=True) ridge.fit(anscombe[['x']], anscombe['y']) # Get linear equation m = ridge.coef_[0].round(2) b = ridge.intercept_.round(2) title = f'Ridge Regression, alpha={alpha} \n y = {m}x + {b}' # Get predictions anscombe['y_pred'] = ridge.predict(anscombe[['x']]) # Plot predictions anscombe.plot('x', 'y_pred', ax=ax, title=title) plt.show() for alpha in range(10): ridge_anscombe(alpha=alpha) ``` When the Ridge Regression has no regularization (`alpha=0`) then it is identical to Ordinary Least Squares Regression. When we increase the regularization, the predictions looks less and less like OLS and more and more like the mean baseline. The predictions are less sensitive to changes in the independent variable. You may ask, how should we decide the amount of regularization? [The StatQuest video answers,](https://youtu.be/Q81RR3yKn30?t=602) > So how do we decide what value to give lambda? We just try a bunch of values for lambda, and use cross-validation typically 10-fold cross-validation, to determine which one results in the lowest variance. DOUBLE BAM!!! You'll learn more about cross-validation next sprint. For now, the good news is scikit-learn gives us [RidgeCV](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.RidgeCV.html), "Ridge regression with built-in cross-validation." Also, notice that scikit-learn calls the regularization parameter "alpha", but StatQuest calls it "lambda." The greek letters are different, but the concept is the same. Let's try these values for alpha: ``` alphas = [0.01, 0.1, 1.0, 10.0, 100.0] ``` We'll use [RidgeCV](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.RidgeCV.html) to find the best alpha: ``` from sklearn.linear_model import RidgeCV ridge = RidgeCV(alphas=alphas, normalize=True) ridge.fit(anscombe[['x']], anscombe['y']) ridge.alpha_ ``` The fit looks similar to Ordinary Least Squares Regression, but slightly less influenced by the outlier: ``` # Plot data ax = anscombe.plot.scatter('x', 'y') # Get linear equation m = ridge.coef_[0].round(2) b = ridge.intercept_.round(2) title = f'Ridge Regression, alpha={ridge.alpha_} \n y = {m}x + {b}' # Get predictions anscombe['y_pred'] = ridge.predict(anscombe[['x']]) # Plot predictions anscombe.plot('x', 'y_pred', ax=ax, title=title) plt.show() ``` ### NYC, 1 feature Let's go back to our other New York City dataset, to demonstrate regularization with Ridge Regresson: ``` from IPython.display import display, HTML # Try a range of alpha parameters for Ridge Regression. # The scikit-learn docs explain, # alpha : Regularization strength; must be a positive float. Regularization # improves the conditioning of the problem and reduces the variance of the # estimates. Larger values specify stronger regularization. # https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.Ridge.html for alpha in [0.001, 0.01, 0.1, 1.0, 10.0, 100.0]: # Fit Ridge Regression model feature = 'bedrooms' display(HTML(f'Ridge Regression, with alpha={alpha}')) model = Ridge(alpha=alpha, normalize=True) model.fit(X_train[[feature]], y_train) # Get Test MAE y_pred = model.predict(X_test[[feature]]) mae = mean_absolute_error(y_test, y_pred) display(HTML(f'Test Mean Absolute Error: ${mae:,.0f}')) train.plot.scatter(feature, target, alpha=0.05) plt.plot(X_test[feature], y_pred) plt.show() ``` ### NYC, multiple features ``` for alpha in [0.001, 0.01, 0.1, 1.0, 1, 100.0, 1000.0]: # Fit Ridge Regression model display(HTML(f'Ridge Regression, with alpha={alpha}')) model = Ridge(alpha=alpha, normalize=True) model.fit(X_train, y_train) y_pred = model.predict(X_test) # Get Test MAE mae = mean_absolute_error(y_test, y_pred) display(HTML(f'Test Mean Absolute Error: ${mae:,.0f}')) # Plot coefficients coefficients = pd.Series(model.coef_, X_train.columns) plt.figure(figsize=(16,8)) coefficients.sort_values().plot.barh(color='grey') plt.xlim(-400,700) plt.show() ``` ### Regularization just means "add bias" OK, there's a bit more to it than that. But that's the core intuition - the problem is the model working "too well", so fix it by making it harder for the model! It may sound strange - a technique that is purposefully "worse" - but in certain situations, it can really get results. What's bias? In the context of statistics and machine learning, bias is when a predictive model fails to identify relationships between features and the output. In a word, bias is *underfitting*. We want to add bias to the model because of the [bias-variance tradeoff](https://en.wikipedia.org/wiki/Bias%E2%80%93variance_tradeoff) - variance is the sensitivity of a model to the random noise in its training data (i.e. *overfitting*), and bias and variance are naturally (inversely) related. Increasing one will always decrease the other, with regards to the overall generalization error (predictive accuracy on unseen data). Visually, the result looks like this: ![Regularization example plot](https://upload.wikimedia.org/wikipedia/commons/0/02/Regularization.svg) The blue line is overfit, using more dimensions than are needed to explain the data and so much of the movement is based on noise and won't generalize well. The green line still fits the data, but is less susceptible to the noise - depending on how exactly we parameterize "noise" we may throw out actual correlation, but if we balance it right we keep that signal and greatly improve generalizability. ## Challenge In your assignment, you will fit a Ridge Regression model. You can try Linear Regression too — depending on how many features you select, your errors will probably blow up! # Review For your assignment, we're going back to our other **New York City** real estate dataset. Instead of predicting apartment rents, you'll predict property sales prices. But not just for condos in Tribeca... Instead, predict property sales prices for **One Family Dwellings** (`BUILDING_CLASS_CATEGORY` == `'01 ONE FAMILY DWELLINGS'`). Use a subset of the data where the **sale price was more than \\$100 thousand and less than $2 million.** You'll practice all of the module's objectives to build your best model yet!
github_jupyter
%%capture import sys # If you're on Colab: if 'google.colab' in sys.modules: DATA_PATH = 'https://raw.githubusercontent.com/LambdaSchool/DS-Unit-2-Applied-Modeling/master/data/' !pip install category_encoders==2.* # If you're working locally: else: DATA_PATH = '../data/' import numpy as np import pandas as pd # Read New York City apartment rental listing data df = pd.read_csv(DATA_PATH+'apartments/renthop-nyc.csv') assert df.shape == (49352, 34) # Remove the most extreme 1% prices, # the most extreme .1% latitudes, & # the most extreme .1% longitudes df = df[(df['price'] >= np.percentile(df['price'], 0.5)) & (df['price'] <= np.percentile(df['price'], 99.5)) & (df['latitude'] >= np.percentile(df['latitude'], 0.05)) & (df['latitude'] < np.percentile(df['latitude'], 99.95)) & (df['longitude'] >= np.percentile(df['longitude'], 0.05)) & (df['longitude'] <= np.percentile(df['longitude'], 99.95))] # Do train/test split # Use data from April & May 2016 to train # Use data from June 2016 to test df['created'] = pd.to_datetime(df['created'], infer_datetime_format=True) cutoff = pd.to_datetime('2016-06-01') train = df[df.created < cutoff] test = df[df.created >= cutoff] # TODO train.describe() # TODO train.describe(include='object') # TODO train['interest_level'].value_counts() train.groupby('interest_level')['price'].mean() # TODO target = 'price' high_cardinality = ['display_address','street_address','description','created'] features = train.columns.drop([target] + high_cardinality) # TODO X_train = train[features] y_train = train[target] X_test = test[features] y_test = test[target] # TODO df.shape, X_train.shape, X_test.shape # TODO import category_encoders as ce encoder = ce.OneHotEncoder(use_cat_names=True) X_train = encoder.fit_transform(X_train) X_train.head() X_train[['interest_level_high','interest_level_medium','interest_level_low']].head() X_test = encoder.transform(X_test) X_test.head() def engineer_features(X): # Avoid SettingWithCopyWarning X = X.copy() # How many total perks does each apartment have? perk_cols = ['elevator', 'cats_allowed', 'hardwood_floors', 'dogs_allowed', 'doorman', 'dishwasher', 'no_fee', 'laundry_in_building', 'fitness_center', 'pre-war', 'laundry_in_unit', 'roof_deck', 'outdoor_space', 'dining_room', 'high_speed_internet', 'balcony', 'swimming_pool', 'new_construction', 'exclusive', 'terrace', 'loft', 'garden_patio', 'common_outdoor_space', 'wheelchair_access'] X['perk_count'] = X[perk_cols].sum(axis=1) # Are cats or dogs allowed? X['cats_or_dogs'] = (X['cats_allowed']==1) | (X['dogs_allowed']==1) # Are cats and dogs allowed? X['cats_and_dogs'] = (X['cats_allowed']==1) & (X['dogs_allowed']==1) # Total number of rooms (beds + baths) X['rooms'] = X['bedrooms'] + X['bathrooms'] return X X_train = engineer_features(X_train) X_test = engineer_features(X_test) # How many features do we have currently? features = X_train.columns n = len(features) n # How many ways to choose 1 to n features? from math import factorial def n_choose_k(n, k): return factorial(n)/(factorial(k)*factorial(n-k)) combinations = sum(n_choose_k(n,k) for k in range(1,n+1)) print(f'{combinations:,.0f}') # TODO: Select the 15 features that best correlate with the target # (15 is an arbitrary starting point here) from sklearn.feature_selection import SelectKBest, f_regression selector = SelectKBest(score_func=f_regression, k=15) # SelectKBest has a similar API to what we've seen before. # IMPORTANT! # .fit_transform on the train set # .transform on test set X_train_selected = selector.fit_transform(X_train, y_train) X_train_selected.shape # TODO: Which features were selected? selected_mask = selector.get_support() all_names = X_train.columns selected_names = all_names[selected_mask] unselected_names = all_names[~selected_mask] print('Features Selected:') for name in selected_names: print(name) print() print('Features not selected:') for name in unselected_names: print(name) # TODO: How many features should be selected? # You can try a range of values for k, # then choose the model with the best score. # If multiple models "tie" for the best score, # choose the simplest model. # You decide what counts as a tie! from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_absolute_error for k in range(1, len(X_train.columns)+1): print(f'{k} features') selector = SelectKBest(score_func=f_regression, k=k) X_train_selected = selector.fit_transform(X_train, y_train) X_test_selected = selector.transform(X_test) model = LinearRegression() model.fit(X_train_selected, y_train) y_pred = model.predict(X_test_selected) mae = mean_absolute_error(y_test, y_pred) print(f'Test Mean Absolute Error: ${mae:,.0f} \n') 1 features Test MAE: $183,641 2 features Test MAE: $182,569 3 features Test MAE: $182,569 4 features Test MAE: $183,441 5 features Test MAE: $186,532 6 features Test MAE: $176,121 7 features Test MAE: $177,001 8 features Test MAE: $176,707 9 features Test MAE: $170,969 10 features Test MAE: $170,977 11 features Test MAE: $170,507 12 features Test MAE: $162,301 13 features Test MAE: $163,559 14 features Test MAE: $162,562 15 features Test MAE: $162,550 16 features Test MAE: $162,678 17 features Test MAE: $162,419 18 features Test MAE: $162,177 19 features Test MAE: $162,177 20 features Test MAE: $157,893 21 features Test MAE: $157,966 22 features Test MAE: $157,966 23 features Test MAE: $157,966 24 features Test MAE: $157,630 25 features Test MAE: $157,580 26 features Test MAE: $25,968,990,575,776,280 27 features Test MAE: $157,550 28 features Test MAE: $87,300,193,986,380,608 29 features Test MAE: $158,491 30 features Test MAE: $17,529,140,644,990,770 31 features Test MAE: $24,191,458,933,688,856 32 features Test MAE: $15,214,122,471,992,104 33 features Test MAE: $15,539,731,847,001,626 34 features Test MAE: $26,823,915,969,200,480 35 features Test MAE: $3,813,290,272,870,121 36 features Test MAE: $157,900 37 features Test MAE: $157,900 38 features Test MAE: $158,911 39 features Test MAE: $9,101,846,282,581,472 40 features Test MAE: $1,424,168,120,777,820 41 features Test MAE: $158,261 42 features Test MAE: $158,261 43 features Test MAE: $4,784,333,158,313,152 44 features Test MAE: $1,329,759,264,341,476 45 features Test MAE: $158,451 46 features Test MAE: $158,450 47 features Test MAE: $158,450 48 features Test MAE: $1,331,383,815,682,658 49 features Test MAE: $1,504,319,420,789,134 50 features Test MAE: $2,285,927,437,866,492 BLOCK -97,035 ZIP_CODE -152,985 COMMERCIAL_UNITS -4,115,324,664,197,034,496 TOTAL_UNITS -2,872,516,607,892,124,160 GROSS_SQUARE_FEET 123,739 BOROUGH_3 146,876 BOROUGH_4 197,262 BOROUGH_2 -55,917 BOROUGH_5 -84,107 NEIGHBORHOOD_OTHER 56,036 NEIGHBORHOOD_FLUSHING-NORTH 63,394 NEIGHBORHOOD_FOREST HILLS 46,411 NEIGHBORHOOD_BOROUGH PARK 29,915 TAX_CLASS_AT_PRESENT_1D -545,831,543,721,722,112 BUILDING_CLASS_AT_PRESENT_A5 -1,673 BUILDING_CLASS_AT_PRESENT_A3 5,516,361,218,128,626 BUILDING_CLASS_AT_PRESENT_S1 1,735,885,668,110,473,216 BUILDING_CLASS_AT_PRESENT_A6 -25,974,113,243,185,788 BUILDING_CLASS_AT_PRESENT_A8 -760,608,646,332,801,664 BUILDING_CLASS_AT_PRESENT_S0 941,854,072,479,442,176 BUILDING_CLASS_AT_TIME_OF_SALE_A5 -24,599 BUILDING_CLASS_AT_TIME_OF_SALE_A3 -5,516,361,218,111,506 BUILDING_CLASS_AT_TIME_OF_SALE_S1 4,253,055,231,847,939,072 BUILDING_CLASS_AT_TIME_OF_SALE_A6 25,974,113,243,176,404 BUILDING_CLASS_AT_TIME_OF_SALE_A8 -541,733,439,448,260,800 BUILDING_CLASS_AT_TIME_OF_SALE_S0 990,851,394,820,416,512 import seaborn as sns anscombe = sns.load_dataset('anscombe').query('dataset=="III"') anscombe.plot.scatter('x', 'y'); %matplotlib inline # Plot data ax = anscombe.plot.scatter('x', 'y') # Fit linear model ols = LinearRegression() ols.fit(anscombe[['x']], anscombe['y']) # Get linear equation m = ols.coef_[0].round(2) b = ols.intercept_.round(2) title = f'Linear Regression \n y = {m}x + {b}' # Get predictions anscombe['y_pred'] = ols.predict(anscombe[['x']]) # Plot predictions anscombe.plot('x', 'y_pred', ax=ax, title=title); # Plot data ax = anscombe.plot.scatter('x', 'y') # Mean baseline mean = anscombe['y'].mean() anscombe['y_pred'] = mean title = f'Mean Baseline \n y = 0x + {mean:.2f}' # Plot "predictions" anscombe.plot('x', 'y_pred', ax=ax, title=title); import matplotlib.pyplot as plt from sklearn.linear_model import Ridge def ridge_anscombe(alpha): """ Fit & plot a ridge regression model, with Anscombe Quartet dataset III. alpha : positive float, regularization strength """ # Load data anscombe = sns.load_dataset('anscombe').query('dataset=="III"') # Plot data ax = anscombe.plot.scatter('x', 'y') # Fit linear model ridge = Ridge(alpha=alpha, normalize=True) ridge.fit(anscombe[['x']], anscombe['y']) # Get linear equation m = ridge.coef_[0].round(2) b = ridge.intercept_.round(2) title = f'Ridge Regression, alpha={alpha} \n y = {m}x + {b}' # Get predictions anscombe['y_pred'] = ridge.predict(anscombe[['x']]) # Plot predictions anscombe.plot('x', 'y_pred', ax=ax, title=title) plt.show() for alpha in range(10): ridge_anscombe(alpha=alpha) alphas = [0.01, 0.1, 1.0, 10.0, 100.0] from sklearn.linear_model import RidgeCV ridge = RidgeCV(alphas=alphas, normalize=True) ridge.fit(anscombe[['x']], anscombe['y']) ridge.alpha_ # Plot data ax = anscombe.plot.scatter('x', 'y') # Get linear equation m = ridge.coef_[0].round(2) b = ridge.intercept_.round(2) title = f'Ridge Regression, alpha={ridge.alpha_} \n y = {m}x + {b}' # Get predictions anscombe['y_pred'] = ridge.predict(anscombe[['x']]) # Plot predictions anscombe.plot('x', 'y_pred', ax=ax, title=title) plt.show() from IPython.display import display, HTML # Try a range of alpha parameters for Ridge Regression. # The scikit-learn docs explain, # alpha : Regularization strength; must be a positive float. Regularization # improves the conditioning of the problem and reduces the variance of the # estimates. Larger values specify stronger regularization. # https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.Ridge.html for alpha in [0.001, 0.01, 0.1, 1.0, 10.0, 100.0]: # Fit Ridge Regression model feature = 'bedrooms' display(HTML(f'Ridge Regression, with alpha={alpha}')) model = Ridge(alpha=alpha, normalize=True) model.fit(X_train[[feature]], y_train) # Get Test MAE y_pred = model.predict(X_test[[feature]]) mae = mean_absolute_error(y_test, y_pred) display(HTML(f'Test Mean Absolute Error: ${mae:,.0f}')) train.plot.scatter(feature, target, alpha=0.05) plt.plot(X_test[feature], y_pred) plt.show() for alpha in [0.001, 0.01, 0.1, 1.0, 1, 100.0, 1000.0]: # Fit Ridge Regression model display(HTML(f'Ridge Regression, with alpha={alpha}')) model = Ridge(alpha=alpha, normalize=True) model.fit(X_train, y_train) y_pred = model.predict(X_test) # Get Test MAE mae = mean_absolute_error(y_test, y_pred) display(HTML(f'Test Mean Absolute Error: ${mae:,.0f}')) # Plot coefficients coefficients = pd.Series(model.coef_, X_train.columns) plt.figure(figsize=(16,8)) coefficients.sort_values().plot.barh(color='grey') plt.xlim(-400,700) plt.show()
0.243283
0.987104
# Modelagem de Hiperparâmetros ``` import numpy as np import pandas as pd import math import matplotlib.pyplot as plt import clf_vAngra_lib as vCLF from astropy.stats import mad_std from sklearn.preprocessing import StandardScaler from sklearn.neural_network import MLPClassifier from sklearn.model_selection import KFold from sklearn.model_selection import cross_validate from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import f1_score %matplotlib inline #plt.style.use('seaborn-white') plt.rcParams['xtick.labelsize'] = 18 plt.rcParams['ytick.labelsize'] = 18 plt.rcParams['axes.labelsize'] = 18 plt.rcParams['axes.titlesize'] = 18 plt.rcParams['legend.fontsize'] = 18 ``` ## Load dos Dados ``` df = pd.read_csv('../data/DataFrame_Aqst.csv',index_col=0) df.head() ``` ## Algoritmo v-Angra ``` Y = np.array(df['Label']) X = np.array(df.drop(['Label'], axis=1)) sigma = np.linspace(0.01, 50, 100) kfold = KFold(n_splits=10, shuffle=True, random_state=42) NCLF = np.array([]) for i in sigma: results_NCLF = ([]) for train_index, test_index in kfold.split(X): xTrain, xTest = X[train_index], X[test_index] yTrain, yTest = Y[train_index], Y[test_index] dfTrain = pd.DataFrame(np.concatenate((xTrain, yTrain.reshape(-1,1)), axis=1), columns=['Amp', 'Area', 'Pos_Amp', 'FWHM', 'Label']) dfTest = pd.DataFrame(np.concatenate((xTest, yTest.reshape(-1,1)), axis=1), columns=['Amp', 'Area', 'Pos_Amp', 'FWHM', 'Label']) f1_NC_train, angle = vCLF.NeutrinosClassifier(dfTrain, 'None', i) f1_NC_test, angle = vCLF.NeutrinosClassifier(dfTest, angle, i) results_NCLF = np.append(results_NCLF, f1_NC_test) NCLF = np.concatenate((NCLF, results_NCLF),axis=0) #np.save('NCLF', NCLF.reshape(100,10)) sigma = np.linspace(0.01, 50, 100) NCLF = np.load('../data/NCLF.npy') fig = plt.figure(figsize=(20,8)) plt.subplot(121) plt.plot(sigma, np.mean(NCLF,axis=1), '--ks') plt.xlabel('Sigmas') plt.ylabel('Mean F1') plt.grid() plt.subplot(122) plt.plot(sigma, mad_std(NCLF,axis=1), '--ks') plt.xlabel('Sigmas') plt.ylabel('STD') plt.grid() #plt.savefig('nClf_mean.pdf', format='pdf',dpi=300, bbox_inches='tight', pad_inches=0.1) plt.show() ``` ## Standartização do Dataframe ``` Y = np.array(df['Label']) X = df.drop(['Label'], axis=1) scaler = StandardScaler() X = scaler.fit_transform(X) ``` ## MLP ``` neurons = range(1,21,1) MLP_1 = np.array([]) for i in neurons: MLP = MLPClassifier(hidden_layer_sizes=(i), solver='sgd', max_iter=2000, random_state=1, activation='relu') kfold = KFold(n_splits=10, shuffle=True, random_state=1) results_MLP = cross_validate(MLP, X=X, y=Y, cv=kfold, scoring='f1_micro') MLP_1 = np.concatenate((MLP_1, results_MLP['test_score']),axis=0) #np.save('MLP_1', MLP_1.reshape(20,10)) MLP_2 = np.array([]) neurons = range(1,21) for i in neurons: MLP = MLPClassifier(hidden_layer_sizes=(i,i), solver='sgd', max_iter=2000, random_state=1, activation='relu') kfold = KFold(n_splits=10, shuffle=True, random_state=1) results_MLP = cross_validate(MLP, X=X, y=Y, cv=kfold, scoring='f1_micro') MLP_2 = np.concatenate((MLP_2, results_MLP['test_score']),axis=0) #np.save('MLP_2', MLP_2.reshape(20,10)) MLP_3 = np.array([]) neurons = range(1,21) for i in neurons: MLP = MLPClassifier(hidden_layer_sizes=(i,i,i), solver='sgd', max_iter=2000, random_state=1, activation='relu') kfold = KFold(n_splits=10, shuffle=True, random_state=1) results_MLP = cross_validate(MLP, X=X, y=Y, cv=kfold, scoring='f1_micro') MLP_3 = np.concatenate((MLP_3, results_MLP['test_score']),axis=0) #np.save('MLP_3', MLP_3.reshape(20,10)) MLP_1 = np.load('../data/MLP_1.npy') MLP_2 = np.load('../data/MLP_2.npy') MLP_3 = np.load('../data/MLP_3.npy') fig = plt.figure(figsize=(20,8)) plt.subplot(121) plt.plot(list(range(1,21)), np.mean(MLP_1,axis=1), '--ks',label='1 Camada') plt.plot(list(range(1,21)), np.mean(MLP_2,axis=1), '--kd',label='2 Camadas') plt.plot(list(range(1,21)), np.mean(MLP_3,axis=1), '--ko',label='3 Camadas') plt.xlabel('Neurons') plt.ylabel('Mean F1') plt.legend() plt.grid() plt.subplot(122) plt.plot(list(range(1,21)), mad_std(MLP_1,axis=1), '--ks',label='1 Camada') plt.plot(list(range(1,21)), mad_std(MLP_2,axis=1), '--kd',label='2 Camadas') plt.plot(list(range(1,21)), mad_std(MLP_3,axis=1), '--ko',label='3 Camadas') plt.xlabel('Neurons') plt.ylabel('STD') plt.legend() plt.grid() #plt.savefig('mlp_mean.pdf', format='pdf',dpi=300, bbox_inches='tight', pad_inches=0.1) plt.show() ``` ## Regressão Logística ``` clf_LR = LogisticRegression(random_state=1, max_iter=500, solver='sag') kfold = KFold(n_splits=10, shuffle=True, random_state=42) results_LR = cross_validate(clf_LR, X=X, y=Y, cv=kfold, scoring='accuracy') print('Acurácia:', np.mean(results_LR['test_score'])) print('STD:\t ', mad_std(results_LR['test_score'])) ``` ## Floresta Aleatória ``` f1_RF = np.array([]) std_RF = np.array([]) trees = range(1,201,5) for i in trees: RF = RandomForestClassifier(n_estimators=i, bootstrap=True, random_state=1) kfold = KFold(n_splits=10, shuffle=True, random_state=42) results_RF = cross_validate(RF, X=X, y=Y, cv=kfold, scoring='f1_micro') f1_RF = np.append(f1_RF, (results_RF['test_score'].mean())) std_RF = np.append(std_RF, mad_std(results_RF['test_score'])) f1_RF = np.load('../data/f1_RF.npy') std_RF = np.load('../data/std_RF.npy') fig = plt.figure(figsize=(20,8)) plt.subplot(121) plt.plot(list(range(1,201,5)), f1_RF, '--ks') plt.xlabel('Trees') plt.ylabel('Mean F1') plt.grid() plt.subplot(122) plt.plot(list(range(1,201,5)), std_RF, '--ks') plt.xlabel('Trees') plt.ylabel('STD') plt.grid() #plt.savefig('rf_mean.pdf', format='pdf',dpi=300, bbox_inches='tight', pad_inches=0.1) plt.show() ```
github_jupyter
import numpy as np import pandas as pd import math import matplotlib.pyplot as plt import clf_vAngra_lib as vCLF from astropy.stats import mad_std from sklearn.preprocessing import StandardScaler from sklearn.neural_network import MLPClassifier from sklearn.model_selection import KFold from sklearn.model_selection import cross_validate from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import f1_score %matplotlib inline #plt.style.use('seaborn-white') plt.rcParams['xtick.labelsize'] = 18 plt.rcParams['ytick.labelsize'] = 18 plt.rcParams['axes.labelsize'] = 18 plt.rcParams['axes.titlesize'] = 18 plt.rcParams['legend.fontsize'] = 18 df = pd.read_csv('../data/DataFrame_Aqst.csv',index_col=0) df.head() Y = np.array(df['Label']) X = np.array(df.drop(['Label'], axis=1)) sigma = np.linspace(0.01, 50, 100) kfold = KFold(n_splits=10, shuffle=True, random_state=42) NCLF = np.array([]) for i in sigma: results_NCLF = ([]) for train_index, test_index in kfold.split(X): xTrain, xTest = X[train_index], X[test_index] yTrain, yTest = Y[train_index], Y[test_index] dfTrain = pd.DataFrame(np.concatenate((xTrain, yTrain.reshape(-1,1)), axis=1), columns=['Amp', 'Area', 'Pos_Amp', 'FWHM', 'Label']) dfTest = pd.DataFrame(np.concatenate((xTest, yTest.reshape(-1,1)), axis=1), columns=['Amp', 'Area', 'Pos_Amp', 'FWHM', 'Label']) f1_NC_train, angle = vCLF.NeutrinosClassifier(dfTrain, 'None', i) f1_NC_test, angle = vCLF.NeutrinosClassifier(dfTest, angle, i) results_NCLF = np.append(results_NCLF, f1_NC_test) NCLF = np.concatenate((NCLF, results_NCLF),axis=0) #np.save('NCLF', NCLF.reshape(100,10)) sigma = np.linspace(0.01, 50, 100) NCLF = np.load('../data/NCLF.npy') fig = plt.figure(figsize=(20,8)) plt.subplot(121) plt.plot(sigma, np.mean(NCLF,axis=1), '--ks') plt.xlabel('Sigmas') plt.ylabel('Mean F1') plt.grid() plt.subplot(122) plt.plot(sigma, mad_std(NCLF,axis=1), '--ks') plt.xlabel('Sigmas') plt.ylabel('STD') plt.grid() #plt.savefig('nClf_mean.pdf', format='pdf',dpi=300, bbox_inches='tight', pad_inches=0.1) plt.show() Y = np.array(df['Label']) X = df.drop(['Label'], axis=1) scaler = StandardScaler() X = scaler.fit_transform(X) neurons = range(1,21,1) MLP_1 = np.array([]) for i in neurons: MLP = MLPClassifier(hidden_layer_sizes=(i), solver='sgd', max_iter=2000, random_state=1, activation='relu') kfold = KFold(n_splits=10, shuffle=True, random_state=1) results_MLP = cross_validate(MLP, X=X, y=Y, cv=kfold, scoring='f1_micro') MLP_1 = np.concatenate((MLP_1, results_MLP['test_score']),axis=0) #np.save('MLP_1', MLP_1.reshape(20,10)) MLP_2 = np.array([]) neurons = range(1,21) for i in neurons: MLP = MLPClassifier(hidden_layer_sizes=(i,i), solver='sgd', max_iter=2000, random_state=1, activation='relu') kfold = KFold(n_splits=10, shuffle=True, random_state=1) results_MLP = cross_validate(MLP, X=X, y=Y, cv=kfold, scoring='f1_micro') MLP_2 = np.concatenate((MLP_2, results_MLP['test_score']),axis=0) #np.save('MLP_2', MLP_2.reshape(20,10)) MLP_3 = np.array([]) neurons = range(1,21) for i in neurons: MLP = MLPClassifier(hidden_layer_sizes=(i,i,i), solver='sgd', max_iter=2000, random_state=1, activation='relu') kfold = KFold(n_splits=10, shuffle=True, random_state=1) results_MLP = cross_validate(MLP, X=X, y=Y, cv=kfold, scoring='f1_micro') MLP_3 = np.concatenate((MLP_3, results_MLP['test_score']),axis=0) #np.save('MLP_3', MLP_3.reshape(20,10)) MLP_1 = np.load('../data/MLP_1.npy') MLP_2 = np.load('../data/MLP_2.npy') MLP_3 = np.load('../data/MLP_3.npy') fig = plt.figure(figsize=(20,8)) plt.subplot(121) plt.plot(list(range(1,21)), np.mean(MLP_1,axis=1), '--ks',label='1 Camada') plt.plot(list(range(1,21)), np.mean(MLP_2,axis=1), '--kd',label='2 Camadas') plt.plot(list(range(1,21)), np.mean(MLP_3,axis=1), '--ko',label='3 Camadas') plt.xlabel('Neurons') plt.ylabel('Mean F1') plt.legend() plt.grid() plt.subplot(122) plt.plot(list(range(1,21)), mad_std(MLP_1,axis=1), '--ks',label='1 Camada') plt.plot(list(range(1,21)), mad_std(MLP_2,axis=1), '--kd',label='2 Camadas') plt.plot(list(range(1,21)), mad_std(MLP_3,axis=1), '--ko',label='3 Camadas') plt.xlabel('Neurons') plt.ylabel('STD') plt.legend() plt.grid() #plt.savefig('mlp_mean.pdf', format='pdf',dpi=300, bbox_inches='tight', pad_inches=0.1) plt.show() clf_LR = LogisticRegression(random_state=1, max_iter=500, solver='sag') kfold = KFold(n_splits=10, shuffle=True, random_state=42) results_LR = cross_validate(clf_LR, X=X, y=Y, cv=kfold, scoring='accuracy') print('Acurácia:', np.mean(results_LR['test_score'])) print('STD:\t ', mad_std(results_LR['test_score'])) f1_RF = np.array([]) std_RF = np.array([]) trees = range(1,201,5) for i in trees: RF = RandomForestClassifier(n_estimators=i, bootstrap=True, random_state=1) kfold = KFold(n_splits=10, shuffle=True, random_state=42) results_RF = cross_validate(RF, X=X, y=Y, cv=kfold, scoring='f1_micro') f1_RF = np.append(f1_RF, (results_RF['test_score'].mean())) std_RF = np.append(std_RF, mad_std(results_RF['test_score'])) f1_RF = np.load('../data/f1_RF.npy') std_RF = np.load('../data/std_RF.npy') fig = plt.figure(figsize=(20,8)) plt.subplot(121) plt.plot(list(range(1,201,5)), f1_RF, '--ks') plt.xlabel('Trees') plt.ylabel('Mean F1') plt.grid() plt.subplot(122) plt.plot(list(range(1,201,5)), std_RF, '--ks') plt.xlabel('Trees') plt.ylabel('STD') plt.grid() #plt.savefig('rf_mean.pdf', format='pdf',dpi=300, bbox_inches='tight', pad_inches=0.1) plt.show()
0.469763
0.832747
# LNet in TF #### Dependencies ``` import numpy as np np.random.seed(42) import tensorflow as tf tf.set_random_seed(42) from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) ``` #### Set hyperparameters ``` display_progress = 40 epochs = 10 batch_size = 128 wt_init = tf.contrib.layers.xavier_initializer() # input layer: n_input = 784 # first convolutional layer: n_conv_1 = 32 k_conv_1 = 3 # k_size # second convolutional layer: n_conv_2 = 64 k_conv_2 = 3 # max pooling layer: pool_size = 2 mp_layer_dropout = 0.25 # dense layer: n_dense = 128 dense_layer_dropout = 0.5 # output layer: n_classes = 10 ``` #### Define Placeholders Tensors ``` x = tf.placeholder(tf.float32, [None, n_input]) y = tf.placeholder(tf.float32, [None, n_classes]) ``` #### Define layers relu layers ``` def dense(x, W, b): z = tf.add(tf.matmul(x, W), b) a = tf.nn.relu(z) return a # convolutional layer with ReLU activation: def conv2d(x, W, b, stride_length=1): xW = tf.nn.conv2d(x, W, strides=[1, stride_length, stride_length, 1], padding='SAME') z = tf.nn.bias_add(xW, b) a = tf.nn.relu(z) return a # max-pooling layer: def maxpooling2d(x, p_size): return tf.nn.max_pool(x, ksize=[1, p_size, p_size, 1], strides=[1, p_size, p_size, 1], padding='SAME') ``` #### Design neural architecture ``` def network(x, weights, biases, n_in, mp_psize, mp_dropout, dense_dropout): # reshape linear MNIST pixel input into square image: square_dimensions = int(np.sqrt(n_in)) square_x = tf.reshape(x, shape=[-1, square_dimensions, square_dimensions, 1]) # convolutional and max-pooling layers: conv_1 = conv2d(square_x, weights['W_c1'], biases['b_c1']) conv_2 = conv2d(conv_1, weights['W_c2'], biases['b_c2']) pool_1 = maxpooling2d(conv_2, mp_psize) pool_1 = tf.nn.dropout(pool_1, 1-mp_dropout) # dense layer: flat = tf.reshape(pool_1, [-1, weights['W_d1'].get_shape().as_list()[0]]) dense_1 = dense(flat, weights['W_d1'], biases['b_d1']) dense_1 = tf.nn.dropout(dense_1, 1-dense_dropout) # output layer: out_layer_z = tf.add(tf.matmul(dense_1, weights['W_out']), biases['b_out']) return out_layer_z ``` #### Define variable dictionaries ``` bias_dict = { 'b_c1': tf.Variable(tf.zeros([n_conv_1])), 'b_c2': tf.Variable(tf.zeros([n_conv_2])), 'b_d1': tf.Variable(tf.zeros([n_dense])), 'b_out': tf.Variable(tf.zeros([n_classes])) } # calculate number of inputs to dense layer: full_square_length = np.sqrt(n_input) pooled_square_length = int(full_square_length / pool_size) dense_inputs = pooled_square_length**2 * n_conv_2 weight_dict = { 'W_c1': tf.get_variable('W_c1', [k_conv_1, k_conv_1, 1, n_conv_1], initializer=wt_init), 'W_c2': tf.get_variable('W_c2', [k_conv_2, k_conv_2, n_conv_1, n_conv_2], initializer=wt_init), 'W_d1': tf.get_variable('W_d1', [dense_inputs, n_dense], initializer=wt_init), 'W_out': tf.get_variable('W_out', [n_dense, n_classes], initializer=wt_init) } ``` #### Build Model ``` predictions = network(x, weight_dict, bias_dict, n_input, pool_size, mp_layer_dropout, dense_layer_dropout) ``` #### Define loss and optimiser ``` cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=predictions, labels=y)) optimizer = tf.train.AdamOptimizer().minimize(cost) ``` #### Define evaluation Metrics ``` correct_prediction = tf.equal(tf.argmax(predictions, 1), tf.argmax(y, 1)) accuracy_pct = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) * 100 ``` #### Create Ops ``` initializer_op = tf.global_variables_initializer() ``` #### Train the model ``` with tf.Session() as session: session.run(initializer_op) print("Training for", epochs, "epochs.") # loop over epochs: for epoch in range(epochs): avg_cost = 0.0 # track cost to monitor performance during training avg_accuracy_pct = 0.0 # loop over all batches of the epoch: n_batches = int(mnist.train.num_examples / batch_size) for i in range(n_batches): if i % display_progress == 0: print("Step " + str(i+1), " of " + str(n_batches) + " in epoch " + str(epoch+1)) batch_x, batch_y = mnist.train.next_batch(batch_size) # feed batch data to run optimization and fetching cost and accuracy: _, batch_cost, batch_acc = session.run([optimizer, cost, accuracy_pct], feed_dict={x: batch_x, y: batch_y}) # accumulate mean loss and accuracy over epoch: avg_cost += batch_cost / n_batches avg_accuracy_pct += batch_acc / n_batches # output logs at end of each epoch of training: print("Epoch " '%03d' % (epoch+1), ": cost = " '{:.3f}'.format(avg_cost), "accuracy = " '{:.2f}'.format(avg_accuracy_pct) + "%") print("Training Complete. Testing Model.\n") test_cost = cost.eval({x: mnist.test.images, y: mnist.test.labels}) test_accuracy_pct = accuracy_pct.eval({x: mnist.test.images, y: mnist.test.labels}) print("Test Cost:", '{:.3f}'.format(test_cost)) print("Test Accuracy: ", '{:.2f}'.format(test_accuracy_pct) + "%") ```
github_jupyter
import numpy as np np.random.seed(42) import tensorflow as tf tf.set_random_seed(42) from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) display_progress = 40 epochs = 10 batch_size = 128 wt_init = tf.contrib.layers.xavier_initializer() # input layer: n_input = 784 # first convolutional layer: n_conv_1 = 32 k_conv_1 = 3 # k_size # second convolutional layer: n_conv_2 = 64 k_conv_2 = 3 # max pooling layer: pool_size = 2 mp_layer_dropout = 0.25 # dense layer: n_dense = 128 dense_layer_dropout = 0.5 # output layer: n_classes = 10 x = tf.placeholder(tf.float32, [None, n_input]) y = tf.placeholder(tf.float32, [None, n_classes]) def dense(x, W, b): z = tf.add(tf.matmul(x, W), b) a = tf.nn.relu(z) return a # convolutional layer with ReLU activation: def conv2d(x, W, b, stride_length=1): xW = tf.nn.conv2d(x, W, strides=[1, stride_length, stride_length, 1], padding='SAME') z = tf.nn.bias_add(xW, b) a = tf.nn.relu(z) return a # max-pooling layer: def maxpooling2d(x, p_size): return tf.nn.max_pool(x, ksize=[1, p_size, p_size, 1], strides=[1, p_size, p_size, 1], padding='SAME') def network(x, weights, biases, n_in, mp_psize, mp_dropout, dense_dropout): # reshape linear MNIST pixel input into square image: square_dimensions = int(np.sqrt(n_in)) square_x = tf.reshape(x, shape=[-1, square_dimensions, square_dimensions, 1]) # convolutional and max-pooling layers: conv_1 = conv2d(square_x, weights['W_c1'], biases['b_c1']) conv_2 = conv2d(conv_1, weights['W_c2'], biases['b_c2']) pool_1 = maxpooling2d(conv_2, mp_psize) pool_1 = tf.nn.dropout(pool_1, 1-mp_dropout) # dense layer: flat = tf.reshape(pool_1, [-1, weights['W_d1'].get_shape().as_list()[0]]) dense_1 = dense(flat, weights['W_d1'], biases['b_d1']) dense_1 = tf.nn.dropout(dense_1, 1-dense_dropout) # output layer: out_layer_z = tf.add(tf.matmul(dense_1, weights['W_out']), biases['b_out']) return out_layer_z bias_dict = { 'b_c1': tf.Variable(tf.zeros([n_conv_1])), 'b_c2': tf.Variable(tf.zeros([n_conv_2])), 'b_d1': tf.Variable(tf.zeros([n_dense])), 'b_out': tf.Variable(tf.zeros([n_classes])) } # calculate number of inputs to dense layer: full_square_length = np.sqrt(n_input) pooled_square_length = int(full_square_length / pool_size) dense_inputs = pooled_square_length**2 * n_conv_2 weight_dict = { 'W_c1': tf.get_variable('W_c1', [k_conv_1, k_conv_1, 1, n_conv_1], initializer=wt_init), 'W_c2': tf.get_variable('W_c2', [k_conv_2, k_conv_2, n_conv_1, n_conv_2], initializer=wt_init), 'W_d1': tf.get_variable('W_d1', [dense_inputs, n_dense], initializer=wt_init), 'W_out': tf.get_variable('W_out', [n_dense, n_classes], initializer=wt_init) } predictions = network(x, weight_dict, bias_dict, n_input, pool_size, mp_layer_dropout, dense_layer_dropout) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=predictions, labels=y)) optimizer = tf.train.AdamOptimizer().minimize(cost) correct_prediction = tf.equal(tf.argmax(predictions, 1), tf.argmax(y, 1)) accuracy_pct = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) * 100 initializer_op = tf.global_variables_initializer() with tf.Session() as session: session.run(initializer_op) print("Training for", epochs, "epochs.") # loop over epochs: for epoch in range(epochs): avg_cost = 0.0 # track cost to monitor performance during training avg_accuracy_pct = 0.0 # loop over all batches of the epoch: n_batches = int(mnist.train.num_examples / batch_size) for i in range(n_batches): if i % display_progress == 0: print("Step " + str(i+1), " of " + str(n_batches) + " in epoch " + str(epoch+1)) batch_x, batch_y = mnist.train.next_batch(batch_size) # feed batch data to run optimization and fetching cost and accuracy: _, batch_cost, batch_acc = session.run([optimizer, cost, accuracy_pct], feed_dict={x: batch_x, y: batch_y}) # accumulate mean loss and accuracy over epoch: avg_cost += batch_cost / n_batches avg_accuracy_pct += batch_acc / n_batches # output logs at end of each epoch of training: print("Epoch " '%03d' % (epoch+1), ": cost = " '{:.3f}'.format(avg_cost), "accuracy = " '{:.2f}'.format(avg_accuracy_pct) + "%") print("Training Complete. Testing Model.\n") test_cost = cost.eval({x: mnist.test.images, y: mnist.test.labels}) test_accuracy_pct = accuracy_pct.eval({x: mnist.test.images, y: mnist.test.labels}) print("Test Cost:", '{:.3f}'.format(test_cost)) print("Test Accuracy: ", '{:.2f}'.format(test_accuracy_pct) + "%")
0.76769
0.919462
``` import sys sys.path.append('..') import torch import pandas as pd import numpy as np import pickle import argparse import networkx as nx from torch_geometric.utils import dense_to_sparse, degree import matplotlib.pyplot as plt from src.gcn import GCNSynthetic from src.utils.utils import normalize_adj, get_neighbourhood ``` ### Syn5 dataset (tree grid) , best params so far: SGD, epochs=500, LR=0.1, beta=0.5 #### Uses correct version of symmetry constraint #### For tree-grid, class 0 = base tree, class 1 = grid ``` header = ["node_idx", "new_idx", "cf_adj", "sub_adj", "y_pred_cf", "y_pred_orig", "label", "num_nodes", "node_dict", "loss_graph_dist"] # For original model dataset = "syn5" hidden = 20 seed = 42 dropout = 0.0 # Load original dataset and model with open("../data/gnn_explainer/{}.pickle".format(dataset), "rb") as f: data = pickle.load(f) adj = torch.Tensor(data["adj"]).squeeze() # Does not include self loops features = torch.Tensor(data["feat"]).squeeze() labels = torch.tensor(data["labels"]).squeeze() idx_train = torch.tensor(data["train_idx"]) idx_test = torch.tensor(data["test_idx"]) edge_index = dense_to_sparse(adj) norm_adj = normalize_adj(adj) model = GCNSynthetic(nfeat=features.shape[1], nhid=hidden, nout=hidden, nclass=len(labels.unique()), dropout=dropout) model.load_state_dict(torch.load("../models/gcn_3layer_{}.pt".format(dataset))) model.eval() output = model(features, norm_adj) y_pred_orig = torch.argmax(output, dim=1) print("test set y_true counts: {}".format(np.unique(labels[idx_test].numpy(), return_counts=True))) print("test set y_pred_orig counts: {}".format(np.unique(y_pred_orig[idx_test].numpy(), return_counts=True))) print("Whole graph counts: {}".format(np.unique(labels.numpy(), return_counts=True))) num_epochs = 500 # Load cf examples for test set with open("../baselines/results/random_perturb/{}_baseline_cf_examples_epochs{}".format(dataset, num_epochs), "rb") as f: cf_examples = pickle.load(f) df = pd.DataFrame(cf_examples, columns=header) print("ALL CF EXAMPLES") print("Num cf examples found: {}/{}".format(len(df), len(idx_test))) print("Average graph distance: {}".format(np.mean(df["loss_graph_dist"]))) df.head() # Add num edges to df num_edges = [] for i in df.index: num_edges.append(sum(sum(df["sub_adj"][i]))/2) df["num_edges"] = num_edges ``` ### FINAL NUMBERS ``` print("Num cf examples found: {}/{}".format(len(df), len(idx_test))) print("Coverage: {}".format(len(df)/len(idx_test))) print("Average graph distance: {}".format(np.mean(df["loss_graph_dist"]))) print("Average prop comp graph perturbed: {}".format(np.mean(df["loss_graph_dist"]/df["num_edges"]))) font = {'weight' : 'normal', 'size' : 18} plt.rc('font', **font) # Plot graph loss of cf examples bins = [i+0.5 for i in range(45)] plt.hist(df["loss_graph_dist"], bins=bins, color='g', weights=np.ones(len(df))/len(df)) plt.xlabel("Explanation Size") plt.xticks([0, 10, 20, 30, 40]) plt.ylim(0, 0.65) plt.ylabel("Prop CF examples") # For accuracy, only look at motif nodes df_motif = df[df["y_pred_orig"] != 0].reset_index(drop=True) accuracy = [] # Get original predictions dict_ypred_orig = dict(zip(sorted(np.concatenate((idx_train.numpy(), idx_test.numpy()))), y_pred_orig.numpy())) for i in range(len(df_motif)): node_idx = df_motif["node_idx"][i] new_idx = df_motif["new_idx"][i] _, _, _, node_dict = get_neighbourhood(int(node_idx), edge_index, 4, features, labels) # Confirm idx mapping is correct if node_dict[node_idx] == df_motif["new_idx"][i]: cf_adj = df_motif["cf_adj"][i] sub_adj = df_motif["sub_adj"][i] perturb = np.abs(cf_adj - sub_adj) perturb_edges = np.nonzero(perturb) # Edge indices nodes_involved = np.unique(np.concatenate((perturb_edges[0], perturb_edges[1]), axis=0)) perturb_nodes = nodes_involved[nodes_involved != new_idx] # Remove original node # Retrieve original node idxs for original predictions perturb_nodes_orig_idx = [] for j in perturb_nodes: perturb_nodes_orig_idx.append([key for (key, value) in node_dict.items() if value == j]) perturb_nodes_orig_idx = np.array(perturb_nodes_orig_idx).flatten() # Retrieve original predictions perturb_nodes_orig_ypred = np.array([dict_ypred_orig[k] for k in perturb_nodes_orig_idx]) nodes_in_motif = perturb_nodes_orig_ypred[perturb_nodes_orig_ypred != 0] prop_correct = len(nodes_in_motif)/len(perturb_nodes_orig_idx) accuracy.append([node_idx, new_idx, perturb_nodes_orig_idx, perturb_nodes_orig_ypred, nodes_in_motif, prop_correct]) df_accuracy = pd.DataFrame(accuracy, columns=["node_idx", "new_idx", "perturb_nodes_orig_idx", "perturb_nodes_orig_ypred", "nodes_in_motif", "prop_correct"]) print("Accuracy", np.mean(df_accuracy["prop_correct"])) ```
github_jupyter
import sys sys.path.append('..') import torch import pandas as pd import numpy as np import pickle import argparse import networkx as nx from torch_geometric.utils import dense_to_sparse, degree import matplotlib.pyplot as plt from src.gcn import GCNSynthetic from src.utils.utils import normalize_adj, get_neighbourhood header = ["node_idx", "new_idx", "cf_adj", "sub_adj", "y_pred_cf", "y_pred_orig", "label", "num_nodes", "node_dict", "loss_graph_dist"] # For original model dataset = "syn5" hidden = 20 seed = 42 dropout = 0.0 # Load original dataset and model with open("../data/gnn_explainer/{}.pickle".format(dataset), "rb") as f: data = pickle.load(f) adj = torch.Tensor(data["adj"]).squeeze() # Does not include self loops features = torch.Tensor(data["feat"]).squeeze() labels = torch.tensor(data["labels"]).squeeze() idx_train = torch.tensor(data["train_idx"]) idx_test = torch.tensor(data["test_idx"]) edge_index = dense_to_sparse(adj) norm_adj = normalize_adj(adj) model = GCNSynthetic(nfeat=features.shape[1], nhid=hidden, nout=hidden, nclass=len(labels.unique()), dropout=dropout) model.load_state_dict(torch.load("../models/gcn_3layer_{}.pt".format(dataset))) model.eval() output = model(features, norm_adj) y_pred_orig = torch.argmax(output, dim=1) print("test set y_true counts: {}".format(np.unique(labels[idx_test].numpy(), return_counts=True))) print("test set y_pred_orig counts: {}".format(np.unique(y_pred_orig[idx_test].numpy(), return_counts=True))) print("Whole graph counts: {}".format(np.unique(labels.numpy(), return_counts=True))) num_epochs = 500 # Load cf examples for test set with open("../baselines/results/random_perturb/{}_baseline_cf_examples_epochs{}".format(dataset, num_epochs), "rb") as f: cf_examples = pickle.load(f) df = pd.DataFrame(cf_examples, columns=header) print("ALL CF EXAMPLES") print("Num cf examples found: {}/{}".format(len(df), len(idx_test))) print("Average graph distance: {}".format(np.mean(df["loss_graph_dist"]))) df.head() # Add num edges to df num_edges = [] for i in df.index: num_edges.append(sum(sum(df["sub_adj"][i]))/2) df["num_edges"] = num_edges print("Num cf examples found: {}/{}".format(len(df), len(idx_test))) print("Coverage: {}".format(len(df)/len(idx_test))) print("Average graph distance: {}".format(np.mean(df["loss_graph_dist"]))) print("Average prop comp graph perturbed: {}".format(np.mean(df["loss_graph_dist"]/df["num_edges"]))) font = {'weight' : 'normal', 'size' : 18} plt.rc('font', **font) # Plot graph loss of cf examples bins = [i+0.5 for i in range(45)] plt.hist(df["loss_graph_dist"], bins=bins, color='g', weights=np.ones(len(df))/len(df)) plt.xlabel("Explanation Size") plt.xticks([0, 10, 20, 30, 40]) plt.ylim(0, 0.65) plt.ylabel("Prop CF examples") # For accuracy, only look at motif nodes df_motif = df[df["y_pred_orig"] != 0].reset_index(drop=True) accuracy = [] # Get original predictions dict_ypred_orig = dict(zip(sorted(np.concatenate((idx_train.numpy(), idx_test.numpy()))), y_pred_orig.numpy())) for i in range(len(df_motif)): node_idx = df_motif["node_idx"][i] new_idx = df_motif["new_idx"][i] _, _, _, node_dict = get_neighbourhood(int(node_idx), edge_index, 4, features, labels) # Confirm idx mapping is correct if node_dict[node_idx] == df_motif["new_idx"][i]: cf_adj = df_motif["cf_adj"][i] sub_adj = df_motif["sub_adj"][i] perturb = np.abs(cf_adj - sub_adj) perturb_edges = np.nonzero(perturb) # Edge indices nodes_involved = np.unique(np.concatenate((perturb_edges[0], perturb_edges[1]), axis=0)) perturb_nodes = nodes_involved[nodes_involved != new_idx] # Remove original node # Retrieve original node idxs for original predictions perturb_nodes_orig_idx = [] for j in perturb_nodes: perturb_nodes_orig_idx.append([key for (key, value) in node_dict.items() if value == j]) perturb_nodes_orig_idx = np.array(perturb_nodes_orig_idx).flatten() # Retrieve original predictions perturb_nodes_orig_ypred = np.array([dict_ypred_orig[k] for k in perturb_nodes_orig_idx]) nodes_in_motif = perturb_nodes_orig_ypred[perturb_nodes_orig_ypred != 0] prop_correct = len(nodes_in_motif)/len(perturb_nodes_orig_idx) accuracy.append([node_idx, new_idx, perturb_nodes_orig_idx, perturb_nodes_orig_ypred, nodes_in_motif, prop_correct]) df_accuracy = pd.DataFrame(accuracy, columns=["node_idx", "new_idx", "perturb_nodes_orig_idx", "perturb_nodes_orig_ypred", "nodes_in_motif", "prop_correct"]) print("Accuracy", np.mean(df_accuracy["prop_correct"]))
0.561575
0.683672
``` import numpy as np import cv2 as cv img = cv.imread('data_hierarchy2.png') img_white_bg = cv.imread('data_hierarchy4.png') """缩小图像,方便看效果 """ def resizeImg(src): height, width = src.shape[:2] size = (int(width * 0.3), int(height * 0.3)) # bgr img = cv.resize(src, size, interpolation=cv.INTER_AREA) return img """找出ROI,用于分割原图 原图有三块区域,一个是地块区域,一个是颜色示例区域,一个距离标尺区域 假设倒排后的轮廓列表是按照0地块,1标尺,2...N颜色排列 """ def findROIContours(src): copy = src.copy() gray = cv.cvtColor(copy, cv.COLOR_BGR2GRAY) # cv.imshow("gray", gray) # 低于thresh都变为黑色,maxval是给binary用的 # 白底 254, 255 黑底 0, 255 threshold = cv.threshold(gray, 0, 255, cv.THRESH_BINARY)[1] # cv.imshow("threshold", threshold) contours, hierarchy = cv.findContours(threshold, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) sortedCnts = sorted(contours, key = cv.contourArea, reverse=True) # cv.drawContours(copy, [maxCnt], -1, (255, 0, 0), 2) # cv.imshow("roi contours", copy) return sortedCnts """按照mask,截取roi """ def getROIByContour(src, cnt): copy = src.copy() mask = np.zeros(copy.shape[:2], np.uint8) mask = cv.fillConvexPoly(mask, cnt, (255,255,255)) # cv.imshow("mask", mask) # print(mask.shape) # print(copy.dtype) roi = cv.bitwise_and(copy, copy, mask=mask) # cv.imshow("roi", roi) return roi """找出所有的地块轮廓 """ def findAllBlockContours(src): copy = src.copy() cv.imshow("findAllBlockContours copy", copy) gray = cv.cvtColor(copy, cv.COLOR_BGR2GRAY) cv.imshow("findAllBlockContours gray", gray) # 这个canny的threshold到底该怎么计算? edges = cv.Canny(gray, 60, 150) cv.imshow("findAllBlockContours edges", edges) contours, hierarchy = cv.findContours(edges, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) for cnt in contours: if cv.contourArea(cnt) > 1000: cv.drawContours(copy, [cnt], -1, (255, 0, 0), 2) cv.imshow("findAllBlockContours", copy) return contours """找出颜色示例里的颜色BGR """ def findBGRColors(cnts): colors = [] for cnt in cnts: epsilon = 0.01 * cv.arcLength(cnt, True) approxCurve = cv.approxPolyDP(cnt, epsilon, True) if len(approxCurve) == 4 and cv.contourArea(cnt) > 1000: x,y,w,h = cv.boundingRect(cnt) # 缩小矩形,去掉边上的干扰 x1,y1,x2,y2 = x+5, y+5, x+w-5, y+h-5 rect = np.array([[x1,y1],[x2,y1],[x2,y2],[x1,y2]]) # print(rect) colorRegion = getROIByContour(img_white_bg, rect) meanMask = np.zeros(img_white_bg.shape[:2], np.uint8) meanMask[y1:y2, x1:x2]=255 # cv.imshow("findColorRegions meanMask", meanMask) b,g,r,a = cv.mean(colorRegion, meanMask) # print(r,g,b) # cv.imshow("findColorRegions", colorRegion) colors.append((b,g,r)) return colors """将BGR转换成HSV """ def convertBGRtoHSV(bgrColors): hsvs = [] for bgr_tuple in bgrColors: b, g, r = bgr_tuple[0] / 255, bgr_tuple[1] / 255, bgr_tuple[2] / 255 rgb_min = min(r, g, b) v = max(r, g, b) if v != 0: s = (v - rgb_min) / v else: s = 0 if r == v: h = (g - b) / (v - rgb_min) * 60 if g == v: h = 120 + (b - r) / (v - rgb_min) * 60 if b == v: h = 240 + (r - g) / (v - rgb_min) * 60 if h < 0: h = h + 360 hsvs.append([h / 2, s * 255, v * 255]) return hsvs def convertHsvToLowerAndUpperList(hsvColors): hsvLowAndUpList = [] threshold = 1 for hsv in hsvColors: h,s,v = hsv[0],hsv[1],hsv[2] lower = [h - threshold, 43,46] upper = [h + threshold, 255, 255] if h == 0: lower[0] = h if h == 180: upper[0] = h hsvLowAndUpList.append((lower, upper)) # todo: 红色特殊[0,10], [156,180] hsvLowAndUpList.append(([156, 43,46], [180, 255, 255])) return hsvLowAndUpList # img = resizeImg(img) # img_white_bg = resizeImg(img_white_bg) sortedCnts = findROIContours(img) rootRegion = getROIByContour(img_white_bg, sortedCnts[0]) # 找出地块,color来检测地块内色块 # blockCnts = findAllBlockContours(rootRegion) # print(len(sortedCnts[2:])) bgrColors = findBGRColors(sortedCnts[2:]) print(bgrColors) hsvColors = convertBGRtoHSV(bgrColors) print(hsvColors) hsvLowAndUpList = convertHsvToLowerAndUpperList(hsvColors) print(hsvLowAndUpList) # # BGR转化为HSV HSV = cv.cvtColor(img, cv.COLOR_BGR2HSV) # cv.imshow("imageHSV", HSV) # cv.imshow('image', img) color = hsvLowAndUpList for (lower, upper) in color: lower = np.array(lower, dtype="uint8") upper = np.array(upper, dtype="uint8") # 根据阈值找到对应颜色区域 mask = cv.inRange(HSV, lower, upper) mask = 255 - mask output = cv.bitwise_and(img_white_bg, img_white_bg, mask=mask) # output = cv.cvtColor(output,cv.COLOR_HSV2BGR) # 展示图片 cv.imshow("images", np.hstack([resizeImg(img), resizeImg(output)])) contours, hierarchy = cv.findContours(mask, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) print(mask.shape) # print(mask[0]) print(len(contours)) cv.drawContours(img, contours, -1, (0, 0, 255), 1) for i in contours: print(cv.contourArea(i)) # 计算缺陷区域面积 x, y, w, h = cv.boundingRect(i) # 画矩形框 cv.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 1) # cv.imwrite(show_result_path, match_img_color) # cv.imshow("detect", img) # cv.imshow("chanle", img) cv.waitKey(0) cv.waitKey(0) cv.destroyAllWindows() ```
github_jupyter
import numpy as np import cv2 as cv img = cv.imread('data_hierarchy2.png') img_white_bg = cv.imread('data_hierarchy4.png') """缩小图像,方便看效果 """ def resizeImg(src): height, width = src.shape[:2] size = (int(width * 0.3), int(height * 0.3)) # bgr img = cv.resize(src, size, interpolation=cv.INTER_AREA) return img """找出ROI,用于分割原图 原图有三块区域,一个是地块区域,一个是颜色示例区域,一个距离标尺区域 假设倒排后的轮廓列表是按照0地块,1标尺,2...N颜色排列 """ def findROIContours(src): copy = src.copy() gray = cv.cvtColor(copy, cv.COLOR_BGR2GRAY) # cv.imshow("gray", gray) # 低于thresh都变为黑色,maxval是给binary用的 # 白底 254, 255 黑底 0, 255 threshold = cv.threshold(gray, 0, 255, cv.THRESH_BINARY)[1] # cv.imshow("threshold", threshold) contours, hierarchy = cv.findContours(threshold, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) sortedCnts = sorted(contours, key = cv.contourArea, reverse=True) # cv.drawContours(copy, [maxCnt], -1, (255, 0, 0), 2) # cv.imshow("roi contours", copy) return sortedCnts """按照mask,截取roi """ def getROIByContour(src, cnt): copy = src.copy() mask = np.zeros(copy.shape[:2], np.uint8) mask = cv.fillConvexPoly(mask, cnt, (255,255,255)) # cv.imshow("mask", mask) # print(mask.shape) # print(copy.dtype) roi = cv.bitwise_and(copy, copy, mask=mask) # cv.imshow("roi", roi) return roi """找出所有的地块轮廓 """ def findAllBlockContours(src): copy = src.copy() cv.imshow("findAllBlockContours copy", copy) gray = cv.cvtColor(copy, cv.COLOR_BGR2GRAY) cv.imshow("findAllBlockContours gray", gray) # 这个canny的threshold到底该怎么计算? edges = cv.Canny(gray, 60, 150) cv.imshow("findAllBlockContours edges", edges) contours, hierarchy = cv.findContours(edges, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) for cnt in contours: if cv.contourArea(cnt) > 1000: cv.drawContours(copy, [cnt], -1, (255, 0, 0), 2) cv.imshow("findAllBlockContours", copy) return contours """找出颜色示例里的颜色BGR """ def findBGRColors(cnts): colors = [] for cnt in cnts: epsilon = 0.01 * cv.arcLength(cnt, True) approxCurve = cv.approxPolyDP(cnt, epsilon, True) if len(approxCurve) == 4 and cv.contourArea(cnt) > 1000: x,y,w,h = cv.boundingRect(cnt) # 缩小矩形,去掉边上的干扰 x1,y1,x2,y2 = x+5, y+5, x+w-5, y+h-5 rect = np.array([[x1,y1],[x2,y1],[x2,y2],[x1,y2]]) # print(rect) colorRegion = getROIByContour(img_white_bg, rect) meanMask = np.zeros(img_white_bg.shape[:2], np.uint8) meanMask[y1:y2, x1:x2]=255 # cv.imshow("findColorRegions meanMask", meanMask) b,g,r,a = cv.mean(colorRegion, meanMask) # print(r,g,b) # cv.imshow("findColorRegions", colorRegion) colors.append((b,g,r)) return colors """将BGR转换成HSV """ def convertBGRtoHSV(bgrColors): hsvs = [] for bgr_tuple in bgrColors: b, g, r = bgr_tuple[0] / 255, bgr_tuple[1] / 255, bgr_tuple[2] / 255 rgb_min = min(r, g, b) v = max(r, g, b) if v != 0: s = (v - rgb_min) / v else: s = 0 if r == v: h = (g - b) / (v - rgb_min) * 60 if g == v: h = 120 + (b - r) / (v - rgb_min) * 60 if b == v: h = 240 + (r - g) / (v - rgb_min) * 60 if h < 0: h = h + 360 hsvs.append([h / 2, s * 255, v * 255]) return hsvs def convertHsvToLowerAndUpperList(hsvColors): hsvLowAndUpList = [] threshold = 1 for hsv in hsvColors: h,s,v = hsv[0],hsv[1],hsv[2] lower = [h - threshold, 43,46] upper = [h + threshold, 255, 255] if h == 0: lower[0] = h if h == 180: upper[0] = h hsvLowAndUpList.append((lower, upper)) # todo: 红色特殊[0,10], [156,180] hsvLowAndUpList.append(([156, 43,46], [180, 255, 255])) return hsvLowAndUpList # img = resizeImg(img) # img_white_bg = resizeImg(img_white_bg) sortedCnts = findROIContours(img) rootRegion = getROIByContour(img_white_bg, sortedCnts[0]) # 找出地块,color来检测地块内色块 # blockCnts = findAllBlockContours(rootRegion) # print(len(sortedCnts[2:])) bgrColors = findBGRColors(sortedCnts[2:]) print(bgrColors) hsvColors = convertBGRtoHSV(bgrColors) print(hsvColors) hsvLowAndUpList = convertHsvToLowerAndUpperList(hsvColors) print(hsvLowAndUpList) # # BGR转化为HSV HSV = cv.cvtColor(img, cv.COLOR_BGR2HSV) # cv.imshow("imageHSV", HSV) # cv.imshow('image', img) color = hsvLowAndUpList for (lower, upper) in color: lower = np.array(lower, dtype="uint8") upper = np.array(upper, dtype="uint8") # 根据阈值找到对应颜色区域 mask = cv.inRange(HSV, lower, upper) mask = 255 - mask output = cv.bitwise_and(img_white_bg, img_white_bg, mask=mask) # output = cv.cvtColor(output,cv.COLOR_HSV2BGR) # 展示图片 cv.imshow("images", np.hstack([resizeImg(img), resizeImg(output)])) contours, hierarchy = cv.findContours(mask, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) print(mask.shape) # print(mask[0]) print(len(contours)) cv.drawContours(img, contours, -1, (0, 0, 255), 1) for i in contours: print(cv.contourArea(i)) # 计算缺陷区域面积 x, y, w, h = cv.boundingRect(i) # 画矩形框 cv.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 1) # cv.imwrite(show_result_path, match_img_color) # cv.imshow("detect", img) # cv.imshow("chanle", img) cv.waitKey(0) cv.waitKey(0) cv.destroyAllWindows()
0.162979
0.363252
If you're opening this Notebook on colab, you will probably need to install the most recent versions of 🤗 Transformers and 🤗 Datasets. We will also need `scipy` and `scikit-learn` for some of the metrics. Uncomment the following cell and run it. We will also need `scipy` and `scikit-learn` for some of the metrics. We will be using `wandb`, the [Weights & Biases Python API](https://wandb.me/intro) to track our metrics. We have already installed it in the cell below, let's log into our acoount to allow tracking. ``` ! pip install transformers ! pip install datasets ! pip install huggingface-hub ! pip install wandb ``` If you're opening this notebook locally, make sure your environment has an install from the last version of those libraries. To be able to share your model with the community and generate results like the one shown in the picture below via the inference API, there are a few more steps to follow. First you have to store your authentication token from the Hugging Face website (sign up [here](https://huggingface.co/join) if you haven't already!) then uncomment the following cell and input your username and password (this only works on Colab, in a regular notebook, you need to do this in a terminal): ``` import wandb # Log in to your W&B account wandb.login() ``` # Fine-tuning a model on a text classification task In this notebook, we will see how to fine-tune one of the [🤗 Transformers](https://github.com/huggingface/transformers) model to a text classification task of the [GLUE Benchmark](https://gluebenchmark.com/). The GLUE Benchmark is a group of nine classification tasks on sentences or pairs of sentences which are: - [CoLA](https://nyu-mll.github.io/CoLA/) (Corpus of Linguistic Acceptability) Determine if a sentence is grammatically correct or not.is a dataset containing sentences labeled grammatically correct or not. - [MNLI](https://arxiv.org/abs/1704.05426) (Multi-Genre Natural Language Inference) Determine if a sentence entails, contradicts or is unrelated to a given hypothesis. (This dataset has two versions, one with the validation and test set coming from the same distribution, another called mismatched where the validation and test use out-of-domain data.) - [MRPC](https://www.microsoft.com/en-us/download/details.aspx?id=52398) (Microsoft Research Paraphrase Corpus) Determine if two sentences are paraphrases from one another or not. - [QNLI](https://rajpurkar.github.io/SQuAD-explorer/) (Question-answering Natural Language Inference) Determine if the answer to a question is in the second sentence or not. (This dataset is built from the SQuAD dataset.) - [QQP](https://data.quora.com/First-Quora-Dataset-Release-Question-Pairs) (Quora Question Pairs2) Determine if two questions are semantically equivalent or not. - [RTE](https://aclweb.org/aclwiki/Recognizing_Textual_Entailment) (Recognizing Textual Entailment) Determine if a sentence entails a given hypothesis or not. - [SST-2](https://nlp.stanford.edu/sentiment/index.html) (Stanford Sentiment Treebank) Determine if the sentence has a positive or negative sentiment. - [STS-B](http://ixa2.si.ehu.es/stswiki/index.php/STSbenchmark) (Semantic Textual Similarity Benchmark) Determine the similarity of two sentences with a score from 1 to 5. - [WNLI](https://cs.nyu.edu/faculty/davise/papers/WinogradSchemas/WS.html) (Winograd Natural Language Inference) Determine if a sentence with an anonymous pronoun and a sentence with this pronoun replaced are entailed or not. (This dataset is built from the Winograd Schema Challenge dataset.) We will see how to easily load the dataset for each one of those tasks and use the `Trainer` API to fine-tune a model on it. We will accomplish sentiment analysis which goes by the acronym 'sst2': ``` task = "sst2" model_checkpoint = "distilbert-base-uncased" batch_size = 16 ``` ## Loading the dataset We will use the [🤗 Datasets](https://github.com/huggingface/datasets) library to download the data and get the metric we need to use for evaluation (to compare our model to the benchmark). This can be easily done with the functions `load_dataset` and `load_metric`. ``` from datasets import load_dataset dataset = load_dataset("glue", "sst2") ``` The `dataset` object itself is [`DatasetDict`](https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasetdict), which contains one key for the training, validation and test set. ## Preprocessing the data Before we can feed those texts to our model, we need to preprocess them. This is done by a 🤗 Transformers `Tokenizer` which will (as the name indicates) tokenize the inputs (including converting the tokens to their corresponding IDs in the pretrained vocabulary) and put it in a format the model expects, as well as generate the other inputs that model requires. To do all of this, we instantiate our tokenizer with the `AutoTokenizer.from_pretrained` method, which will ensure: - we get a tokenizer that corresponds to the model architecture we want to use, - we download the vocabulary used when pretraining this specific checkpoint. That vocabulary will be cached, so it's not downloaded again the next time we run the cell. ``` from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained(model_checkpoint) ``` You can directly call this tokenizer on one sentence or a pair of sentences: ``` tokenizer("Hello, this one sentence!", "And this sentence goes with it.") ``` Let's see an example: ``` sample = dataset["train"][0]["sentence"] print(f"Sentence: {sample}") ``` We can them write the function that will preprocess our samples. We just feed them to the `tokenizer` with the arguments `truncation=True` and `padding='longest`. This will ensure that an input longer that what the model selected can handle will be truncated to the maximum length accepted by the model, and all inputs will be padded to the maximum input length to give us a single input array. A more performant method that reduces the number of padding tokens is to write a generator or `tf.data.Dataset` to only pad each *batch* to the maximum length in that batch, but most GLUE tasks are relatively quick on modern GPUs either way. ``` def preprocess_function(examples): return tokenizer(examples["sentence"], truncation=True) ``` To apply this function on all the sentences (or pairs of sentences) in our dataset, we just use the `map` method of our `dataset` object we created earlier. This will apply the function on all the elements of all the splits in `dataset`, so our training, validation and testing data will be preprocessed in one single command. ``` pre_tokenizer_columns = set(dataset["train"].features) encoded_dataset = dataset.map(preprocess_function, batched=True) tokenizer_columns = list(set(encoded_dataset["train"].features) - pre_tokenizer_columns) print("Columns added by tokenizer:", tokenizer_columns) ``` Even better, the results are automatically cached by the 🤗 Datasets library to avoid spending time on this step the next time you run your notebook. The 🤗 Datasets library is normally smart enough to detect when the function you pass to map has changed (and thus requires to not use the cache data). For instance, it will properly detect if you change the task in the first cell and rerun the notebook. 🤗 Datasets warns you when it uses cached files, you can pass `load_from_cache_file=False` in the call to `map` to not use the cached files and force the preprocessing to be applied again. Note that we passed `batched=True` to encode the texts by batches together. This is to leverage the full benefit of the fast tokenizer we loaded earlier, which will use multi-threading to treat the texts in a batch concurrently. Finally, we convert our datasets to `tf.data.Dataset`. There's a built-in method for this, so all you need to do is specify the columns you want (both for the inputs and the labels), whether the data should be shuffled, the batch size, and an optional collation function, that controls how a batch of samples is combined. We'll need to supply a `DataCollator` for this. The `DataCollator` handles grouping each batch of samples together, and different tasks will require different data collators. In this case, we will use the `DataCollatorWithPadding`, because our samples need to be padded to the same length to form a batch. Remember to supply the `return_tensors` argument too - our data collators can handle multiple frameworks, so you need to be clear that you want TensorFlow tensors back. ``` from transformers import DataCollatorWithPadding data_collator = DataCollatorWithPadding(tokenizer=tokenizer, return_tensors="tf") tf_train_dataset = encoded_dataset["train"].to_tf_dataset( columns=tokenizer_columns, label_cols=["labels"], shuffle=True, batch_size=16, collate_fn=data_collator, ) tf_validation_dataset = encoded_dataset["validation"].to_tf_dataset( columns=tokenizer_columns, label_cols=["labels"], shuffle=False, batch_size=16, collate_fn=data_collator, ) ``` ## Fine-tuning the model Now that our data is ready, we can download the pretrained model and fine-tune it. Since all our tasks are about sentence classification, we use the `TFAutoModelForSequenceClassification` class. Like with the tokenizer, the `from_pretrained` method will download and cache the model for us. The only thing we have to specify is the number of labels for our problem (which is always 2, except for STS-B which is a regression problem and MNLI where we have 3 labels). We also need to get the appropriate loss function (SparseCategoricalCrossentropy for every task except STSB, which as a regression problem requires MeanSquaredError). Note that all models in `transformers` compute loss internally too, and you can train on this loss value. This can be very helpful when the loss is not easy to specify yourself. To use this, pass the labels as a `labels` key in the input dictionary, and then compile the model without specifying a loss. You can see examples of this approach in several of the other TensorFlow notebooks. ``` from transformers import TFAutoModelForSequenceClassification import tensorflow as tf loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) num_labels = 2 model = TFAutoModelForSequenceClassification.from_pretrained( model_checkpoint, num_labels=num_labels ) ``` The warning is telling us we are throwing away some weights (the `vocab_transform` and `vocab_layer_norm` layers) and randomly initializing some other (the `pre_classifier` and `classifier` layers). This is absolutely normal in this case, because we are removing the head used to pretrain the model on a masked language modeling objective and replacing it with a new head for which we don't have pretrained weights, so the library warns us we should fine-tune this model before using it for inference, which is exactly what we are going to do. ``` optimizer = tf.keras.optimizers.Adam(learning_rate=0.0001) model.compile(optimizer=optimizer, loss=loss) ``` We can now finetune our model by just calling the `fit` method. Be sure to pass the TF datasets, and not the original datasets! We can also add a callback to sync up our model with the Hub - this allows us to resume training from other machines and even test the model's inference quality midway through training! Make sure to change the `username` if you do. If you don't want to do this, simply remove the callbacks argument in the call to `fit()`. ``` !curl -s https://packagecloud.io/install/repositories/github/git-lfs/script.deb.sh | sudo bash !apt install git-lfs !git-lfs install !huggingface-cli login ``` ## Weights & Biases Experiment Tracking Weights and Biases is a one stop for tracking your experiments, model weights and datasets, running hyper parameter sweeps. For now, we will call `wandb.init()` using the API to initialise our project ``` wandb.init(entity = "mervenoyan", project = "keras-workshop") config = wandb.config config.batch_size = 16 ``` Weights and Biases currently has integrations for all major Python frameworks, since we are working with Keras, we can grab the handy `wandb.keras.WandbCallback()` to log our weights and experiment ``` wandb_callback = wandb.keras.WandbCallback(log_weights = True) from transformers.keras_callbacks import PushToHubCallback, KerasMetricCallback from tensorflow.keras.callbacks import TensorBoard from datasets import load_metric push_to_hub_callback = PushToHubCallback( output_dir="./text_classification_model_save", tokenizer=tokenizer, hub_model_id="keras-io/sentiment-analysis", ) metric_name = "accuracy" metric = load_metric("glue", "sst2") def compute_metrics(eval_predictions): predictions, labels = eval_predictions predictions = predictions[:, 0] return metric.compute(predictions=predictions, references=labels) metric_callback = KerasMetricCallback( metric_fn=compute_metrics, eval_dataset=tf_validation_dataset ) callbacks = [metric_callback, wandb_callback, push_to_hub_callback] model.fit( tf_train_dataset, validation_data=tf_validation_dataset, epochs=5, callbacks = callbacks ) ``` ### Directly load model from Hub! ``` from transformers import pipeline text_clf = pipeline("text-classification", "keras-io/sentiment-analysis") text_clf("I love HuggingFace!") ``` ## Let's build a demo! ``` !pip install gradio import gradio as gr gr.Interface.load("huggingface/keras-io/sentiment-analysis", examples=[["I love Tensorflow"]], theme="grass", title="Sentiment Analysis with Keras", description="This model can detect sentiment").launch() ```
github_jupyter
! pip install transformers ! pip install datasets ! pip install huggingface-hub ! pip install wandb import wandb # Log in to your W&B account wandb.login() task = "sst2" model_checkpoint = "distilbert-base-uncased" batch_size = 16 from datasets import load_dataset dataset = load_dataset("glue", "sst2") from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained(model_checkpoint) tokenizer("Hello, this one sentence!", "And this sentence goes with it.") sample = dataset["train"][0]["sentence"] print(f"Sentence: {sample}") def preprocess_function(examples): return tokenizer(examples["sentence"], truncation=True) pre_tokenizer_columns = set(dataset["train"].features) encoded_dataset = dataset.map(preprocess_function, batched=True) tokenizer_columns = list(set(encoded_dataset["train"].features) - pre_tokenizer_columns) print("Columns added by tokenizer:", tokenizer_columns) from transformers import DataCollatorWithPadding data_collator = DataCollatorWithPadding(tokenizer=tokenizer, return_tensors="tf") tf_train_dataset = encoded_dataset["train"].to_tf_dataset( columns=tokenizer_columns, label_cols=["labels"], shuffle=True, batch_size=16, collate_fn=data_collator, ) tf_validation_dataset = encoded_dataset["validation"].to_tf_dataset( columns=tokenizer_columns, label_cols=["labels"], shuffle=False, batch_size=16, collate_fn=data_collator, ) from transformers import TFAutoModelForSequenceClassification import tensorflow as tf loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) num_labels = 2 model = TFAutoModelForSequenceClassification.from_pretrained( model_checkpoint, num_labels=num_labels ) optimizer = tf.keras.optimizers.Adam(learning_rate=0.0001) model.compile(optimizer=optimizer, loss=loss) !curl -s https://packagecloud.io/install/repositories/github/git-lfs/script.deb.sh | sudo bash !apt install git-lfs !git-lfs install !huggingface-cli login wandb.init(entity = "mervenoyan", project = "keras-workshop") config = wandb.config config.batch_size = 16 wandb_callback = wandb.keras.WandbCallback(log_weights = True) from transformers.keras_callbacks import PushToHubCallback, KerasMetricCallback from tensorflow.keras.callbacks import TensorBoard from datasets import load_metric push_to_hub_callback = PushToHubCallback( output_dir="./text_classification_model_save", tokenizer=tokenizer, hub_model_id="keras-io/sentiment-analysis", ) metric_name = "accuracy" metric = load_metric("glue", "sst2") def compute_metrics(eval_predictions): predictions, labels = eval_predictions predictions = predictions[:, 0] return metric.compute(predictions=predictions, references=labels) metric_callback = KerasMetricCallback( metric_fn=compute_metrics, eval_dataset=tf_validation_dataset ) callbacks = [metric_callback, wandb_callback, push_to_hub_callback] model.fit( tf_train_dataset, validation_data=tf_validation_dataset, epochs=5, callbacks = callbacks ) from transformers import pipeline text_clf = pipeline("text-classification", "keras-io/sentiment-analysis") text_clf("I love HuggingFace!") !pip install gradio import gradio as gr gr.Interface.load("huggingface/keras-io/sentiment-analysis", examples=[["I love Tensorflow"]], theme="grass", title="Sentiment Analysis with Keras", description="This model can detect sentiment").launch()
0.732113
0.975296
# dislib tutorial This tutorial will show the basics of using [dislib](https://dislib.bsc.es). ## Requirements Apart from dislib, this notebook requires [PyCOMPSs 2.5](https://www.bsc.es/research-and-development/software-and-apps/software-list/comp-superscalar/). ## Setup First, we need to start an interactive PyCOMPSs session: ``` import pycompss.interactive as ipycompss ipycompss.start(graph=True, monitor=1000) ``` Next, we import dislib and we are all set to start working! ``` import dislib as ds ``` ## Distributed arrays The main data structure in dislib is the distributed array (or ds-array). These arrays are a distributed representation of a 2-dimensional array that can be operated as a regular Python object. Usually, rows in the array represent samples, while columns represent features. To create a random array we can run the following NumPy-like command: ``` x = ds.random_array(shape=(500, 500), block_size=(100, 100)) print(x.shape) x ``` Now `x` is a 500x500 ds-array of random numbers stored in blocks of 100x100 elements. Note that `x` is not stored in memory. Instead, `random_array` generates the contents of the array in tasks that are usually executed remotely. This allows the creation of really big arrays. The content of `x` is a list of `Futures` that represent the actual data (wherever it is stored). To see this, we can access the `_blocks` field of `x`: ``` x._blocks[0][0] ``` `block_size` is useful to control the granularity of dislib algorithms. To retrieve the actual contents of `x`, we use `collect`, which synchronizes the data and returns the equivalent NumPy array: ``` x.collect() ``` Another way of creating ds-arrays is using array-like structures like NumPy arrays or lists: ``` x1 = ds.array([[1, 2, 3], [4, 5, 6]], block_size=(1, 3)) x1 ``` Distributed arrays can also store sparse data in CSR format: ``` from scipy.sparse import csr_matrix sp = csr_matrix([[0, 0, 1], [1, 0, 1]]) x_sp = ds.array(sp, block_size=(1, 3)) x_sp ``` In this case, `collect` returns a CSR matrix as well: ``` x_sp.collect() ``` ### Loading data A typical way of creating ds-arrays is to load data from disk. Dislib currently supports reading data in CSV and SVMLight formats like this: ``` x, y = ds.load_svmlight_file("../tests/files/libsvm/1", block_size=(20, 100), n_features=780, store_sparse=True) print(x) csv = ds.load_txt_file("../tests/files/csv/1", block_size=(500, 122)) print(csv) ``` ### Slicing Similar to NumPy, ds-arrays support the following types of slicing: (Note that slicing a ds-array creates a new ds-array) ``` x = ds.random_array((50, 50), (10, 10)) ``` Get a single row: ``` x[4] ``` Get a single element: ``` x[2, 3] ``` Get a set of rows or a set of columns: ``` # Consecutive rows print(x[10:20]) # Consecutive columns print(x[:, 10:20]) # Non consecutive rows print(x[[3, 7, 22]]) # Non consecutive columns print(x[:, [5, 9, 48]]) ``` Get any set of elements: ``` x[0:5, 40:45] ``` ### Other functions Apart from this, ds-arrays also provide other useful operations like `transpose` and `mean`: ``` x.mean(axis=0).collect() x.transpose().collect() ``` ## Machine learning with dislib Dislib provides an estimator-based API very similar to [scikit-learn](https://scikit-learn.org/stable/). To run an algorithm, we first create an estimator. For example, a K-means estimator: ``` from dislib.cluster import KMeans km = KMeans(n_clusters=3) ``` Now, we create a ds-array with some blob data, and fit the estimator: ``` from sklearn.datasets import make_blobs # create ds-array x, y = make_blobs(n_samples=1500) x_ds = ds.array(x, block_size=(500, 2)) km.fit(x_ds) ``` Finally, we can make predictions on new (or the same) data: ``` y_pred = km.predict(x_ds) y_pred ``` `y_pred` is a ds-array of predicted labels for `x_ds` Let's plot the results ``` %matplotlib inline import matplotlib.pyplot as plt centers = km.centers # set the color of each sample to the predicted label plt.scatter(x[:, 0], x[:, 1], c=y_pred.collect()) # plot the computed centers in red plt.scatter(centers[:, 0], centers[:, 1], c='red') ``` Note that we need to call `y_pred.collect()` to retrieve the actual labels and plot them. The rest is the same as if we were using scikit-learn. Now let's try a more complex example that uses some preprocessing tools. First, we load a classification data set from scikit-learn into ds-arrays. Note that this step is only necessary for demonstration purposes. Ideally, your data should be already loaded in ds-arrays. ``` from sklearn.datasets import load_breast_cancer from sklearn.model_selection import train_test_split x, y = load_breast_cancer(return_X_y=True) x_train, x_test, y_train, y_test = train_test_split(x, y) x_train = ds.array(x_train, block_size=(100, 10)) y_train = ds.array(y_train.reshape(-1, 1), block_size=(100, 1)) x_test = ds.array(x_test, block_size=(100, 10)) y_test = ds.array(y_test.reshape(-1, 1), block_size=(100, 1)) ``` Next, we can see how support vector machines perform in classifying the data. We first fit the model (ignore any warnings in this step): ``` from dislib.classification import CascadeSVM csvm = CascadeSVM() csvm.fit(x_train, y_train) ``` and now we can make predictions on new data using `csvm.predict()`, or we can get the model accuracy on the test set with: ``` score = csvm.score(x_test, y_test) ``` `score` represents the classifier accuracy, however, it is returned as a `Future`. We need to synchronize to get the actual value: ``` from pycompss.api.api import compss_wait_on print(compss_wait_on(score)) ``` The accuracy should be around 0.6, which is not very good. We can scale the data before classification to improve accuracy. This can be achieved using dislib's `StandardScaler`. The `StandardScaler` provides the same API as other estimators. In this case, however, instead of making predictions on new data, we transform it: ``` from dislib.preprocessing import StandardScaler sc = StandardScaler() # fit the scaler with train data and transform it scaled_train = sc.fit_transform(x_train) # transform test data scaled_test = sc.transform(x_test) ``` Now `scaled_train` and `scaled_test` are the scaled samples. Let's see how SVM perfroms now. ``` csvm.fit(scaled_train, y_train) score = csvm.score(scaled_test, y_test) print(compss_wait_on(score)) ``` The new accuracy should be around 0.9, which is a great improvement! ### Close the session To finish the session, we need to stop PyCOMPSs: ``` ipycompss.stop() ```
github_jupyter
import pycompss.interactive as ipycompss ipycompss.start(graph=True, monitor=1000) import dislib as ds x = ds.random_array(shape=(500, 500), block_size=(100, 100)) print(x.shape) x x._blocks[0][0] x.collect() x1 = ds.array([[1, 2, 3], [4, 5, 6]], block_size=(1, 3)) x1 from scipy.sparse import csr_matrix sp = csr_matrix([[0, 0, 1], [1, 0, 1]]) x_sp = ds.array(sp, block_size=(1, 3)) x_sp x_sp.collect() x, y = ds.load_svmlight_file("../tests/files/libsvm/1", block_size=(20, 100), n_features=780, store_sparse=True) print(x) csv = ds.load_txt_file("../tests/files/csv/1", block_size=(500, 122)) print(csv) x = ds.random_array((50, 50), (10, 10)) x[4] x[2, 3] # Consecutive rows print(x[10:20]) # Consecutive columns print(x[:, 10:20]) # Non consecutive rows print(x[[3, 7, 22]]) # Non consecutive columns print(x[:, [5, 9, 48]]) x[0:5, 40:45] x.mean(axis=0).collect() x.transpose().collect() from dislib.cluster import KMeans km = KMeans(n_clusters=3) from sklearn.datasets import make_blobs # create ds-array x, y = make_blobs(n_samples=1500) x_ds = ds.array(x, block_size=(500, 2)) km.fit(x_ds) y_pred = km.predict(x_ds) y_pred %matplotlib inline import matplotlib.pyplot as plt centers = km.centers # set the color of each sample to the predicted label plt.scatter(x[:, 0], x[:, 1], c=y_pred.collect()) # plot the computed centers in red plt.scatter(centers[:, 0], centers[:, 1], c='red') from sklearn.datasets import load_breast_cancer from sklearn.model_selection import train_test_split x, y = load_breast_cancer(return_X_y=True) x_train, x_test, y_train, y_test = train_test_split(x, y) x_train = ds.array(x_train, block_size=(100, 10)) y_train = ds.array(y_train.reshape(-1, 1), block_size=(100, 1)) x_test = ds.array(x_test, block_size=(100, 10)) y_test = ds.array(y_test.reshape(-1, 1), block_size=(100, 1)) from dislib.classification import CascadeSVM csvm = CascadeSVM() csvm.fit(x_train, y_train) score = csvm.score(x_test, y_test) from pycompss.api.api import compss_wait_on print(compss_wait_on(score)) from dislib.preprocessing import StandardScaler sc = StandardScaler() # fit the scaler with train data and transform it scaled_train = sc.fit_transform(x_train) # transform test data scaled_test = sc.transform(x_test) csvm.fit(scaled_train, y_train) score = csvm.score(scaled_test, y_test) print(compss_wait_on(score)) ipycompss.stop()
0.46393
0.991263
``` !pip install wget !pip install --upgrade scikit-learn import util X1, y1, X2, y2 = util.mnist_init('small') util.image_peek(X1[1], 5 if y1[1] == 1 else 8) util.image_peek(X1[3], 5 if y1[3] == 1 else 8) import numpy as np class Perceptron(object): def __init__(self, dataset, labels, max_iter, lr): self.b = 0 self.w = np.zeros(dataset.shape[1]) self.labels = labels self.dataset = dataset self.max_iter = max_iter self.lr = lr self.func = lambda x: 1 if x > 0 else -1 def fit(self): for i in range(self.max_iter): flag = 0 for x, y in zip(self.dataset, self.labels): y_ = self.func(np.dot(self.w, x) + self.b) if y*y_<0: self.w += (y - y_) * self.lr * x self.b += (y - y_) * self.lr flag = 1 if flag == 0: break def predict(self, test_set): return [self.func(np.dot(self.w, x) + self.b) for x in test_set] def score(self, test_set, test_labels, view=False): if view == True: util.image_peek(self.w, "Weight") y_predict = self.predict(test_set) return sum(y_predict[i] == test_labels[i] for i in range(len(test_labels))) / len(test_labels) clf = Perceptron(X1, y1, 100, 1e-6) clf.fit() print(clf.score(X2, y2, True)) y_pred = clf.predict(X2) print(util.f1_score(y2, y_pred)) print(util.recall_score(y2, y_pred)) clf = Perceptron(X1, y1, 100, 1e-3) clf.fit() print(clf.score(X2, y2)) y_pred = clf.predict(X2) print(util.f1_score(y2, y_pred)) print(util.recall_score(y2, y_pred)) clf = Perceptron(X1, y1, 200, 1e-6) clf.fit() print(clf.score(X2, y2, True)) y_pred = clf.predict(X2) print(util.f1_score(y2, y_pred)) print(util.recall_score(y2, y_pred)) clf = Perceptron(X1, y1, 200, 1e-3) clf.fit() print(clf.score(X2, y2)) y_pred = clf.predict(X2) print(util.f1_score(y2, y_pred)) print(util.recall_score(y2, y_pred)) clf = Perceptron(X1, y1, 400, 1e-6) clf.fit() print(clf.score(X2, y2, True)) y_pred = clf.predict(X2) print(util.f1_score(y2, y_pred)) print(util.recall_score(y2, y_pred)) clf = Perceptron(X1, y1, 400, 1e-3) clf.fit() print(clf.score(X2, y2)) y_pred = clf.predict(X2) print(util.f1_score(y2, y_pred)) print(util.recall_score(y2, y_pred)) class LSEClassifier(object): def __init__(self, dataset, labels, max_iter, lr): self.dataset = np.array([np.append(dataset[i]*labels[i], labels[i]) for i in range(len(dataset))]) self.labels = labels self.b = np.ones(self.dataset.shape[0]) self.w = None self.max_iter = max_iter self.lr = lr def fit(self): for i in range(self.max_iter): self.w = np.dot(np.linalg.pinv(self.dataset), self.b) e = np.dot(self.dataset, self.w) - self.b if np.all(self.b <= 0): break else: self.b = self.b + self.lr*(e*abs(e)) def predict(self, test_set): return np.dot(test_set, self.w) def score(self, test_set, test_labels): test_set = np.array([np.append(test_set[i]*test_labels[i], test_labels[i]) for i in range(len(test_set))]) y_predict = self.predict(test_set) return sum([y_predict[i]>0 for i in range(len(y_predict))])/len(y_predict) clf = LSEClassifier(X1, y1, 20, 1e-4) clf.fit() print(clf.score(X2, y2)) clf = LSEClassifier(X1, y1, 40, 1e-4) clf.fit() print(clf.score(X2, y2)) clf = LSEClassifier(X1, y1, 20, 1e-2) clf.fit() print(clf.score(X2, y2)) clf = LSEClassifier(X1, y1, 40, 1e-2) clf.fit() print(clf.score(X2, y2)) class FisherClassifier(object): def __init__(self, dataset, labels): self.dataset = dataset self.labels = labels self.w = None bnd = None def fit(self): case1_dt = np.array([self.dataset[i] for i in range(self.dataset.shape[0]) if self.labels[i] == 1]) case2_dt = np.array([self.dataset[i] for i in range(self.dataset.shape[0]) if self.labels[i] == -1]) case1_mean = np.mean(case1_dt, axis=0) case2_mean = np.mean(case2_dt, axis=0) case1_sw = np.dot((case1_dt - case1_mean).T, (case1_dt - case1_mean)) case2_sw = np.dot((case2_dt - case2_mean).T, (case2_dt - case2_mean)) self.w = np.dot(np.linalg.pinv(case1_sw + case2_sw), (case1_mean - case2_mean)) self.bnd = (np.dot(self.w, case1_mean) + np.dot(self.w, case2_mean))/2 def score(self, test_set, test_labels, view=False): case1_dt = np.array([test_set[i] for i in range(test_set.shape[0]) if test_labels[i] == 1]) case2_dt = np.array([test_set[i] for i in range(test_set.shape[0]) if test_labels[i] == -1]) case1_proj = [np.dot(self.w, x) for x in case1_dt] case2_proj = [np.dot(self.w, x) for x in case2_dt] case1_ac = sum([x>self.bnd for x in case1_proj])/len(case1_proj) case2_ac = sum([x<self.bnd for x in case2_proj])/len(case2_proj) total_ac = sum([x>self.bnd for x in case1_proj]+[x<self.bnd for x in case2_proj])/(len(case1_proj)+len(case2_proj)) return case1_ac, case2_ac, total_ac clf = FisherClassifier(X1, y1) clf.fit() clf.score(X2, y2) X1, y1, X2, y2 = util.mnist_init('complete') util.image_peek(X1[1], y1[1]) ac = [] for z1, z2 in util.convert2ovr(y1, y2): clf = Perceptron(X1, z1, 200, 1e-3) clf.fit() ac.append(clf.score(X2, z2)) print(ac) np.mean(ac, axis=0) ```
github_jupyter
!pip install wget !pip install --upgrade scikit-learn import util X1, y1, X2, y2 = util.mnist_init('small') util.image_peek(X1[1], 5 if y1[1] == 1 else 8) util.image_peek(X1[3], 5 if y1[3] == 1 else 8) import numpy as np class Perceptron(object): def __init__(self, dataset, labels, max_iter, lr): self.b = 0 self.w = np.zeros(dataset.shape[1]) self.labels = labels self.dataset = dataset self.max_iter = max_iter self.lr = lr self.func = lambda x: 1 if x > 0 else -1 def fit(self): for i in range(self.max_iter): flag = 0 for x, y in zip(self.dataset, self.labels): y_ = self.func(np.dot(self.w, x) + self.b) if y*y_<0: self.w += (y - y_) * self.lr * x self.b += (y - y_) * self.lr flag = 1 if flag == 0: break def predict(self, test_set): return [self.func(np.dot(self.w, x) + self.b) for x in test_set] def score(self, test_set, test_labels, view=False): if view == True: util.image_peek(self.w, "Weight") y_predict = self.predict(test_set) return sum(y_predict[i] == test_labels[i] for i in range(len(test_labels))) / len(test_labels) clf = Perceptron(X1, y1, 100, 1e-6) clf.fit() print(clf.score(X2, y2, True)) y_pred = clf.predict(X2) print(util.f1_score(y2, y_pred)) print(util.recall_score(y2, y_pred)) clf = Perceptron(X1, y1, 100, 1e-3) clf.fit() print(clf.score(X2, y2)) y_pred = clf.predict(X2) print(util.f1_score(y2, y_pred)) print(util.recall_score(y2, y_pred)) clf = Perceptron(X1, y1, 200, 1e-6) clf.fit() print(clf.score(X2, y2, True)) y_pred = clf.predict(X2) print(util.f1_score(y2, y_pred)) print(util.recall_score(y2, y_pred)) clf = Perceptron(X1, y1, 200, 1e-3) clf.fit() print(clf.score(X2, y2)) y_pred = clf.predict(X2) print(util.f1_score(y2, y_pred)) print(util.recall_score(y2, y_pred)) clf = Perceptron(X1, y1, 400, 1e-6) clf.fit() print(clf.score(X2, y2, True)) y_pred = clf.predict(X2) print(util.f1_score(y2, y_pred)) print(util.recall_score(y2, y_pred)) clf = Perceptron(X1, y1, 400, 1e-3) clf.fit() print(clf.score(X2, y2)) y_pred = clf.predict(X2) print(util.f1_score(y2, y_pred)) print(util.recall_score(y2, y_pred)) class LSEClassifier(object): def __init__(self, dataset, labels, max_iter, lr): self.dataset = np.array([np.append(dataset[i]*labels[i], labels[i]) for i in range(len(dataset))]) self.labels = labels self.b = np.ones(self.dataset.shape[0]) self.w = None self.max_iter = max_iter self.lr = lr def fit(self): for i in range(self.max_iter): self.w = np.dot(np.linalg.pinv(self.dataset), self.b) e = np.dot(self.dataset, self.w) - self.b if np.all(self.b <= 0): break else: self.b = self.b + self.lr*(e*abs(e)) def predict(self, test_set): return np.dot(test_set, self.w) def score(self, test_set, test_labels): test_set = np.array([np.append(test_set[i]*test_labels[i], test_labels[i]) for i in range(len(test_set))]) y_predict = self.predict(test_set) return sum([y_predict[i]>0 for i in range(len(y_predict))])/len(y_predict) clf = LSEClassifier(X1, y1, 20, 1e-4) clf.fit() print(clf.score(X2, y2)) clf = LSEClassifier(X1, y1, 40, 1e-4) clf.fit() print(clf.score(X2, y2)) clf = LSEClassifier(X1, y1, 20, 1e-2) clf.fit() print(clf.score(X2, y2)) clf = LSEClassifier(X1, y1, 40, 1e-2) clf.fit() print(clf.score(X2, y2)) class FisherClassifier(object): def __init__(self, dataset, labels): self.dataset = dataset self.labels = labels self.w = None bnd = None def fit(self): case1_dt = np.array([self.dataset[i] for i in range(self.dataset.shape[0]) if self.labels[i] == 1]) case2_dt = np.array([self.dataset[i] for i in range(self.dataset.shape[0]) if self.labels[i] == -1]) case1_mean = np.mean(case1_dt, axis=0) case2_mean = np.mean(case2_dt, axis=0) case1_sw = np.dot((case1_dt - case1_mean).T, (case1_dt - case1_mean)) case2_sw = np.dot((case2_dt - case2_mean).T, (case2_dt - case2_mean)) self.w = np.dot(np.linalg.pinv(case1_sw + case2_sw), (case1_mean - case2_mean)) self.bnd = (np.dot(self.w, case1_mean) + np.dot(self.w, case2_mean))/2 def score(self, test_set, test_labels, view=False): case1_dt = np.array([test_set[i] for i in range(test_set.shape[0]) if test_labels[i] == 1]) case2_dt = np.array([test_set[i] for i in range(test_set.shape[0]) if test_labels[i] == -1]) case1_proj = [np.dot(self.w, x) for x in case1_dt] case2_proj = [np.dot(self.w, x) for x in case2_dt] case1_ac = sum([x>self.bnd for x in case1_proj])/len(case1_proj) case2_ac = sum([x<self.bnd for x in case2_proj])/len(case2_proj) total_ac = sum([x>self.bnd for x in case1_proj]+[x<self.bnd for x in case2_proj])/(len(case1_proj)+len(case2_proj)) return case1_ac, case2_ac, total_ac clf = FisherClassifier(X1, y1) clf.fit() clf.score(X2, y2) X1, y1, X2, y2 = util.mnist_init('complete') util.image_peek(X1[1], y1[1]) ac = [] for z1, z2 in util.convert2ovr(y1, y2): clf = Perceptron(X1, z1, 200, 1e-3) clf.fit() ac.append(clf.score(X2, z2)) print(ac) np.mean(ac, axis=0)
0.472927
0.597549
<a href="https://colab.research.google.com/github/ren1406/startbootstrap-freelancer/blob/master/08_sentiment_analysis_with_bert.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Sentiment Analysis with BERT > TL;DR In this tutorial, you'll learn how to fine-tune BERT for sentiment analysis. You'll do the required text preprocessing (special tokens, padding, and attention masks) and build a Sentiment Classifier using the amazing Transformers library by Hugging Face! - [Read the tutorial](https://www.curiousily.com/posts/sentiment-analysis-with-bert-and-hugging-face-using-pytorch-and-python/) - [Run the notebook in your browser (Google Colab)](https://colab.research.google.com/drive/1PHv-IRLPCtv7oTcIGbsgZHqrB5LPvB7S) - [Read the `Getting Things Done with Pytorch` book](https://github.com/curiousily/Getting-Things-Done-with-Pytorch) You'll learn how to: - Intuitively understand what BERT is - Preprocess text data for BERT and build PyTorch Dataset (tokenization, attention masks, and padding) - Use Transfer Learning to build Sentiment Classifier using the Transformers library by Hugging Face - Evaluate the model on test data - Predict sentiment on raw text Let's get started! ``` #@title Watch the video tutorial from IPython.display import YouTubeVideo YouTubeVideo('8N-nM3QW7O0', width=720, height=420) !nvidia-smi ``` ## What is BERT? BERT (introduced in [this paper](https://arxiv.org/abs/1810.04805)) stands for Bidirectional Encoder Representations from Transformers. If you don't know what most of that means - you've come to the right place! Let's unpack the main ideas: - Bidirectional - to understand the text you're looking you'll have to look back (at the previous words) and forward (at the next words) - Transformers - The [Attention Is All You Need](https://arxiv.org/abs/1706.03762) paper presented the Transformer model. The Transformer reads entire sequences of tokens at once. In a sense, the model is non-directional, while LSTMs read sequentially (left-to-right or right-to-left). The attention mechanism allows for learning contextual relations between words (e.g. `his` in a sentence refers to Jim). - (Pre-trained) contextualized word embeddings - [The ELMO paper](https://arxiv.org/abs/1802.05365v2) introduced a way to encode words based on their meaning/context. Nails has multiple meanings - fingernails and metal nails. BERT was trained by masking 15% of the tokens with the goal to guess them. An additional objective was to predict the next sentence. Let's look at examples of these tasks: ### Masked Language Modeling (Masked LM) The objective of this task is to guess the masked tokens. Let's look at an example, and try to not make it harder than it has to be: That's `[mask]` she `[mask]` -> That's what she said ### Next Sentence Prediction (NSP) Given a pair of two sentences, the task is to say whether or not the second follows the first (binary classification). Let's continue with the example: *Input* = `[CLS]` That's `[mask]` she `[mask]`. [SEP] Hahaha, nice! [SEP] *Label* = *IsNext* *Input* = `[CLS]` That's `[mask]` she `[mask]`. [SEP] Dwight, you ignorant `[mask]`! [SEP] *Label* = *NotNext* The training corpus was comprised of two entries: [Toronto Book Corpus](https://arxiv.org/abs/1506.06724) (800M words) and English Wikipedia (2,500M words). While the original Transformer has an encoder (for reading the input) and a decoder (that makes the prediction), BERT uses only the decoder. BERT is simply a pre-trained stack of Transformer Encoders. How many Encoders? We have two versions - with 12 (BERT base) and 24 (BERT Large). ### Is This Thing Useful in Practice? The BERT paper was released along with [the source code](https://github.com/google-research/bert) and pre-trained models. The best part is that you can do Transfer Learning (thanks to the ideas from OpenAI Transformer) with BERT for many NLP tasks - Classification, Question Answering, Entity Recognition, etc. You can train with small amounts of data and achieve great performance! ## Setup We'll need [the Transformers library](https://huggingface.co/transformers/) by Hugging Face: ``` !pip install -q -U watermark !pip install -qq transformers %reload_ext watermark %watermark -v -p numpy,pandas,torch,transformers #@title Setup & Config import transformers from transformers import BertModel, BertTokenizer, AdamW, get_linear_schedule_with_warmup import torch import numpy as np import pandas as pd import seaborn as sns from pylab import rcParams import matplotlib.pyplot as plt from matplotlib import rc from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix, classification_report from collections import defaultdict from textwrap import wrap from torch import nn, optim from torch.utils.data import Dataset, DataLoader import torch.nn.functional as F %matplotlib inline %config InlineBackend.figure_format='retina' sns.set(style='whitegrid', palette='muted', font_scale=1.2) HAPPY_COLORS_PALETTE = ["#01BEFE", "#FFDD00", "#FF7D00", "#FF006D", "#ADFF02", "#8F00FF"] sns.set_palette(sns.color_palette(HAPPY_COLORS_PALETTE)) rcParams['figure.figsize'] = 12, 8 RANDOM_SEED = 42 np.random.seed(RANDOM_SEED) torch.manual_seed(RANDOM_SEED) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") device ``` ## Data Exploration We'll load the Google Play app reviews dataset, that we've put together in the previous part: ``` !gdown --id 1S6qMioqPJjyBLpLVz4gmRTnJHnjitnuV !gdown --id 1zdmewp7ayS4js4VtrJEHzAheSW-5NBZv df = pd.read_csv("reviews.csv") df.head() df.shape ``` We have about 16k examples. Let's check for missing values: ``` df.info() ``` Great, no missing values in the score and review texts! Do we have class imbalance? ``` sns.countplot(df.score) plt.xlabel('review score'); ``` That's hugely imbalanced, but it's okay. We're going to convert the dataset into negative, neutral and positive sentiment: ``` def to_sentiment(rating): rating = int(rating) if rating <= 2: return 0 elif rating == 3: return 1 else: return 2 df['sentiment'] = df.score.apply(to_sentiment) class_names = ['negative', 'neutral', 'positive'] ax = sns.countplot(df.sentiment) plt.xlabel('review sentiment') ax.set_xticklabels(class_names); ``` The balance was (mostly) restored. ## Data Preprocessing You might already know that Machine Learning models don't work with raw text. You need to convert text to numbers (of some sort). BERT requires even more attention (good one, right?). Here are the requirements: - Add special tokens to separate sentences and do classification - Pass sequences of constant length (introduce padding) - Create array of 0s (pad token) and 1s (real token) called *attention mask* The Transformers library provides (you've guessed it) a wide variety of Transformer models (including BERT). It works with TensorFlow and PyTorch! It also includes prebuild tokenizers that do the heavy lifting for us! ``` PRE_TRAINED_MODEL_NAME = 'bert-base-multilingual-cased' ``` > You can use a cased and uncased version of BERT and tokenizer. I've experimented with both. The cased version works better. Intuitively, that makes sense, since "BAD" might convey more sentiment than "bad". Let's load a pre-trained [BertTokenizer](https://huggingface.co/transformers/model_doc/bert.html#berttokenizer): ``` tokenizer = BertTokenizer.from_pretrained(PRE_TRAINED_MODEL_NAME) ``` We'll use this text to understand the tokenization process: ``` sample_txt = 'hang aplikasinya force close' ``` Some basic operations can convert the text to tokens and tokens to unique integers (ids): ``` tokens = tokenizer.tokenize(sample_txt) token_ids = tokenizer.convert_tokens_to_ids(tokens) print(f' Sentence: {sample_txt}') print(f' Tokens: {tokens}') print(f'Token IDs: {token_ids}') ``` ### Special Tokens `[SEP]` - marker for ending of a sentence ``` tokenizer.sep_token, tokenizer.sep_token_id ``` `[CLS]` - we must add this token to the start of each sentence, so BERT knows we're doing classification ``` tokenizer.cls_token, tokenizer.cls_token_id ``` There is also a special token for padding: ``` tokenizer.pad_token, tokenizer.pad_token_id ``` BERT understands tokens that were in the training set. Everything else can be encoded using the `[UNK]` (unknown) token: ``` tokenizer.unk_token, tokenizer.unk_token_id ``` All of that work can be done using the [`encode_plus()`](https://huggingface.co/transformers/main_classes/tokenizer.html#transformers.PreTrainedTokenizer.encode_plus) method: ``` encoding = tokenizer.encode_plus( sample_txt, max_length=32, add_special_tokens=True, # Add '[CLS]' and '[SEP]' return_token_type_ids=False, pad_to_max_length=True, return_attention_mask=True, return_tensors='pt', # Return PyTorch tensors ) encoding.keys() ``` The token ids are now stored in a Tensor and padded to a length of 32: ``` print(len(encoding['input_ids'][0])) encoding['input_ids'][0] ``` The attention mask has the same length: ``` print(len(encoding['attention_mask'][0])) encoding['attention_mask'] ``` We can inverse the tokenization to have a look at the special tokens: ``` tokenizer.convert_ids_to_tokens(encoding['input_ids'][0]) ``` ### Choosing Sequence Length BERT works with fixed-length sequences. We'll use a simple strategy to choose the max length. Let's store the token length of each review: ``` token_lens = [] for txt in df.content: tokens = tokenizer.encode(txt, max_length=512) token_lens.append(len(tokens)) ``` and plot the distribution: ``` sns.distplot(token_lens) plt.xlim([0, 256]); plt.xlabel('Token count'); ``` Most of the reviews seem to contain less than 128 tokens, but we'll be on the safe side and choose a maximum length of 160. ``` MAX_LEN = 160 ``` We have all building blocks required to create a PyTorch dataset. Let's do it: ``` class GPReviewDataset(Dataset): def __init__(self, reviews, targets, tokenizer, max_len): self.reviews = reviews self.targets = targets self.tokenizer = tokenizer self.max_len = max_len def __len__(self): return len(self.reviews) def __getitem__(self, item): review = str(self.reviews[item]) target = self.targets[item] encoding = self.tokenizer.encode_plus( review, add_special_tokens=True, max_length=self.max_len, return_token_type_ids=False, pad_to_max_length=True, return_attention_mask=True, return_tensors='pt', ) return { 'review_text': review, 'input_ids': encoding['input_ids'].flatten(), 'attention_mask': encoding['attention_mask'].flatten(), 'targets': torch.tensor(target, dtype=torch.long) } ``` The tokenizer is doing most of the heavy lifting for us. We also return the review texts, so it'll be easier to evaluate the predictions from our model. Let's split the data: ``` df_train, df_test = train_test_split(df, test_size=0.1, random_state=RANDOM_SEED) df_val, df_test = train_test_split(df_test, test_size=0.5, random_state=RANDOM_SEED) df_train.shape, df_val.shape, df_test.shape ``` We also need to create a couple of data loaders. Here's a helper function to do it: ``` def create_data_loader(df, tokenizer, max_len, batch_size): ds = GPReviewDataset( reviews=df.content.to_numpy(), targets=df.sentiment.to_numpy(), tokenizer=tokenizer, max_len=max_len ) return DataLoader( ds, batch_size=batch_size, num_workers=4 ) BATCH_SIZE = 16 train_data_loader = create_data_loader(df_train, tokenizer, MAX_LEN, BATCH_SIZE) val_data_loader = create_data_loader(df_val, tokenizer, MAX_LEN, BATCH_SIZE) test_data_loader = create_data_loader(df_test, tokenizer, MAX_LEN, BATCH_SIZE) ``` Let's have a look at an example batch from our training data loader: ``` data = next(iter(train_data_loader)) data.keys() print(data['input_ids'].shape) print(data['attention_mask'].shape) print(data['targets'].shape) ``` ## Sentiment Classification with BERT and Hugging Face There are a lot of helpers that make using BERT easy with the Transformers library. Depending on the task you might want to use [BertForSequenceClassification](https://huggingface.co/transformers/model_doc/bert.html#bertforsequenceclassification), [BertForQuestionAnswering](https://huggingface.co/transformers/model_doc/bert.html#bertforquestionanswering) or something else. But who cares, right? We're *hardcore*! We'll use the basic [BertModel](https://huggingface.co/transformers/model_doc/bert.html#bertmodel) and build our sentiment classifier on top of it. Let's load the model: ``` bert_model = BertModel.from_pretrained(PRE_TRAINED_MODEL_NAME) ``` And try to use it on the encoding of our sample text: ``` last_hidden_state, pooled_output = bert_model( input_ids=encoding['input_ids'], attention_mask=encoding['attention_mask'] ) ``` The `last_hidden_state` is a sequence of hidden states of the last layer of the model. Obtaining the `pooled_output` is done by applying the [BertPooler](https://github.com/huggingface/transformers/blob/edf0582c0be87b60f94f41c659ea779876efc7be/src/transformers/modeling_bert.py#L426) on `last_hidden_state`: ``` last_hidden_state.shape ``` We have the hidden state for each of our 32 tokens (the length of our example sequence). But why 768? This is the number of hidden units in the feedforward-networks. We can verify that by checking the config: ``` bert_model.config.hidden_size ``` You can think of the `pooled_output` as a summary of the content, according to BERT. Albeit, you might try and do better. Let's look at the shape of the output: ``` pooled_output.shape ``` We can use all of this knowledge to create a classifier that uses the BERT model: ``` class SentimentClassifier(nn.Module): def __init__(self, n_classes): super(SentimentClassifier, self).__init__() self.bert = BertModel.from_pretrained(PRE_TRAINED_MODEL_NAME) self.drop = nn.Dropout(p=0.3) self.out = nn.Linear(self.bert.config.hidden_size, n_classes) def forward(self, input_ids, attention_mask): _, pooled_output = self.bert( input_ids=input_ids, attention_mask=attention_mask ) output = self.drop(pooled_output) return self.out(output) ``` Our classifier delegates most of the heavy lifting to the BertModel. We use a dropout layer for some regularization and a fully-connected layer for our output. Note that we're returning the raw output of the last layer since that is required for the cross-entropy loss function in PyTorch to work. This should work like any other PyTorch model. Let's create an instance and move it to the GPU: ``` model = SentimentClassifier(len(class_names)) model = model.to(device) ``` We'll move the example batch of our training data to the GPU: ``` input_ids = data['input_ids'].to(device) attention_mask = data['attention_mask'].to(device) print(input_ids.shape) # batch size x seq length print(attention_mask.shape) # batch size x seq length ``` To get the predicted probabilities from our trained model, we'll apply the softmax function to the outputs: ``` F.softmax(model(input_ids, attention_mask), dim=1) ``` ### Training To reproduce the training procedure from the BERT paper, we'll use the [AdamW](https://huggingface.co/transformers/main_classes/optimizer_schedules.html#adamw) optimizer provided by Hugging Face. It corrects weight decay, so it's similar to the original paper. We'll also use a linear scheduler with no warmup steps: ``` EPOCHS = 10 optimizer = AdamW(model.parameters(), lr=2e-5, correct_bias=False) total_steps = len(train_data_loader) * EPOCHS scheduler = get_linear_schedule_with_warmup( optimizer, num_warmup_steps=0, num_training_steps=total_steps ) loss_fn = nn.CrossEntropyLoss().to(device) ``` How do we come up with all hyperparameters? The BERT authors have some recommendations for fine-tuning: - Batch size: 16, 32 - Learning rate (Adam): 5e-5, 3e-5, 2e-5 - Number of epochs: 2, 3, 4 We're going to ignore the number of epochs recommendation but stick with the rest. Note that increasing the batch size reduces the training time significantly, but gives you lower accuracy. Let's continue with writing a helper function for training our model for one epoch: ``` def train_epoch( model, data_loader, loss_fn, optimizer, device, scheduler, n_examples ): model = model.train() losses = [] correct_predictions = 0 for d in data_loader: input_ids = d["input_ids"].to(device) attention_mask = d["attention_mask"].to(device) targets = d["targets"].to(device) outputs = model( input_ids=input_ids, attention_mask=attention_mask ) _, preds = torch.max(outputs, dim=1) loss = loss_fn(outputs, targets) correct_predictions += torch.sum(preds == targets) losses.append(loss.item()) loss.backward() nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0) optimizer.step() scheduler.step() optimizer.zero_grad() return correct_predictions.double() / n_examples, np.mean(losses) ``` Training the model should look familiar, except for two things. The scheduler gets called every time a batch is fed to the model. We're avoiding exploding gradients by clipping the gradients of the model using [clip_grad_norm_](https://pytorch.org/docs/stable/nn.html#clip-grad-norm). Let's write another one that helps us evaluate the model on a given data loader: ``` def eval_model(model, data_loader, loss_fn, device, n_examples): model = model.eval() losses = [] correct_predictions = 0 with torch.no_grad(): for d in data_loader: input_ids = d["input_ids"].to(device) attention_mask = d["attention_mask"].to(device) targets = d["targets"].to(device) outputs = model( input_ids=input_ids, attention_mask=attention_mask ) _, preds = torch.max(outputs, dim=1) loss = loss_fn(outputs, targets) correct_predictions += torch.sum(preds == targets) losses.append(loss.item()) return correct_predictions.double() / n_examples, np.mean(losses) ``` Using those two, we can write our training loop. We'll also store the training history: ``` %%time history = defaultdict(list) best_accuracy = 0 for epoch in range(EPOCHS): print(f'Epoch {epoch + 1}/{EPOCHS}') print('-' * 10) train_acc, train_loss = train_epoch( model, train_data_loader, loss_fn, optimizer, device, scheduler, len(df_train) ) print(f'Train loss {train_loss} accuracy {train_acc}') val_acc, val_loss = eval_model( model, val_data_loader, loss_fn, device, len(df_val) ) print(f'Val loss {val_loss} accuracy {val_acc}') print() history['train_acc'].append(train_acc) history['train_loss'].append(train_loss) history['val_acc'].append(val_acc) history['val_loss'].append(val_loss) if val_acc > best_accuracy: torch.save(model.state_dict(), 'best_model_state.bin') best_accuracy = val_acc ``` Note that we're storing the state of the best model, indicated by the highest validation accuracy. Whoo, this took some time! We can look at the training vs validation accuracy: ``` plt.plot(history['train_acc'], label='train accuracy') plt.plot(history['val_acc'], label='validation accuracy') plt.title('Training history') plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.legend() plt.ylim([0, 1]); ``` The training accuracy starts to approach 100% after 10 epochs or so. You might try to fine-tune the parameters a bit more, but this will be good enough for us. Don't want to wait? Uncomment the next cell to download my pre-trained model: ``` # !gdown --id 1V8itWtowCYnb2Bc9KlK9SxGff9WwmogA # model = SentimentClassifier(len(class_names)) # model.load_state_dict(torch.load('best_model_state.bin')) # model = model.to(device) ``` ## Evaluation So how good is our model on predicting sentiment? Let's start by calculating the accuracy on the test data: ``` test_acc, _ = eval_model( model, test_data_loader, loss_fn, device, len(df_test) ) test_acc.item() ``` The accuracy is about 1% lower on the test set. Our model seems to generalize well. We'll define a helper function to get the predictions from our model: ``` def get_predictions(model, data_loader): model = model.eval() review_texts = [] predictions = [] prediction_probs = [] real_values = [] with torch.no_grad(): for d in data_loader: texts = d["review_text"] input_ids = d["input_ids"].to(device) attention_mask = d["attention_mask"].to(device) targets = d["targets"].to(device) outputs = model( input_ids=input_ids, attention_mask=attention_mask ) _, preds = torch.max(outputs, dim=1) probs = F.softmax(outputs, dim=1) review_texts.extend(texts) predictions.extend(preds) prediction_probs.extend(probs) real_values.extend(targets) predictions = torch.stack(predictions).cpu() prediction_probs = torch.stack(prediction_probs).cpu() real_values = torch.stack(real_values).cpu() return review_texts, predictions, prediction_probs, real_values ``` This is similar to the evaluation function, except that we're storing the text of the reviews and the predicted probabilities (by applying the softmax on the model outputs): ``` y_review_texts, y_pred, y_pred_probs, y_test = get_predictions( model, test_data_loader ) ``` Let's have a look at the classification report ``` print(classification_report(y_test, y_pred, target_names=class_names)) ``` Looks like it is really hard to classify neutral (3 stars) reviews. And I can tell you from experience, looking at many reviews, those are hard to classify. We'll continue with the confusion matrix: ``` def show_confusion_matrix(confusion_matrix): hmap = sns.heatmap(confusion_matrix, annot=True, fmt="d", cmap="Blues") hmap.yaxis.set_ticklabels(hmap.yaxis.get_ticklabels(), rotation=0, ha='right') hmap.xaxis.set_ticklabels(hmap.xaxis.get_ticklabels(), rotation=30, ha='right') plt.ylabel('True sentiment') plt.xlabel('Predicted sentiment'); cm = confusion_matrix(y_test, y_pred) df_cm = pd.DataFrame(cm, index=class_names, columns=class_names) show_confusion_matrix(df_cm) ``` This confirms that our model is having difficulty classifying neutral reviews. It mistakes those for negative and positive at a roughly equal frequency. That's a good overview of the performance of our model. But let's have a look at an example from our test data: ``` idx = 2 review_text = y_review_texts[idx] true_sentiment = y_test[idx] pred_df = pd.DataFrame({ 'class_names': class_names, 'values': y_pred_probs[idx] }) print("\n".join(wrap(review_text))) print() print(f'True sentiment: {class_names[true_sentiment]}') ``` Now we can look at the confidence of each sentiment of our model: ``` sns.barplot(x='values', y='class_names', data=pred_df, orient='h') plt.ylabel('sentiment') plt.xlabel('probability') plt.xlim([0, 1]); ``` ### Predicting on Raw Text Let's use our model to predict the sentiment of some raw text: ``` review_text = "I love completing my todos! Best app ever!!!" ``` We have to use the tokenizer to encode the text: ``` encoded_review = tokenizer.encode_plus( review_text, max_length=MAX_LEN, add_special_tokens=True, return_token_type_ids=False, pad_to_max_length=True, return_attention_mask=True, return_tensors='pt', ) ``` Let's get the predictions from our model: ``` input_ids = encoded_review['input_ids'].to(device) attention_mask = encoded_review['attention_mask'].to(device) output = model(input_ids, attention_mask) _, prediction = torch.max(output, dim=1) print(f'Review text: {review_text}') print(f'Sentiment : {class_names[prediction]}') ``` ## Summary Nice job! You learned how to use BERT for sentiment analysis. You built a custom classifier using the Hugging Face library and trained it on our app reviews dataset! - [Read the tutorial](https://www.curiousily.com/posts/sentiment-analysis-with-bert-and-hugging-face-using-pytorch-and-python/) - [Run the notebook in your browser (Google Colab)](https://colab.research.google.com/drive/1PHv-IRLPCtv7oTcIGbsgZHqrB5LPvB7S) - [Read the `Getting Things Done with Pytorch` book](https://github.com/curiousily/Getting-Things-Done-with-Pytorch) You learned how to: - Intuitively understand what BERT is - Preprocess text data for BERT and build PyTorch Dataset (tokenization, attention masks, and padding) - Use Transfer Learning to build Sentiment Classifier using the Transformers library by Hugging Face - Evaluate the model on test data - Predict sentiment on raw text Next, we'll learn how to deploy our trained model behind a REST API and build a simple web app to access it. ## References - [BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://arxiv.org/abs/1810.04805) - [L11 Language Models - Alec Radford (OpenAI)](https://www.youtube.com/watch?v=BnpB3GrpsfM) - [The Illustrated BERT, ELMo, and co.](https://jalammar.github.io/illustrated-bert/) - [BERT Fine-Tuning Tutorial with PyTorch](https://mccormickml.com/2019/07/22/BERT-fine-tuning/) - [How to Fine-Tune BERT for Text Classification?](https://arxiv.org/pdf/1905.05583.pdf) - [Huggingface Transformers](https://huggingface.co/transformers/) - [BERT Explained: State of the art language model for NLP](https://towardsdatascience.com/bert-explained-state-of-the-art-language-model-for-nlp-f8b21a9b6270)
github_jupyter
#@title Watch the video tutorial from IPython.display import YouTubeVideo YouTubeVideo('8N-nM3QW7O0', width=720, height=420) !nvidia-smi !pip install -q -U watermark !pip install -qq transformers %reload_ext watermark %watermark -v -p numpy,pandas,torch,transformers #@title Setup & Config import transformers from transformers import BertModel, BertTokenizer, AdamW, get_linear_schedule_with_warmup import torch import numpy as np import pandas as pd import seaborn as sns from pylab import rcParams import matplotlib.pyplot as plt from matplotlib import rc from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix, classification_report from collections import defaultdict from textwrap import wrap from torch import nn, optim from torch.utils.data import Dataset, DataLoader import torch.nn.functional as F %matplotlib inline %config InlineBackend.figure_format='retina' sns.set(style='whitegrid', palette='muted', font_scale=1.2) HAPPY_COLORS_PALETTE = ["#01BEFE", "#FFDD00", "#FF7D00", "#FF006D", "#ADFF02", "#8F00FF"] sns.set_palette(sns.color_palette(HAPPY_COLORS_PALETTE)) rcParams['figure.figsize'] = 12, 8 RANDOM_SEED = 42 np.random.seed(RANDOM_SEED) torch.manual_seed(RANDOM_SEED) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") device !gdown --id 1S6qMioqPJjyBLpLVz4gmRTnJHnjitnuV !gdown --id 1zdmewp7ayS4js4VtrJEHzAheSW-5NBZv df = pd.read_csv("reviews.csv") df.head() df.shape df.info() sns.countplot(df.score) plt.xlabel('review score'); def to_sentiment(rating): rating = int(rating) if rating <= 2: return 0 elif rating == 3: return 1 else: return 2 df['sentiment'] = df.score.apply(to_sentiment) class_names = ['negative', 'neutral', 'positive'] ax = sns.countplot(df.sentiment) plt.xlabel('review sentiment') ax.set_xticklabels(class_names); PRE_TRAINED_MODEL_NAME = 'bert-base-multilingual-cased' tokenizer = BertTokenizer.from_pretrained(PRE_TRAINED_MODEL_NAME) sample_txt = 'hang aplikasinya force close' tokens = tokenizer.tokenize(sample_txt) token_ids = tokenizer.convert_tokens_to_ids(tokens) print(f' Sentence: {sample_txt}') print(f' Tokens: {tokens}') print(f'Token IDs: {token_ids}') tokenizer.sep_token, tokenizer.sep_token_id tokenizer.cls_token, tokenizer.cls_token_id tokenizer.pad_token, tokenizer.pad_token_id tokenizer.unk_token, tokenizer.unk_token_id encoding = tokenizer.encode_plus( sample_txt, max_length=32, add_special_tokens=True, # Add '[CLS]' and '[SEP]' return_token_type_ids=False, pad_to_max_length=True, return_attention_mask=True, return_tensors='pt', # Return PyTorch tensors ) encoding.keys() print(len(encoding['input_ids'][0])) encoding['input_ids'][0] print(len(encoding['attention_mask'][0])) encoding['attention_mask'] tokenizer.convert_ids_to_tokens(encoding['input_ids'][0]) token_lens = [] for txt in df.content: tokens = tokenizer.encode(txt, max_length=512) token_lens.append(len(tokens)) sns.distplot(token_lens) plt.xlim([0, 256]); plt.xlabel('Token count'); MAX_LEN = 160 class GPReviewDataset(Dataset): def __init__(self, reviews, targets, tokenizer, max_len): self.reviews = reviews self.targets = targets self.tokenizer = tokenizer self.max_len = max_len def __len__(self): return len(self.reviews) def __getitem__(self, item): review = str(self.reviews[item]) target = self.targets[item] encoding = self.tokenizer.encode_plus( review, add_special_tokens=True, max_length=self.max_len, return_token_type_ids=False, pad_to_max_length=True, return_attention_mask=True, return_tensors='pt', ) return { 'review_text': review, 'input_ids': encoding['input_ids'].flatten(), 'attention_mask': encoding['attention_mask'].flatten(), 'targets': torch.tensor(target, dtype=torch.long) } df_train, df_test = train_test_split(df, test_size=0.1, random_state=RANDOM_SEED) df_val, df_test = train_test_split(df_test, test_size=0.5, random_state=RANDOM_SEED) df_train.shape, df_val.shape, df_test.shape def create_data_loader(df, tokenizer, max_len, batch_size): ds = GPReviewDataset( reviews=df.content.to_numpy(), targets=df.sentiment.to_numpy(), tokenizer=tokenizer, max_len=max_len ) return DataLoader( ds, batch_size=batch_size, num_workers=4 ) BATCH_SIZE = 16 train_data_loader = create_data_loader(df_train, tokenizer, MAX_LEN, BATCH_SIZE) val_data_loader = create_data_loader(df_val, tokenizer, MAX_LEN, BATCH_SIZE) test_data_loader = create_data_loader(df_test, tokenizer, MAX_LEN, BATCH_SIZE) data = next(iter(train_data_loader)) data.keys() print(data['input_ids'].shape) print(data['attention_mask'].shape) print(data['targets'].shape) bert_model = BertModel.from_pretrained(PRE_TRAINED_MODEL_NAME) last_hidden_state, pooled_output = bert_model( input_ids=encoding['input_ids'], attention_mask=encoding['attention_mask'] ) last_hidden_state.shape bert_model.config.hidden_size pooled_output.shape class SentimentClassifier(nn.Module): def __init__(self, n_classes): super(SentimentClassifier, self).__init__() self.bert = BertModel.from_pretrained(PRE_TRAINED_MODEL_NAME) self.drop = nn.Dropout(p=0.3) self.out = nn.Linear(self.bert.config.hidden_size, n_classes) def forward(self, input_ids, attention_mask): _, pooled_output = self.bert( input_ids=input_ids, attention_mask=attention_mask ) output = self.drop(pooled_output) return self.out(output) model = SentimentClassifier(len(class_names)) model = model.to(device) input_ids = data['input_ids'].to(device) attention_mask = data['attention_mask'].to(device) print(input_ids.shape) # batch size x seq length print(attention_mask.shape) # batch size x seq length F.softmax(model(input_ids, attention_mask), dim=1) EPOCHS = 10 optimizer = AdamW(model.parameters(), lr=2e-5, correct_bias=False) total_steps = len(train_data_loader) * EPOCHS scheduler = get_linear_schedule_with_warmup( optimizer, num_warmup_steps=0, num_training_steps=total_steps ) loss_fn = nn.CrossEntropyLoss().to(device) def train_epoch( model, data_loader, loss_fn, optimizer, device, scheduler, n_examples ): model = model.train() losses = [] correct_predictions = 0 for d in data_loader: input_ids = d["input_ids"].to(device) attention_mask = d["attention_mask"].to(device) targets = d["targets"].to(device) outputs = model( input_ids=input_ids, attention_mask=attention_mask ) _, preds = torch.max(outputs, dim=1) loss = loss_fn(outputs, targets) correct_predictions += torch.sum(preds == targets) losses.append(loss.item()) loss.backward() nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0) optimizer.step() scheduler.step() optimizer.zero_grad() return correct_predictions.double() / n_examples, np.mean(losses) def eval_model(model, data_loader, loss_fn, device, n_examples): model = model.eval() losses = [] correct_predictions = 0 with torch.no_grad(): for d in data_loader: input_ids = d["input_ids"].to(device) attention_mask = d["attention_mask"].to(device) targets = d["targets"].to(device) outputs = model( input_ids=input_ids, attention_mask=attention_mask ) _, preds = torch.max(outputs, dim=1) loss = loss_fn(outputs, targets) correct_predictions += torch.sum(preds == targets) losses.append(loss.item()) return correct_predictions.double() / n_examples, np.mean(losses) %%time history = defaultdict(list) best_accuracy = 0 for epoch in range(EPOCHS): print(f'Epoch {epoch + 1}/{EPOCHS}') print('-' * 10) train_acc, train_loss = train_epoch( model, train_data_loader, loss_fn, optimizer, device, scheduler, len(df_train) ) print(f'Train loss {train_loss} accuracy {train_acc}') val_acc, val_loss = eval_model( model, val_data_loader, loss_fn, device, len(df_val) ) print(f'Val loss {val_loss} accuracy {val_acc}') print() history['train_acc'].append(train_acc) history['train_loss'].append(train_loss) history['val_acc'].append(val_acc) history['val_loss'].append(val_loss) if val_acc > best_accuracy: torch.save(model.state_dict(), 'best_model_state.bin') best_accuracy = val_acc plt.plot(history['train_acc'], label='train accuracy') plt.plot(history['val_acc'], label='validation accuracy') plt.title('Training history') plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.legend() plt.ylim([0, 1]); # !gdown --id 1V8itWtowCYnb2Bc9KlK9SxGff9WwmogA # model = SentimentClassifier(len(class_names)) # model.load_state_dict(torch.load('best_model_state.bin')) # model = model.to(device) test_acc, _ = eval_model( model, test_data_loader, loss_fn, device, len(df_test) ) test_acc.item() def get_predictions(model, data_loader): model = model.eval() review_texts = [] predictions = [] prediction_probs = [] real_values = [] with torch.no_grad(): for d in data_loader: texts = d["review_text"] input_ids = d["input_ids"].to(device) attention_mask = d["attention_mask"].to(device) targets = d["targets"].to(device) outputs = model( input_ids=input_ids, attention_mask=attention_mask ) _, preds = torch.max(outputs, dim=1) probs = F.softmax(outputs, dim=1) review_texts.extend(texts) predictions.extend(preds) prediction_probs.extend(probs) real_values.extend(targets) predictions = torch.stack(predictions).cpu() prediction_probs = torch.stack(prediction_probs).cpu() real_values = torch.stack(real_values).cpu() return review_texts, predictions, prediction_probs, real_values y_review_texts, y_pred, y_pred_probs, y_test = get_predictions( model, test_data_loader ) print(classification_report(y_test, y_pred, target_names=class_names)) def show_confusion_matrix(confusion_matrix): hmap = sns.heatmap(confusion_matrix, annot=True, fmt="d", cmap="Blues") hmap.yaxis.set_ticklabels(hmap.yaxis.get_ticklabels(), rotation=0, ha='right') hmap.xaxis.set_ticklabels(hmap.xaxis.get_ticklabels(), rotation=30, ha='right') plt.ylabel('True sentiment') plt.xlabel('Predicted sentiment'); cm = confusion_matrix(y_test, y_pred) df_cm = pd.DataFrame(cm, index=class_names, columns=class_names) show_confusion_matrix(df_cm) idx = 2 review_text = y_review_texts[idx] true_sentiment = y_test[idx] pred_df = pd.DataFrame({ 'class_names': class_names, 'values': y_pred_probs[idx] }) print("\n".join(wrap(review_text))) print() print(f'True sentiment: {class_names[true_sentiment]}') sns.barplot(x='values', y='class_names', data=pred_df, orient='h') plt.ylabel('sentiment') plt.xlabel('probability') plt.xlim([0, 1]); review_text = "I love completing my todos! Best app ever!!!" encoded_review = tokenizer.encode_plus( review_text, max_length=MAX_LEN, add_special_tokens=True, return_token_type_ids=False, pad_to_max_length=True, return_attention_mask=True, return_tensors='pt', ) input_ids = encoded_review['input_ids'].to(device) attention_mask = encoded_review['attention_mask'].to(device) output = model(input_ids, attention_mask) _, prediction = torch.max(output, dim=1) print(f'Review text: {review_text}') print(f'Sentiment : {class_names[prediction]}')
0.819533
0.986258
<a href="https://colab.research.google.com/github/pedroescobedob/DS-Unit-2-Linear-Models/blob/master/Pedro_Escobedo_assignment_regression_classification_2.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Lambda School Data Science *Unit 2, Sprint 1, Module 2* --- # Regression 2 ## Assignment You'll continue to **predict how much it costs to rent an apartment in NYC,** using the dataset from renthop.com. - [ ] Do train/test split. Use data from April & May 2016 to train. Use data from June 2016 to test. - [ ] Engineer at least two new features. (See below for explanation & ideas.) - [ ] Fit a linear regression model with at least two features. - [ ] Get the model's coefficients and intercept. - [ ] Get regression metrics RMSE, MAE, and $R^2$, for both the train and test data. - [ ] What's the best test MAE you can get? Share your score and features used with your cohort on Slack! - [ ] As always, commit your notebook to your fork of the GitHub repo. #### [Feature Engineering](https://en.wikipedia.org/wiki/Feature_engineering) > "Some machine learning projects succeed and some fail. What makes the difference? Easily the most important factor is the features used." — Pedro Domingos, ["A Few Useful Things to Know about Machine Learning"](https://homes.cs.washington.edu/~pedrod/papers/cacm12.pdf) > "Coming up with features is difficult, time-consuming, requires expert knowledge. 'Applied machine learning' is basically feature engineering." — Andrew Ng, [Machine Learning and AI via Brain simulations](https://forum.stanford.edu/events/2011/2011slides/plenary/2011plenaryNg.pdf) > Feature engineering is the process of using domain knowledge of the data to create features that make machine learning algorithms work. #### Feature Ideas - Does the apartment have a description? - How long is the description? - How many total perks does each apartment have? - Are cats _or_ dogs allowed? - Are cats _and_ dogs allowed? - Total number of rooms (beds + baths) - Ratio of beds to baths - What's the neighborhood, based on address or latitude & longitude? ## Stretch Goals - [ ] If you want more math, skim [_An Introduction to Statistical Learning_](http://faculty.marshall.usc.edu/gareth-james/ISL/ISLR%20Seventh%20Printing.pdf), Chapter 3.1, Simple Linear Regression, & Chapter 3.2, Multiple Linear Regression - [ ] If you want more introduction, watch [Brandon Foltz, Statistics 101: Simple Linear Regression](https://www.youtube.com/watch?v=ZkjP5RJLQF4) (20 minutes, over 1 million views) - [ ] Add your own stretch goal(s) ! ``` %%capture import sys # If you're on Colab: if 'google.colab' in sys.modules: DATA_PATH = 'https://raw.githubusercontent.com/LambdaSchool/DS-Unit-2-Applied-Modeling/master/data/' !pip install category_encoders==2.* # If you're working locally: else: DATA_PATH = '../data/' # Ignore this Numpy warning when using Plotly Express: # FutureWarning: Method .ptp is deprecated and will be removed in a future version. Use numpy.ptp instead. import warnings warnings.filterwarnings(action='ignore', category=FutureWarning, module='numpy') import numpy as np import pandas as pd # Read New York City apartment rental listing data df = pd.read_csv(DATA_PATH+'apartments/renthop-nyc.csv') assert df.shape == (49352, 34) # Remove the most extreme 1% prices, # the most extreme .1% latitudes, & # the most extreme .1% longitudes df = df[(df['price'] >= np.percentile(df['price'], 0.5)) & (df['price'] <= np.percentile(df['price'], 99.5)) & (df['latitude'] >= np.percentile(df['latitude'], 0.05)) & (df['latitude'] < np.percentile(df['latitude'], 99.95)) & (df['longitude'] >= np.percentile(df['longitude'], 0.05)) & (df['longitude'] <= np.percentile(df['longitude'], 99.95))] df.head() # Change the date. df['created'] = pd.to_datetime(df['created']) trainDf = df[(df['created'] >= pd.to_datetime('April 1st, 2016')) & (df['created'] < pd.to_datetime('June 1st, 2016'))] testDf = df[(df['created'] >= pd.to_datetime('April 1st, 2016')) & (df['created'] < pd.to_datetime('July 1st, 2016'))] # Two new features df['description length'] = df['description'].str.len().fillna(0) df['total perks'] = df[df.columns[10:]].T.sum() # Make interest into a measurable quantity. int_values = {'low': 0, 'medium': 1, 'high': 2} df['interest_level'] = df['interest_level'].map(int_values) df.head() from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score features = ['description length', 'total perks', 'bathrooms', 'bedrooms'] # df.reindex(columns=['description length', 'total perks']) target = ['price'] model = LinearRegression() # Train X_train = trainDf[features] y_train = trainDf[target] model.fit(X_train, y_train) model.intercept_, model.coef_ # Predictions y_pred = model.predict(X_train) mse = mean_squared_error(y_train, y_pred) rmse = np.sqrt(mse) mae = mean_absolute_error(y_train, y_pred) r2 = r2_score(y_train, y_pred) print('Intercept', model.intercept_) # coefficients = pd.Series(model.coef_, features) # print(coefficients.to_string()) print('r2: ', model.score(X_train, y_train)) print('MSE: ', mse) print('RMSE: ', rmse) print('MAE: ', mae) print('r2: ', r2) # Test X_test = testDf[features] y_test = testDf[target] model.fit(X_test, y_test) model.intercept_, model.coef_ y_pred = model.predict(X_test) # regression metrics from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score mse = mean_squared_error(y_test, y_pred) rmse = np.sqrt(mse) mae = mean_absolute_error(y_test, y_pred) r2 = r2_score(y_test, y_pred) print('Intercept', model.intercept_) # coefficients = pd.Series(model.coef_, features) # print(coefficients.to_string()) print('r2: ', model.score(X_test, y_test)) print('MSE: ', mse) print('RMSE: ', rmse) print('MAE: ', mae) print('r2: ', r2) ```
github_jupyter
%%capture import sys # If you're on Colab: if 'google.colab' in sys.modules: DATA_PATH = 'https://raw.githubusercontent.com/LambdaSchool/DS-Unit-2-Applied-Modeling/master/data/' !pip install category_encoders==2.* # If you're working locally: else: DATA_PATH = '../data/' # Ignore this Numpy warning when using Plotly Express: # FutureWarning: Method .ptp is deprecated and will be removed in a future version. Use numpy.ptp instead. import warnings warnings.filterwarnings(action='ignore', category=FutureWarning, module='numpy') import numpy as np import pandas as pd # Read New York City apartment rental listing data df = pd.read_csv(DATA_PATH+'apartments/renthop-nyc.csv') assert df.shape == (49352, 34) # Remove the most extreme 1% prices, # the most extreme .1% latitudes, & # the most extreme .1% longitudes df = df[(df['price'] >= np.percentile(df['price'], 0.5)) & (df['price'] <= np.percentile(df['price'], 99.5)) & (df['latitude'] >= np.percentile(df['latitude'], 0.05)) & (df['latitude'] < np.percentile(df['latitude'], 99.95)) & (df['longitude'] >= np.percentile(df['longitude'], 0.05)) & (df['longitude'] <= np.percentile(df['longitude'], 99.95))] df.head() # Change the date. df['created'] = pd.to_datetime(df['created']) trainDf = df[(df['created'] >= pd.to_datetime('April 1st, 2016')) & (df['created'] < pd.to_datetime('June 1st, 2016'))] testDf = df[(df['created'] >= pd.to_datetime('April 1st, 2016')) & (df['created'] < pd.to_datetime('July 1st, 2016'))] # Two new features df['description length'] = df['description'].str.len().fillna(0) df['total perks'] = df[df.columns[10:]].T.sum() # Make interest into a measurable quantity. int_values = {'low': 0, 'medium': 1, 'high': 2} df['interest_level'] = df['interest_level'].map(int_values) df.head() from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score features = ['description length', 'total perks', 'bathrooms', 'bedrooms'] # df.reindex(columns=['description length', 'total perks']) target = ['price'] model = LinearRegression() # Train X_train = trainDf[features] y_train = trainDf[target] model.fit(X_train, y_train) model.intercept_, model.coef_ # Predictions y_pred = model.predict(X_train) mse = mean_squared_error(y_train, y_pred) rmse = np.sqrt(mse) mae = mean_absolute_error(y_train, y_pred) r2 = r2_score(y_train, y_pred) print('Intercept', model.intercept_) # coefficients = pd.Series(model.coef_, features) # print(coefficients.to_string()) print('r2: ', model.score(X_train, y_train)) print('MSE: ', mse) print('RMSE: ', rmse) print('MAE: ', mae) print('r2: ', r2) # Test X_test = testDf[features] y_test = testDf[target] model.fit(X_test, y_test) model.intercept_, model.coef_ y_pred = model.predict(X_test) # regression metrics from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score mse = mean_squared_error(y_test, y_pred) rmse = np.sqrt(mse) mae = mean_absolute_error(y_test, y_pred) r2 = r2_score(y_test, y_pred) print('Intercept', model.intercept_) # coefficients = pd.Series(model.coef_, features) # print(coefficients.to_string()) print('r2: ', model.score(X_test, y_test)) print('MSE: ', mse) print('RMSE: ', rmse) print('MAE: ', mae) print('r2: ', r2)
0.390127
0.974018
<a href="https://colab.research.google.com/github/falconlee236/handson-ml2/blob/master/chapter3.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` from sklearn.datasets import fetch_openml mnist = fetch_openml('mnist_784', version=1) mnist.keys() X, y = mnist['data'], mnist['target'] X.shape y.shape import matplotlib as mpl import matplotlib.pyplot as plt some_digit = X[0] some_digit_image = some_digit.reshape(28, 28) plt.imshow(some_digit_image, cmap='binary') plt.axis('on') plt.show() y[0] import numpy as np y = y.astype(np.uint8) X_train, X_test, y_train, y_test = X[:60000], X[60000:], y[:60000], y[60000:] y_train_5 = (y_train == 5) y_test_5 = (y_test == 5) from sklearn.linear_model import SGDClassifier sgd_clf = SGDClassifier(random_state=42) sgd_clf.fit(X_train, y_train_5) sgd_clf.predict([some_digit]) from sklearn.model_selection import StratifiedKFold from sklearn.base import clone skfolds = StratifiedKFold(n_splits=3, random_state=42, shuffle=True) for train_index, test_index in skfolds.split(X_train, y_train_5): clone_clf = clone(sgd_clf) X_train_folds = X_train[train_index] y_train_folds = y_train_5[train_index] X_test_fold = X_train[test_index] y_test_fold = y_train_5[test_index] clone_clf.fit(X_train_folds, y_train_folds) y_pred = clone_clf.predict(X_test_fold) n_corret = sum(y_pred == y_test_fold) print(n_corret / len(y_pred)) from sklearn.model_selection import cross_val_score cross_val_score(sgd_clf, X_train, y_train_5, cv=3, scoring='accuracy') from sklearn.base import BaseEstimator class Never5Classifier(BaseEstimator): def fit(self, X, y=None): return self def predict(self, X): return np.zeros((len(X), 1), dtype=bool) never_5_clf = Never5Classifier() cross_val_score(never_5_clf, X_train, y_train_5, cv=3, scoring='accuracy') from sklearn.model_selection import cross_val_predict y_train_pred = cross_val_predict(sgd_clf, X_train, y_train_5, cv=3) from sklearn.metrics import confusion_matrix confusion_matrix(y_train_5, y_train_pred) y_train_perfect_predictions = y_train_5 confusion_matrix(y_train_5, y_train_perfect_predictions) from sklearn.metrics import precision_score, recall_score precision_score(y_train_5, y_train_pred) recall_score(y_train_5, y_train_pred) from sklearn.metrics import f1_score f1_score(y_train_5, y_train_pred) y_scores = sgd_clf.decision_function([some_digit]) y_scores threshold = 0 y_some_digit_pred = (y_scores > threshold) y_some_digit_pred threshold = 8000 y_some_digit_pred = (y_scores > threshold) y_some_digit_pred y_scores = cross_val_predict(sgd_clf, X_train, y_train_5, cv=3, method='decision_function') from sklearn.metrics import precision_recall_curve precisions, recalls, thresholds = precision_recall_curve(y_train_5, y_scores) def plot_precision_recall_vs_threshold(precisions, recalls, thresholds): plt.plot(thresholds, precisions[:-1], "b--", label='precision') plt.plot(thresholds, recalls[:-1], "g-", label='recall') plt.legend() plt.grid(True) plt.xlabel('threshold') plot_precision_recall_vs_threshold(precisions, recalls, thresholds) plt.show() threshold_90_precision = thresholds[np.argmax(precisions >= 0.90)] threshold_90_precision y_train_pred_90 = (y_scores >= threshold_90_precision) precision_score(y_train_5, y_train_pred_90) recall_score(y_train_5, y_train_pred_90) from sklearn.metrics import roc_curve fpr, tpr, thresholds = roc_curve(y_train_5, y_scores) def plot_roc_curve(fpr, tpr, label=None): plt.plot(fpr, tpr, linewidth=2, label=label) plt.plot([0, 1], [0, 1], 'k--') plt.grid(True) plt.xlabel('FPR') plt.ylabel('TPR(Recall)') plot_roc_curve(fpr, tpr) plt.show() from sklearn.metrics import roc_auc_score roc_auc_score(y_train_5, y_scores) from sklearn.ensemble import RandomForestClassifier forest_clf = RandomForestClassifier(random_state=42) y_probas_forest = cross_val_predict(forest_clf, X_train, y_train_5, cv=3, method='predict_proba') y_scores_forest = y_probas_forest[:, 1] fpr_forest, tpr_forest, thresholds_forest = roc_curve(y_train_5, y_scores_forest) plt.plot(fpr, tpr, "b:", label="SGD") plot_roc_curve(fpr_forest, tpr_forest, "random forest") plt.legend(loc="lower right") plt.show() roc_auc_score(y_train_5, y_scores_forest) from sklearn.svm import SVC svm_clf = SVC() svm_clf.fit(X_train, y_train) svm_clf.predict([some_digit]) some_digit_scores = svm_clf.decision_function([some_digit]) some_digit_scores np.argmax(some_digit_scores) svm_clf.classes_ from sklearn.multiclass import OneVsRestClassifier ovr_clf = OneVsRestClassifier(SVC()) ovr_clf.fit(X_train, y_train) ovr_clf.predict([some_digit]) len(ovr_clf.estimators_) sgd_clf.fit(X_train, y_train) sgd_clf.predict([some_digit]) sgd_clf.decision_function([some_digit]) cross_val_score(sgd_clf, X_train, y_train, cv=3, scoring='accuracy') from sklearn.preprocessing import StandardScaler scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train.astype(np.float64)) cross_val_score(sgd_clf, X_train_scaled, y_train, cv=3, scoring='accuracy') y_train_pred = cross_val_predict(sgd_clf, X_train_scaled, y_train, cv=3) conf_mx = confusion_matrix(y_train, y_train_pred) conf_mx plt.matshow(conf_mx, cmap=plt.cm.gray) plt.show() row_sums = conf_mx.sum(axis=1, keepdims=True) norm_conf_mx = conf_mx / row_sums np.fill_diagonal(norm_conf_mx, 0) plt.matshow(norm_conf_mx, cmap=plt.cm.gray) plt.show() from sklearn.neighbors import KNeighborsClassifier y_train_large = (y_train >= 7) y_train_odd = (y_train % 2 == 1) y_multilabel = np.c_[y_train_large, y_train_odd] knn_clf = KNeighborsClassifier() knn_clf.fit(X_train, y_multilabel) knn_clf.predict([some_digit]) y_train_knn_pred = cross_val_predict(knn_clf, X_train, y_multilabel, cv=3) f1_score(y_multilabel, y_train_knn_pred, average='macro') noise = np.random.randint(0, 100, (len(X_train), 784)) X_train_mod = X_train + noise noise = np.random.randint(0, 100, (len(X_test), 784)) X_test_mod = X_test + noise y_train_mod = X_train y_test_mode = X_test knn_clf.fit(X_train_mod, y_train_mod) clean_digit = knn_clf.predict([X_test_mod[4]]) ```
github_jupyter
from sklearn.datasets import fetch_openml mnist = fetch_openml('mnist_784', version=1) mnist.keys() X, y = mnist['data'], mnist['target'] X.shape y.shape import matplotlib as mpl import matplotlib.pyplot as plt some_digit = X[0] some_digit_image = some_digit.reshape(28, 28) plt.imshow(some_digit_image, cmap='binary') plt.axis('on') plt.show() y[0] import numpy as np y = y.astype(np.uint8) X_train, X_test, y_train, y_test = X[:60000], X[60000:], y[:60000], y[60000:] y_train_5 = (y_train == 5) y_test_5 = (y_test == 5) from sklearn.linear_model import SGDClassifier sgd_clf = SGDClassifier(random_state=42) sgd_clf.fit(X_train, y_train_5) sgd_clf.predict([some_digit]) from sklearn.model_selection import StratifiedKFold from sklearn.base import clone skfolds = StratifiedKFold(n_splits=3, random_state=42, shuffle=True) for train_index, test_index in skfolds.split(X_train, y_train_5): clone_clf = clone(sgd_clf) X_train_folds = X_train[train_index] y_train_folds = y_train_5[train_index] X_test_fold = X_train[test_index] y_test_fold = y_train_5[test_index] clone_clf.fit(X_train_folds, y_train_folds) y_pred = clone_clf.predict(X_test_fold) n_corret = sum(y_pred == y_test_fold) print(n_corret / len(y_pred)) from sklearn.model_selection import cross_val_score cross_val_score(sgd_clf, X_train, y_train_5, cv=3, scoring='accuracy') from sklearn.base import BaseEstimator class Never5Classifier(BaseEstimator): def fit(self, X, y=None): return self def predict(self, X): return np.zeros((len(X), 1), dtype=bool) never_5_clf = Never5Classifier() cross_val_score(never_5_clf, X_train, y_train_5, cv=3, scoring='accuracy') from sklearn.model_selection import cross_val_predict y_train_pred = cross_val_predict(sgd_clf, X_train, y_train_5, cv=3) from sklearn.metrics import confusion_matrix confusion_matrix(y_train_5, y_train_pred) y_train_perfect_predictions = y_train_5 confusion_matrix(y_train_5, y_train_perfect_predictions) from sklearn.metrics import precision_score, recall_score precision_score(y_train_5, y_train_pred) recall_score(y_train_5, y_train_pred) from sklearn.metrics import f1_score f1_score(y_train_5, y_train_pred) y_scores = sgd_clf.decision_function([some_digit]) y_scores threshold = 0 y_some_digit_pred = (y_scores > threshold) y_some_digit_pred threshold = 8000 y_some_digit_pred = (y_scores > threshold) y_some_digit_pred y_scores = cross_val_predict(sgd_clf, X_train, y_train_5, cv=3, method='decision_function') from sklearn.metrics import precision_recall_curve precisions, recalls, thresholds = precision_recall_curve(y_train_5, y_scores) def plot_precision_recall_vs_threshold(precisions, recalls, thresholds): plt.plot(thresholds, precisions[:-1], "b--", label='precision') plt.plot(thresholds, recalls[:-1], "g-", label='recall') plt.legend() plt.grid(True) plt.xlabel('threshold') plot_precision_recall_vs_threshold(precisions, recalls, thresholds) plt.show() threshold_90_precision = thresholds[np.argmax(precisions >= 0.90)] threshold_90_precision y_train_pred_90 = (y_scores >= threshold_90_precision) precision_score(y_train_5, y_train_pred_90) recall_score(y_train_5, y_train_pred_90) from sklearn.metrics import roc_curve fpr, tpr, thresholds = roc_curve(y_train_5, y_scores) def plot_roc_curve(fpr, tpr, label=None): plt.plot(fpr, tpr, linewidth=2, label=label) plt.plot([0, 1], [0, 1], 'k--') plt.grid(True) plt.xlabel('FPR') plt.ylabel('TPR(Recall)') plot_roc_curve(fpr, tpr) plt.show() from sklearn.metrics import roc_auc_score roc_auc_score(y_train_5, y_scores) from sklearn.ensemble import RandomForestClassifier forest_clf = RandomForestClassifier(random_state=42) y_probas_forest = cross_val_predict(forest_clf, X_train, y_train_5, cv=3, method='predict_proba') y_scores_forest = y_probas_forest[:, 1] fpr_forest, tpr_forest, thresholds_forest = roc_curve(y_train_5, y_scores_forest) plt.plot(fpr, tpr, "b:", label="SGD") plot_roc_curve(fpr_forest, tpr_forest, "random forest") plt.legend(loc="lower right") plt.show() roc_auc_score(y_train_5, y_scores_forest) from sklearn.svm import SVC svm_clf = SVC() svm_clf.fit(X_train, y_train) svm_clf.predict([some_digit]) some_digit_scores = svm_clf.decision_function([some_digit]) some_digit_scores np.argmax(some_digit_scores) svm_clf.classes_ from sklearn.multiclass import OneVsRestClassifier ovr_clf = OneVsRestClassifier(SVC()) ovr_clf.fit(X_train, y_train) ovr_clf.predict([some_digit]) len(ovr_clf.estimators_) sgd_clf.fit(X_train, y_train) sgd_clf.predict([some_digit]) sgd_clf.decision_function([some_digit]) cross_val_score(sgd_clf, X_train, y_train, cv=3, scoring='accuracy') from sklearn.preprocessing import StandardScaler scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train.astype(np.float64)) cross_val_score(sgd_clf, X_train_scaled, y_train, cv=3, scoring='accuracy') y_train_pred = cross_val_predict(sgd_clf, X_train_scaled, y_train, cv=3) conf_mx = confusion_matrix(y_train, y_train_pred) conf_mx plt.matshow(conf_mx, cmap=plt.cm.gray) plt.show() row_sums = conf_mx.sum(axis=1, keepdims=True) norm_conf_mx = conf_mx / row_sums np.fill_diagonal(norm_conf_mx, 0) plt.matshow(norm_conf_mx, cmap=plt.cm.gray) plt.show() from sklearn.neighbors import KNeighborsClassifier y_train_large = (y_train >= 7) y_train_odd = (y_train % 2 == 1) y_multilabel = np.c_[y_train_large, y_train_odd] knn_clf = KNeighborsClassifier() knn_clf.fit(X_train, y_multilabel) knn_clf.predict([some_digit]) y_train_knn_pred = cross_val_predict(knn_clf, X_train, y_multilabel, cv=3) f1_score(y_multilabel, y_train_knn_pred, average='macro') noise = np.random.randint(0, 100, (len(X_train), 784)) X_train_mod = X_train + noise noise = np.random.randint(0, 100, (len(X_test), 784)) X_test_mod = X_test + noise y_train_mod = X_train y_test_mode = X_test knn_clf.fit(X_train_mod, y_train_mod) clean_digit = knn_clf.predict([X_test_mod[4]])
0.850407
0.870652
``` import os import numpy as np import pandas as pd home_folder = os.path.expanduser("~") data_folder = os.path.join(home_folder, "Data", "basketball") data_filename = os.path.join(data_folder, "leagues_NBA_2014_games_games.csv") results = pd.read_csv(data_filename) results.ix[:5] # Don't read the first row, as it is blank, and parse the date column as a date results = pd.read_csv(data_filename, parse_dates=["Date"], skiprows=[0,]) # Fix the name of the columns results.columns = ["Date", "Score Type", "Visitor Team", "VisitorPts", "Home Team", "HomePts", "OT?", "Notes"] results.ix[:5] results["HomeWin"] = results["VisitorPts"] < results["HomePts"] # Our "class values" y_true = results["HomeWin"].values results.ix[:5] print("Home Win percentage: {0:.1f}%".format(100 * results["HomeWin"].sum() / results["HomeWin"].count())) results["HomeLastWin"] = False results["VisitorLastWin"] = False # This creates two new columns, all set to False results.ix[:5] # Now compute the actual values for these # Did the home and visitor teams win their last game? from collections import defaultdict won_last = defaultdict(int) for index, row in results.iterrows(): # Note that this is not efficient home_team = row["Home Team"] visitor_team = row["Visitor Team"] row["HomeLastWin"] = won_last[home_team] row["VisitorLastWin"] = won_last[visitor_team] results.ix[index] = row # Set current win won_last[home_team] = row["HomeWin"] won_last[visitor_team] = not row["HomeWin"] results.ix[20:25] from sklearn.tree import DecisionTreeClassifier clf = DecisionTreeClassifier(random_state=14) from sklearn.cross_validation import cross_val_score # Create a dataset with just the neccessary information X_previouswins = results[["HomeLastWin", "VisitorLastWin"]].values clf = DecisionTreeClassifier(random_state=14) scores = cross_val_score(clf, X_previouswins, y_true, scoring='accuracy') print("Using just the last result from the home and visitor teams") print("Accuracy: {0:.1f}%".format(np.mean(scores) * 100)) # What about win streaks? results["HomeWinStreak"] = 0 results["VisitorWinStreak"] = 0 # Did the home and visitor teams win their last game? from collections import defaultdict win_streak = defaultdict(int) for index, row in results.iterrows(): # Note that this is not efficient home_team = row["Home Team"] visitor_team = row["Visitor Team"] row["HomeWinStreak"] = win_streak[home_team] row["VisitorWinStreak"] = win_streak[visitor_team] results.ix[index] = row # Set current win if row["HomeWin"]: win_streak[home_team] += 1 win_streak[visitor_team] = 0 else: win_streak[home_team] = 0 win_streak[visitor_team] += 1 clf = DecisionTreeClassifier(random_state=14) X_winstreak = results[["HomeLastWin", "VisitorLastWin", "HomeWinStreak", "VisitorWinStreak"]].values scores = cross_val_score(clf, X_winstreak, y_true, scoring='accuracy') print("Using whether the home team is ranked higher") print("Accuracy: {0:.1f}%".format(np.mean(scores) * 100)) # Let's try see which team is better on the ladder. Using the previous year's ladder ladder_filename = os.path.join(data_folder, "leagues_NBA_2013_standings_expanded-standings.csv") ladder = pd.read_csv(ladder_filename, skiprows=[0,1]) ladder # We can create a new feature -- HomeTeamRanksHigher\ results["HomeTeamRanksHigher"] = 0 for index, row in results.iterrows(): home_team = row["Home Team"] visitor_team = row["Visitor Team"] if home_team == "New Orleans Pelicans": home_team = "New Orleans Hornets" elif visitor_team == "New Orleans Pelicans": visitor_team = "New Orleans Hornets" home_rank = ladder[ladder["Team"] == home_team]["Rk"].values[0] visitor_rank = ladder[ladder["Team"] == visitor_team]["Rk"].values[0] row["HomeTeamRanksHigher"] = int(home_rank > visitor_rank) results.ix[index] = row results[:5] X_homehigher = results[["HomeLastWin", "VisitorLastWin", "HomeTeamRanksHigher"]].values clf = DecisionTreeClassifier(random_state=14) scores = cross_val_score(clf, X_homehigher, y_true, scoring='accuracy') print("Using whether the home team is ranked higher") print("Accuracy: {0:.1f}%".format(np.mean(scores) * 100)) from sklearn.grid_search import GridSearchCV parameter_space = { "max_depth": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], } clf = DecisionTreeClassifier(random_state=14) grid = GridSearchCV(clf, parameter_space) grid.fit(X_homehigher, y_true) print("Accuracy: {0:.1f}%".format(grid.best_score_ * 100)) # Who won the last match? We ignore home/visitor for this bit last_match_winner = defaultdict(int) results["HomeTeamWonLast"] = 0 for index, row in results.iterrows(): home_team = row["Home Team"] visitor_team = row["Visitor Team"] teams = tuple(sorted([home_team, visitor_team])) # Sort for a consistent ordering # Set in the row, who won the last encounter row["HomeTeamWonLast"] = 1 if last_match_winner[teams] == row["Home Team"] else 0 results.ix[index] = row # Who won this one? winner = row["Home Team"] if row["HomeWin"] else row["Visitor Team"] last_match_winner[teams] = winner results.ix[:5] X_home_higher = results[["HomeTeamRanksHigher", "HomeTeamWonLast"]].values clf = DecisionTreeClassifier(random_state=14) scores = cross_val_score(clf, X_home_higher, y_true, scoring='accuracy') print("Using whether the home team is ranked higher") print("Accuracy: {0:.1f}%".format(np.mean(scores) * 100)) from sklearn.preprocessing import LabelEncoder, OneHotEncoder encoding = LabelEncoder() encoding.fit(results["Home Team"].values) home_teams = encoding.transform(results["Home Team"].values) visitor_teams = encoding.transform(results["Visitor Team"].values) X_teams = np.vstack([home_teams, visitor_teams]).T onehot = OneHotEncoder() X_teams = onehot.fit_transform(X_teams).todense() clf = DecisionTreeClassifier(random_state=14) scores = cross_val_score(clf, X_teams, y_true, scoring='accuracy') print("Accuracy: {0:.1f}%".format(np.mean(scores) * 100)) from sklearn.ensemble import RandomForestClassifier clf = RandomForestClassifier(random_state=14) scores = cross_val_score(clf, X_teams, y_true, scoring='accuracy') print("Using full team labels is ranked higher") print("Accuracy: {0:.1f}%".format(np.mean(scores) * 100)) X_all = np.hstack([X_home_higher, X_teams]) print(X_all.shape) clf = RandomForestClassifier(random_state=14) scores = cross_val_score(clf, X_all, y_true, scoring='accuracy') print("Using whether the home team is ranked higher") print("Accuracy: {0:.1f}%".format(np.mean(scores) * 100)) #n_estimators=10, criterion='gini', max_depth=None, #min_samples_split=2, min_samples_leaf=1, #max_features='auto', #max_leaf_nodes=None, bootstrap=True, #oob_score=False, n_jobs=1, #random_state=None, verbose=0, min_density=None, compute_importances=None parameter_space = { "max_features": [2, 10, 'auto'], "n_estimators": [100,], "criterion": ["gini", "entropy"], "min_samples_leaf": [2, 4, 6], } clf = RandomForestClassifier(random_state=14) grid = GridSearchCV(clf, parameter_space) grid.fit(X_all, y_true) print("Accuracy: {0:.1f}%".format(grid.best_score_ * 100)) print(grid.best_estimator_) ```
github_jupyter
import os import numpy as np import pandas as pd home_folder = os.path.expanduser("~") data_folder = os.path.join(home_folder, "Data", "basketball") data_filename = os.path.join(data_folder, "leagues_NBA_2014_games_games.csv") results = pd.read_csv(data_filename) results.ix[:5] # Don't read the first row, as it is blank, and parse the date column as a date results = pd.read_csv(data_filename, parse_dates=["Date"], skiprows=[0,]) # Fix the name of the columns results.columns = ["Date", "Score Type", "Visitor Team", "VisitorPts", "Home Team", "HomePts", "OT?", "Notes"] results.ix[:5] results["HomeWin"] = results["VisitorPts"] < results["HomePts"] # Our "class values" y_true = results["HomeWin"].values results.ix[:5] print("Home Win percentage: {0:.1f}%".format(100 * results["HomeWin"].sum() / results["HomeWin"].count())) results["HomeLastWin"] = False results["VisitorLastWin"] = False # This creates two new columns, all set to False results.ix[:5] # Now compute the actual values for these # Did the home and visitor teams win their last game? from collections import defaultdict won_last = defaultdict(int) for index, row in results.iterrows(): # Note that this is not efficient home_team = row["Home Team"] visitor_team = row["Visitor Team"] row["HomeLastWin"] = won_last[home_team] row["VisitorLastWin"] = won_last[visitor_team] results.ix[index] = row # Set current win won_last[home_team] = row["HomeWin"] won_last[visitor_team] = not row["HomeWin"] results.ix[20:25] from sklearn.tree import DecisionTreeClassifier clf = DecisionTreeClassifier(random_state=14) from sklearn.cross_validation import cross_val_score # Create a dataset with just the neccessary information X_previouswins = results[["HomeLastWin", "VisitorLastWin"]].values clf = DecisionTreeClassifier(random_state=14) scores = cross_val_score(clf, X_previouswins, y_true, scoring='accuracy') print("Using just the last result from the home and visitor teams") print("Accuracy: {0:.1f}%".format(np.mean(scores) * 100)) # What about win streaks? results["HomeWinStreak"] = 0 results["VisitorWinStreak"] = 0 # Did the home and visitor teams win their last game? from collections import defaultdict win_streak = defaultdict(int) for index, row in results.iterrows(): # Note that this is not efficient home_team = row["Home Team"] visitor_team = row["Visitor Team"] row["HomeWinStreak"] = win_streak[home_team] row["VisitorWinStreak"] = win_streak[visitor_team] results.ix[index] = row # Set current win if row["HomeWin"]: win_streak[home_team] += 1 win_streak[visitor_team] = 0 else: win_streak[home_team] = 0 win_streak[visitor_team] += 1 clf = DecisionTreeClassifier(random_state=14) X_winstreak = results[["HomeLastWin", "VisitorLastWin", "HomeWinStreak", "VisitorWinStreak"]].values scores = cross_val_score(clf, X_winstreak, y_true, scoring='accuracy') print("Using whether the home team is ranked higher") print("Accuracy: {0:.1f}%".format(np.mean(scores) * 100)) # Let's try see which team is better on the ladder. Using the previous year's ladder ladder_filename = os.path.join(data_folder, "leagues_NBA_2013_standings_expanded-standings.csv") ladder = pd.read_csv(ladder_filename, skiprows=[0,1]) ladder # We can create a new feature -- HomeTeamRanksHigher\ results["HomeTeamRanksHigher"] = 0 for index, row in results.iterrows(): home_team = row["Home Team"] visitor_team = row["Visitor Team"] if home_team == "New Orleans Pelicans": home_team = "New Orleans Hornets" elif visitor_team == "New Orleans Pelicans": visitor_team = "New Orleans Hornets" home_rank = ladder[ladder["Team"] == home_team]["Rk"].values[0] visitor_rank = ladder[ladder["Team"] == visitor_team]["Rk"].values[0] row["HomeTeamRanksHigher"] = int(home_rank > visitor_rank) results.ix[index] = row results[:5] X_homehigher = results[["HomeLastWin", "VisitorLastWin", "HomeTeamRanksHigher"]].values clf = DecisionTreeClassifier(random_state=14) scores = cross_val_score(clf, X_homehigher, y_true, scoring='accuracy') print("Using whether the home team is ranked higher") print("Accuracy: {0:.1f}%".format(np.mean(scores) * 100)) from sklearn.grid_search import GridSearchCV parameter_space = { "max_depth": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], } clf = DecisionTreeClassifier(random_state=14) grid = GridSearchCV(clf, parameter_space) grid.fit(X_homehigher, y_true) print("Accuracy: {0:.1f}%".format(grid.best_score_ * 100)) # Who won the last match? We ignore home/visitor for this bit last_match_winner = defaultdict(int) results["HomeTeamWonLast"] = 0 for index, row in results.iterrows(): home_team = row["Home Team"] visitor_team = row["Visitor Team"] teams = tuple(sorted([home_team, visitor_team])) # Sort for a consistent ordering # Set in the row, who won the last encounter row["HomeTeamWonLast"] = 1 if last_match_winner[teams] == row["Home Team"] else 0 results.ix[index] = row # Who won this one? winner = row["Home Team"] if row["HomeWin"] else row["Visitor Team"] last_match_winner[teams] = winner results.ix[:5] X_home_higher = results[["HomeTeamRanksHigher", "HomeTeamWonLast"]].values clf = DecisionTreeClassifier(random_state=14) scores = cross_val_score(clf, X_home_higher, y_true, scoring='accuracy') print("Using whether the home team is ranked higher") print("Accuracy: {0:.1f}%".format(np.mean(scores) * 100)) from sklearn.preprocessing import LabelEncoder, OneHotEncoder encoding = LabelEncoder() encoding.fit(results["Home Team"].values) home_teams = encoding.transform(results["Home Team"].values) visitor_teams = encoding.transform(results["Visitor Team"].values) X_teams = np.vstack([home_teams, visitor_teams]).T onehot = OneHotEncoder() X_teams = onehot.fit_transform(X_teams).todense() clf = DecisionTreeClassifier(random_state=14) scores = cross_val_score(clf, X_teams, y_true, scoring='accuracy') print("Accuracy: {0:.1f}%".format(np.mean(scores) * 100)) from sklearn.ensemble import RandomForestClassifier clf = RandomForestClassifier(random_state=14) scores = cross_val_score(clf, X_teams, y_true, scoring='accuracy') print("Using full team labels is ranked higher") print("Accuracy: {0:.1f}%".format(np.mean(scores) * 100)) X_all = np.hstack([X_home_higher, X_teams]) print(X_all.shape) clf = RandomForestClassifier(random_state=14) scores = cross_val_score(clf, X_all, y_true, scoring='accuracy') print("Using whether the home team is ranked higher") print("Accuracy: {0:.1f}%".format(np.mean(scores) * 100)) #n_estimators=10, criterion='gini', max_depth=None, #min_samples_split=2, min_samples_leaf=1, #max_features='auto', #max_leaf_nodes=None, bootstrap=True, #oob_score=False, n_jobs=1, #random_state=None, verbose=0, min_density=None, compute_importances=None parameter_space = { "max_features": [2, 10, 'auto'], "n_estimators": [100,], "criterion": ["gini", "entropy"], "min_samples_leaf": [2, 4, 6], } clf = RandomForestClassifier(random_state=14) grid = GridSearchCV(clf, parameter_space) grid.fit(X_all, y_true) print("Accuracy: {0:.1f}%".format(grid.best_score_ * 100)) print(grid.best_estimator_)
0.523177
0.28613
# Weakly imposing a Dirichlet boundary condition This tutorial shows how to implement the weak imposition of a Dirichlet boundary condition, as proposed in the paper <a href='https://bempp.com/publications.html#Betcke2019'>Boundary Element Methods with Weakly Imposed Boundary Conditions (2019)</a>. First, we import Bempp and NumPy. ``` import bempp.api import numpy as np ``` Next, we define the grid for our problem, and the function spaces that we will use. In this example, we use a sphere with P1 and DUAL0 function spaces. ``` h = 0.3 grid = bempp.api.shapes.sphere(h=h) p1 = bempp.api.function_space(grid, "P", 1) dual0 = bempp.api.function_space(grid, "DUAL", 0) ``` Next, we define the blocked operators proposed in the paper: $$\left(\left(\begin{array}{cc}-\mathsf{K}&\mathsf{V}\\\mathsf{W}&\mathsf{K}'\end{array}\right)+ \left(\begin{array}{cc}\tfrac12\mathsf{Id}&0\\\beta\mathsf{Id}&-\tfrac12\mathsf{Id}\end{array}\right)\right) \left(\begin{array}{c}u\\\lambda\end{array}\right) = \left(\begin{array}{c}g_\text{D}\\\beta g_\text{D}\end{array}\right),$$ where $\beta>0$ is a parameter of our choice. In this example, we use $\beta=0.1$. ``` beta = 0.1 multi = bempp.api.BlockedOperator(2,2) multi[0,0] = -bempp.api.operators.boundary.laplace.double_layer(p1, p1, dual0, assembler="fmm") multi[0,1] = bempp.api.operators.boundary.laplace.single_layer(dual0, p1, dual0, assembler="fmm") multi[1,0] = bempp.api.operators.boundary.laplace.hypersingular(p1, dual0, p1, assembler="fmm") multi[1,1] = bempp.api.operators.boundary.laplace.adjoint_double_layer(dual0, dual0, p1, assembler="fmm") diri = bempp.api.BlockedOperator(2,2) diri[0,0] = 0.5 * bempp.api.operators.boundary.sparse.identity(p1, p1, dual0) diri[1,0] = beta * bempp.api.operators.boundary.sparse.identity(p1, dual0, p1) diri[1,1] = -0.5 * bempp.api.operators.boundary.sparse.identity(dual0, dual0, p1) ``` Next, we define the function $g_\text{D}$, and define the right hand side. Here, we use $$g_\text{D}=\sin(\pi x)\sin(\pi y)\sinh(\sqrt2\pi z),$$ as in section 5 of the paper. ``` @bempp.api.real_callable def f(x, n, d, res): res[0] = np.sin(np.pi*x[0]) * np.sin(np.pi*x[1]) * np.sinh(np.sqrt(2)*np.pi*x[2]) f_fun = bempp.api.GridFunction(p1, fun=f) rhs = [2*diri[0,0]*f_fun, diri[1,0]*f_fun] ``` Now we solve the system. We set `use_strong_form=True` to activate mass matrix preconditioning. ``` sol, info, it_count = bempp.api.linalg.gmres(multi+diri, rhs, return_iteration_count=True, use_strong_form=True) print(f"Solution took {it_count} iterations") ``` For this problem, we know the analytic solution. We compute the error in the $\mathcal{B}_\text{D}$ norm: ``` @bempp.api.real_callable def g(x, n, d, res): grad = np.array([ np.cos(np.pi*x[0]) * np.sin(np.pi*x[1]) * np.sinh(np.sqrt(2)*np.pi*x[2]) * np.pi, np.sin(np.pi*x[0]) * np.cos(np.pi*x[1]) * np.sinh(np.sqrt(2)*np.pi*x[2]) * np.pi, np.sin(np.pi*x[0]) * np.sin(np.pi*x[1]) * np.cosh(np.sqrt(2)*np.pi*x[2]) * np.pi * np.sqrt(2) ]) res[0] = np.dot(grad, n) g_fun = bempp.api.GridFunction(dual0, fun=g) e_fun = [sol[0]-f_fun,sol[1]-g_fun] error = 0 # V norm slp = bempp.api.operators.boundary.laplace.single_layer(dual0, p1, dual0, assembler="fmm") hyp = bempp.api.operators.boundary.laplace.hypersingular(p1, dual0, p1, assembler="fmm") error += np.sqrt(np.dot(e_fun[1].coefficients.conjugate(),(slp * e_fun[1]).projections(dual0))) error += np.sqrt(np.dot(e_fun[0].coefficients.conjugate(),(hyp * e_fun[0]).projections(p1))) # D part error += beta**.5 * e_fun[0].l2_norm() print(f"Error: {error}") ```
github_jupyter
import bempp.api import numpy as np h = 0.3 grid = bempp.api.shapes.sphere(h=h) p1 = bempp.api.function_space(grid, "P", 1) dual0 = bempp.api.function_space(grid, "DUAL", 0) beta = 0.1 multi = bempp.api.BlockedOperator(2,2) multi[0,0] = -bempp.api.operators.boundary.laplace.double_layer(p1, p1, dual0, assembler="fmm") multi[0,1] = bempp.api.operators.boundary.laplace.single_layer(dual0, p1, dual0, assembler="fmm") multi[1,0] = bempp.api.operators.boundary.laplace.hypersingular(p1, dual0, p1, assembler="fmm") multi[1,1] = bempp.api.operators.boundary.laplace.adjoint_double_layer(dual0, dual0, p1, assembler="fmm") diri = bempp.api.BlockedOperator(2,2) diri[0,0] = 0.5 * bempp.api.operators.boundary.sparse.identity(p1, p1, dual0) diri[1,0] = beta * bempp.api.operators.boundary.sparse.identity(p1, dual0, p1) diri[1,1] = -0.5 * bempp.api.operators.boundary.sparse.identity(dual0, dual0, p1) @bempp.api.real_callable def f(x, n, d, res): res[0] = np.sin(np.pi*x[0]) * np.sin(np.pi*x[1]) * np.sinh(np.sqrt(2)*np.pi*x[2]) f_fun = bempp.api.GridFunction(p1, fun=f) rhs = [2*diri[0,0]*f_fun, diri[1,0]*f_fun] sol, info, it_count = bempp.api.linalg.gmres(multi+diri, rhs, return_iteration_count=True, use_strong_form=True) print(f"Solution took {it_count} iterations") @bempp.api.real_callable def g(x, n, d, res): grad = np.array([ np.cos(np.pi*x[0]) * np.sin(np.pi*x[1]) * np.sinh(np.sqrt(2)*np.pi*x[2]) * np.pi, np.sin(np.pi*x[0]) * np.cos(np.pi*x[1]) * np.sinh(np.sqrt(2)*np.pi*x[2]) * np.pi, np.sin(np.pi*x[0]) * np.sin(np.pi*x[1]) * np.cosh(np.sqrt(2)*np.pi*x[2]) * np.pi * np.sqrt(2) ]) res[0] = np.dot(grad, n) g_fun = bempp.api.GridFunction(dual0, fun=g) e_fun = [sol[0]-f_fun,sol[1]-g_fun] error = 0 # V norm slp = bempp.api.operators.boundary.laplace.single_layer(dual0, p1, dual0, assembler="fmm") hyp = bempp.api.operators.boundary.laplace.hypersingular(p1, dual0, p1, assembler="fmm") error += np.sqrt(np.dot(e_fun[1].coefficients.conjugate(),(slp * e_fun[1]).projections(dual0))) error += np.sqrt(np.dot(e_fun[0].coefficients.conjugate(),(hyp * e_fun[0]).projections(p1))) # D part error += beta**.5 * e_fun[0].l2_norm() print(f"Error: {error}")
0.282295
0.980581
# Traitement de signal ## Atelier \#1 : Initiation à Jupyter ### Support de cours disponible à l'adresse : [https://www.github.com/a-mhamdi/isetbz](https://www.github.com/a-mhamdi/isetbz) --- **Objectifs** 1. Apprendre à programmer en **Python**; 2. Se servir de l'environnement **Jupyter Notebook**; 3. Utiliser les bibliothèques du calcul scientifique. ## Variables numériques & Types ``` a = 1 # Un entier print('La variable a = {} est de type {}'.format(a, type(a))) b = -1.25 # Un nombre réel print('La variable b = {} est de type {}'.format(b, type(b))) c = 1+0.5j # Un nombre complexe print('La variable c = {} est de type {}'.format(c, type(c))) ``` ## Les chaînes de caractères ``` msg = "Mon Premier TP !" print(msg, type(msg), sep = '\n***\n') # \n : retour à la ligne print(msg + 3* '\nPython est simple') longMsg = """Ceci est un message, sur plusieurs lignes""" print(longMsg) ``` *Indexation* ``` # Indexation positive print(msg, msg[1:5], sep = ' -----> ') # Indexation négative print(msg, msg[-5:-1], sep = ' -----> ') ``` *Opérations sur les chaînes* ``` msg = 'Un message' print(len(msg)) print(msg.lower()) print(msg.upper()) print(msg.split(' ')) print(msg.replace('mes', 'MES')) print('a' in msg) # Vérifier si msg contient la lettre 'a' prix, nombre, perso = 100, 3, 'Un client' print('{} demande {} pièces pour un prix de {} MDT !'.format(perso, nombre, prix)) print('{1} demande {2} pièces pour un prix de {0} MDT !'.format(prix, perso, nombre)) ``` ## Binaire, octal & hexadécimal ``` x = 0b0101 # 0b : binaire print(x, type(x), sep = '\t----\t') # \t : tabulation y = 0xAF # Ox : hexadécimal print(y, type(y), sep = '\t' + '---'*5 + '\t') z = 0o010 # 0o : octal print(z, type(z), sep = ', ') ``` *Boolean* ``` a = True b = False print(a) print(b) print("50 > 20 ? : {} \n50 < 20 ? : {} \n50 = 20 ? : {}\n50 /= 20 ? : {}" .format(50 > 20, 50 < 20, 50 == 20, 50 != 20) ) print(bool(123), bool(0), bool('TP'), bool()) var1 = 100 print(isinstance(var1, int)) var2 = -100.35 print(isinstance(var2, int)) print(isinstance(var2, float)) ``` ## Listes, tuples & dictionnaires Nous étudierons ici trois types de groupement de données, indexés et non ordonnés, dans le langage de programmation **Python** : 1. *Liste* est une collection modifiable. Elle autorise les termes redondants ; 2. *Tuple* est une collection immuable. Il autorise aussi la redondance ; 3. *Dictionnaire* est une collection modifiable. Un terme en double est interdit. Lors du choix d'un type, il est utile de comprendre ses caractéristiques et de savoir comment **Python** gère ses définitions. ### Opérations sur les listes ``` maListe = ['a', 'b', 'c', 1, True] # Une liste mixte print(maListe) print(len(maListe)) # Taille de maListe print(maListe[1:3]) # Accès aux élements de maListe maListe[0] = ['1', 0] # Liste combinée print(maListe) print(maListe[3:]) print(maListe[:3]) maListe.append('etc') # Insertion de 'etc' à la fin de maListe print(maListe) maListe.insert(1, 'xyz') # Insertion de 'xyz' print(maListe) maListe.pop(1) print(maListe) maListe.pop() print(maListe) del maListe[0] print(maListe) maListe.append('b') print(maListe) maListe.remove('b') print(maListe) # Loop for k in maListe: print(k) maListe.clear() print(maListe) ``` | ***Méthode*** | ***Description*** | | -------- | -----------------------------------| | **copy()** | Renvoyer une copie de la liste | | **list()** | Transformer en une liste | | **extend ()** | Ajouter les éléments d'une liste (ou tout autre itérable), à la fin de la liste actuelle | | **count()** | Renvoyer le nombre d'occurrences de la valeur spécifiée | **index()** | Retourner l'index de la première occurrence de la valeur spécifiée | | **reverse()** | Inverser l'ordre la liste | | **sort()** | Trier la liste | ### Opérations sur les tuples ``` ce_tuple = (1, 2, 3) print(ce_tuple) ce_tuple = (1, '1', 2, 'texte') print(ce_tuple) print(len(ce_tuple)) print(ce_tuple[1:]) try: ce_tuple.append('xyz') # Déclencher une erreur except Exception as err: print(err) ma_liste = list(ce_tuple) ma_liste.append('xyz') print(ma_liste, type(ma_liste), sep = ', ') nv_tuple = tuple(ma_liste) # Convertir 'ma_liste' en tuple 'new_tuple' print(nv_tuple, type(nv_tuple), sep = ', ') try: ce_tuple.insert(1, 'xyz') # Déclencher une erreur except Exception as err: print(err) # Loop for k in ce_tuple: print(k) res_tuple = ce_tuple + nv_tuple print(res_tuple) ``` ### Opérations sur les dictionnaires ``` # monDict = {"key": "value"} monDict = { "Parcours" : "GM", "Spécialité" : "ElnI", "Sem" : "4" } print(monDict, type(monDict), sep = ', ') print(monDict["Sem"]) sem = monDict.get("Sem") print(sem) monDict["Parcours"] = "GE" print(monDict) # Boucle for d in monDict: print(d, monDict[d], sep = '\t|\t') for k in monDict.keys(): print(k) for v in monDict.values(): print(v) ``` ## NumPy La documentation officielle est disponible via ce lien : [https://numpy.org/](https://numpy.org/) Commençons d'abord par importer le module de calcul numérique **NumPy**. Nous le référençons désormais par l'acronyme *np* ``` import numpy as np ``` *NumPy vs Liste* ``` a_np = np.arange(6) # NumPy print("a_np = ", a_np) print(type(a_np)) a_lst = list(range(0,6)) # Liste print("a_lst = ", a_lst) print(type(a_lst)) # Comparaison print("2 * a_np = ", a_np * 2) print("2 * a_lst = ", a_lst * 2) v_np = np.array([1, 2, 3, 4, 5, 6]) # NB : parenthèses puis crochets, i.e, ([]) print(v_np) v_np = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) print(v_np) print(type(v_np)) print(v_np[0]) v_np.ndim # Dimensions de v_np v_np.shape # Nombre de lignes et de colonnes v_np.size # Nombre d'éléments dans v_np = 3 * 4 ``` Une autre démarche pour créer une matrice de taille (3,3) par exemple est : ``` u = np.arange(9).reshape(3,3) print(u) ``` Nous passons maintenant à présenter quelques opérations de base sur les matrices ``` M = np.array([[1, 2], [1, 2]]) print(M) N = np.array([[0, 3], [4, 5]]) print(N) ``` *Addition* ``` print(M + N) print(np.add(M, N)) ``` *Soustraction* ``` print(M-N) print(np.subtract(M, N)) ``` *Mutiplication élément par élément* _<u>(en: Elementwise Product)</u>_ $$ \left[\begin{array}{cc}1&2\\1&2\end{array}\right] .\times \left[\begin{array}{cc}0&3\\4&5\end{array}\right] \quad =\quad \left[\begin{array}{cc}0&6\\4&10\end{array}\right] $$ ``` print(M * N) print(np.multiply(M, N)) ``` *Produit matriciel* $$ \left[\begin{array}{cc}1&2\\1&2\end{array}\right] \times \left[\begin{array}{cc}0&3\\4&5\end{array}\right] \quad =\quad \left[\begin{array}{cc}8&13\\8&13\end{array}\right] $$ ``` print(M.dot(N)) print(np.dot(M, N)) ``` *Division élément par élément* _<u>(en: Elementwise Division)</u>_ $$ \left[\begin{array}{cc}0&3\\4&5\end{array}\right] ./ \left[\begin{array}{cc}1&2\\1&2\end{array}\right] \quad =\quad \left[\begin{array}{cc}0:1&3:2\\4:1&5:2\end{array}\right] $$ ``` print(N / M) print(np.divide(N, M)) ``` *Calcul du déterminant* ``` print("Déterminant de M :") print(np.linalg.det(M)) print("Déterminant de N :") print(np.linalg.det(N)) ``` ## Matplotlib De plus amples informations peuvent être trouvées à ce site : [https://matplotlib.org/](https://matplotlib.org/) ``` import numpy as np import matplotlib.pyplot as plt plt.style.use("ggplot") plt.rcParams['figure.figsize'] = [15, 10] ``` Nous créons une fonction sinusoïdale qu'on dénote par $x$ de période 1 sec, rehaussée d'une valeur constante de 1. ``` # Fonction continue t = np.arange(0.0, 2.0, 0.01) x = 1 + np.sin(2 * np.pi * t) # Fréquence = 1Hz ``` Les commandes qui permettent de tracer le graphique de $x$ sont : ``` plt.plot(t, x) # Donner un titre au graphique plt.title(r"$x(t) = 1+\sin\left(2\pi\frac{t}{1}\right)$") plt.xlabel("$t$ (sec)") # Nommer l'axe des abscisses # Fonction échantillonnée t = np.arange(0.0, 2.0, 0.1) y = np.sin(2*np.pi*t) # Pareil ! Signal sinusoïdal de fréquence 1Hz plt.stem(t, y) plt.xlabel("$t$ (sec)") ```
github_jupyter
a = 1 # Un entier print('La variable a = {} est de type {}'.format(a, type(a))) b = -1.25 # Un nombre réel print('La variable b = {} est de type {}'.format(b, type(b))) c = 1+0.5j # Un nombre complexe print('La variable c = {} est de type {}'.format(c, type(c))) msg = "Mon Premier TP !" print(msg, type(msg), sep = '\n***\n') # \n : retour à la ligne print(msg + 3* '\nPython est simple') longMsg = """Ceci est un message, sur plusieurs lignes""" print(longMsg) # Indexation positive print(msg, msg[1:5], sep = ' -----> ') # Indexation négative print(msg, msg[-5:-1], sep = ' -----> ') msg = 'Un message' print(len(msg)) print(msg.lower()) print(msg.upper()) print(msg.split(' ')) print(msg.replace('mes', 'MES')) print('a' in msg) # Vérifier si msg contient la lettre 'a' prix, nombre, perso = 100, 3, 'Un client' print('{} demande {} pièces pour un prix de {} MDT !'.format(perso, nombre, prix)) print('{1} demande {2} pièces pour un prix de {0} MDT !'.format(prix, perso, nombre)) x = 0b0101 # 0b : binaire print(x, type(x), sep = '\t----\t') # \t : tabulation y = 0xAF # Ox : hexadécimal print(y, type(y), sep = '\t' + '---'*5 + '\t') z = 0o010 # 0o : octal print(z, type(z), sep = ', ') a = True b = False print(a) print(b) print("50 > 20 ? : {} \n50 < 20 ? : {} \n50 = 20 ? : {}\n50 /= 20 ? : {}" .format(50 > 20, 50 < 20, 50 == 20, 50 != 20) ) print(bool(123), bool(0), bool('TP'), bool()) var1 = 100 print(isinstance(var1, int)) var2 = -100.35 print(isinstance(var2, int)) print(isinstance(var2, float)) maListe = ['a', 'b', 'c', 1, True] # Une liste mixte print(maListe) print(len(maListe)) # Taille de maListe print(maListe[1:3]) # Accès aux élements de maListe maListe[0] = ['1', 0] # Liste combinée print(maListe) print(maListe[3:]) print(maListe[:3]) maListe.append('etc') # Insertion de 'etc' à la fin de maListe print(maListe) maListe.insert(1, 'xyz') # Insertion de 'xyz' print(maListe) maListe.pop(1) print(maListe) maListe.pop() print(maListe) del maListe[0] print(maListe) maListe.append('b') print(maListe) maListe.remove('b') print(maListe) # Loop for k in maListe: print(k) maListe.clear() print(maListe) ce_tuple = (1, 2, 3) print(ce_tuple) ce_tuple = (1, '1', 2, 'texte') print(ce_tuple) print(len(ce_tuple)) print(ce_tuple[1:]) try: ce_tuple.append('xyz') # Déclencher une erreur except Exception as err: print(err) ma_liste = list(ce_tuple) ma_liste.append('xyz') print(ma_liste, type(ma_liste), sep = ', ') nv_tuple = tuple(ma_liste) # Convertir 'ma_liste' en tuple 'new_tuple' print(nv_tuple, type(nv_tuple), sep = ', ') try: ce_tuple.insert(1, 'xyz') # Déclencher une erreur except Exception as err: print(err) # Loop for k in ce_tuple: print(k) res_tuple = ce_tuple + nv_tuple print(res_tuple) # monDict = {"key": "value"} monDict = { "Parcours" : "GM", "Spécialité" : "ElnI", "Sem" : "4" } print(monDict, type(monDict), sep = ', ') print(monDict["Sem"]) sem = monDict.get("Sem") print(sem) monDict["Parcours"] = "GE" print(monDict) # Boucle for d in monDict: print(d, monDict[d], sep = '\t|\t') for k in monDict.keys(): print(k) for v in monDict.values(): print(v) import numpy as np a_np = np.arange(6) # NumPy print("a_np = ", a_np) print(type(a_np)) a_lst = list(range(0,6)) # Liste print("a_lst = ", a_lst) print(type(a_lst)) # Comparaison print("2 * a_np = ", a_np * 2) print("2 * a_lst = ", a_lst * 2) v_np = np.array([1, 2, 3, 4, 5, 6]) # NB : parenthèses puis crochets, i.e, ([]) print(v_np) v_np = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) print(v_np) print(type(v_np)) print(v_np[0]) v_np.ndim # Dimensions de v_np v_np.shape # Nombre de lignes et de colonnes v_np.size # Nombre d'éléments dans v_np = 3 * 4 u = np.arange(9).reshape(3,3) print(u) M = np.array([[1, 2], [1, 2]]) print(M) N = np.array([[0, 3], [4, 5]]) print(N) print(M + N) print(np.add(M, N)) print(M-N) print(np.subtract(M, N)) print(M * N) print(np.multiply(M, N)) print(M.dot(N)) print(np.dot(M, N)) print(N / M) print(np.divide(N, M)) print("Déterminant de M :") print(np.linalg.det(M)) print("Déterminant de N :") print(np.linalg.det(N)) import numpy as np import matplotlib.pyplot as plt plt.style.use("ggplot") plt.rcParams['figure.figsize'] = [15, 10] # Fonction continue t = np.arange(0.0, 2.0, 0.01) x = 1 + np.sin(2 * np.pi * t) # Fréquence = 1Hz plt.plot(t, x) # Donner un titre au graphique plt.title(r"$x(t) = 1+\sin\left(2\pi\frac{t}{1}\right)$") plt.xlabel("$t$ (sec)") # Nommer l'axe des abscisses # Fonction échantillonnée t = np.arange(0.0, 2.0, 0.1) y = np.sin(2*np.pi*t) # Pareil ! Signal sinusoïdal de fréquence 1Hz plt.stem(t, y) plt.xlabel("$t$ (sec)")
0.121751
0.913368
# Strings In previous lectures we have seen strings being used numerous times. Today we are going to go into a bit more detail. First, some terminology: * 'single-quote character' refers to unicode character 34, --> { ' } * 'double-quote character' refers to unicode character 39, --> { " } * and if I say 'quote-character' then I refer to both/either of the above. Okay, lets begin! ## What is a string? A string is basically a bunch of unicode characters, this makes them the ideal data type for storing written text. The Syntax: {quote-character} unicode characters {MATCHING quote-character} Examples: * "hello" # Valid syntax * 'hello' # also valid syntax * "hello' # doesn't work; uses both quotation characters. And just as with numbers, we can also convert other data-types to strings using the str function. ## Why do both single and double quote characters work? The reason Python accepts the use of single OR double quote characters is to make it easier for dealing with text that actually contains quote-characters. Suppose for instance we wanted to store the following sentence as a string: > "Ahhh!!!! spiders!", cried the monster. "Do not worry" said our hero, "I have a sharp spoon". wow, I'm hooked; with epic character development like that maybe I should be writing novels instead of programming tutorials? Anyway, I digress. The point is if I try to save this sentence with double-quotes, problems occur. But I can save the string as is if wrap my string with single-quote characters. As demonstrated by the next two code snippets. ``` # wrapping text with double quotes... cool_story_bro = ""Ahhh!!!! spiders!", cried the monster. "Do not worry" said our hero, "I have a sharp spoon"." print(cool_story_bro) # wrapping text with single quotes... cool_story_bro = '"Ahhh!!!! spiders!", cried the monster."Do not worry" said our hero, "I have a sharp spoon".' print(cool_story_bro) ``` ## Because I messed up, you have homework. When I first wrote the example it took me about 10 minutes to actually get it working, I just couldn't figure out what the problem was! It turns out that in the original draft my spider-maiming hero said the phrase: “don’t worry” The ' character in don't was messing up my attempt to enclose the whole string within single quotes. Here, let me show you: ``` cool_story_bro = '"Ahhh!!!! spiders!", cried the monster."Don't worry" said our hero, "I have a sharp spoon".' print(cool_story_bro) ``` So what was my genius solution? Well obviously we cheat and change the text! “don’t worry” --> “do not worry” Problem...err….solved? Anyway, Python does have ways of handling such inputs, your homework for this week to figure out how to make my intended string work – if it takes you less than 10 minutes then congratulations, you figured it out faster than I did. :) ## The str function Just like the int() and float() functions, the str function is a good way to convert one data-type to another. If I have the an integer and I want to store it as a string I can simply call the str() function, and Python will do the rest. The code snippet below will take any float/integer and return a string representation of that number. ``` def num_to_string(number): """takes a number of type float/int, returns string of that number""" return str(number) # For an explanation of the next three lines of code, please see the 'calling functions' lecture. a = num_to_string(4555549099511) # large integer b = num_to_string(-0.0044352334) # negative float c = num_to_string(4.3e10) # scientific notation print(a, type(a)) print(b, type(b)) print(c, type(c)) # and notice that we can use the float/int methods to convert the strings back to numbers just as easily... print( float(c), type(float(c)) ) ``` ## Why might you want to do this? One reason you might want to store a number as a string is because if you convert a number to a string you have access to more 'methods' which may make some processes easier. for example, lets suppose I want to find out what the first two digits of the number are. Converting a number to a string makes this process easy since strings are iterable and can be indexed into, whereas numbers cannot. Thats a lot of techinical jargon right now, but don't worry we shall cover indexing later. ``` def first_two_digits(number): n = str(number) # < -- convert number to string n = n[:2] # < -- get the first two characters via slicing (more on slicing later). n = int(n) # < -- converting n back to a number. return n print(first_two_digits(100000)) print(first_two_digits(933323)) print(first_two_digits(11)) ``` ## Escape Characters Text frequently has ‘meta-data’ attached to it, by meta-data in this context I’m mainly talking about things like HTML tags; font colour, size, stylings (e.g **bold**, *italic*), and so on. The normal process for handling this is to have the code embedded into the text itself. In other words, the text itself has characters that Python has parse as commands. But for some applications you might want to have the ability to literally print every character passed in. So example, in the example directly below we have two lines of text, a pink heading and some text with tags. Crucially these two pieces of text are the same; the difference in what we see is the difference between literally printing the HTML tags versus executing them. > <h1 style="color:pink;">This is a heading</h1> &lt;h1 style=&quot;color:pink;&quot;&gt;This is a heading&lt;/h1&gt; So, how does the computer know to interpret text in one way and not the other? Well, the solution is something called “escape characters”. Just for completeness, to show you the tags to get pink text I had to use several HTML escape characters, I typed the following monstrocity: > &amp;lt;h1 style=&amp;quot;color:pink;&amp;quot;&amp;gt;This is a heading&amp;lt;/h1&amp;gt; Thats a complex line of jargon I couldn't have done without the help of [this tool](https://www.freeformatter.com/html-escape.html). So yeah, escaping in HTML can be bit tricky but fortunately for us escape characters in Python are a bit easier to work with. Consider the following lines of code. ``` a = "\\" b = "\" ``` At first glance this code seems perfectly fine, right? The variable 'A' should be the string \\\ right? And variable 'B' should just be a single backslash. But we don't get that, Python throws and error! What’s going on here? Well, the reason is that the backslash character (\\) is an escape character in Python. To actually get Python to literally print "\\\\" or "\\" we would actually have to type out: ``` a = "\\\\" # double \\ b = "\\" # single \ print(a, b) # Note that I didn't have to do any escaping in the comments, thats because Python just ignores comments! ``` It is important to be aware of these Python features because If you don't know this stuff it you can be easily 'caught-out' the moment you start trying to parse complex strings. In what follows I have a (hopefully humorous) example of why you should care about this stuff. Let’s talk *pathing*. ``` directory = "C:\Documents\pictures\selfies" print(directory) ``` So let's imagine we are building some sort of code that saves a directory as a string for use later on. If we print this particular directory we get no surprises, it just works as we would expect. But hold-up, what if I wanted to send my girlfriend a naughty photo! inside of my 'selfies' folder I have a 'nudes' folder. And inside the 'nudes' folder I have a plethora of Jpegs; my little sausage pictured from a variety of different angles wearing an assortment of novelty hats. <img src="http://i.imgur.com/wVrnjgc.png" style="width:300px;height:170px;" ALIGN="right"> > “Wait, did he just say little?” On this occasion however, let's pretend I'm not a total weirdo (debatable), I want to sent her something *arty*, something *classy*. [scurries through folder...] [finds ... 'tasteful.jpeg' ] Alright, lets code that up and see what happens... ``` directory2 = "C:\Documents\pictures\selfies\nudes\tasteful.jpeg" print(directory2) ``` Oh dear! It seems like python doesn't want me to send dick-pics over the internet afterall! thats a pity, a big pity (wink wink). What has gone wrong? Well, basically every time Python see's a backslash character it looks to see what the next character is. In the case of directory above, we have the following: \\D, \\p, \\s, \\n, \\t This first time we ran the code we didn't get any errors because \\D \\p where not special 'commands'. However, both \\n and \\t are special commands in Python. These commands get executed and we get a different result. ## New line... As an aside, \\n is a very useful command to use within strings. It starts a new line, and splitting data up into separate lines frequently comes in useful. "{some text}\n{more text}" Simple example: ``` greeting = "hello\nworld" print(greeting) # using \t (which is tab) greeting = "hello\tworld" print(greeting) # There are other commands of course, but I feel that most of them are not useful enough to be worth teaching. ``` In short, \n is a newline, and \t is tab. Thus, if we are trying to save/open files/folders on windows systems that start with t or n we can end up having some difficulties. There are a few solutions to this problem. If you are dealing with directories specificially then the best choice is to you the os module. This module will fix a number of these issues for you (the os module works on linux and windows machines). for example: ``` import os directory = "C:\Documents\pictures\selfies" photo_name = "santa_hat2.jpeg" ## the bad way path_to_photo_1 = directory + "\\" + photo_name ## the good way path_to_photo_2 = os.path.join(directory, photo_name) print(path_to_photo_1) print(path_to_photo_2) ``` However, the above method only works for file systems, how can we solve this problem in a more general way? ## Raw strings... So what can we do if we want Python to ignore these commands? Well, the simplest solution is to put an 'r' before the string starts. The 'r' here tells Python we want a *raw string.* ``` string1 = r"\nevery\nword\nis\non\na\nnew\nline" # notice the 'r' BEFORE the double-quote mark? string2 = "\nevery\nword\nis\non\na\nnew\nline" # without the 'r', for comparision. print("The raw string version looks like this:\n", string1) print("\n") print("The normal version of string looks like this:\n", string2) ``` ## A Few More Operations... Strings are a huge topic in Python, and we are going to have come back to them latter. But for now, let me leave you with a few basic operations you can perform on strings... ``` # Repeating strings # {string} * {integer} # Examples: print("a" * 10) print("abc" * 3) # Concatenation # {string} + {string} # Examples: print("ab" + "c") print("a" + "b" + "c") # Membership # {string} in {string} # Examples: print("a" in "ab") print("a" in "cb") print("abc" in "aabbcc") # must be an exact match. ``` ### HOMEWORK ASSIGNMENT Name a variable "cool_story_bro" and then assign the the following text as a string: >"Ahhh!!!! spiders!", cried the monster."Don't worry" said our hero, "I have a sharp spoon". Once complete, print it. ``` # Your answer here… ```
github_jupyter
# wrapping text with double quotes... cool_story_bro = ""Ahhh!!!! spiders!", cried the monster. "Do not worry" said our hero, "I have a sharp spoon"." print(cool_story_bro) # wrapping text with single quotes... cool_story_bro = '"Ahhh!!!! spiders!", cried the monster."Do not worry" said our hero, "I have a sharp spoon".' print(cool_story_bro) cool_story_bro = '"Ahhh!!!! spiders!", cried the monster."Don't worry" said our hero, "I have a sharp spoon".' print(cool_story_bro) def num_to_string(number): """takes a number of type float/int, returns string of that number""" return str(number) # For an explanation of the next three lines of code, please see the 'calling functions' lecture. a = num_to_string(4555549099511) # large integer b = num_to_string(-0.0044352334) # negative float c = num_to_string(4.3e10) # scientific notation print(a, type(a)) print(b, type(b)) print(c, type(c)) # and notice that we can use the float/int methods to convert the strings back to numbers just as easily... print( float(c), type(float(c)) ) def first_two_digits(number): n = str(number) # < -- convert number to string n = n[:2] # < -- get the first two characters via slicing (more on slicing later). n = int(n) # < -- converting n back to a number. return n print(first_two_digits(100000)) print(first_two_digits(933323)) print(first_two_digits(11)) a = "\\" b = "\" a = "\\\\" # double \\ b = "\\" # single \ print(a, b) # Note that I didn't have to do any escaping in the comments, thats because Python just ignores comments! directory = "C:\Documents\pictures\selfies" print(directory) directory2 = "C:\Documents\pictures\selfies\nudes\tasteful.jpeg" print(directory2) greeting = "hello\nworld" print(greeting) # using \t (which is tab) greeting = "hello\tworld" print(greeting) # There are other commands of course, but I feel that most of them are not useful enough to be worth teaching. import os directory = "C:\Documents\pictures\selfies" photo_name = "santa_hat2.jpeg" ## the bad way path_to_photo_1 = directory + "\\" + photo_name ## the good way path_to_photo_2 = os.path.join(directory, photo_name) print(path_to_photo_1) print(path_to_photo_2) string1 = r"\nevery\nword\nis\non\na\nnew\nline" # notice the 'r' BEFORE the double-quote mark? string2 = "\nevery\nword\nis\non\na\nnew\nline" # without the 'r', for comparision. print("The raw string version looks like this:\n", string1) print("\n") print("The normal version of string looks like this:\n", string2) # Repeating strings # {string} * {integer} # Examples: print("a" * 10) print("abc" * 3) # Concatenation # {string} + {string} # Examples: print("ab" + "c") print("a" + "b" + "c") # Membership # {string} in {string} # Examples: print("a" in "ab") print("a" in "cb") print("abc" in "aabbcc") # must be an exact match. # Your answer here…
0.227555
0.910147
``` from pomegranate import * import seaborn %pylab inline seaborn.set_style('whitegrid') numpy.set_printoptions(suppress=True) ``` # Naive Bayes and Bayes Classifiers: A Tutorial author: Jacob Schreiber <br> contact: [email protected] Bayes classifiers are some of the simplest machine learning models that exist, due to their intuitive probabilistic interpretation and simple fitting step. Each class is modeled as a probability distribution, and the data is interpreted as samples drawn from these underlying distributions. Fitting the model to data is as simple as calculating maximum likelihood parameters for the data that falls under each class, and making predictions is as simple as using Bayes' rule to determine which class is most likely given the distributions. Bayes' Rule is the following: \begin{equation} P(M|D) = \frac{P(D|M)P(M)}{P(D)} \end{equation} where M stands for the model and D stands for the data. $P(M)$ is known as the <i>prior</i>, because it is the probability that a sample is of a certain class before you even know what the sample is. This is generally just the frequency of each class. Intuitively, it makes sense that you would want to model this, because if one class occurs 10x more than another class, it is more likely that a given sample will belong to that distribution. $P(D|M)$ is the likelihood, or the probability, of the data under a given model. Lastly, $P(M|D)$ is the posterior, which is the probability of each component of the model, or class, being the component which generated the data. It is called the posterior because the prior corresponds to probabilities before seeing data, and the posterior corresponds to probabilities after observing the data. In cases where the prior is uniform, the posterior is just equal to the normalized likelihoods. This equation forms the basis of most probabilistic modeling, with interesting priors allowing the user to inject sophisticated expert knowledge into the problem directly. Let's take a look at some single dimensional data in order to introduce these concepts more thoroughly. ``` X = numpy.concatenate((numpy.random.normal(3, 1, 200), numpy.random.normal(10, 2, 1000))) y = numpy.concatenate((numpy.zeros(200), numpy.ones(1000))) x1 = X[:200] x2 = X[200:] plt.figure(figsize=(16, 5)) plt.hist(x1, bins=25, color='m', edgecolor='m', label="Class A") plt.hist(x2, bins=25, color='c', edgecolor='c', label="Class B") plt.xlabel("Value", fontsize=14) plt.ylabel("Count", fontsize=14) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.show() ``` The data seems like it comes from two normal distributions, with the cyan class being more prevalent than the magenta class. A natural way to model this data would be to create a normal distribution for the cyan data, and another for the magenta distribution. Let's take a look at doing that. All we need to do is use the `from_samples` class method of the `NormalDistribution` class. ``` d1 = NormalDistribution.from_samples(x1) d2 = NormalDistribution.from_samples(x2) idxs = numpy.arange(0, 15, 0.1) p1 = map(d1.probability, idxs) p2 = map(d2.probability, idxs) plt.figure(figsize=(16, 5)) plt.plot(idxs, p1, color='m'); plt.fill_between(idxs, 0, p1, facecolor='m', alpha=0.2) plt.plot(idxs, p2, color='c'); plt.fill_between(idxs, 0, p2, facecolor='c', alpha=0.2) plt.xlabel("Value", fontsize=14) plt.ylabel("Probability", fontsize=14) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.show() ``` It looks like some aspects of the data are captured well by doing things this way-- specifically the mean and variance of the normal distributions. This allows us to easily calculate $P(D|M)$ as the probability of a sample under either the cyan or magenta distributions using the normal (or Gaussian) probability density equation: \begin{align} P(D|M) &= P(x|\mu, \sigma) \\ &= \frac{1}{\sqrt{2\pi\sigma^{2}}} exp \left(-\frac{(x-u)^{2}}{2\sigma^{2}} \right) \end{align} However, if we look at the original data, we see that the cyan distributions is both much wider than the purple distribution and much taller, as there were more samples from that class in general. If we reduce that data down to these two distributions, we lose the class imbalance. We want our prior to model this class imbalance, with the reasoning being that if we randomly draw a sample from the samples observed thus far, it is far more likely to be a cyan than a magenta sample. Let's take a look at this class imbalance exactly. ``` magenta_prior = 1. * len(x1) / len(X) cyan_prior = 1. * len(x2) / len(X) plt.figure(figsize=(4, 6)) plt.title("Prior Probabilities P(M)", fontsize=14) plt.bar(0, magenta_prior, facecolor='m', edgecolor='m') plt.bar(1, cyan_prior, facecolor='c', edgecolor='c') plt.xticks([0, 1], ['P(Magenta)', 'P(Cyan)'], fontsize=14) plt.yticks(fontsize=14) plt.show() ``` The prior $P(M)$ is a vector of probabilities over the classes that the model can predict, also known as components. In this case, if we draw a sample randomly from the data that we have, there is a ~83% chance that it will come from the cyan class and a ~17% chance that it will come from the magenta class. Let's multiply the probability densities we got before by this imbalance. ``` d1 = NormalDistribution.from_samples(x1) d2 = NormalDistribution.from_samples(x2) idxs = numpy.arange(0, 15, 0.1) p_magenta = numpy.array(map(d1.probability, idxs)) * magenta_prior p_cyan = numpy.array(map(d2.probability, idxs)) * cyan_prior plt.figure(figsize=(16, 5)) plt.plot(idxs, p_magenta, color='m'); plt.fill_between(idxs, 0, p_magenta, facecolor='m', alpha=0.2) plt.plot(idxs, p_cyan, color='c'); plt.fill_between(idxs, 0, p_cyan, facecolor='c', alpha=0.2) plt.xlabel("Value", fontsize=14) plt.ylabel("P(M)P(D|M)", fontsize=14) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.show() ``` This looks a lot more faithful to the original data, and actually corresponds to $P(M)P(D|M)$, the prior multiplied by the likelihood. However, these aren't actually probability distributions anymore, as they no longer integrate to 1. This is why the $P(M)P(D|M)$ term has to be normalized by the $P(D)$ term in Bayes' rule in order to get a probability distribution over the components. However, $P(D)$ is difficult to determine exactly-- what is the probability of the data? Well, we can sum over the classes to get that value, since $P(D) = \sum_{i=1}^{c} P(D|M)P(M)$ for a problem with c classes. This translates into $P(D) = P(M=Cyan)P(D|M=Cyan) + P(M=Magenta)P(D|M=Magenta)$ for this specific problem, and those values can just be pulled from the unnormalized plots above. This gives us the full Bayes' rule, with the posterior $P(M|D)$ being the proportion of density of the above plot coming from each of the two distributions at any point on the line. Let's take a look at the posterior probabilities of the two classes on the same line. ``` magenta_posterior = p_magenta / (p_magenta + p_cyan) cyan_posterior = p_cyan / (p_magenta + p_cyan) plt.figure(figsize=(16, 5)) plt.subplot(211) plt.plot(idxs, p_magenta, color='m'); plt.fill_between(idxs, 0, p_magenta, facecolor='m', alpha=0.2) plt.plot(idxs, p_cyan, color='c'); plt.fill_between(idxs, 0, p_cyan, facecolor='c', alpha=0.2) plt.xlabel("Value", fontsize=14) plt.ylabel("P(M)P(D|M)", fontsize=14) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.subplot(212) plt.plot(idxs, magenta_posterior, color='m') plt.plot(idxs, cyan_posterior, color='c') plt.xlabel("Value", fontsize=14) plt.ylabel("P(M|D)", fontsize=14) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.show() ``` The top plot shows the same densities as before, while the bottom plot shows the proportion of the density belonging to either class at that point. This proportion is known as the posterior $P(M|D)$, and can be interpreted as the probability of that point belonging to each class. This is one of the native benefits of probabilistic models, that instead of providing a hard class label for each sample, they can provide a soft label in the form of the probability of belonging to each class. We can implement all of this simply in pomegranate using the `NaiveBayes` class. ``` idxs = idxs.reshape(idxs.shape[0], 1) X = X.reshape(X.shape[0], 1) model = NaiveBayes.from_samples(NormalDistribution, X, y) posteriors = model.predict_proba(idxs) plt.figure(figsize=(14, 4)) plt.plot(idxs, posteriors[:,0], color='m') plt.plot(idxs, posteriors[:,1], color='c') plt.xlabel("Value", fontsize=14) plt.ylabel("P(M|D)", fontsize=14) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.show() ``` Looks like we're getting the same plots for the posteriors just through fitting the naive Bayes model directly to data. The predictions made will come directly from the posteriors in this plot, with cyan predictions happening whenever the cyan posterior is greater than the magenta posterior, and vice-versa. ## Naive Bayes In the univariate setting, naive Bayes is identical to a general Bayes classifier. The divergence occurs in the multivariate setting, the naive Bayes model assumes independence of all features, while a Bayes classifier is more general and can support more complicated interactions or covariances between features. Let's take a look at what this means in terms of Bayes' rule. \begin{align} P(M|D) &= \frac{P(M)P(D|M)}{P(D)} \\ &= \frac{P(M)\prod_{i=1}^{d}P(D_{i}|M_{i})}{P(D)} \end{align} This looks fairly simple to compute, as we just need to pass each dimension into the appropriate distribution and then multiply the returned probabilities together. This simplicity is one of the reasons why naive Bayes is so widely used. Let's look closer at using this in pomegranate, starting off by generating two blobs of data that overlap a bit and inspecting them. ``` X = numpy.concatenate([numpy.random.normal(3, 2, size=(150, 2)), numpy.random.normal(7, 1, size=(250, 2))]) y = numpy.concatenate([numpy.zeros(150), numpy.ones(250)]) plt.figure(figsize=(8, 8)) plt.scatter(X[y == 0, 0], X[y == 0, 1], color='c') plt.scatter(X[y == 1, 0], X[y == 1, 1], color='m') plt.xlim(-2, 10) plt.ylim(-4, 12) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.show() ``` Now, let's fit our naive Bayes model to this data using pomegranate. We can use the `from_samples` class method, pass in the distribution that we want to model each dimension, and then the data. We choose to use `NormalDistribution` in this particular case, but any supported distribution would work equally well, such as `BernoulliDistribution` or `ExponentialDistribution`. To ensure we get the correct decision boundary, let's also plot the boundary recovered by sklearn. ``` from sklearn.naive_bayes import GaussianNB model = NaiveBayes.from_samples(NormalDistribution, X, y) clf = GaussianNB().fit(X, y) xx, yy = np.meshgrid(np.arange(-2, 10, 0.02), np.arange(-4, 12, 0.02)) Z1 = model.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape) Z2 = clf.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape) plt.figure(figsize=(16, 8)) plt.subplot(121) plt.title("pomegranate naive Bayes", fontsize=16) plt.scatter(X[y == 0, 0], X[y == 0, 1], color='c') plt.scatter(X[y == 1, 0], X[y == 1, 1], color='m') plt.contour(xx, yy, Z1) plt.xlim(-2, 10) plt.ylim(-4, 12) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.subplot(122) plt.title("sklearn naive Bayes", fontsize=16) plt.scatter(X[y == 0, 0], X[y == 0, 1], color='c') plt.scatter(X[y == 1, 0], X[y == 1, 1], color='m') plt.contour(xx, yy, Z2) plt.xlim(-2, 10) plt.ylim(-4, 12) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.show() ``` Drawing the decision boundary helps to verify that we've produced a good result by cleanly splitting the two blobs from each other. Bayes' rule provides a great deal of flexibility in terms of what the actually likelihood functions are. For example, when considering a multivariate distribution, there is no need for each dimension to be modeled by the same distribution. In fact, each dimension can be modeled by a different distribution, as long as we can multiply the $P(D|M)$ terms together. Let's consider the example of some noisy signals that have been segmented. We know that they come from two underlying phenomena, the cyan phenomena and the magenta phenomena, and want to classify future segments. To do this, we have three features-- the mean signal of the segment, the standard deviation, and the duration. ``` def plot_signal(X, n): plt.figure(figsize=(16, 6)) t_current = 0 for i in range(n): mu, std, t = X[i] chunk = numpy.random.normal(mu, std, int(t)) plt.plot(numpy.arange(t_current, t_current+t), chunk, c='cm'[i % 2]) t_current += t plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.xlabel("Time (s)", fontsize=14) plt.ylabel("Signal", fontsize=14) plt.ylim(20, 40) plt.show() def create_signal(n): X, y = [], [] for i in range(n): mu = numpy.random.normal(30.0, 0.4) std = numpy.random.lognormal(-0.1, 0.4) t = int(numpy.random.exponential(50)) + 1 X.append([mu, std, int(t)]) y.append(0) mu = numpy.random.normal(30.5, 0.8) std = numpy.random.lognormal(-0.3, 0.6) t = int(numpy.random.exponential(200)) + 1 X.append([mu, std, int(t)]) y.append(1) return numpy.array(X), numpy.array(y) X_train, y_train = create_signal(1000) X_test, y_test = create_signal(250) plot_signal(X_train, 20) ``` We can start by modeling each variable as Gaussians, like before, and see what accuracy we get. ``` model = NaiveBayes.from_samples(NormalDistribution, X_train, y_train) print "Gaussian Naive Bayes: ", (model.predict(X_test) == y_test).mean() clf = GaussianNB().fit(X_train, y_train) print "sklearn Gaussian Naive Bayes: ", (clf.predict(X_test) == y_test).mean() ``` We get identical values for sklearn and for pomegranate, which is good. However, let's take a look at the data itself to see whether a Gaussian distribution is the appropriate distribution for the data. ``` plt.figure(figsize=(14, 4)) plt.subplot(131) plt.title("Mean") plt.hist(X_train[y_train == 0, 0], color='c', alpha=0.5, bins=25) plt.hist(X_train[y_train == 1, 0], color='m', alpha=0.5, bins=25) plt.subplot(132) plt.title("Standard Deviation") plt.hist(X_train[y_train == 0, 1], color='c', alpha=0.5, bins=25) plt.hist(X_train[y_train == 1, 1], color='m', alpha=0.5, bins=25) plt.subplot(133) plt.title("Duration") plt.hist(X_train[y_train == 0, 2], color='c', alpha=0.5, bins=25) plt.hist(X_train[y_train == 1, 2], color='m', alpha=0.5, bins=25) plt.show() ``` So, unsurprisingly (since you can see that I used non-Gaussian distributions to generate the data originally), it looks like only the mean follows a normal distribution, whereas the standard deviation seems to follow either a gamma or a log-normal distribution. We can take advantage of that by explicitly using these distributions instead of approximating them as normal distributions. pomegranate is flexible enough to allow for this, whereas sklearn currently is not. ``` model = NaiveBayes.from_samples(NormalDistribution, X_train, y_train) print "Gaussian Naive Bayes: ", (model.predict(X_test) == y_test).mean() clf = GaussianNB().fit(X_train, y_train) print "sklearn Gaussian Naive Bayes: ", (clf.predict(X_test) == y_test).mean() model = NaiveBayes.from_samples([NormalDistribution, LogNormalDistribution, ExponentialDistribution], X_train, y_train) print "Heterogeneous Naive Bayes: ", (model.predict(X_test) == y_test).mean() ``` It looks like we're able to get a small improvement in accuracy just by using appropriate distributions for the features, without any type of data transformation or filtering. This certainly seems worthwhile if you can determine what the appropriate underlying distribution is. Next, there's obviously the issue of speed. Let's compare the speed of the pomegranate implementation and the sklearn implementation. ``` %timeit GaussianNB().fit(X_train, y_train) %timeit NaiveBayes.from_samples(NormalDistribution, X_train, y_train) %timeit NaiveBayes.from_samples([NormalDistribution, LogNormalDistribution, ExponentialDistribution], X_train, y_train) ``` Looks as if on this small dataset they're all taking approximately the same time. This is pretty much expected, as the fitting step is fairly simple and both implementations use C-level numerics for the calculations. We can give a more thorough treatment of the speed comparison on larger datasets. Let's look at the average time it takes to fit a model to data of increasing dimensionality across 25 runs. ``` pom_time, skl_time = [], [] n1, n2 = 15000, 60000, for d in range(1, 101, 5): X = numpy.concatenate([numpy.random.normal(3, 2, size=(n1, d)), numpy.random.normal(7, 1, size=(n2, d))]) y = numpy.concatenate([numpy.zeros(n1), numpy.ones(n2)]) tic = time.time() for i in range(25): GaussianNB().fit(X, y) skl_time.append((time.time() - tic) / 25) tic = time.time() for i in range(25): NaiveBayes.from_samples(NormalDistribution, X, y) pom_time.append((time.time() - tic) / 25) plt.figure(figsize=(14, 6)) plt.plot(range(1, 101, 5), pom_time, color='c', label="pomegranate") plt.plot(range(1, 101, 5), skl_time, color='m', label="sklearn") plt.xticks(fontsize=14) plt.xlabel("Number of Dimensions", fontsize=14) plt.yticks(fontsize=14) plt.ylabel("Time (s)") plt.legend(fontsize=14) plt.show() ``` It appears as if the two implementations are basically the same speed. This is unsurprising given the simplicity of the calculations, and as mentioned before, the low level implementation. ## Bayes Classifiers The natural generalization of the naive Bayes classifier is to allow any multivariate function take the place of $P(D|M)$ instead of it being the product of several univariate probability distributions. One immediate difference is that now instead of creating a Gaussian model with effectively a diagonal covariance matrix, you can now create one with a full covariance matrix. Let's see an example of that at work. ``` tilt_a = [[-2, 0.5], [5, 2]] tilt_b = [[-1, 1.5], [3, 3]] X = numpy.concatenate((numpy.random.normal(4, 1, size=(250, 2)).dot(tilt_a), numpy.random.normal(3, 1, size=(800, 2)).dot(tilt_b))) y = numpy.concatenate((numpy.zeros(250), numpy.ones(800))) model_a = NaiveBayes.from_samples(NormalDistribution, X, y) model_b = BayesClassifier.from_samples(MultivariateGaussianDistribution, X, y) xx, yy = np.meshgrid(np.arange(-5, 30, 0.02), np.arange(0, 25, 0.02)) Z1 = model_a.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape) Z2 = model_b.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape) plt.figure(figsize=(18, 8)) plt.subplot(121) plt.contour(xx, yy, Z1) plt.scatter(X[y == 0, 0], X[y == 0, 1], color='c', alpha=0.3) plt.scatter(X[y == 1, 0], X[y == 1, 1], color='m', alpha=0.3) plt.xlim(-5, 30) plt.ylim(0, 25) plt.subplot(122) plt.contour(xx, yy, Z2) plt.scatter(X[y == 0, 0], X[y == 0, 1], color='c', alpha=0.3) plt.scatter(X[y == 1, 0], X[y == 1, 1], color='m', alpha=0.3) plt.xlim(-5, 30) plt.ylim(0, 25) plt.show() ``` It looks like we are able to get a better boundary between the two blobs of data. The primary for this is because the data don't form spherical clusters, like you assume when you force a diagonal covariance matrix, but are tilted ellipsoids, that can be better modeled by a full covariance matrix. We can quantify this quickly by looking at performance on the training data. ``` print "naive training accuracy: {:4.4}".format((model_a.predict(X) == y).mean()) print "bayes classifier training accuracy: {:4.4}".format((model_b.predict(X) == y).mean()) ``` Looks like there is a significant boost. Naturally you'd want to evaluate the performance of the model on separate validation data, but for the purposes of demonstrating the effect of a full covariance matrix this should be sufficient. While using a full covariance matrix is certainly more complicated than using only the diagonal, there is no reason that the $P(D|M)$ has to even be a single simple distribution versus a full probabilistic model. After all, all probabilistic models, including general mixtures, hidden Markov models, and Bayesian networks, can calculate $P(D|M)$. Let's take a look at an example of using a mixture model instead of a single gaussian distribution. ``` X = numpy.empty(shape=(0, 2)) X = numpy.concatenate((X, numpy.random.normal(4, 1, size=(200, 2)).dot([[-2, 0.5], [2, 0.5]]))) X = numpy.concatenate((X, numpy.random.normal(3, 1, size=(350, 2)).dot([[-1, 2], [1, 0.8]]))) X = numpy.concatenate((X, numpy.random.normal(7, 1, size=(700, 2)).dot([[-0.75, 0.8], [0.9, 1.5]]))) X = numpy.concatenate((X, numpy.random.normal(6, 1, size=(120, 2)).dot([[-1.5, 1.2], [0.6, 1.2]]))) y = numpy.concatenate((numpy.zeros(550), numpy.ones(820))) model_a = BayesClassifier.from_samples(MultivariateGaussianDistribution, X, y) gmm_a = GeneralMixtureModel.from_samples(MultivariateGaussianDistribution, 2, X[y == 0]) gmm_b = GeneralMixtureModel.from_samples(MultivariateGaussianDistribution, 2, X[y == 1]) model_b = BayesClassifier([gmm_a, gmm_b], weights=numpy.array([1-y.mean(), y.mean()])) xx, yy = np.meshgrid(np.arange(-10, 10, 0.02), np.arange(0, 25, 0.02)) Z1 = model_a.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape) Z2 = model_b.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape) centroids1 = numpy.array([distribution.mu for distribution in model_a.distributions]) centroids2 = numpy.concatenate([[distribution.mu for distribution in component.distributions] for component in model_b.distributions]) plt.figure(figsize=(18, 8)) plt.subplot(121) plt.contour(xx, yy, Z1) plt.scatter(X[y == 0, 0], X[y == 0, 1], color='c', alpha=0.3) plt.scatter(X[y == 1, 0], X[y == 1, 1], color='m', alpha=0.3) plt.scatter(centroids1[:,0], centroids1[:,1], color='k', s=100) plt.subplot(122) plt.contour(xx, yy, Z2) plt.scatter(X[y == 0, 0], X[y == 0, 1], color='c', alpha=0.3) plt.scatter(X[y == 1, 0], X[y == 1, 1], color='m', alpha=0.3) plt.scatter(centroids2[:,0], centroids2[:,1], color='k', s=100) plt.show() ``` Frequently in the real world you will end up with data that looks like the ones in the above plots, not neatly falling into any single simple distribution. Using a mixture here allowed us to model the various components separately and get a more sophisticated decision boundary that doesn't seem to be extremely overfit. If one wanted to use hidden Markov models to model sequences, all that needs to change is passing in `HiddenMarkovModel` objects instead of `GeneralMixtureModel` ones. Likewise, Bayesian networks are similarly supported and can be passed in just as easily. In fact, the most stacking one could reasonably do is to create a Bayes classifier that distinguishes mixtures of hidden Markov models with mixture emissions (GMM-HMM-GMMs) from each other!
github_jupyter
from pomegranate import * import seaborn %pylab inline seaborn.set_style('whitegrid') numpy.set_printoptions(suppress=True) X = numpy.concatenate((numpy.random.normal(3, 1, 200), numpy.random.normal(10, 2, 1000))) y = numpy.concatenate((numpy.zeros(200), numpy.ones(1000))) x1 = X[:200] x2 = X[200:] plt.figure(figsize=(16, 5)) plt.hist(x1, bins=25, color='m', edgecolor='m', label="Class A") plt.hist(x2, bins=25, color='c', edgecolor='c', label="Class B") plt.xlabel("Value", fontsize=14) plt.ylabel("Count", fontsize=14) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.show() d1 = NormalDistribution.from_samples(x1) d2 = NormalDistribution.from_samples(x2) idxs = numpy.arange(0, 15, 0.1) p1 = map(d1.probability, idxs) p2 = map(d2.probability, idxs) plt.figure(figsize=(16, 5)) plt.plot(idxs, p1, color='m'); plt.fill_between(idxs, 0, p1, facecolor='m', alpha=0.2) plt.plot(idxs, p2, color='c'); plt.fill_between(idxs, 0, p2, facecolor='c', alpha=0.2) plt.xlabel("Value", fontsize=14) plt.ylabel("Probability", fontsize=14) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.show() magenta_prior = 1. * len(x1) / len(X) cyan_prior = 1. * len(x2) / len(X) plt.figure(figsize=(4, 6)) plt.title("Prior Probabilities P(M)", fontsize=14) plt.bar(0, magenta_prior, facecolor='m', edgecolor='m') plt.bar(1, cyan_prior, facecolor='c', edgecolor='c') plt.xticks([0, 1], ['P(Magenta)', 'P(Cyan)'], fontsize=14) plt.yticks(fontsize=14) plt.show() d1 = NormalDistribution.from_samples(x1) d2 = NormalDistribution.from_samples(x2) idxs = numpy.arange(0, 15, 0.1) p_magenta = numpy.array(map(d1.probability, idxs)) * magenta_prior p_cyan = numpy.array(map(d2.probability, idxs)) * cyan_prior plt.figure(figsize=(16, 5)) plt.plot(idxs, p_magenta, color='m'); plt.fill_between(idxs, 0, p_magenta, facecolor='m', alpha=0.2) plt.plot(idxs, p_cyan, color='c'); plt.fill_between(idxs, 0, p_cyan, facecolor='c', alpha=0.2) plt.xlabel("Value", fontsize=14) plt.ylabel("P(M)P(D|M)", fontsize=14) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.show() magenta_posterior = p_magenta / (p_magenta + p_cyan) cyan_posterior = p_cyan / (p_magenta + p_cyan) plt.figure(figsize=(16, 5)) plt.subplot(211) plt.plot(idxs, p_magenta, color='m'); plt.fill_between(idxs, 0, p_magenta, facecolor='m', alpha=0.2) plt.plot(idxs, p_cyan, color='c'); plt.fill_between(idxs, 0, p_cyan, facecolor='c', alpha=0.2) plt.xlabel("Value", fontsize=14) plt.ylabel("P(M)P(D|M)", fontsize=14) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.subplot(212) plt.plot(idxs, magenta_posterior, color='m') plt.plot(idxs, cyan_posterior, color='c') plt.xlabel("Value", fontsize=14) plt.ylabel("P(M|D)", fontsize=14) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.show() idxs = idxs.reshape(idxs.shape[0], 1) X = X.reshape(X.shape[0], 1) model = NaiveBayes.from_samples(NormalDistribution, X, y) posteriors = model.predict_proba(idxs) plt.figure(figsize=(14, 4)) plt.plot(idxs, posteriors[:,0], color='m') plt.plot(idxs, posteriors[:,1], color='c') plt.xlabel("Value", fontsize=14) plt.ylabel("P(M|D)", fontsize=14) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.show() X = numpy.concatenate([numpy.random.normal(3, 2, size=(150, 2)), numpy.random.normal(7, 1, size=(250, 2))]) y = numpy.concatenate([numpy.zeros(150), numpy.ones(250)]) plt.figure(figsize=(8, 8)) plt.scatter(X[y == 0, 0], X[y == 0, 1], color='c') plt.scatter(X[y == 1, 0], X[y == 1, 1], color='m') plt.xlim(-2, 10) plt.ylim(-4, 12) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.show() from sklearn.naive_bayes import GaussianNB model = NaiveBayes.from_samples(NormalDistribution, X, y) clf = GaussianNB().fit(X, y) xx, yy = np.meshgrid(np.arange(-2, 10, 0.02), np.arange(-4, 12, 0.02)) Z1 = model.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape) Z2 = clf.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape) plt.figure(figsize=(16, 8)) plt.subplot(121) plt.title("pomegranate naive Bayes", fontsize=16) plt.scatter(X[y == 0, 0], X[y == 0, 1], color='c') plt.scatter(X[y == 1, 0], X[y == 1, 1], color='m') plt.contour(xx, yy, Z1) plt.xlim(-2, 10) plt.ylim(-4, 12) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.subplot(122) plt.title("sklearn naive Bayes", fontsize=16) plt.scatter(X[y == 0, 0], X[y == 0, 1], color='c') plt.scatter(X[y == 1, 0], X[y == 1, 1], color='m') plt.contour(xx, yy, Z2) plt.xlim(-2, 10) plt.ylim(-4, 12) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.show() def plot_signal(X, n): plt.figure(figsize=(16, 6)) t_current = 0 for i in range(n): mu, std, t = X[i] chunk = numpy.random.normal(mu, std, int(t)) plt.plot(numpy.arange(t_current, t_current+t), chunk, c='cm'[i % 2]) t_current += t plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.xlabel("Time (s)", fontsize=14) plt.ylabel("Signal", fontsize=14) plt.ylim(20, 40) plt.show() def create_signal(n): X, y = [], [] for i in range(n): mu = numpy.random.normal(30.0, 0.4) std = numpy.random.lognormal(-0.1, 0.4) t = int(numpy.random.exponential(50)) + 1 X.append([mu, std, int(t)]) y.append(0) mu = numpy.random.normal(30.5, 0.8) std = numpy.random.lognormal(-0.3, 0.6) t = int(numpy.random.exponential(200)) + 1 X.append([mu, std, int(t)]) y.append(1) return numpy.array(X), numpy.array(y) X_train, y_train = create_signal(1000) X_test, y_test = create_signal(250) plot_signal(X_train, 20) model = NaiveBayes.from_samples(NormalDistribution, X_train, y_train) print "Gaussian Naive Bayes: ", (model.predict(X_test) == y_test).mean() clf = GaussianNB().fit(X_train, y_train) print "sklearn Gaussian Naive Bayes: ", (clf.predict(X_test) == y_test).mean() plt.figure(figsize=(14, 4)) plt.subplot(131) plt.title("Mean") plt.hist(X_train[y_train == 0, 0], color='c', alpha=0.5, bins=25) plt.hist(X_train[y_train == 1, 0], color='m', alpha=0.5, bins=25) plt.subplot(132) plt.title("Standard Deviation") plt.hist(X_train[y_train == 0, 1], color='c', alpha=0.5, bins=25) plt.hist(X_train[y_train == 1, 1], color='m', alpha=0.5, bins=25) plt.subplot(133) plt.title("Duration") plt.hist(X_train[y_train == 0, 2], color='c', alpha=0.5, bins=25) plt.hist(X_train[y_train == 1, 2], color='m', alpha=0.5, bins=25) plt.show() model = NaiveBayes.from_samples(NormalDistribution, X_train, y_train) print "Gaussian Naive Bayes: ", (model.predict(X_test) == y_test).mean() clf = GaussianNB().fit(X_train, y_train) print "sklearn Gaussian Naive Bayes: ", (clf.predict(X_test) == y_test).mean() model = NaiveBayes.from_samples([NormalDistribution, LogNormalDistribution, ExponentialDistribution], X_train, y_train) print "Heterogeneous Naive Bayes: ", (model.predict(X_test) == y_test).mean() %timeit GaussianNB().fit(X_train, y_train) %timeit NaiveBayes.from_samples(NormalDistribution, X_train, y_train) %timeit NaiveBayes.from_samples([NormalDistribution, LogNormalDistribution, ExponentialDistribution], X_train, y_train) pom_time, skl_time = [], [] n1, n2 = 15000, 60000, for d in range(1, 101, 5): X = numpy.concatenate([numpy.random.normal(3, 2, size=(n1, d)), numpy.random.normal(7, 1, size=(n2, d))]) y = numpy.concatenate([numpy.zeros(n1), numpy.ones(n2)]) tic = time.time() for i in range(25): GaussianNB().fit(X, y) skl_time.append((time.time() - tic) / 25) tic = time.time() for i in range(25): NaiveBayes.from_samples(NormalDistribution, X, y) pom_time.append((time.time() - tic) / 25) plt.figure(figsize=(14, 6)) plt.plot(range(1, 101, 5), pom_time, color='c', label="pomegranate") plt.plot(range(1, 101, 5), skl_time, color='m', label="sklearn") plt.xticks(fontsize=14) plt.xlabel("Number of Dimensions", fontsize=14) plt.yticks(fontsize=14) plt.ylabel("Time (s)") plt.legend(fontsize=14) plt.show() tilt_a = [[-2, 0.5], [5, 2]] tilt_b = [[-1, 1.5], [3, 3]] X = numpy.concatenate((numpy.random.normal(4, 1, size=(250, 2)).dot(tilt_a), numpy.random.normal(3, 1, size=(800, 2)).dot(tilt_b))) y = numpy.concatenate((numpy.zeros(250), numpy.ones(800))) model_a = NaiveBayes.from_samples(NormalDistribution, X, y) model_b = BayesClassifier.from_samples(MultivariateGaussianDistribution, X, y) xx, yy = np.meshgrid(np.arange(-5, 30, 0.02), np.arange(0, 25, 0.02)) Z1 = model_a.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape) Z2 = model_b.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape) plt.figure(figsize=(18, 8)) plt.subplot(121) plt.contour(xx, yy, Z1) plt.scatter(X[y == 0, 0], X[y == 0, 1], color='c', alpha=0.3) plt.scatter(X[y == 1, 0], X[y == 1, 1], color='m', alpha=0.3) plt.xlim(-5, 30) plt.ylim(0, 25) plt.subplot(122) plt.contour(xx, yy, Z2) plt.scatter(X[y == 0, 0], X[y == 0, 1], color='c', alpha=0.3) plt.scatter(X[y == 1, 0], X[y == 1, 1], color='m', alpha=0.3) plt.xlim(-5, 30) plt.ylim(0, 25) plt.show() print "naive training accuracy: {:4.4}".format((model_a.predict(X) == y).mean()) print "bayes classifier training accuracy: {:4.4}".format((model_b.predict(X) == y).mean()) X = numpy.empty(shape=(0, 2)) X = numpy.concatenate((X, numpy.random.normal(4, 1, size=(200, 2)).dot([[-2, 0.5], [2, 0.5]]))) X = numpy.concatenate((X, numpy.random.normal(3, 1, size=(350, 2)).dot([[-1, 2], [1, 0.8]]))) X = numpy.concatenate((X, numpy.random.normal(7, 1, size=(700, 2)).dot([[-0.75, 0.8], [0.9, 1.5]]))) X = numpy.concatenate((X, numpy.random.normal(6, 1, size=(120, 2)).dot([[-1.5, 1.2], [0.6, 1.2]]))) y = numpy.concatenate((numpy.zeros(550), numpy.ones(820))) model_a = BayesClassifier.from_samples(MultivariateGaussianDistribution, X, y) gmm_a = GeneralMixtureModel.from_samples(MultivariateGaussianDistribution, 2, X[y == 0]) gmm_b = GeneralMixtureModel.from_samples(MultivariateGaussianDistribution, 2, X[y == 1]) model_b = BayesClassifier([gmm_a, gmm_b], weights=numpy.array([1-y.mean(), y.mean()])) xx, yy = np.meshgrid(np.arange(-10, 10, 0.02), np.arange(0, 25, 0.02)) Z1 = model_a.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape) Z2 = model_b.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape) centroids1 = numpy.array([distribution.mu for distribution in model_a.distributions]) centroids2 = numpy.concatenate([[distribution.mu for distribution in component.distributions] for component in model_b.distributions]) plt.figure(figsize=(18, 8)) plt.subplot(121) plt.contour(xx, yy, Z1) plt.scatter(X[y == 0, 0], X[y == 0, 1], color='c', alpha=0.3) plt.scatter(X[y == 1, 0], X[y == 1, 1], color='m', alpha=0.3) plt.scatter(centroids1[:,0], centroids1[:,1], color='k', s=100) plt.subplot(122) plt.contour(xx, yy, Z2) plt.scatter(X[y == 0, 0], X[y == 0, 1], color='c', alpha=0.3) plt.scatter(X[y == 1, 0], X[y == 1, 1], color='m', alpha=0.3) plt.scatter(centroids2[:,0], centroids2[:,1], color='k', s=100) plt.show()
0.562417
0.957118
# Time sequence primer using Pytorch ``` import torch torch.__version__ from torch.utils import data import torch.nn as nn import numpy as np from matplotlib import pyplot as plt %matplotlib inline from torch.utils.tensorboard import SummaryWriter from IPython import embed import pandas as pd ``` ## Time varying signal ``` N = 1000 t = np.arange(N) x = np.sin(0.01*t) + 0.2 * np.random.normal(size=N) plt.plot(x) ``` $$y_t = data_t, x_t = data_{t-1}... data_{t-1-M}$$ ## Define features & labels - input is a history of points of size k: $x[0:k]$ - output is the point at time k+1 given k points: $x[k]$ ``` M = 5 i = 1 # history of 10 for signal x: x[0:10] print(i, i+M) print(x[i:i + (M)]) print(i, i+(M+1)) print(x[i:i + (M+1)]) print(i+M) print(x[i+M]) X = [] y = [] for i in range(0, N-M): X.append(x[i:(i+M)]) y.append(x[i+M]) print(X[0],y[0]) print(X[1],y[1]) tutu = torch.from_numpy(X[0]) print(tutu) print(type(tutu)) len(X) ``` ## Train / Test partition ``` test_size = int(len(ds) * 0.20) train_size = int(len(ds) * 0.8) print(test_size) print(train_size) X_train, X_test = X[0:train_size], X[train_size:] y_train, y_test = y[0:train_size], y[train_size:] ``` ## Pytorch Dataset this will allow use to use pytorch dataloader class to define batches and potentially paralellize processing per batch ``` class TimeDataset(data.Dataset): 'Characterizes a dataset for PyTorch' def __init__(self, features, labels): 'Initialization' self.labels = labels self.features = features self.dtype = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.FloatTensor def __len__(self): 'Denotes the total number of samples' return len(self.features) def __getitem__(self, index): 'Generates one sample of data' # Load data and get label X = torch.from_numpy(self.features[index]) # expecting numpy array not float y = torch.from_numpy(np.array(self.labels[index])) sample = {'X': X, 'y':y } return sample ds = TimeDataset(X,y) print(ds[0]) train_ds = TimeDataset(X_train, y_train) test_ds = TimeDataset(X_test, y_test) print(test_ds[0]) ``` ## Pytorch DataLoader ``` params_train = {'batch_size': 64, 'shuffle': False, 'num_workers': 1 } params_test = {'batch_size': 64, 'shuffle': False, 'num_workers': 1 } train_dl = data.DataLoader(train_ds, **params_train) test_dl = data.DataLoader(test_ds, **params_test) type(test_dl) for i, batch in enumerate(test_dl): print(batch['y']) ``` ## Model ``` print(test_dl.dataset.features[0]) print(params) params['batch_size'] n_in = len(test_dl.dataset.features[0]) n_out = 1 n_h = 10 def weights_init(m): if isinstance(m, nn.Linear): nn.init.xavier_normal_(m.weight.data) m.bias.data.zero_() #nn.init.xavier_normal(m.bias) # nn.init.xavier_normal_(m.weight.data) # nn.init.normal_(m.bias.data) class VanillaMLP(nn.Module): def __init__(self, n_in, n_h, n_out): super(VanillaMLP, self).__init__() self.layers = nn.Sequential( nn.Linear(n_in, n_h), nn.ReLU(), nn.Linear(n_h,n_out) ) def forward(self, x): pred = self.layers(x) return pred model = VanillaMLP(n_in, n_h, n_out).float() #model.apply(weights_init) print(model) #optimizer = torch.optim.Adam(model.parameters(), lr=0.01) optimizer = torch.optim.SGD(model.parameters(), lr=0.01) loss_fn = nn.MSELoss() ``` ## Training ``` writer = SummaryWriter() epochs = 100 mean_train_losses = [] mean_valid_losses = [] valid_acc_list = [] for epoch in range(epochs): model.train() train_losses = [] valid_losses = [] for i, batch in enumerate(train_dl): optimizer.zero_grad() # embed() y_hat = model(batch['X'].float()) loss = loss_fn(y_hat, batch['y'].float()) writer.add_scalar('loss/train',loss, epoch) loss.backward() optimizer.step() train_losses.append(loss.item()) model.eval() correct = 0 total = 0 with torch.no_grad(): for i, batch in enumerate(test_dl): y_hat = model(batch['X'].float()) loss = loss_fn(y_hat, batch['y'].float()) writer.add_scalar('loss/valid',loss, epoch) valid_losses.append(loss.item()) mean_train_losses.append(np.mean(train_losses)) mean_valid_losses.append(np.mean(valid_losses)) if (epoch%10 == 0): print('epoch : {}, train loss : {:.4f}, valid loss : {:.4f} '\ .format(epoch, np.mean(train_losses), np.mean(valid_losses))) writer.close() ``` ## Plot ### matplotlib ``` fig, ax1 = plt.subplots(nrows=1) #, figsize=(15, 10)) ax1.plot(mean_train_losses, label='train') ax1.plot(mean_valid_losses, label='valid') lines, labels = ax1.get_legend_handles_labels() ax1.legend(lines, labels, loc='best') ``` ### Tensorboard ``` !tensorboard --logdir runs ``` ## Predict ``` type(X) T = torch.from_numpy(np.array(X)) predictions = model(T.float()) predictions.shape fig, ax1 = plt.subplots(nrows=1) #, figsize=(15, 10)) ax1.plot(x, label='data') ax1.plot(predictions.detach().numpy(), label='predictions') lines, labels = ax1.get_legend_handles_labels() ax1.legend(lines, labels, loc='best') ``` ## Discussion The problem with this model is that after a certain time step, the predictions are based on already predicted values and the error explodes
github_jupyter
import torch torch.__version__ from torch.utils import data import torch.nn as nn import numpy as np from matplotlib import pyplot as plt %matplotlib inline from torch.utils.tensorboard import SummaryWriter from IPython import embed import pandas as pd N = 1000 t = np.arange(N) x = np.sin(0.01*t) + 0.2 * np.random.normal(size=N) plt.plot(x) M = 5 i = 1 # history of 10 for signal x: x[0:10] print(i, i+M) print(x[i:i + (M)]) print(i, i+(M+1)) print(x[i:i + (M+1)]) print(i+M) print(x[i+M]) X = [] y = [] for i in range(0, N-M): X.append(x[i:(i+M)]) y.append(x[i+M]) print(X[0],y[0]) print(X[1],y[1]) tutu = torch.from_numpy(X[0]) print(tutu) print(type(tutu)) len(X) test_size = int(len(ds) * 0.20) train_size = int(len(ds) * 0.8) print(test_size) print(train_size) X_train, X_test = X[0:train_size], X[train_size:] y_train, y_test = y[0:train_size], y[train_size:] class TimeDataset(data.Dataset): 'Characterizes a dataset for PyTorch' def __init__(self, features, labels): 'Initialization' self.labels = labels self.features = features self.dtype = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.FloatTensor def __len__(self): 'Denotes the total number of samples' return len(self.features) def __getitem__(self, index): 'Generates one sample of data' # Load data and get label X = torch.from_numpy(self.features[index]) # expecting numpy array not float y = torch.from_numpy(np.array(self.labels[index])) sample = {'X': X, 'y':y } return sample ds = TimeDataset(X,y) print(ds[0]) train_ds = TimeDataset(X_train, y_train) test_ds = TimeDataset(X_test, y_test) print(test_ds[0]) params_train = {'batch_size': 64, 'shuffle': False, 'num_workers': 1 } params_test = {'batch_size': 64, 'shuffle': False, 'num_workers': 1 } train_dl = data.DataLoader(train_ds, **params_train) test_dl = data.DataLoader(test_ds, **params_test) type(test_dl) for i, batch in enumerate(test_dl): print(batch['y']) print(test_dl.dataset.features[0]) print(params) params['batch_size'] n_in = len(test_dl.dataset.features[0]) n_out = 1 n_h = 10 def weights_init(m): if isinstance(m, nn.Linear): nn.init.xavier_normal_(m.weight.data) m.bias.data.zero_() #nn.init.xavier_normal(m.bias) # nn.init.xavier_normal_(m.weight.data) # nn.init.normal_(m.bias.data) class VanillaMLP(nn.Module): def __init__(self, n_in, n_h, n_out): super(VanillaMLP, self).__init__() self.layers = nn.Sequential( nn.Linear(n_in, n_h), nn.ReLU(), nn.Linear(n_h,n_out) ) def forward(self, x): pred = self.layers(x) return pred model = VanillaMLP(n_in, n_h, n_out).float() #model.apply(weights_init) print(model) #optimizer = torch.optim.Adam(model.parameters(), lr=0.01) optimizer = torch.optim.SGD(model.parameters(), lr=0.01) loss_fn = nn.MSELoss() writer = SummaryWriter() epochs = 100 mean_train_losses = [] mean_valid_losses = [] valid_acc_list = [] for epoch in range(epochs): model.train() train_losses = [] valid_losses = [] for i, batch in enumerate(train_dl): optimizer.zero_grad() # embed() y_hat = model(batch['X'].float()) loss = loss_fn(y_hat, batch['y'].float()) writer.add_scalar('loss/train',loss, epoch) loss.backward() optimizer.step() train_losses.append(loss.item()) model.eval() correct = 0 total = 0 with torch.no_grad(): for i, batch in enumerate(test_dl): y_hat = model(batch['X'].float()) loss = loss_fn(y_hat, batch['y'].float()) writer.add_scalar('loss/valid',loss, epoch) valid_losses.append(loss.item()) mean_train_losses.append(np.mean(train_losses)) mean_valid_losses.append(np.mean(valid_losses)) if (epoch%10 == 0): print('epoch : {}, train loss : {:.4f}, valid loss : {:.4f} '\ .format(epoch, np.mean(train_losses), np.mean(valid_losses))) writer.close() fig, ax1 = plt.subplots(nrows=1) #, figsize=(15, 10)) ax1.plot(mean_train_losses, label='train') ax1.plot(mean_valid_losses, label='valid') lines, labels = ax1.get_legend_handles_labels() ax1.legend(lines, labels, loc='best') !tensorboard --logdir runs type(X) T = torch.from_numpy(np.array(X)) predictions = model(T.float()) predictions.shape fig, ax1 = plt.subplots(nrows=1) #, figsize=(15, 10)) ax1.plot(x, label='data') ax1.plot(predictions.detach().numpy(), label='predictions') lines, labels = ax1.get_legend_handles_labels() ax1.legend(lines, labels, loc='best')
0.878705
0.943504
# 上下文无关文法分析 **分析器**根据文法产生式处理输入的句子,并建立一个或多个符合文法的组成结构。文法是一个格式良好的声明规范,它实际上只是一个字符串,而不是程序。分析器是文法的解释程序,它搜索符合文法的所有树的空间找出一棵边缘有所需句子的树。 在本节中,我们将看到两个简单的分析算法,一种自上而下的方法成为递归下降分析,一种自下而上的方法成为移进-规约分析。我们也将看到一些更复杂的算法,一种带自下而上过滤的自上而下的方法称为左角落分析,一种动态规划技术称为图表分析。 ## 递归下降分析 一种最简单的分析器将一个文法作为如何将一个高层次的目标分解成几个低层次的子目标的规范来解释。顶层的目标是找到一个 S,S -> NP VP 产生式允许分析器替换这个目标为两个子目标:找到一个 NP,然后找到一个 VP。每个这些子目标都可以再次被子目标的子目标替代,使用左侧有 NP 和 VP 的产生式。递归下降分析器在上述过程中建立分析树,带着最初的目标创建根节点 S,然后随着使用文法的产生式递归扩展不断向下延伸分析树。 ![rdparser1-6.png](resources/rdparser1-6.png) 在这个过程中,分析器往往被迫在多种可能的产生式种选择。例如:从第 3 步到第 4 步,它试图找到左侧有 N 的产生式,第一个是 N -> man,当这不起作用时就回溯,按顺序尝试其他左侧有 N 的产生式,知道它得到 N -> dog,与输入句子的下一个词相匹配。一段时间后,如第 5 步所示,它发现了一个完整的分析树,这是一个涵盖了整个句子的树,没有任何悬着的边。发现了分析树后我们可以让分析器寻找其他额外的分析树,它会再次回溯和探索选择其他产生式,以免遗漏任何一个产生分析树的情况。 NLTK 提供了一个递归下降分析器 [nltk.RecursiveDescentParser](http://www.nltk.org/_modules/nltk/parse/recursivedescent.html#RecursiveDescentParser),它可以接受一个可选的参数 trace,如果 trace 大于零,分析器将报告它解析文本的步骤: ``` import nltk grammar1 = nltk.CFG.fromstring(""" S -> NP VP VP -> V NP | V NP PP PP -> P NP V -> "saw" | "ate" | "walked" NP -> "John" | "Mary" | "Bob" | Det N | Det N PP Det -> "a" | "an" | "the" | "my" N -> "man" | "dog" | "cat" | "telescope" | "park" P -> "in" | "on" | "by" | "with" """) rd_parser = nltk.RecursiveDescentParser(grammar1) sent = 'Mary saw a dog'.split() for tree in rd_parser.parse(sent): print(tree) ``` 递归下降分析有三个主要的缺点:首先,左递归产生式,如:NP -> NP PP,会进入死循环。第二,分析器浪费了很多时间处理不符合输入句子的词和结构。第三,回溯过程中可能会丢弃分析过的成分,它们将需要在之后再次重建。 递归下降分析时一个**自上而下分析**,自上而下分析器在检查输入之前先使用文法预测输入将是什么。然而,由于输入对分析器一直是可用的,从一开始就考虑输入的句子会是更明智的做法,这种做法被称为**自下而上分析**。 ## 移进-规约分析 一种简单的自下而上分析器是移进-规约分析器。与所有自下而上的分析器一样,移进-规约分析器尝试找到对应文法产生式**右侧**的词和短语的序列,用左侧的替换它们,直到整个句子规约为一个 S。 移进-规约分析器反复将下一个输入词推到堆栈,这是**移进**操作。如果堆栈上的前 n 项匹配一些产生式右侧的 n 个项目,那么就把它们弹出栈,并把产生式左边的项目压入栈,这种替换前 n 项为一项的操作就是**规约**操作。此操作只适用于堆栈的顶部,规约栈中的项目必须在后面的项目被压入栈之前做。当所有的输入都使用过,堆栈中只剩一个项目,也就是一棵分析树作为它的根节点 S 时,分析器完成。 我们可以使用图形化示范 nltk.app.srparser() 看到移进-规约分析算法执行步骤: ![srparser1-6.png](resources/srparser1-6.png) NLTK 中提供了 [nltk.ShiftReduceParser](http://www.nltk.org/_modules/nltk/parse/shiftreduce.html#ShiftReduceParser),移进-规约分析器的一个简单实现。这个分析器不执行任何回溯,所以它不能保证一定能找到一个文本的解析,即使确实存在这样一个解析。此外,它最多只会找到一个解析,即使有多个解析存在。 ``` sr_parser = nltk.ShiftReduceParser(grammar1) sent = 'Mary saw a dog'.split() for tree in sr_parser.parse(sent): print(tree) ``` 即使输入的句子是符合语法的,移进-归于分析器也有可能会到达一个死胡同,而不能找到任何解析,问题出现的原因是较早前做出的选择不能被分析器撤销。 在分析的过程中,分析器通常面临两种选择:当有多种规约可能时选择哪个规约(规约-规约冲突);当移进和规约都可以时选择哪个动作。移进-规约分析器可以改进执行策略来解决这些冲突。例如:它可以通过只有在不能规约时才移进,解决移进-规约冲突;它可以通过优先执行从堆栈中移除更多项的规约操作,解决规约-规约冲突。 移进-规约分析器相比递归下降分析器的好处是,它们只建立与输入中的词对应的结构,而且每个结构只建立一次。例如:NP(Det(the), N(man)) 只建立和压入栈一次,不管以后 VP -> V NP PP 规约或者 NP -> NP PP 规约会不会用到。 ## 左角落分析器 递归下降分析器的问题之一是当它遇到一个左递归产生式时,会进入无限循环,这是因为它盲目应用文法产生式而不考虑实际输入的句子,可以使用左角落分析器解决这一问题。 **左角落分析器**是一个带自下而上过滤的自上而下分析器。在开始工作之前,左角落分析器预处理上下文无关文法建立一个表,其中每行包含两个单元,第一个存放非终结符(如 S、NP、VP 等),第二个存放那个非终结符可能的左角落集合。用 grammar1 的文法演示如下: | 类型 | 左角落(非终结符) | |------|--------------------| | S | NP | | NP | Det | | VP | V | | PP | P | 分析器每次考虑产生式时,它会检查下一个输入词是否与左角落表格中至少一种非终结符的类别相容。例如分析 John saw Mary 这个句子,首先是 S -> NP VP,然后在替换 NP 时,我们发现 NP 的左角落是 Det,它和 John 不相容,因此可以掠过 NP -> Det N 和 NP -> Det N PP 这两条规则,直接与 NP -> 'John' | 'Mary' | 'Bob' 进行比较。 ## 符合语法规则的子串表 上面讨论的三种简单的分析器在完整性和效率上都有限制,为了弥补这些,我们可以使用动态规划算法解决。动态规划算法可以存储计算的中间结果,并在适当的时候重用它们,能显著提高效率。这种技术应用到句法分析,我们可以存储分析任务的部分解决方案,然后在必要的时候查找它们,直到达到最终解决方案。这种分析方法叫做**图表分析**,存储中间结果的表格被称为**符合语法规则的子串表(well-formed substring table,WFST)。 我们将句子用如下的结构表示,那么 WFST[i][j] 表示的是从第 i 个节点到第 j 个节点的子串对应的结构类型。例如:shot 是从节点 1 到节点 2 的子串,且文法中有产生式 V -> 'short',因此我们将 WSFT[1][2] 设置为 V。 ![chart_positions1.png](resources/chart_positions1.png) ``` groucho_grammar = nltk.CFG.fromstring(""" S -> NP VP PP -> P NP NP -> Det N | Det N PP | 'I' VP -> V NP | VP PP Det -> 'an' | 'my' N -> 'elephant' | 'pajamas' V -> 'shot' P -> 'in' """) text = ['I', 'shot', 'an', 'elephant', 'in', 'my', 'pajamas'] print(groucho_grammar.productions(rhs=text[1])) ``` 这里我们定义 init_wfst 方法来初始化 WFST 表格,定义单个单词所属的类别。其中用到了 grammar 对象的 [productions](https://www.nltk.org/_modules/nltk/grammar.html#CFG.productions) 方法来过滤符合条件的产生式,它可以接收 rhs 参数来匹配产生式右侧的第一个符号,也可以接收 lhs 参数匹配产生式左侧的符号。 ``` def init_wfst(tokens, grammar): numtokens = len(tokens) wfst = [[None for i in range(numtokens + 1)] for j in range(numtokens + 1)] for i in range(numtokens): productions = grammar.productions(rhs=tokens[i]) wfst[i][i + 1] = productions[0].lhs() return wfst def complete_wfst(wfst, tokens, grammar, trace=False): index = dict((p.rhs(), p.lhs()) for p in grammar.productions()) numtokens = len(tokens) for span in range(2, numtokens + 1): for start in range(numtokens + 1 - span): end = start + span for mid in range(start + 1, end): nt1, nt2 = wfst[start][mid], wfst[mid][end] if nt1 and nt2 and (nt1, nt2) in index: wfst[start][end] = index[(nt1, nt2)] if trace: print("[%s] %3s [%s] %3s [%s] ==> [%s] %3s [%s]" % (start, nt1, mid, nt2, end, start, index[(nt1,nt2)], end)) return wfst def display(wfst, tokens): print('\nWFST ' + ' '.join(('%-4d' % i) for i in range(1, len(wfst)))) for i in range(len(wfst) - 1): print("%d " % i, end=" ") for j in range(1, len(wfst)): print("%-4s" % (wfst[i][j] or '.'), end=" ") print() tokens = "I shot an elephant in my pajamas".split() wfst0 = init_wfst(tokens, groucho_grammar) display(wfst0, tokens) ``` 应用动态规划的思想,对于单词 an 我们有 Det 位于(2,3)单元格,对于单词 elephant 我们有 N 位于(3,4)单元格,那么对于 an elephant 我们应该在(2,4)单元格中放入 NP,因为文法中有 NP -> Det N 的产生式。更一般的,我们可以在(i,j)输入 A,如果有一个产生式 A -> B C,并且我们在(i,k)中找到非终结符 B,在(k,j)中找到非终结符 C。 逐步增加 i 和 j 之间的步长,直到 i 和 j 分别代表整个字符串的开头和结尾,我们就填写完了整个 WFST 表格,具体代码可以参考 complete_wsft 方法: ``` wfst1 = complete_wfst(wfst0, tokens, groucho_grammar) display(wfst1, tokens) ``` 通过调用函数 complete_wfst() 时设置 trace 为 True,我们可以看到 WFST 创建过程中的跟踪输出: ``` wfst1 = complete_wfst(wfst0, tokens, groucho_grammar, trace=True) ``` 最终,只要我们在(0,7)单元格中可以构建 S 节点,就表明我们已经为整个输入字符串找到了一个解析,解析图如下所示: ![chart_positions2.png](resources/chart_positions2.png) WFST 有几个缺点。首先,WFST 本身不是一个分析树,所以该技术严格地说是认识到一个句子被一个文法承认,而不是分析它。其次,它要求每个非词汇文法产生式是二元的,不过我们可以将任意的 CFG 转换为这种形式。第三,作为一个自下而上的方法,它潜在的存在浪费,它会在不符合文法的地方提出成分。 最后,WFST 不能表示句子中的结构歧义,如果一个子串有多种解析方式,前面的都会被最后一种覆盖。
github_jupyter
import nltk grammar1 = nltk.CFG.fromstring(""" S -> NP VP VP -> V NP | V NP PP PP -> P NP V -> "saw" | "ate" | "walked" NP -> "John" | "Mary" | "Bob" | Det N | Det N PP Det -> "a" | "an" | "the" | "my" N -> "man" | "dog" | "cat" | "telescope" | "park" P -> "in" | "on" | "by" | "with" """) rd_parser = nltk.RecursiveDescentParser(grammar1) sent = 'Mary saw a dog'.split() for tree in rd_parser.parse(sent): print(tree) sr_parser = nltk.ShiftReduceParser(grammar1) sent = 'Mary saw a dog'.split() for tree in sr_parser.parse(sent): print(tree) groucho_grammar = nltk.CFG.fromstring(""" S -> NP VP PP -> P NP NP -> Det N | Det N PP | 'I' VP -> V NP | VP PP Det -> 'an' | 'my' N -> 'elephant' | 'pajamas' V -> 'shot' P -> 'in' """) text = ['I', 'shot', 'an', 'elephant', 'in', 'my', 'pajamas'] print(groucho_grammar.productions(rhs=text[1])) def init_wfst(tokens, grammar): numtokens = len(tokens) wfst = [[None for i in range(numtokens + 1)] for j in range(numtokens + 1)] for i in range(numtokens): productions = grammar.productions(rhs=tokens[i]) wfst[i][i + 1] = productions[0].lhs() return wfst def complete_wfst(wfst, tokens, grammar, trace=False): index = dict((p.rhs(), p.lhs()) for p in grammar.productions()) numtokens = len(tokens) for span in range(2, numtokens + 1): for start in range(numtokens + 1 - span): end = start + span for mid in range(start + 1, end): nt1, nt2 = wfst[start][mid], wfst[mid][end] if nt1 and nt2 and (nt1, nt2) in index: wfst[start][end] = index[(nt1, nt2)] if trace: print("[%s] %3s [%s] %3s [%s] ==> [%s] %3s [%s]" % (start, nt1, mid, nt2, end, start, index[(nt1,nt2)], end)) return wfst def display(wfst, tokens): print('\nWFST ' + ' '.join(('%-4d' % i) for i in range(1, len(wfst)))) for i in range(len(wfst) - 1): print("%d " % i, end=" ") for j in range(1, len(wfst)): print("%-4s" % (wfst[i][j] or '.'), end=" ") print() tokens = "I shot an elephant in my pajamas".split() wfst0 = init_wfst(tokens, groucho_grammar) display(wfst0, tokens) wfst1 = complete_wfst(wfst0, tokens, groucho_grammar) display(wfst1, tokens) wfst1 = complete_wfst(wfst0, tokens, groucho_grammar, trace=True)
0.272702
0.777596
# 批量规范化 :label:`sec_batch_norm` 训练深层神经网络是十分困难的,特别是在较短的时间内使他们收敛更加棘手。 在本节中,我们将介绍*批量规范化*(batch normalization) :cite:`Ioffe.Szegedy.2015`,这是一种流行且有效的技术,可持续加速深层网络的收敛速度。 再结合在 :numref:`sec_resnet`中将介绍的残差块,批量规范化使得研究人员能够训练100层以上的网络。 ## 训练深层网络 为什么需要批量规范化层呢?让我们来回顾一下训练神经网络时出现的一些实际挑战。 首先,数据预处理的方式通常会对最终结果产生巨大影响。 回想一下我们应用多层感知机来预测房价的例子( :numref:`sec_kaggle_house`)。 使用真实数据时,我们的第一步是标准化输入特征,使其平均值为0,方差为1。 直观地说,这种标准化可以很好地与我们的优化器配合使用,因为它可以将参数的量级进行统一。 第二,对于典型的多层感知机或卷积神经网络。当我们训练时,中间层中的变量(例如,多层感知机中的仿射变换输出)可能具有更广的变化范围:不论是沿着从输入到输出的层,跨同一层中的单元,或是随着时间的推移,模型参数的随着训练更新变幻莫测。 批量规范化的发明者非正式地假设,这些变量分布中的这种偏移可能会阻碍网络的收敛。 直观地说,我们可能会猜想,如果一个层的可变值是另一层的100倍,这可能需要对学习率进行补偿调整。 第三,更深层的网络很复杂,容易过拟合。 这意味着正则化变得更加重要。 批量规范化应用于单个可选层(也可以应用到所有层),其原理如下:在每次训练迭代中,我们首先规范化输入,即通过减去其均值并除以其标准差,其中两者均基于当前小批量处理。 接下来,我们应用比例系数和比例偏移。 正是由于这个基于*批量*统计的*标准化*,才有了*批量规范化*的名称。 请注意,如果我们尝试使用大小为1的小批量应用批量规范化,我们将无法学到任何东西。 这是因为在减去均值之后,每个隐藏单元将为0。 所以,只有使用足够大的小批量,批量规范化这种方法才是有效且稳定的。 请注意,在应用批量规范化时,批量大小的选择可能比没有批量规范化时更重要。 从形式上来说,用$\mathbf{x} \in \mathcal{B}$表示一个来自小批量$\mathcal{B}$的输入,批量规范化$\mathrm{BN}$根据以下表达式转换$\mathbf{x}$: $$\mathrm{BN}(\mathbf{x}) = \boldsymbol{\gamma} \odot \frac{\mathbf{x} - \hat{\boldsymbol{\mu}}_\mathcal{B}}{\hat{\boldsymbol{\sigma}}_\mathcal{B}} + \boldsymbol{\beta}.$$ :eqlabel:`eq_batchnorm` 在 :eqref:`eq_batchnorm`中,$\hat{\boldsymbol{\mu}}_\mathcal{B}$是小批量$\mathcal{B}$的样本均值,$\hat{\boldsymbol{\sigma}}_\mathcal{B}$是小批量$\mathcal{B}$的样本标准差。 应用标准化后,生成的小批量的平均值为0和单位方差为1。 由于单位方差(与其他一些魔法数)是一个主观的选择,因此我们通常包含 *拉伸参数*(scale)$\boldsymbol{\gamma}$和*偏移参数*(shift)$\boldsymbol{\beta}$,它们的形状与$\mathbf{x}$相同。 请注意,$\boldsymbol{\gamma}$和$\boldsymbol{\beta}$是需要与其他模型参数一起学习的参数。 由于在训练过程中,中间层的变化幅度不能过于剧烈,而批量规范化将每一层主动居中,并将它们重新调整为给定的平均值和大小(通过$\hat{\boldsymbol{\mu}}_\mathcal{B}$和${\hat{\boldsymbol{\sigma}}_\mathcal{B}}$)。 从形式上来看,我们计算出 :eqref:`eq_batchnorm`中的$\hat{\boldsymbol{\mu}}_\mathcal{B}$和${\hat{\boldsymbol{\sigma}}_\mathcal{B}}$,如下所示: $$\begin{aligned} \hat{\boldsymbol{\mu}}_\mathcal{B} &= \frac{1}{|\mathcal{B}|} \sum_{\mathbf{x} \in \mathcal{B}} \mathbf{x},\\ \hat{\boldsymbol{\sigma}}_\mathcal{B}^2 &= \frac{1}{|\mathcal{B}|} \sum_{\mathbf{x} \in \mathcal{B}} (\mathbf{x} - \hat{\boldsymbol{\mu}}_{\mathcal{B}})^2 + \epsilon.\end{aligned}$$ 请注意,我们在方差估计值中添加一个小的常量$\epsilon > 0$,以确保我们永远不会尝试除以零,即使在经验方差估计值可能消失的情况下也是如此。估计值$\hat{\boldsymbol{\mu}}_\mathcal{B}$和${\hat{\boldsymbol{\sigma}}_\mathcal{B}}$通过使用平均值和方差的噪声(noise)估计来抵消缩放问题。 你可能会认为这种噪声是一个问题,而事实上它是有益的。 事实证明,这是深度学习中一个反复出现的主题。 由于尚未在理论上明确的原因,优化中的各种噪声源通常会导致更快的训练和较少的过拟合:这种变化似乎是正则化的一种形式。 在一些初步研究中, :cite:`Teye.Azizpour.Smith.2018`和 :cite:`Luo.Wang.Shao.ea.2018`分别将批量规范化的性质与贝叶斯先验相关联。 这些理论揭示了为什么批量规范化最适应$50 \sim 100$范围中的中等批量大小的难题。 另外,批量规范化层在”训练模式“(通过小批量统计数据规范化)和“预测模式”(通过数据集统计规范化)中的功能不同。 在训练过程中,我们无法得知使用整个数据集来估计平均值和方差,所以只能根据每个小批次的平均值和方差不断训练模型。 而在预测模式下,可以根据整个数据集精确计算批量规范化所需的平均值和方差。 现在,我们了解一下批量规范化在实践中是如何工作的。 ## 批量规范化层 回想一下,批量规范化和其他层之间的一个关键区别是,由于批量规范化在完整的小批量上运行,因此我们不能像以前在引入其他层时那样忽略批量大小。 我们在下面讨论这两种情况:全连接层和卷积层,他们的批量规范化实现略有不同。 ### 全连接层 通常,我们将批量规范化层置于全连接层中的仿射变换和激活函数之间。 设全连接层的输入为u,权重参数和偏置参数分别为$\mathbf{W}$和$\mathbf{b}$,激活函数为$\phi$,批量规范化的运算符为$\mathrm{BN}$。 那么,使用批量规范化的全连接层的输出的计算详情如下: $$\mathbf{h} = \phi(\mathrm{BN}(\mathbf{W}\mathbf{x} + \mathbf{b}) ).$$ 回想一下,均值和方差是在应用变换的"相同"小批量上计算的。 ### 卷积层 同样,对于卷积层,我们可以在卷积层之后和非线性激活函数之前应用批量规范化。 当卷积有多个输出通道时,我们需要对这些通道的“每个”输出执行批量规范化,每个通道都有自己的拉伸(scale)和偏移(shift)参数,这两个参数都是标量。 假设我们的小批量包含$m$个样本,并且对于每个通道,卷积的输出具有高度$p$和宽度$q$。 那么对于卷积层,我们在每个输出通道的$m \cdot p \cdot q$个元素上同时执行每个批量规范化。 因此,在计算平均值和方差时,我们会收集所有空间位置的值,然后在给定通道内应用相同的均值和方差,以便在每个空间位置对值进行规范化。 ### 预测过程中的批量规范化 正如我们前面提到的,批量规范化在训练模式和预测模式下的行为通常不同。 首先,将训练好的模型用于预测时,我们不再需要样本均值中的噪声以及在微批次上估计每个小批次产生的样本方差了。 其次,例如,我们可能需要使用我们的模型对逐个样本进行预测。 一种常用的方法是通过移动平均估算整个训练数据集的样本均值和方差,并在预测时使用它们得到确定的输出。 可见,和暂退法一样,批量规范化层在训练模式和预测模式下的计算结果也是不一样的。 ## (**从零实现**) 下面,我们从头开始实现一个具有张量的批量规范化层。 ``` import tensorflow as tf from d2l import tensorflow as d2l def batch_norm(X, gamma, beta, moving_mean, moving_var, eps): # 计算移动方差元平方根的倒数 inv = tf.cast(tf.math.rsqrt(moving_var + eps), X.dtype) # 缩放和移位 inv *= gamma Y = X * inv + (beta - moving_mean * inv) return Y ``` 我们现在可以[**创建一个正确的`BatchNorm`层**]。 这个层将保持适当的参数:拉伸`gamma`和偏移`beta`,这两个参数将在训练过程中更新。 此外,我们的层将保存均值和方差的移动平均值,以便在模型预测期间随后使用。 撇开算法细节,注意我们实现层的基础设计模式。 通常情况下,我们用一个单独的函数定义其数学原理,比如说`batch_norm`。 然后,我们将此功能集成到一个自定义层中,其代码主要处理数据移动到训练设备(如GPU)、分配和初始化任何必需的变量、跟踪移动平均线(此处为均值和方差)等问题。 为了方便起见,我们并不担心在这里自动推断输入形状,因此我们需要指定整个特征的数量。 不用担心,深度学习框架中的批量规范化API将为我们解决上述问题,我们稍后将展示这一点。 ``` class BatchNorm(tf.keras.layers.Layer): def __init__(self, **kwargs): super(BatchNorm, self).__init__(**kwargs) def build(self, input_shape): weight_shape = [input_shape[-1], ] # 参与求梯度和迭代的拉伸和偏移参数,分别初始化成1和0 self.gamma = self.add_weight(name='gamma', shape=weight_shape, initializer=tf.initializers.ones, trainable=True) self.beta = self.add_weight(name='beta', shape=weight_shape, initializer=tf.initializers.zeros, trainable=True) # 非模型参数的变量初始化为0和1 self.moving_mean = self.add_weight(name='moving_mean', shape=weight_shape, initializer=tf.initializers.zeros, trainable=False) self.moving_variance = self.add_weight(name='moving_variance', shape=weight_shape, initializer=tf.initializers.ones, trainable=False) super(BatchNorm, self).build(input_shape) def assign_moving_average(self, variable, value): momentum = 0.9 delta = variable * momentum + value * (1 - momentum) return variable.assign(delta) @tf.function def call(self, inputs, training): if training: axes = list(range(len(inputs.shape) - 1)) batch_mean = tf.reduce_mean(inputs, axes, keepdims=True) batch_variance = tf.reduce_mean(tf.math.squared_difference( inputs, tf.stop_gradient(batch_mean)), axes, keepdims=True) batch_mean = tf.squeeze(batch_mean, axes) batch_variance = tf.squeeze(batch_variance, axes) mean_update = self.assign_moving_average( self.moving_mean, batch_mean) variance_update = self.assign_moving_average( self.moving_variance, batch_variance) self.add_update(mean_update) self.add_update(variance_update) mean, variance = batch_mean, batch_variance else: mean, variance = self.moving_mean, self.moving_variance output = batch_norm(inputs, moving_mean=mean, moving_var=variance, beta=self.beta, gamma=self.gamma, eps=1e-5) return output ``` ## 使用批量规范化层的 LeNet 为了更好理解如何[**应用`BatchNorm`**],下面我们将其应用(**于LeNet模型**)( :numref:`sec_lenet`)。 回想一下,批量规范化是在卷积层或全连接层之后、相应的激活函数之前应用的。 ``` # 回想一下,这个函数必须传递给d2l.train_ch6。 # 或者说为了利用我们现有的CPU/GPU设备,需要在strategy.scope()建立模型 def net(): return tf.keras.models.Sequential([ tf.keras.layers.Conv2D(filters=6, kernel_size=5, input_shape=(28, 28, 1)), BatchNorm(), tf.keras.layers.Activation('sigmoid'), tf.keras.layers.AvgPool2D(pool_size=2, strides=2), tf.keras.layers.Conv2D(filters=16, kernel_size=5), BatchNorm(), tf.keras.layers.Activation('sigmoid'), tf.keras.layers.AvgPool2D(pool_size=2, strides=2), tf.keras.layers.Flatten(), tf.keras.layers.Dense(120), BatchNorm(), tf.keras.layers.Activation('sigmoid'), tf.keras.layers.Dense(84), BatchNorm(), tf.keras.layers.Activation('sigmoid'), tf.keras.layers.Dense(10)] ) ``` 和以前一样,我们将[**在Fashion-MNIST数据集上训练网络**]。 这个代码与我们第一次训练LeNet( :numref:`sec_lenet`)时几乎完全相同,主要区别在于学习率大得多。 ``` lr, num_epochs, batch_size = 1.0, 10, 256 train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size) net = d2l.train_ch6(net, train_iter, test_iter, num_epochs, lr, d2l.try_gpu()) ``` 让我们来看看从第一个批量规范化层中学到的[**拉伸参数`gamma`和偏移参数`beta`**]。 ``` tf.reshape(net.layers[1].gamma, (-1,)), tf.reshape(net.layers[1].beta, (-1,)) ``` ## [**简明实现**] 除了使用我们刚刚定义的`BatchNorm`,我们也可以直接使用深度学习框架中定义的`BatchNorm`。 该代码看起来几乎与我们上面的代码相同。 ``` def net(): return tf.keras.models.Sequential([ tf.keras.layers.Conv2D(filters=6, kernel_size=5, input_shape=(28, 28, 1)), tf.keras.layers.BatchNormalization(), tf.keras.layers.Activation('sigmoid'), tf.keras.layers.AvgPool2D(pool_size=2, strides=2), tf.keras.layers.Conv2D(filters=16, kernel_size=5), tf.keras.layers.BatchNormalization(), tf.keras.layers.Activation('sigmoid'), tf.keras.layers.AvgPool2D(pool_size=2, strides=2), tf.keras.layers.Flatten(), tf.keras.layers.Dense(120), tf.keras.layers.BatchNormalization(), tf.keras.layers.Activation('sigmoid'), tf.keras.layers.Dense(84), tf.keras.layers.BatchNormalization(), tf.keras.layers.Activation('sigmoid'), tf.keras.layers.Dense(10), ]) ``` 下面,我们[**使用相同超参数来训练模型**]。 请注意,通常高级API变体运行速度快得多,因为它的代码已编译为C++或CUDA,而我们的自定义代码由Python实现。 ``` d2l.train_ch6(net, train_iter, test_iter, num_epochs, lr, d2l.try_gpu()) ``` ## 争议 直观地说,批量规范化被认为可以使优化更加平滑。 然而,我们必须小心区分直觉和对我们观察到的现象的真实解释。 回想一下,我们甚至不知道简单的神经网络(多层感知机和传统的卷积神经网络)为什么如此有效。 即使在暂退法和权重衰减的情况下,它们仍然非常灵活,因此无法通过常规的学习理论泛化保证来解释它们是否能够泛化到看不见的数据。 在提出批量规范化的论文中,作者除了介绍了其应用,还解释了其原理:通过减少*内部协变量偏移*(internal covariate shift)。 据推测,作者所说的“内部协变量转移”类似于上述的投机直觉,即变量值的分布在训练过程中会发生变化。 然而,这种解释有两个问题: 1、这种偏移与严格定义的*协变量偏移*(covariate shift)非常不同,所以这个名字用词不当。 2、这种解释只提供了一种不明确的直觉,但留下了一个有待后续挖掘的问题:为什么这项技术如此有效? 本书旨在传达实践者用来发展深层神经网络的直觉。 然而,重要的是将这些指导性直觉与既定的科学事实区分开来。 最终,当你掌握了这些方法,并开始撰写自己的研究论文时,你会希望清楚地区分技术和直觉。 随着批量规范化的普及,“内部协变量偏移”的解释反复出现在技术文献的辩论,特别是关于“如何展示机器学习研究”的更广泛的讨论中。 Ali Rahimi在接受2017年NeurIPS大会的“接受时间考验奖”(Test of Time Award)时发表了一篇令人难忘的演讲。他将“内部协变量转移”作为焦点,将现代深度学习的实践比作炼金术。 他对该示例进行了详细回顾 :cite:`Lipton.Steinhardt.2018`,概述了机器学习中令人不安的趋势。 此外,一些作者对批量规范化的成功提出了另一种解释:在某些方面,批量规范化的表现出与原始论文 :cite:`Santurkar.Tsipras.Ilyas.ea.2018`中声称的行为是相反的。 然而,与机器学习文献中成千上万类似模糊的说法相比,内部协变量偏移没有更值得批评。 很可能,它作为这些辩论的焦点而产生共鸣,要归功于目标受众对它的广泛认可。 批量规范化已经被证明是一种不可或缺的方法。它适用于几乎所有图像分类器,并在学术界获得了数万引用。 ## 小结 * 在模型训练过程中,批量规范化利用小批量的均值和标准差,不断调整神经网络的中间输出,使整个神经网络各层的中间输出值更加稳定。 * 批量规范化在全连接层和卷积层的使用略有不同。 * 批量规范化层和暂退层一样,在训练模式和预测模式下计算不同。 * 批量规范化有许多有益的副作用,主要是正则化。另一方面,”减少内部协变量偏移“的原始动机似乎不是一个有效的解释。 ## 练习 1. 在使用批量规范化之前,我们是否可以从全连接层或卷积层中删除偏置参数?为什么? 1. 比较LeNet在使用和不使用批量规范化情况下的学习率。 1. 绘制训练和测试准确度的提高。 1. 你的学习率有多高? 1. 我们是否需要在每个层中进行批量规范化?尝试一下? 1. 你可以通过批量规范化来替换暂退法吗?行为会如何改变? 1. 确定参数`beta`和`gamma`,并观察和分析结果。 1. 查看高级API中有关`BatchNorm`的在线文档,以查看其他批量规范化的应用。 1. 研究思路:想想你可以应用的其他“规范化”转换?你可以应用概率积分变换吗?全秩协方差估计可以么? [Discussions](https://discuss.d2l.ai/t/1875)
github_jupyter
import tensorflow as tf from d2l import tensorflow as d2l def batch_norm(X, gamma, beta, moving_mean, moving_var, eps): # 计算移动方差元平方根的倒数 inv = tf.cast(tf.math.rsqrt(moving_var + eps), X.dtype) # 缩放和移位 inv *= gamma Y = X * inv + (beta - moving_mean * inv) return Y class BatchNorm(tf.keras.layers.Layer): def __init__(self, **kwargs): super(BatchNorm, self).__init__(**kwargs) def build(self, input_shape): weight_shape = [input_shape[-1], ] # 参与求梯度和迭代的拉伸和偏移参数,分别初始化成1和0 self.gamma = self.add_weight(name='gamma', shape=weight_shape, initializer=tf.initializers.ones, trainable=True) self.beta = self.add_weight(name='beta', shape=weight_shape, initializer=tf.initializers.zeros, trainable=True) # 非模型参数的变量初始化为0和1 self.moving_mean = self.add_weight(name='moving_mean', shape=weight_shape, initializer=tf.initializers.zeros, trainable=False) self.moving_variance = self.add_weight(name='moving_variance', shape=weight_shape, initializer=tf.initializers.ones, trainable=False) super(BatchNorm, self).build(input_shape) def assign_moving_average(self, variable, value): momentum = 0.9 delta = variable * momentum + value * (1 - momentum) return variable.assign(delta) @tf.function def call(self, inputs, training): if training: axes = list(range(len(inputs.shape) - 1)) batch_mean = tf.reduce_mean(inputs, axes, keepdims=True) batch_variance = tf.reduce_mean(tf.math.squared_difference( inputs, tf.stop_gradient(batch_mean)), axes, keepdims=True) batch_mean = tf.squeeze(batch_mean, axes) batch_variance = tf.squeeze(batch_variance, axes) mean_update = self.assign_moving_average( self.moving_mean, batch_mean) variance_update = self.assign_moving_average( self.moving_variance, batch_variance) self.add_update(mean_update) self.add_update(variance_update) mean, variance = batch_mean, batch_variance else: mean, variance = self.moving_mean, self.moving_variance output = batch_norm(inputs, moving_mean=mean, moving_var=variance, beta=self.beta, gamma=self.gamma, eps=1e-5) return output # 回想一下,这个函数必须传递给d2l.train_ch6。 # 或者说为了利用我们现有的CPU/GPU设备,需要在strategy.scope()建立模型 def net(): return tf.keras.models.Sequential([ tf.keras.layers.Conv2D(filters=6, kernel_size=5, input_shape=(28, 28, 1)), BatchNorm(), tf.keras.layers.Activation('sigmoid'), tf.keras.layers.AvgPool2D(pool_size=2, strides=2), tf.keras.layers.Conv2D(filters=16, kernel_size=5), BatchNorm(), tf.keras.layers.Activation('sigmoid'), tf.keras.layers.AvgPool2D(pool_size=2, strides=2), tf.keras.layers.Flatten(), tf.keras.layers.Dense(120), BatchNorm(), tf.keras.layers.Activation('sigmoid'), tf.keras.layers.Dense(84), BatchNorm(), tf.keras.layers.Activation('sigmoid'), tf.keras.layers.Dense(10)] ) lr, num_epochs, batch_size = 1.0, 10, 256 train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size) net = d2l.train_ch6(net, train_iter, test_iter, num_epochs, lr, d2l.try_gpu()) tf.reshape(net.layers[1].gamma, (-1,)), tf.reshape(net.layers[1].beta, (-1,)) def net(): return tf.keras.models.Sequential([ tf.keras.layers.Conv2D(filters=6, kernel_size=5, input_shape=(28, 28, 1)), tf.keras.layers.BatchNormalization(), tf.keras.layers.Activation('sigmoid'), tf.keras.layers.AvgPool2D(pool_size=2, strides=2), tf.keras.layers.Conv2D(filters=16, kernel_size=5), tf.keras.layers.BatchNormalization(), tf.keras.layers.Activation('sigmoid'), tf.keras.layers.AvgPool2D(pool_size=2, strides=2), tf.keras.layers.Flatten(), tf.keras.layers.Dense(120), tf.keras.layers.BatchNormalization(), tf.keras.layers.Activation('sigmoid'), tf.keras.layers.Dense(84), tf.keras.layers.BatchNormalization(), tf.keras.layers.Activation('sigmoid'), tf.keras.layers.Dense(10), ]) d2l.train_ch6(net, train_iter, test_iter, num_epochs, lr, d2l.try_gpu())
0.754192
0.769946
# Naive Bayes model Naive Bayes is a classification technique used to build classifier using the Bayes Theorem. It assumes that predictors are different. In simple word sit assumes that the presence of a particular feature is not related in any way to the presence of another. There are 3 type sof Naive Bayes models #### Gaussian #### Multinomial #### Bernoulli We are going to build all three of them ## Dataset We are going to make us of scikit-learns inbuilt Breast Cancer Wisconsin Dataset ### Preparing the data ``` from sklearn.datasets import load_breast_cancer data = load_breast_cancer() label_names = data['target_names'] labels = data['target'] feature_names = data['feature_names'] features = data['data'] ``` We have gotten all the core components of our data which we will use Now to split the data into training sets and test sets ``` from sklearn.model_selection import train_test_split train_data, test_data, train_label, test_label = train_test_split(features, labels, test_size=0.40, random_state=40) ``` ### Trick If you want to see all the objects that can be imported from a particular module in python ``` import sklearn.naive_bayes as nb print(dir(nb)) ``` The above code goes into the naive_bayes module from the sklearn module and brings all the functions in the module ## Building Naive Bayes Models ### Gaussian Naive Bayes ``` from sklearn.naive_bayes import GaussianNB #now to initialize the model gnb = GaussianNB () model = gnb.fit(train_data, train_label) ``` #### Accuracy of Gaussian Naive Bayes ``` #now we will get our models prediction prediction = gnb.predict(test_data) print(prediction) #now we find the accuracy from sklearn.metrics import accuracy_score accuracy = accuracy_score(test_label, prediction) print(" Gaussian Accuracy:") print(accuracy) ``` ### Multinomial Naive Bayes ``` from sklearn.naive_bayes import MultinomialNB #Now to initialize the Multinomial naive_bayes model mnb = MultinomialNB() model = mnb.fit(train_data, train_label) ``` #### Accuracy of Multinomial ``` prediction = mnb.predict(test_data) print(prediction) Accuracy = accuracy_score(test_label, prediction) print("Multinomial Accuracy:") print(Accuracy) ``` ### Bernoulli Naive Bayes ``` from sklearn.naive_bayes import BernoulliNB #Now to initialize the model bnb = BernoulliNB() model = bnb.fit(train_data, train_label) ``` #### Accuracy of Bernoulli Naive Bayes ``` prediction = bnb.predict(test_data) print(prediction) Accuracy = accuracy_score(test_label, prediction) print("Bernoulli Accuracy:") print(Accuracy) ```
github_jupyter
from sklearn.datasets import load_breast_cancer data = load_breast_cancer() label_names = data['target_names'] labels = data['target'] feature_names = data['feature_names'] features = data['data'] from sklearn.model_selection import train_test_split train_data, test_data, train_label, test_label = train_test_split(features, labels, test_size=0.40, random_state=40) import sklearn.naive_bayes as nb print(dir(nb)) from sklearn.naive_bayes import GaussianNB #now to initialize the model gnb = GaussianNB () model = gnb.fit(train_data, train_label) #now we will get our models prediction prediction = gnb.predict(test_data) print(prediction) #now we find the accuracy from sklearn.metrics import accuracy_score accuracy = accuracy_score(test_label, prediction) print(" Gaussian Accuracy:") print(accuracy) from sklearn.naive_bayes import MultinomialNB #Now to initialize the Multinomial naive_bayes model mnb = MultinomialNB() model = mnb.fit(train_data, train_label) prediction = mnb.predict(test_data) print(prediction) Accuracy = accuracy_score(test_label, prediction) print("Multinomial Accuracy:") print(Accuracy) from sklearn.naive_bayes import BernoulliNB #Now to initialize the model bnb = BernoulliNB() model = bnb.fit(train_data, train_label) prediction = bnb.predict(test_data) print(prediction) Accuracy = accuracy_score(test_label, prediction) print("Bernoulli Accuracy:") print(Accuracy)
0.615435
0.992647
``` from IPython.core.display import display, HTML display(HTML("<style>.container { width:100% !important; }</style>")) import pandas as pd import numpy as np import warnings warnings.filterwarnings("ignore") ``` ### LSTMs for Human Activity Recognition Human Activity Recognition (HAR) using smartphones dataset and an LSTM RNN. Classifying the type of movement amongst six categories: 1. WALKING, 2. WALKING_UPSTAIRS, 3. WALKING_DOWNSTAIRS, 4. SITTING, 5. STANDING, 6. LAYING. Compared to the classical Machine Learning approaches, Recurrent Neural Networks (RNN) with Long Short-Term Memory cells (LSTMs) require no or almost no feature engineering at all. Remember, we needed a lot of feature engineering to be done in for our Machine Learning models to achieve the accuracy it has! (96% max). In RNN-LSTMs, raw data can be fed directly into the neural network which acts like a black box, without ay feature engineering whatsoever! Other research in this topic of activity recognition uses a huge amount of feature engineering, which are signal processing approaches combined with classical Machine Learning/Data Science techniques. The approach here is rather very simple in terms of how much was the data preprocessed. Almost none. All we need to take care is how we design our Deep Learning models. We will TensorFlow and Keras Libraries to demonstrate the usage of an LSTM, a type of Artificial Neural Network that can process sequential data / time series data. ### How the data was recorded? Please watch this Youtube video link I have attached below to see how the data was recorded. <p align="center"> <a href="http://www.youtube.com/watch?feature=player_embedded&v=XOEN9W05_4A " target="_blank"><img src="http://img.youtube.com/vi/XOEN9W05_4A/0.jpg" alt="Video of the experiment" width="400" height="300" border="10" /></a> <a href="https://youtu.be/XOEN9W05_4A"><center>[Watch video]</center></a> </p> ### Details about the input data I will be using a special type of Recurrent Neural Network called LSTM on the dataset to learn (as a cellphone attached on the waist) to recognise what type of activity the user is doing. Few very important points about the dataset are as follows: 1. These sensor signals are preprocessed by applying noise filters and then sampled in fixed-width windows(sliding windows) of 2.56 seconds each with 50% overlap. ie., each window has 128 readings. 2. From Each window, a feature vector was obtianed by calculating variables from the time and frequency domain. In our dataset, each datapoint represents a window with different readings 3. The accelertion signal was saperated into Body and Gravity acceleration signals(___tBodyAcc-XYZ___ and ___tGravityAcc-XYZ___) using some low pass filter with corner frequecy of 0.3Hz. 4. After that, the body linear acceleration and angular velocity were derived in time to obtian _jerk signals_ (___tBodyAccJerk-XYZ___ and ___tBodyGyroJerk-XYZ___). 5. The magnitude of these 3-dimensional signals were calculated using the Euclidian norm. This magnitudes are represented as features with names like _tBodyAccMag_, _tGravityAccMag_, _tBodyAccJerkMag_, _tBodyGyroMag_ and _tBodyGyroJerkMag_. 6. Finally, We've got frequency domain signals from some of the available signals by applying a FFT (Fast Fourier Transform). These signals obtained were labeled with ___prefix 'f'___ just like original signals with ___prefix 't'___. These signals are labeled as ___fBodyAcc-XYZ___, ___fBodyGyroMag___ etc.,. 7. These are the signals that we got so far. + tBodyAcc-XYZ + tGravityAcc-XYZ + tBodyAccJerk-XYZ + tBodyGyro-XYZ + tBodyGyroJerk-XYZ + tBodyAccMag + tGravityAccMag + tBodyAccJerkMag + tBodyGyroMag + tBodyGyroJerkMag + fBodyAcc-XYZ + fBodyAccJerk-XYZ + fBodyGyro-XYZ + fBodyAccMag + fBodyAccJerkMag + fBodyGyroMag + fBodyGyroJerkMag ### Y_Labels(Encoded) + In the dataset, Y_labels are represented as numbers from 1 to 6 as their identifiers. - WALKING as __1__ - WALKING_UPSTAIRS as __2__ - WALKING_DOWNSTAIRS as __3__ - SITTING as __4__ - STANDING as __5__ - LAYING as __6__ ### What is an RNN? For details about what RNNs are please visit this wonderful article written by Andrej Karpathy titled "The Unreasonable Effectiveness of Recurrent Neural Networks". As explained in [this article](http://karpathy.github.io/2015/05/21/rnn-effectiveness/), an RNN takes many input vectors to process them and output other vectors. It can be roughly pictured like in the image below, imagining each rectangle has a vectorial depth and other special hidden quirks in the image below. **In our case, the "many to one" architecture is used**: we accept time series of feature vectors (one vector per time step) to convert them to a probability vector at the output for classification. Note that a "one to one" architecture would be a standard feedforward neural network. > <a href="http://karpathy.github.io/2015/05/21/rnn-effectiveness/" ><img src="http://karpathy.github.io/assets/rnn/diags.jpeg" /></a> > http://karpathy.github.io/2015/05/21/rnn-effectiveness/ ### What is an LSTM? An LSTM is an improved RNN. It is more complex, but easier to train, avoiding what is called the vanishing gradient problem. I recommend [this article](http://colah.github.io/posts/2015-08-Understanding-LSTMs/) for you to learn more on LSTMs. ### Take the class labels into a Dictionary ``` # Activities are the class labels # It is a 6 class classification ACTIVITIES = { 0: 'WALKING', 1: 'WALKING_UPSTAIRS', 2: 'WALKING_DOWNSTAIRS', 3: 'SITTING', 4: 'STANDING', 5: 'LAYING', } ``` ### Utility functions to obtain the train and test data ``` # Data directory DATADIR = 'UCI_HAR_Dataset' # Raw data signals # Signals are from Accelerometer and Gyroscope # The signals are in x,y,z directions # Sensor signals are filtered to have only body acceleration # excluding the acceleration due to gravity # Triaxial acceleration from the accelerometer is total acceleration SIGNALS = [ "body_acc_x", "body_acc_y", "body_acc_z", "body_gyro_x", "body_gyro_y", "body_gyro_z", "total_acc_x", "total_acc_y", "total_acc_z" ] # Utility function to read the data from csv file def _read_csv(filename): return pd.read_csv(filename, delim_whitespace=True, header=None) # Utility function to load the signal data def load_signals(subset): signals_data = [] for signal in SIGNALS: filename = f'{DATADIR}/{subset}/Inertial Signals/{signal}_{subset}.txt' signals_data.append(_read_csv(filename).as_matrix()) # Transpose is used to change the dimensionality of the output, # aggregating the signals by combination of sample/timestep. # Resultant shape is (7352 train/2947 test samples, 128 timesteps, 9 signals) return np.transpose(signals_data, (1, 2, 0)) def load_y(subset): """ The objective that we are trying to predict is a integer, from 1 to 6, that represents a human activity. We return a binary representation of every sample objective as a 6 bits vector using One Hot Encoding (https://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html) """ filename = f'{DATADIR}/{subset}/y_{subset}.txt' y = _read_csv(filename)[0] return pd.get_dummies(y).as_matrix() def load_data(): """ Obtain the dataset from multiple files. Returns: X_train, X_test, y_train, y_test """ X_train, X_test = load_signals('train'), load_signals('test') y_train, y_test = load_y('train'), load_y('test') return X_train, X_test, y_train, y_test ``` ### Utility functions to assess model performance ``` #Train vs Test loss import matplotlib.pyplot as plt import numpy as np from sklearn.metrics import confusion_matrix import itertools #This function is used to plot/update the train and test loss after each epoch. def plt_dynamic_loss(x, vy, ty, ax, colors=['b']): #plt.figure(figsize=(7,7)) ax.plot(x, vy, 'b', label="Validation Loss") ax.plot(x, ty, 'r', label="Train Loss") plt.legend() plt.grid() fig.canvas.draw() #Utility function to plot the confusion matrices #https://scikit-learn.org/stable/modules/generated/sklearn.metrics.confusion_matrix.html def plot_confusion_matrix(cm_df, classes, normalize, title): if normalize: cm = cm_df.values cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] plt.figure(figsize = (7,7)) plt.imshow(cm, interpolation='nearest', cmap=plt.cm.Greens) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=90) plt.yticks(tick_marks, classes) fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt),horizontalalignment="center",color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.xlabel('Predicted labels') plt.ylabel('True labels') else: import seaborn as sn plt.figure(figsize = (6,5)) ax = sn.heatmap(cm_df, annot=True, fmt='d', cmap=plt.cm.Blues) #fmt='d' for decimal integer. ax.set_xlabel("Predicted Labels") ax.set_ylabel("True Labels") ax.set_title(title) #Utility function to design the confusion matrix DF def get_confusion_matrix(Y_true, Y_pred): Y_true = pd.Series([ACTIVITIES[y] for y in np.argmax(Y_true, axis=1)]) Y_pred = pd.Series([ACTIVITIES[y] for y in np.argmax(Y_pred, axis=1)]) cm_df = pd.crosstab(Y_true, Y_pred, rownames=['True'], colnames=['Pred']) return cm_df ``` ### Start building a Deep Learning model using TensorFlow ``` # Importing tensorflow np.random.seed(42) import tensorflow as tf tf.set_random_seed(42) # Configuring a session session_conf = tf.ConfigProto(intra_op_parallelism_threads=1,inter_op_parallelism_threads=1) # Import Keras from keras import backend as K sess = tf.Session(graph=tf.get_default_graph(), config=session_conf) K.set_session(sess) # Importing libraries from keras.models import Sequential from keras.layers import LSTM from keras.layers.core import Dense, Dropout # Utility function to count the number of classes def _count_classes(y): return len(set([tuple(category) for category in y])) # Loading the train and test data X_train, X_test, y_train, y_test = load_data() y_train X_train.shape #X_train contains 7352 entries. Each data point has 9 distinct features. Each feature is represented by a 128 dimensional vector #Vector representation of a single feature X_train[0] #Number of features for one datapoint X_train[0][0] #Documentation timesteps = len(X_train[0]) input_dim = len(X_train[0][0]) n_classes = _count_classes(y_train) print(timesteps) print(input_dim) print(len(X_train)) #Read more about the correct way of data normalization: https://stats.stackexchange.com/questions/174823/how-to-apply-standardization-normalization-to-train-and-testset-if-prediction-i #Normalize the data to avoid exploding gradient problem: https://stackoverflow.com/questions/40050397/deep-learning-nan-loss-reasons ``` ### 1. Defining the Architecture of LSTM. This is our baseline model with 32 LSTM Units. ``` import warnings warnings.filterwarnings("ignore") # Initializing parameters epochs = 30 batch_size = 16 n_hidden = 32 #32 LSTM Units # Initiliazing the sequential model1 model1 = Sequential() # Configuring the parameters model1.add(LSTM(n_hidden, input_shape=(timesteps, input_dim))) # Adding a dropout layer model1.add(Dropout(0.5)) # Adding a dense output layer with sigmoid activation model1.add(Dense(n_classes, activation='sigmoid')) model1.summary() ``` ### Compiling and Training the model ``` # Compiling the model model1.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy']) # Training the model model1.fit(X_train, y_train, batch_size=batch_size, validation_data=(X_test, y_test), epochs=epochs) ``` ### Score evaluation ``` results = [] #Plot the train and test loss vs number of epochs score_test = model1.evaluate(X_test, y_test, verbose=1) score_train = model1.evaluate(X_train, y_train, verbose=1) print('\nValidation accuracy:', score_test[1]) print('Train Accuracy:', score_train[1]) print('\nValidation Loss:', score_test[0]) print('Train Loss:', score_train[0]) scores = [score_test[1], score_train[1], score_test[0], score_train[0]] results.append(scores) ``` - With a simple 2 layer architecture we got 89% accuracy and a loss of 0.37. Not bad by any means, considering the fact that we did not do any feature engineering whatsoever! - Looking at the train and test loss, we can say there might be a small overfitting. - We can further improve the performace with Hyperparameter tuning. For now let's plot the Train vs Cross Validation Loss, and also the Confusion Matrix to get an idea about individual class accuracies, precisions, recalls. ### Plot the Train and Validation loss for all epochs to get an idea if our model is overfitted/underfitted. ``` history1=model1.history #Get the history object which stores all the histories of test/train/validation loss/accuracy #Plot train vs test loss fig,ax = plt.subplots(1,1) ax.set_xlabel('Epoch') ; ax.set_ylabel('Categorical Crossentropy Loss') #List of epoch numbers x = list(range(1,epochs+1)) #Display the model val_loss = history1.history['val_loss'] #Validation Loss loss = history1.history['loss'] #Training Loss plt_dynamic_loss(x, val_loss, loss, ax) ``` ### Plot Confusion Matrices to evaluate the model. ``` #Get the confusion matrix y_pred=model1.predict(X_test) cm_df=get_confusion_matrix(y_test, y_pred) #Prepare the confusion matrix by using get_confusion_matrix() defined above. classes=list(cm_df.index) #Class names = Index Names or Column Names in cm_df #Plot a Non-Normalized confusion matrix plot_confusion_matrix(cm_df, classes, normalize=False, title="NON-NORMALIZED CONFUSION MATRIX") #Plot a Normalized confusion matrix plot_confusion_matrix(cm_df, classes, normalize=True, title="NORMALIZED CONFUSION MATRIX") ``` ## Manual Hyperparameter tuning Section. ### 2. Model with 1 LSTM Layer having 16 LSTM units ``` import warnings warnings.filterwarnings("ignore") '''Initializing parameters''' epochs = 30 batch_size = 16 n_hidden = 16 #16 LSTM Units '''Define and train the model''' model2 = Sequential() # Initiliazing the sequential model2 model2.add(LSTM(n_hidden, input_shape=(timesteps, input_dim))) # Configuring the parameters model2.add(Dropout(0.5)) # Adding a dropout layer model2.add(Dense(n_classes, activation='sigmoid')) # Adding a dense output layer with sigmoid activation model2.summary() model2.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy']) # Compiling the model model2.fit(X_train, y_train, batch_size=batch_size, validation_data=(X_test, y_test), epochs=epochs) # Training the model '''Get the history object which stores all the histories of test/train/validation loss/accuracy''' history2=model2.history '''Get the train and test loss''' score_test = model2.evaluate(X_test, y_test, verbose=1) score_train = model2.evaluate(X_train, y_train, verbose=1) print('\nValidation accuracy:', score_test[1]) print('Train Accuracy:', score_train[1]) print('\nValidation Loss:', score_test[0]) print('Train Loss:', score_train[0]) scores = [score_test[1], score_train[1], score_test[0], score_train[0]] results.append(scores) ``` By using just a single LSTM layer with 16 LSTM units, we have obtained a test loss of 0.22 and test accuracy of 85%. However, our model looks overfitted. We will try to reduce the overfitting by using aggressive dropouts. We will also use Batch Normalization. ``` '''Plot train vs test loss''' fig,ax = plt.subplots(1,1) ax.set_xlabel('Epoch') ; ax.set_ylabel('Categorical Crossentropy Loss') x = list(range(1,epochs+1)) #List of epoch numbers val_loss = history2.history['val_loss'] #Validation Loss loss = history2.history['loss'] #Training Loss plt_dynamic_loss(x, val_loss, loss, ax) #Display the model '''Plot the confusion matrix''' y_pred=model2.predict(X_test) cm_df=get_confusion_matrix(y_test, y_pred) #Prepare the confusion matrix by using get_confusion_matrix() defined above. classes=list(cm_df.index) #Class names = Index Names or Column Names in cm_df plot_confusion_matrix(cm_df, classes, normalize=False, title="NON-NORMALIZED CONFUSION MATRIX") #Plot a Non-Normalized confusion matrix plot_confusion_matrix(cm_df, classes, normalize=True, title="NORMALIZED CONFUSION MATRIX") #Plot a Normalized confusion matrix ``` ### 3. Model with 1 LSTM Layer having 64 LSTM units + Larger Dropout (0.55) ``` import warnings warnings.filterwarnings("ignore") from keras.layers.normalization import BatchNormalization '''Initializing parameters''' epochs = 30 batch_size = 16 model3 = Sequential() model3.add(LSTM(64, input_shape=(timesteps, input_dim))) model3.add(Dropout(0.55)) model3.add(Dense(n_classes, activation='sigmoid')) model3.summary() model3.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy']) model3.fit(X_train, y_train, batch_size=batch_size, validation_data=(X_test, y_test), epochs=epochs) '''Get the history object which stores all the histories of test/train/validation loss/accuracy''' history3=model3.history '''Get the train and test loss''' score_test = model3.evaluate(X_test, y_test, verbose=1) score_train = model3.evaluate(X_train, y_train, verbose=1) print('\nValidation accuracy:', score_test[1]) print('Train Accuracy:', score_train[1]) print('\nValidation Loss:', score_test[0]) print('Train Loss:', score_train[0]) scores = [score_test[1], score_train[1], score_test[0], score_train[0]] results.append(scores) ``` We have able to manage to increase the accuracy to more than 90. Not bad. We will experiment with some more options. We will try with 128 LSTM units and see where things goes. But, we will use a dropout of 0.5. Using 0.6 or 0.7 gave me a exploding gradient problem. Tried a few things like adding decay to the RMSProp optimizer, adding a very small epsilon value. None of them seems to work though. ``` '''Plot train vs test loss''' fig,ax = plt.subplots(1,1) ax.set_xlabel('Epoch') ; ax.set_ylabel('Categorical Crossentropy Loss') x = list(range(1,epochs+1)) #List of epoch numbers val_loss = history3.history['val_loss'] #Validation Loss loss = history3.history['loss'] #Training Loss plt_dynamic_loss(x, val_loss, loss, ax) #Display the model '''Plot the confusion matrix''' y_pred=model3.predict(X_test) cm_df=get_confusion_matrix(y_test, y_pred) #Prepare the confusion matrix by using get_confusion_matrix() defined above. classes=list(cm_df.index) #Class names = Index Names or Column Names in cm_df plot_confusion_matrix(cm_df, classes, normalize=False, title="NON-NORMALIZED CONFUSION MATRIX") #Plot a Non-Normalized confusion matrix plot_confusion_matrix(cm_df, classes, normalize=True, title="NORMALIZED CONFUSION MATRIX") #Plot a Normalized confusion matrix ``` ### 4. Model with 1 LSTM Layer having 128 LSTM units + Batch Normalization ``` import keras import warnings warnings.filterwarnings("ignore") '''Initializing parameters''' epochs = 30 batch_size = 16 '''Define and train the model''' model4 = Sequential() # Initiliazing the sequential model3 model4.add(LSTM(128, input_shape=(timesteps, input_dim))) # Configuring the parameters model4.add(BatchNormalization()) model4.add(Dropout(0.40)) # Adding a dropout layer model4.add(Dense(n_classes, activation='sigmoid')) # Adding a dense output layer with sigmoid activation model4.summary() optim=keras.optimizers.RMSprop(epsilon=0.00001, decay=1e-6, clipnorm =1) model4.compile(loss='categorical_crossentropy', optimizer=optim, metrics=['accuracy']) # Compiling the model model4.fit(X_train, y_train, batch_size=batch_size, validation_data=(X_test, y_test), epochs=epochs) # Training the model '''Get the history object which stores all the histories of test/train/validation loss/accuracy''' history4=model4.history '''Get the train and test loss''' score_test = model4.evaluate(X_test, y_test, verbose=1) score_train = model4.evaluate(X_train, y_train, verbose=1) print('\nValidation accuracy:', score_test[1]) print('Train Accuracy:', score_train[1]) print('\nValidation Loss:', score_test[0]) print('Train Loss:', score_train[0]) scores = [score_test[1], score_train[1], score_test[0], score_train[0]] results.append(scores) ``` We have reached an accuracy of more than 92% at the end of 30 epoch. This is good considering the fact that we did not do any feature engineering whatsoever. However, there is still a lot of overfitting. ``` '''Plot train vs test loss''' fig,ax = plt.subplots(1,1) ax.set_xlabel('Epoch') ; ax.set_ylabel('Categorical Crossentropy Loss') x = list(range(1,epochs+1)) #List of epoch numbers val_loss = history4.history['val_loss'] #Validation Loss loss = history4.history['loss'] #Training Loss plt_dynamic_loss(x, val_loss, loss, ax) #Display the model '''Plot the confusion matrix''' y_pred=model4.predict(X_test) cm_df=get_confusion_matrix(y_test, y_pred) #Prepare the confusion matrix by using get_confusion_matrix() defined above. classes=list(cm_df.index) #Class names = Index Names or Column Names in cm_df plot_confusion_matrix(cm_df, classes, normalize=False, title="NON-NORMALIZED CONFUSION MATRIX") #Plot a Non-Normalized confusion matrix plot_confusion_matrix(cm_df, classes, normalize=True, title="NORMALIZED CONFUSION MATRIX") #Plot a Normalized confusion matrix ``` ### 5. Model with 2 LSTM Layers having 32 LSTM units + Dropout (0.5) ``` import warnings warnings.filterwarnings("ignore") '''Initializing parameters''' epochs = 30 batch_size = 16 n_hidden = 32 #32 LSTM Units '''Define and train the model''' model5 = Sequential() # Initiliazing the sequential model5 model5.add(LSTM(n_hidden, return_sequences=True, input_shape=(timesteps, input_dim))) # First LSTM Layer model5.add(Dropout(0.5)) # Adding a dropout layer model5.add(LSTM(n_hidden, input_shape=(timesteps, input_dim))) # Second LSTM Layer model4.add(BatchNormalization()) # Adding batch normalization model5.add(Dropout(0.5)) # Adding a dropout layer model5.add(Dense(n_classes, activation='sigmoid')) # Adding a dense output layer with sigmoid activation model5.summary() model5.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy']) # Compiling the model model5.fit(X_train, y_train, batch_size=batch_size, validation_data=(X_test, y_test), epochs=epochs) # Training the model '''Get the history object which stores all the histories of test/train/validation loss/accuracy''' history5=model5.history '''Get the train and test loss''' score_test = model5.evaluate(X_test, y_test, verbose=1) score_train = model5.evaluate(X_train, y_train, verbose=1) print('\nValidation accuracy:', score_test[1]) print('Train Accuracy:', score_train[1]) print('\nValidation Loss:', score_test[0]) print('Train Loss:', score_train[0]) scores = [score_test[1], score_train[1], score_test[0], score_train[0]] results.append(scores) ``` Here, even though the accuracy obtained is slightly lower than that obtained from a 128 layers LSTM unit, the overfitting has reduced slightly using a two layer LSTM architecture. This is a good news. ``` '''Plot train vs test loss''' fig,ax = plt.subplots(1,1) ax.set_xlabel('Epoch') ; ax.set_ylabel('Categorical Crossentropy Loss') x = list(range(1,epochs+1)) #List of epoch numbers val_loss = history5.history['val_loss'] #Validation Loss loss = history5.history['loss'] #Training Loss plt_dynamic_loss(x, val_loss, loss, ax) #Display the model '''Plot the confusion matrix''' y_pred=model5.predict(X_test) cm_df=get_confusion_matrix(y_test, y_pred) #Prepare the confusion matrix by using get_confusion_matrix() defined above. classes=list(cm_df.index) #Class names = Index Names or Column Names in cm_df plot_confusion_matrix(cm_df, classes, normalize=False, title="NON-NORMALIZED CONFUSION MATRIX") #Plot a Non-Normalized confusion matrix plot_confusion_matrix(cm_df, classes, normalize=True, title="NORMALIZED CONFUSION MATRIX") #Plot a Normalized confusion matrix ``` ### 6. Model with 2 LSTM Layers having 64 LSTM units + Dropout (0.5) ``` import warnings warnings.filterwarnings("ignore") '''Initializing parameters''' epochs = 30 batch_size = 16 n_hidden = 64 #64 LSTM Units '''Define and train the model''' model6 = Sequential() # Initiliazing the sequential model6 model6.add(LSTM(n_hidden, return_sequences=True, input_shape=(timesteps, input_dim))) # First LSTM Layer model6.add(Dropout(0.5)) # Adding a dropout layer model6.add(LSTM(n_hidden, input_shape=(timesteps, input_dim))) # Second LSTM Layer model6.add(BatchNormalization()) # Adding batch normalization model6.add(Dropout(0.5)) # Adding a dropout layer model6.add(Dense(n_classes, activation='sigmoid')) # Adding a dense output layer with sigmoid activation model6.summary() model6.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy']) # Compiling the model model6.fit(X_train, y_train, batch_size=batch_size, validation_data=(X_test, y_test), epochs=epochs) # Training the model '''Get the history object which stores all the histories of test/train/validation loss/accuracy''' history6=model6.history '''Get the train and test loss''' score_test = model6.evaluate(X_test, y_test, verbose=1) score_train = model6.evaluate(X_train, y_train, verbose=1) print('\nValidation accuracy:', score_test[1]) print('Train Accuracy:', score_train[1]) print('\nValidation Loss:', score_test[0]) print('Train Loss:', score_train[0]) scores = [score_test[1], score_train[1], score_test[0], score_train[0]] results.append(scores) ``` Of all the models we have trained so far, this one looks like the leats overfitted model. Train accuracy of 95.9% and test accuracy of 92.84% is not bad! ``` '''Plot train vs test loss''' fig,ax = plt.subplots(1,1) ax.set_xlabel('Epoch') ; ax.set_ylabel('Categorical Crossentropy Loss') x = list(range(1,epochs+1)) #List of epoch numbers val_loss = history6.history['val_loss'] #Validation Loss loss = history6.history['loss'] #Training Loss plt_dynamic_loss(x, val_loss, loss, ax) #Display the model '''Plot the confusion matrix''' y_pred=model6.predict(X_test) cm_df=get_confusion_matrix(y_test, y_pred) #Prepare the confusion matrix by using get_confusion_matrix() defined above. classes=list(cm_df.index) #Class names = Index Names or Column Names in cm_df plot_confusion_matrix(cm_df, classes, normalize=False, title="NON-NORMALIZED CONFUSION MATRIX") #Plot a Non-Normalized confusion matrix plot_confusion_matrix(cm_df, classes, normalize=True, title="NORMALIZED CONFUSION MATRIX") #Plot a Normalized confusion matrix ``` ### 7. Model with 2 LSTM Layers having 128 LSTM units + Dropout (0.5) ``` import warnings warnings.filterwarnings("ignore") '''Initializing parameters''' epochs = 30 batch_size = 16 n_hidden = 128 #64 LSTM Units '''Define and train the model''' model7 = Sequential() # Initiliazing the sequential model7 model7.add(LSTM(n_hidden, return_sequences=True, input_shape=(timesteps, input_dim))) # First LSTM Layer model7.add(Dropout(0.3)) # Adding a dropout layer model7.add(LSTM(n_hidden, input_shape=(timesteps, input_dim))) # Second LSTM Layer model7.add(BatchNormalization()) # Adding batch normalization model7.add(Dropout(0.3)) # Adding a dropout layer model7.add(Dense(n_classes, activation='sigmoid')) # Adding a dense output layer with sigmoid activation model7.summary() model7.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy']) # Compiling the model model7.fit(X_train, y_train, batch_size=batch_size, validation_data=(X_test, y_test), epochs=epochs) # Training the model '''Get the history object which stores all the histories of test/train/validation loss/accuracy''' history7=model7.history '''Get the train and test loss''' score_test = model7.evaluate(X_test, y_test, verbose=1) score_train = model7.evaluate(X_train, y_train, verbose=1) print('\nValidation accuracy:', score_test[1]) print('Train Accuracy:', score_train[1]) print('\nValidation Loss:', score_test[0]) print('Train Loss:', score_train[0]) scores = [score_test[1], score_train[1], score_test[0], score_train[0]] #results.append(scores) ``` Here also, there is a significant amount of overfitting. ``` '''Plot train vs test loss''' fig,ax = plt.subplots(1,1) ax.set_xlabel('Epoch') ; ax.set_ylabel('Categorical Crossentropy Loss') x = list(range(1,epochs+1)) #List of epoch numbers val_loss = history7.history['val_loss'] #Validation Loss loss = history7.history['loss'] #Training Loss plt_dynamic_loss(x, val_loss, loss, ax) #Display the model '''Plot the confusion matrix''' y_pred=model6.predict(X_test) cm_df=get_confusion_matrix(y_test, y_pred) #Prepare the confusion matrix by using get_confusion_matrix() defined above. classes=list(cm_df.index) #Class names = Index Names or Column Names in cm_df plot_confusion_matrix(cm_df, classes, normalize=False, title="NON-NORMALIZED CONFUSION MATRIX") #Plot a Non-Normalized confusion matrix plot_confusion_matrix(cm_df, classes, normalize=True, title="NORMALIZED CONFUSION MATRIX") #Plot a Normalized confusion matrix """### Explanation from: https://stackoverflow.com/questions/40050397/deep-learning-nan-loss-reasons There are lots of things I have seen make a model diverge. 1. Too high of a learning rate. You can often tell if this is the case if the loss begins to increase and then diverges to infinity.I am not to familiar with the DNNClassifier but I am guessing it uses the categorical cross entropy cost function. This involves taking the log of the prediction which diverges as the prediction approaches zero. That is why people usually add a small epsilon value to the prediction to prevent this divergence. I am guessing the DNNClassifier probably does this or uses the tensorflow opp for it. Probably not the issue. 2. Other numerical stability issues can exist such as division by zero where adding the epsilon can help. Another less obvious one if the square root who's derivative can diverge if not properly simplified when dealing with finite precision numbers. Yet again I doubt this is the issue in the case of the DNNClassifier. 3. You may have an issue with the input data. Try calling assert not np.any(np.isnan(x)) on the input data to make sure you are not introducing the nan. Also make sure all of the target values are valid. Finally, make sure the data is properly normalized. You probably want to have the pixels in the range [-1, 1] and not [0, 255]. 4. The labels must be in the domain of the loss function, so if using a logarithmic-based loss function all labels must be non-negative (as noted by evan pu and the comments below). """ ``` ## Hyperparameter tuning using Hyperas. This section of code is not executed. Facing problems with hyperas. Dependency and bug issues. Don't run this. ``` """ from hyperopt import Trials, STATUS_OK, tpe from hyperas import optim from hyperas.distributions import choice, uniform from hyperopt import Trials, STATUS_OK, tpe from hyperas import optim from hyperas.distributions import choice, uniform #ImportError: cannot import name 'conditional' from 'hyperas.distributions' (/root/anaconda3/lib/python3.7/site-packages/hyperas/distributions.py) X_train, X_test, y_train, y_test = load_data() #Defining a data function which is used by Hyperas. This data function directly loads train and test data from the source def data_func(): X_train = X_train X_test = X_test y_train = y_train y_test = y_test return X_train, y_train, X_test, y_test #Defining a model function def model_func(X_train, X_test, y_train, y_test): model = Sequential() model.add(LSTM(units={{choice([32,48,64,80])}}, activation={{choice(['tanh','relu','sigmoid','softplus'])}}, kernel_regularizer=regularizers.l2(0.01),activity_regularizer=regularizers.l2(0.01)), input_shape=(timesteps, input_dim),return_sequences=True) model.add(Dropout({{uniform(0, 1)}})) # Adding a dropout layer #Adding a second LSTM Layer model.add(LSTM(units={{choice([32,48,64,80])}}, activation={{choice(['tanh','relu','sigmoid','softplus'])}}, kernel_regularizer=regularizers.l2(0.01),activity_regularizer=regularizers.l2(0.01)), input_shape=(timesteps, input_dim)) model.add(BatchNormalization()) # Adding batch normalization model.add(Dropout({{uniform(0, 1)}})) # Adding a dropout layer model.add(Dense(n_classes, activation='sigmoid')) # Adding a dense output layer with sigmoid activation # Tune the optimzers adam = keras.optimizers.Adam(lr={{choice([10**-4,10**-3, 10**-2])}}) rmsprop = keras.optimizers.RMSprop(lr={{choice([10**-4,10**-3, 10**-2, 10**-1])}}) sgd = keras.optimizers.SGD(lr={{choice([10**-4,10**-3, 10**-2])}}) choiceval = {{choice(['adam', 'sgd', 'rmsprop'])}} if choiceval == 'adam': optimizer = adam elif choiceval == 'rmsprop': optimizer = rmsprop else: optimizer = sgd model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy']) # Compiling the model model.fit(X_train, y_train, batch_size={{choice([16, 32, 64])}}, validation_data=(X_test, y_test), epochs=epochs) # Training the model #history=model.history score, accuracy = model.evaluate(X_test, y_test, verbose=0) print('Test accuracy:', acc) return {'loss': -accuracy, 'status': STATUS_OK, 'model': model} #Run the model st = dt.now() if __name__ == '__main__': best_run, best_model = optim.minimize(model=model_func,data=data_func,algo=tpe.suggest,max_evals=30,trials=Trials(),notebook_name='HAR_LSTM',verbose=2) X_train, X_test, y_train, y_test = load_data() print("Evalutation of best performing model:") print(best_model.evaluate(X_test, y_test)) print("Best performing model chosen hyper-parameters:") print(best_run) print('\nTime taken to perform Hyperparameter tuning:',dt.now()-st) """ from prettytable import PrettyTable print('Performance Table') x = PrettyTable() x.field_names =["Model","Test Accuracy","Train Accuracy", "Test Loss", "Train Loss"] x.add_row(["1 LSTM layer with 32 LSTM Units",results[0][0]*100,results[0][1]*100,results[0][2],results[0][3]]) x.add_row(["1 LSTM layer with 16 LSTM Units",results[1][0]*100,results[1][1]*100,results[1][2],results[1][3]]) x.add_row(["1 LSTM layer with 64 LSTM Units",results[2][0]*100,results[2][1]*100,results[2][2],results[2][3]]) x.add_row(["1 LSTM layer with 128 LSTM Units",results[3][0]*100,results[3][1]*100,results[3][2],results[3][3]]) x.add_row(["2 LSTM layers with 32 LSTM Units",results[4][0]*100,results[4][1]*100,results[4][2],results[4][3]]) x.add_row(["2 LSTM layers with 64 LSTM Units",results[5][0]*100,results[5][1]*100,results[5][2],results[5][3]]) x.add_row(["2 LSTM layer with 128 LSTM Units",results[6][0]*100,results[6][1]*100,results[6][2],results[6][3]]) print(x) ``` ### What we did so far: 1. This project was to determine the activity of a human and classify them into one of six classes - WALKING, WALKING_UPSTAIRS, WALKING_DOWNSTAIRS, SITTING, STANDING, LAYING. 2. The data was recorded from 30 users using Gyroscope and accelerometer sensors in a smartphone, where they have captured a '3-axial linear acceleration'(tAcc-XYZ) from accelerometer and '3-axial angular velocity' (tGyro-XYZ) from Gyroscope with several variations. 3. There were as many as 561 hand engineered features, which are built by domain experts. 4. After collecting the data, we moved on to the data cleaning stage - we checked for duplicate entries, checked for null values, checked for data imbalances. Then we moved on to EDA. 5. Simple exploratory data analysis tells us that the moving and stationery activities can be very well seperated from each other. 6. We have used TSNE in order to reduce the dimensionality of the data and visualize them in 2D. The TSNE plot looks good. There is some form of seperatability. In general, TSNE has been well able to seperate lying, walking, walking downstairs, walking upstais. The model confuses a lot between sitting and standing. Let's move on to building ML models now. 7. We will apply classical ML techniques to the hand engineered dataset with almost 561 hand made features. This gave as an unbelievable accuracy of more than 96% on unseen data. This is pretty good. By looking at all the confusion matrices, we can tell that the model performed fairly well in determining the activities, except that it confuses between sitting and standing for example. In the real world, domain-knowledge, EDA and feature-engineering matters most. In this experiment, without a doubt Logistic Regression and Support Vector Machines are clear winners! They have been pretty good in classifying all the 6 classes of data. That too with very high precision and recall values. The individual F1 scores for each of the predicted classes also has very high values. In general, the Decision Trees did not perform well. Random Forests and GBDTs did better than Decision Trees. But, both RFs and GBDTs performed poorly as compared to the Logistic Regression and SVM models. 9. Now, since we are done with ML tenchinques, let's find out if we can use the raw data to build some deep learning models with better accuracy. 10. In the deep learning part, no extra features has been hand engineered, we are building models with the raw data as the input. We have tried and experimented with the number of layers, number of LSTM units, optimizers, droput rate etc to see if we can come up with certain parameters which provides a good accuracy. 11. In the deep learning part, we have noticed that the models with 2 LSTM layers performed better than single layered LSTM architectures. Overfitting was reduced, and the accuracy on the unseen data also increases slightly. 12. So, using raw data with with deep learning architectures gace as an accuracy of 92%. This is not bad by any means, cosidering the fact that we did not do any feature engineering whatsoever. 13. The model can be further improved by doing hyperparameter tuning. However, there seems to be a bug in the hyperas official release which hasn't been fixed yet. Will try Hyperas in future and see what improvements can we make. ``` #Save results import pickle as pkl with open("results.pkl", 'wb') as file: pkl.dump(results, file) ```
github_jupyter
from IPython.core.display import display, HTML display(HTML("<style>.container { width:100% !important; }</style>")) import pandas as pd import numpy as np import warnings warnings.filterwarnings("ignore") # Activities are the class labels # It is a 6 class classification ACTIVITIES = { 0: 'WALKING', 1: 'WALKING_UPSTAIRS', 2: 'WALKING_DOWNSTAIRS', 3: 'SITTING', 4: 'STANDING', 5: 'LAYING', } # Data directory DATADIR = 'UCI_HAR_Dataset' # Raw data signals # Signals are from Accelerometer and Gyroscope # The signals are in x,y,z directions # Sensor signals are filtered to have only body acceleration # excluding the acceleration due to gravity # Triaxial acceleration from the accelerometer is total acceleration SIGNALS = [ "body_acc_x", "body_acc_y", "body_acc_z", "body_gyro_x", "body_gyro_y", "body_gyro_z", "total_acc_x", "total_acc_y", "total_acc_z" ] # Utility function to read the data from csv file def _read_csv(filename): return pd.read_csv(filename, delim_whitespace=True, header=None) # Utility function to load the signal data def load_signals(subset): signals_data = [] for signal in SIGNALS: filename = f'{DATADIR}/{subset}/Inertial Signals/{signal}_{subset}.txt' signals_data.append(_read_csv(filename).as_matrix()) # Transpose is used to change the dimensionality of the output, # aggregating the signals by combination of sample/timestep. # Resultant shape is (7352 train/2947 test samples, 128 timesteps, 9 signals) return np.transpose(signals_data, (1, 2, 0)) def load_y(subset): """ The objective that we are trying to predict is a integer, from 1 to 6, that represents a human activity. We return a binary representation of every sample objective as a 6 bits vector using One Hot Encoding (https://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html) """ filename = f'{DATADIR}/{subset}/y_{subset}.txt' y = _read_csv(filename)[0] return pd.get_dummies(y).as_matrix() def load_data(): """ Obtain the dataset from multiple files. Returns: X_train, X_test, y_train, y_test """ X_train, X_test = load_signals('train'), load_signals('test') y_train, y_test = load_y('train'), load_y('test') return X_train, X_test, y_train, y_test #Train vs Test loss import matplotlib.pyplot as plt import numpy as np from sklearn.metrics import confusion_matrix import itertools #This function is used to plot/update the train and test loss after each epoch. def plt_dynamic_loss(x, vy, ty, ax, colors=['b']): #plt.figure(figsize=(7,7)) ax.plot(x, vy, 'b', label="Validation Loss") ax.plot(x, ty, 'r', label="Train Loss") plt.legend() plt.grid() fig.canvas.draw() #Utility function to plot the confusion matrices #https://scikit-learn.org/stable/modules/generated/sklearn.metrics.confusion_matrix.html def plot_confusion_matrix(cm_df, classes, normalize, title): if normalize: cm = cm_df.values cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] plt.figure(figsize = (7,7)) plt.imshow(cm, interpolation='nearest', cmap=plt.cm.Greens) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=90) plt.yticks(tick_marks, classes) fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt),horizontalalignment="center",color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.xlabel('Predicted labels') plt.ylabel('True labels') else: import seaborn as sn plt.figure(figsize = (6,5)) ax = sn.heatmap(cm_df, annot=True, fmt='d', cmap=plt.cm.Blues) #fmt='d' for decimal integer. ax.set_xlabel("Predicted Labels") ax.set_ylabel("True Labels") ax.set_title(title) #Utility function to design the confusion matrix DF def get_confusion_matrix(Y_true, Y_pred): Y_true = pd.Series([ACTIVITIES[y] for y in np.argmax(Y_true, axis=1)]) Y_pred = pd.Series([ACTIVITIES[y] for y in np.argmax(Y_pred, axis=1)]) cm_df = pd.crosstab(Y_true, Y_pred, rownames=['True'], colnames=['Pred']) return cm_df # Importing tensorflow np.random.seed(42) import tensorflow as tf tf.set_random_seed(42) # Configuring a session session_conf = tf.ConfigProto(intra_op_parallelism_threads=1,inter_op_parallelism_threads=1) # Import Keras from keras import backend as K sess = tf.Session(graph=tf.get_default_graph(), config=session_conf) K.set_session(sess) # Importing libraries from keras.models import Sequential from keras.layers import LSTM from keras.layers.core import Dense, Dropout # Utility function to count the number of classes def _count_classes(y): return len(set([tuple(category) for category in y])) # Loading the train and test data X_train, X_test, y_train, y_test = load_data() y_train X_train.shape #X_train contains 7352 entries. Each data point has 9 distinct features. Each feature is represented by a 128 dimensional vector #Vector representation of a single feature X_train[0] #Number of features for one datapoint X_train[0][0] #Documentation timesteps = len(X_train[0]) input_dim = len(X_train[0][0]) n_classes = _count_classes(y_train) print(timesteps) print(input_dim) print(len(X_train)) #Read more about the correct way of data normalization: https://stats.stackexchange.com/questions/174823/how-to-apply-standardization-normalization-to-train-and-testset-if-prediction-i #Normalize the data to avoid exploding gradient problem: https://stackoverflow.com/questions/40050397/deep-learning-nan-loss-reasons import warnings warnings.filterwarnings("ignore") # Initializing parameters epochs = 30 batch_size = 16 n_hidden = 32 #32 LSTM Units # Initiliazing the sequential model1 model1 = Sequential() # Configuring the parameters model1.add(LSTM(n_hidden, input_shape=(timesteps, input_dim))) # Adding a dropout layer model1.add(Dropout(0.5)) # Adding a dense output layer with sigmoid activation model1.add(Dense(n_classes, activation='sigmoid')) model1.summary() # Compiling the model model1.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy']) # Training the model model1.fit(X_train, y_train, batch_size=batch_size, validation_data=(X_test, y_test), epochs=epochs) results = [] #Plot the train and test loss vs number of epochs score_test = model1.evaluate(X_test, y_test, verbose=1) score_train = model1.evaluate(X_train, y_train, verbose=1) print('\nValidation accuracy:', score_test[1]) print('Train Accuracy:', score_train[1]) print('\nValidation Loss:', score_test[0]) print('Train Loss:', score_train[0]) scores = [score_test[1], score_train[1], score_test[0], score_train[0]] results.append(scores) history1=model1.history #Get the history object which stores all the histories of test/train/validation loss/accuracy #Plot train vs test loss fig,ax = plt.subplots(1,1) ax.set_xlabel('Epoch') ; ax.set_ylabel('Categorical Crossentropy Loss') #List of epoch numbers x = list(range(1,epochs+1)) #Display the model val_loss = history1.history['val_loss'] #Validation Loss loss = history1.history['loss'] #Training Loss plt_dynamic_loss(x, val_loss, loss, ax) #Get the confusion matrix y_pred=model1.predict(X_test) cm_df=get_confusion_matrix(y_test, y_pred) #Prepare the confusion matrix by using get_confusion_matrix() defined above. classes=list(cm_df.index) #Class names = Index Names or Column Names in cm_df #Plot a Non-Normalized confusion matrix plot_confusion_matrix(cm_df, classes, normalize=False, title="NON-NORMALIZED CONFUSION MATRIX") #Plot a Normalized confusion matrix plot_confusion_matrix(cm_df, classes, normalize=True, title="NORMALIZED CONFUSION MATRIX") import warnings warnings.filterwarnings("ignore") '''Initializing parameters''' epochs = 30 batch_size = 16 n_hidden = 16 #16 LSTM Units '''Define and train the model''' model2 = Sequential() # Initiliazing the sequential model2 model2.add(LSTM(n_hidden, input_shape=(timesteps, input_dim))) # Configuring the parameters model2.add(Dropout(0.5)) # Adding a dropout layer model2.add(Dense(n_classes, activation='sigmoid')) # Adding a dense output layer with sigmoid activation model2.summary() model2.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy']) # Compiling the model model2.fit(X_train, y_train, batch_size=batch_size, validation_data=(X_test, y_test), epochs=epochs) # Training the model '''Get the history object which stores all the histories of test/train/validation loss/accuracy''' history2=model2.history '''Get the train and test loss''' score_test = model2.evaluate(X_test, y_test, verbose=1) score_train = model2.evaluate(X_train, y_train, verbose=1) print('\nValidation accuracy:', score_test[1]) print('Train Accuracy:', score_train[1]) print('\nValidation Loss:', score_test[0]) print('Train Loss:', score_train[0]) scores = [score_test[1], score_train[1], score_test[0], score_train[0]] results.append(scores) '''Plot train vs test loss''' fig,ax = plt.subplots(1,1) ax.set_xlabel('Epoch') ; ax.set_ylabel('Categorical Crossentropy Loss') x = list(range(1,epochs+1)) #List of epoch numbers val_loss = history2.history['val_loss'] #Validation Loss loss = history2.history['loss'] #Training Loss plt_dynamic_loss(x, val_loss, loss, ax) #Display the model '''Plot the confusion matrix''' y_pred=model2.predict(X_test) cm_df=get_confusion_matrix(y_test, y_pred) #Prepare the confusion matrix by using get_confusion_matrix() defined above. classes=list(cm_df.index) #Class names = Index Names or Column Names in cm_df plot_confusion_matrix(cm_df, classes, normalize=False, title="NON-NORMALIZED CONFUSION MATRIX") #Plot a Non-Normalized confusion matrix plot_confusion_matrix(cm_df, classes, normalize=True, title="NORMALIZED CONFUSION MATRIX") #Plot a Normalized confusion matrix import warnings warnings.filterwarnings("ignore") from keras.layers.normalization import BatchNormalization '''Initializing parameters''' epochs = 30 batch_size = 16 model3 = Sequential() model3.add(LSTM(64, input_shape=(timesteps, input_dim))) model3.add(Dropout(0.55)) model3.add(Dense(n_classes, activation='sigmoid')) model3.summary() model3.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy']) model3.fit(X_train, y_train, batch_size=batch_size, validation_data=(X_test, y_test), epochs=epochs) '''Get the history object which stores all the histories of test/train/validation loss/accuracy''' history3=model3.history '''Get the train and test loss''' score_test = model3.evaluate(X_test, y_test, verbose=1) score_train = model3.evaluate(X_train, y_train, verbose=1) print('\nValidation accuracy:', score_test[1]) print('Train Accuracy:', score_train[1]) print('\nValidation Loss:', score_test[0]) print('Train Loss:', score_train[0]) scores = [score_test[1], score_train[1], score_test[0], score_train[0]] results.append(scores) '''Plot train vs test loss''' fig,ax = plt.subplots(1,1) ax.set_xlabel('Epoch') ; ax.set_ylabel('Categorical Crossentropy Loss') x = list(range(1,epochs+1)) #List of epoch numbers val_loss = history3.history['val_loss'] #Validation Loss loss = history3.history['loss'] #Training Loss plt_dynamic_loss(x, val_loss, loss, ax) #Display the model '''Plot the confusion matrix''' y_pred=model3.predict(X_test) cm_df=get_confusion_matrix(y_test, y_pred) #Prepare the confusion matrix by using get_confusion_matrix() defined above. classes=list(cm_df.index) #Class names = Index Names or Column Names in cm_df plot_confusion_matrix(cm_df, classes, normalize=False, title="NON-NORMALIZED CONFUSION MATRIX") #Plot a Non-Normalized confusion matrix plot_confusion_matrix(cm_df, classes, normalize=True, title="NORMALIZED CONFUSION MATRIX") #Plot a Normalized confusion matrix import keras import warnings warnings.filterwarnings("ignore") '''Initializing parameters''' epochs = 30 batch_size = 16 '''Define and train the model''' model4 = Sequential() # Initiliazing the sequential model3 model4.add(LSTM(128, input_shape=(timesteps, input_dim))) # Configuring the parameters model4.add(BatchNormalization()) model4.add(Dropout(0.40)) # Adding a dropout layer model4.add(Dense(n_classes, activation='sigmoid')) # Adding a dense output layer with sigmoid activation model4.summary() optim=keras.optimizers.RMSprop(epsilon=0.00001, decay=1e-6, clipnorm =1) model4.compile(loss='categorical_crossentropy', optimizer=optim, metrics=['accuracy']) # Compiling the model model4.fit(X_train, y_train, batch_size=batch_size, validation_data=(X_test, y_test), epochs=epochs) # Training the model '''Get the history object which stores all the histories of test/train/validation loss/accuracy''' history4=model4.history '''Get the train and test loss''' score_test = model4.evaluate(X_test, y_test, verbose=1) score_train = model4.evaluate(X_train, y_train, verbose=1) print('\nValidation accuracy:', score_test[1]) print('Train Accuracy:', score_train[1]) print('\nValidation Loss:', score_test[0]) print('Train Loss:', score_train[0]) scores = [score_test[1], score_train[1], score_test[0], score_train[0]] results.append(scores) '''Plot train vs test loss''' fig,ax = plt.subplots(1,1) ax.set_xlabel('Epoch') ; ax.set_ylabel('Categorical Crossentropy Loss') x = list(range(1,epochs+1)) #List of epoch numbers val_loss = history4.history['val_loss'] #Validation Loss loss = history4.history['loss'] #Training Loss plt_dynamic_loss(x, val_loss, loss, ax) #Display the model '''Plot the confusion matrix''' y_pred=model4.predict(X_test) cm_df=get_confusion_matrix(y_test, y_pred) #Prepare the confusion matrix by using get_confusion_matrix() defined above. classes=list(cm_df.index) #Class names = Index Names or Column Names in cm_df plot_confusion_matrix(cm_df, classes, normalize=False, title="NON-NORMALIZED CONFUSION MATRIX") #Plot a Non-Normalized confusion matrix plot_confusion_matrix(cm_df, classes, normalize=True, title="NORMALIZED CONFUSION MATRIX") #Plot a Normalized confusion matrix import warnings warnings.filterwarnings("ignore") '''Initializing parameters''' epochs = 30 batch_size = 16 n_hidden = 32 #32 LSTM Units '''Define and train the model''' model5 = Sequential() # Initiliazing the sequential model5 model5.add(LSTM(n_hidden, return_sequences=True, input_shape=(timesteps, input_dim))) # First LSTM Layer model5.add(Dropout(0.5)) # Adding a dropout layer model5.add(LSTM(n_hidden, input_shape=(timesteps, input_dim))) # Second LSTM Layer model4.add(BatchNormalization()) # Adding batch normalization model5.add(Dropout(0.5)) # Adding a dropout layer model5.add(Dense(n_classes, activation='sigmoid')) # Adding a dense output layer with sigmoid activation model5.summary() model5.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy']) # Compiling the model model5.fit(X_train, y_train, batch_size=batch_size, validation_data=(X_test, y_test), epochs=epochs) # Training the model '''Get the history object which stores all the histories of test/train/validation loss/accuracy''' history5=model5.history '''Get the train and test loss''' score_test = model5.evaluate(X_test, y_test, verbose=1) score_train = model5.evaluate(X_train, y_train, verbose=1) print('\nValidation accuracy:', score_test[1]) print('Train Accuracy:', score_train[1]) print('\nValidation Loss:', score_test[0]) print('Train Loss:', score_train[0]) scores = [score_test[1], score_train[1], score_test[0], score_train[0]] results.append(scores) '''Plot train vs test loss''' fig,ax = plt.subplots(1,1) ax.set_xlabel('Epoch') ; ax.set_ylabel('Categorical Crossentropy Loss') x = list(range(1,epochs+1)) #List of epoch numbers val_loss = history5.history['val_loss'] #Validation Loss loss = history5.history['loss'] #Training Loss plt_dynamic_loss(x, val_loss, loss, ax) #Display the model '''Plot the confusion matrix''' y_pred=model5.predict(X_test) cm_df=get_confusion_matrix(y_test, y_pred) #Prepare the confusion matrix by using get_confusion_matrix() defined above. classes=list(cm_df.index) #Class names = Index Names or Column Names in cm_df plot_confusion_matrix(cm_df, classes, normalize=False, title="NON-NORMALIZED CONFUSION MATRIX") #Plot a Non-Normalized confusion matrix plot_confusion_matrix(cm_df, classes, normalize=True, title="NORMALIZED CONFUSION MATRIX") #Plot a Normalized confusion matrix import warnings warnings.filterwarnings("ignore") '''Initializing parameters''' epochs = 30 batch_size = 16 n_hidden = 64 #64 LSTM Units '''Define and train the model''' model6 = Sequential() # Initiliazing the sequential model6 model6.add(LSTM(n_hidden, return_sequences=True, input_shape=(timesteps, input_dim))) # First LSTM Layer model6.add(Dropout(0.5)) # Adding a dropout layer model6.add(LSTM(n_hidden, input_shape=(timesteps, input_dim))) # Second LSTM Layer model6.add(BatchNormalization()) # Adding batch normalization model6.add(Dropout(0.5)) # Adding a dropout layer model6.add(Dense(n_classes, activation='sigmoid')) # Adding a dense output layer with sigmoid activation model6.summary() model6.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy']) # Compiling the model model6.fit(X_train, y_train, batch_size=batch_size, validation_data=(X_test, y_test), epochs=epochs) # Training the model '''Get the history object which stores all the histories of test/train/validation loss/accuracy''' history6=model6.history '''Get the train and test loss''' score_test = model6.evaluate(X_test, y_test, verbose=1) score_train = model6.evaluate(X_train, y_train, verbose=1) print('\nValidation accuracy:', score_test[1]) print('Train Accuracy:', score_train[1]) print('\nValidation Loss:', score_test[0]) print('Train Loss:', score_train[0]) scores = [score_test[1], score_train[1], score_test[0], score_train[0]] results.append(scores) '''Plot train vs test loss''' fig,ax = plt.subplots(1,1) ax.set_xlabel('Epoch') ; ax.set_ylabel('Categorical Crossentropy Loss') x = list(range(1,epochs+1)) #List of epoch numbers val_loss = history6.history['val_loss'] #Validation Loss loss = history6.history['loss'] #Training Loss plt_dynamic_loss(x, val_loss, loss, ax) #Display the model '''Plot the confusion matrix''' y_pred=model6.predict(X_test) cm_df=get_confusion_matrix(y_test, y_pred) #Prepare the confusion matrix by using get_confusion_matrix() defined above. classes=list(cm_df.index) #Class names = Index Names or Column Names in cm_df plot_confusion_matrix(cm_df, classes, normalize=False, title="NON-NORMALIZED CONFUSION MATRIX") #Plot a Non-Normalized confusion matrix plot_confusion_matrix(cm_df, classes, normalize=True, title="NORMALIZED CONFUSION MATRIX") #Plot a Normalized confusion matrix import warnings warnings.filterwarnings("ignore") '''Initializing parameters''' epochs = 30 batch_size = 16 n_hidden = 128 #64 LSTM Units '''Define and train the model''' model7 = Sequential() # Initiliazing the sequential model7 model7.add(LSTM(n_hidden, return_sequences=True, input_shape=(timesteps, input_dim))) # First LSTM Layer model7.add(Dropout(0.3)) # Adding a dropout layer model7.add(LSTM(n_hidden, input_shape=(timesteps, input_dim))) # Second LSTM Layer model7.add(BatchNormalization()) # Adding batch normalization model7.add(Dropout(0.3)) # Adding a dropout layer model7.add(Dense(n_classes, activation='sigmoid')) # Adding a dense output layer with sigmoid activation model7.summary() model7.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy']) # Compiling the model model7.fit(X_train, y_train, batch_size=batch_size, validation_data=(X_test, y_test), epochs=epochs) # Training the model '''Get the history object which stores all the histories of test/train/validation loss/accuracy''' history7=model7.history '''Get the train and test loss''' score_test = model7.evaluate(X_test, y_test, verbose=1) score_train = model7.evaluate(X_train, y_train, verbose=1) print('\nValidation accuracy:', score_test[1]) print('Train Accuracy:', score_train[1]) print('\nValidation Loss:', score_test[0]) print('Train Loss:', score_train[0]) scores = [score_test[1], score_train[1], score_test[0], score_train[0]] #results.append(scores) '''Plot train vs test loss''' fig,ax = plt.subplots(1,1) ax.set_xlabel('Epoch') ; ax.set_ylabel('Categorical Crossentropy Loss') x = list(range(1,epochs+1)) #List of epoch numbers val_loss = history7.history['val_loss'] #Validation Loss loss = history7.history['loss'] #Training Loss plt_dynamic_loss(x, val_loss, loss, ax) #Display the model '''Plot the confusion matrix''' y_pred=model6.predict(X_test) cm_df=get_confusion_matrix(y_test, y_pred) #Prepare the confusion matrix by using get_confusion_matrix() defined above. classes=list(cm_df.index) #Class names = Index Names or Column Names in cm_df plot_confusion_matrix(cm_df, classes, normalize=False, title="NON-NORMALIZED CONFUSION MATRIX") #Plot a Non-Normalized confusion matrix plot_confusion_matrix(cm_df, classes, normalize=True, title="NORMALIZED CONFUSION MATRIX") #Plot a Normalized confusion matrix """### Explanation from: https://stackoverflow.com/questions/40050397/deep-learning-nan-loss-reasons There are lots of things I have seen make a model diverge. 1. Too high of a learning rate. You can often tell if this is the case if the loss begins to increase and then diverges to infinity.I am not to familiar with the DNNClassifier but I am guessing it uses the categorical cross entropy cost function. This involves taking the log of the prediction which diverges as the prediction approaches zero. That is why people usually add a small epsilon value to the prediction to prevent this divergence. I am guessing the DNNClassifier probably does this or uses the tensorflow opp for it. Probably not the issue. 2. Other numerical stability issues can exist such as division by zero where adding the epsilon can help. Another less obvious one if the square root who's derivative can diverge if not properly simplified when dealing with finite precision numbers. Yet again I doubt this is the issue in the case of the DNNClassifier. 3. You may have an issue with the input data. Try calling assert not np.any(np.isnan(x)) on the input data to make sure you are not introducing the nan. Also make sure all of the target values are valid. Finally, make sure the data is properly normalized. You probably want to have the pixels in the range [-1, 1] and not [0, 255]. 4. The labels must be in the domain of the loss function, so if using a logarithmic-based loss function all labels must be non-negative (as noted by evan pu and the comments below). """ """ from hyperopt import Trials, STATUS_OK, tpe from hyperas import optim from hyperas.distributions import choice, uniform from hyperopt import Trials, STATUS_OK, tpe from hyperas import optim from hyperas.distributions import choice, uniform #ImportError: cannot import name 'conditional' from 'hyperas.distributions' (/root/anaconda3/lib/python3.7/site-packages/hyperas/distributions.py) X_train, X_test, y_train, y_test = load_data() #Defining a data function which is used by Hyperas. This data function directly loads train and test data from the source def data_func(): X_train = X_train X_test = X_test y_train = y_train y_test = y_test return X_train, y_train, X_test, y_test #Defining a model function def model_func(X_train, X_test, y_train, y_test): model = Sequential() model.add(LSTM(units={{choice([32,48,64,80])}}, activation={{choice(['tanh','relu','sigmoid','softplus'])}}, kernel_regularizer=regularizers.l2(0.01),activity_regularizer=regularizers.l2(0.01)), input_shape=(timesteps, input_dim),return_sequences=True) model.add(Dropout({{uniform(0, 1)}})) # Adding a dropout layer #Adding a second LSTM Layer model.add(LSTM(units={{choice([32,48,64,80])}}, activation={{choice(['tanh','relu','sigmoid','softplus'])}}, kernel_regularizer=regularizers.l2(0.01),activity_regularizer=regularizers.l2(0.01)), input_shape=(timesteps, input_dim)) model.add(BatchNormalization()) # Adding batch normalization model.add(Dropout({{uniform(0, 1)}})) # Adding a dropout layer model.add(Dense(n_classes, activation='sigmoid')) # Adding a dense output layer with sigmoid activation # Tune the optimzers adam = keras.optimizers.Adam(lr={{choice([10**-4,10**-3, 10**-2])}}) rmsprop = keras.optimizers.RMSprop(lr={{choice([10**-4,10**-3, 10**-2, 10**-1])}}) sgd = keras.optimizers.SGD(lr={{choice([10**-4,10**-3, 10**-2])}}) choiceval = {{choice(['adam', 'sgd', 'rmsprop'])}} if choiceval == 'adam': optimizer = adam elif choiceval == 'rmsprop': optimizer = rmsprop else: optimizer = sgd model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy']) # Compiling the model model.fit(X_train, y_train, batch_size={{choice([16, 32, 64])}}, validation_data=(X_test, y_test), epochs=epochs) # Training the model #history=model.history score, accuracy = model.evaluate(X_test, y_test, verbose=0) print('Test accuracy:', acc) return {'loss': -accuracy, 'status': STATUS_OK, 'model': model} #Run the model st = dt.now() if __name__ == '__main__': best_run, best_model = optim.minimize(model=model_func,data=data_func,algo=tpe.suggest,max_evals=30,trials=Trials(),notebook_name='HAR_LSTM',verbose=2) X_train, X_test, y_train, y_test = load_data() print("Evalutation of best performing model:") print(best_model.evaluate(X_test, y_test)) print("Best performing model chosen hyper-parameters:") print(best_run) print('\nTime taken to perform Hyperparameter tuning:',dt.now()-st) """ from prettytable import PrettyTable print('Performance Table') x = PrettyTable() x.field_names =["Model","Test Accuracy","Train Accuracy", "Test Loss", "Train Loss"] x.add_row(["1 LSTM layer with 32 LSTM Units",results[0][0]*100,results[0][1]*100,results[0][2],results[0][3]]) x.add_row(["1 LSTM layer with 16 LSTM Units",results[1][0]*100,results[1][1]*100,results[1][2],results[1][3]]) x.add_row(["1 LSTM layer with 64 LSTM Units",results[2][0]*100,results[2][1]*100,results[2][2],results[2][3]]) x.add_row(["1 LSTM layer with 128 LSTM Units",results[3][0]*100,results[3][1]*100,results[3][2],results[3][3]]) x.add_row(["2 LSTM layers with 32 LSTM Units",results[4][0]*100,results[4][1]*100,results[4][2],results[4][3]]) x.add_row(["2 LSTM layers with 64 LSTM Units",results[5][0]*100,results[5][1]*100,results[5][2],results[5][3]]) x.add_row(["2 LSTM layer with 128 LSTM Units",results[6][0]*100,results[6][1]*100,results[6][2],results[6][3]]) print(x) #Save results import pickle as pkl with open("results.pkl", 'wb') as file: pkl.dump(results, file)
0.690142
0.921287
<h1><center>Assignment 3</center></h1> <h1><center>Data Classification</center></h1> <br><br><br><br> ## Names: ### 1. Amr Hendy (46) ### 2. Abdelrhman Yasser (37) ## Introduction to MAGIC Gamma Telescope DataSet The data are MC generated to simulate registration of high energy gamma particles in a ground-based atmospheric Cherenkov gamma telescope using the imaging technique. Cherenkov gamma telescope observes high energy gamma rays, taking advantage of the radiation emitted by charged particles produced inside the electromagnetic showers initiated by the gammas, and developing in the atmosphere. This Cherenkov radiation (of visible to UV wavelengths) leaks through the atmosphere and gets recorded in the detector, allowing reconstruction of the shower parameters. The available information consists of pulses left by the incoming Cherenkov photons on the photomultiplier tubes, arranged in a plane, the camera. Depending on the energy of the primary gamma, a total of few hundreds to some 10000 Cherenkov photons get collected, in patterns (called the shower image), allowing to discriminate statistically those caused by primary gammas (signal) from the images of hadronic showers initiated by cosmic rays in the upper atmosphere (background). Typically, the image of a shower after some pre-processing is an elongated cluster. Its long axis is oriented towards the camera center if the shower axis is parallel to the telescope's optical axis, i.e. if the telescope axis is directed towards a point source. A principal component analysis is performed in the camera plane, which results in a correlation axis and defines an ellipse. If the depositions were distributed as a bivariate Gaussian, this would be an equidensity ellipse. The characteristic parameters of this ellipse (often called Hillas parameters) are among the image parameters that can be used for discrimination. The energy depositions are typically asymmetric along the major axis, and this asymmetry can also be used in discrimination. There are, in addition, further discriminating characteristics, like the extent of the cluster in the image plane, or the total sum of depositions. The data set was generated by a Monte Carlo program, Corsika, described in D. Heck et al., CORSIKA, A Monte Carlo code to simulate extensive air showers, Forschungszentrum Karlsruhe FZKA 6019 (1998). The program was run with parameters allowing to observe events with energies down to below 50 GeV. ## Exploring Dataset We will begin by exploring MAGIC Gamma Telescope Dataset: - Total number of Instances = 19020 we will divide them into 70% (13314 samples) as training set and 30% (5706 samples) as tetsing set. - Classes are gamma (g) and hadron (h), The dataset is distributed between the two classes as following: - 12332 instances for gamma class - 6688 instances for hadron class - Now we will explore the attributes of the dataset: 1. fLength: continuous, describes the major axis of ellipse [mm] 2. fWidth: continuous, describes minor axis of ellipse [mm] 3. fSize: continuous, describes 10-log of sum of content of all pixels [in #phot] 4. fConc: continuous, describes ratio of sum of two highest pixels over fSize [ratio] 5. fConc1: continuous, describes ratio of highest pixel over fSize [ratio] 6. fAsym: continuous, describes distance from highest pixel to center, projected onto major axis [mm] 7. fM3Long: continuous, describes 3rd root of third moment along major axis [mm] 8. fM3Trans: continuous, describes 3rd root of third moment along minor axis [mm] 9. fAlpha: continuous, describes angle of major axis with vector to origin [deg] 10. fDist: continuous, describes distance from origin to center of ellipse [mm] 11. class: g and h , describes gamma (signal), hadron (background) ## Imports ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt from time import time import matplotlib.patches as mpatches ``` ## Loading dataset ``` def load_dataset(): url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/magic/magic04.data' attribute_names = ['fLength', 'fWidth', 'fSize', 'fConc', 'fConc1', 'fAsym', 'fM3Long', 'fM3Trans', 'fAlpha', 'fDist', 'class'] df = pd.read_csv(url, index_col=False, names=attribute_names) return df dataset_df = load_dataset() print("DataSet contains {} samples".format(dataset_df.shape[0])) dataset_df.head() ``` ### Dataset Summary ``` dataset_df.describe() ``` ## Exploring the Balance of class labels ``` classes_cnt = dataset_df['class'].value_counts() print(classes_cnt) ``` **Dataset is imbalanced, so we will randomly put aside the extra readings for the gamma “g” class to make both classes equal in size which balance the dataset.** ### Dataset Balancing ``` random_state = 42 random_samples = dataset_df[dataset_df['class'] == 'g'].sample(n=classes_cnt[0]-classes_cnt[1], random_state=random_state) display(random_samples) balanced_df = dataset_df.drop(random_samples.index); balanced_df['class'].value_counts() ``` ###Separating Features from Class Label ``` X = balanced_df.drop('class', axis=1) Y = balanced_df['class'] ``` ### Dataset Visualization **1) Using BoxPlots** ``` X.iloc[:,:].boxplot(grid=False, fontsize=10, rot=60, figsize=(10,20)) def plot_data(x_data, y_data, x_title, y_title, title, xticks): fig = plt.figure(figsize=(15,8)) plt.plot(x_data, y_data, 'bo') fig.suptitle(title, fontsize=16) plt.xlabel(x_title) plt.ylabel(y_title) plt.xticks(xticks) plt.show() return def plot_pretty_data(X, Y): classes_values = Y.unique() feature_names = list(X.columns) all_x = [] all_y = [] # plotting each class alone for class_val in classes_values: # making feature points x = [] y = [] for i in range(0, len(feature_names)): feature_values = list(X.loc[Y[Y == class_val].index].iloc[:, i]) y = y + feature_values x = x + [i] * len(feature_values) all_x = all_x + x all_y = all_y + y # plotting all classes together plot_data(all_x, all_y, 'Feature Number', 'Feature Value', 'All Classes', [i for i in range(0, len(feature_names))]) plot_pretty_data(X, Y) ``` We can see from the previous figures, features have different ranges so that may cause problems with some classifiers that depends on the distance between the samples. We wil discuss the scaling and normalization in the preprocessing part later. **2) Using Histograms** ``` def plot_histogram(X, Y, bins=15, rwidth=0.5): colors = ['red', 'green', 'blue', 'olive', 'yellow', 'gray', 'black', 'gold', 'skyblue', 'teal'] classes = Y.unique() for class_val in classes: data = X.loc[Y[Y == class_val].index] plt.figure(figsize=(20,10)) plt.title("Class " + class_val ) plt.xlabel("Feature Value") plt.ylabel("Value Frequency") plt.hist(np.array(data), bins=bins, color=np.array(colors), label=classes, rwidth=rwidth) plt.legend() plt.show() plot_histogram(X, Y) ``` **3) Using Correlation Matrix** ``` def visualize_coeff_matrix(mat): fig = plt.figure(figsize = (12,12)) plt.imshow(mat, cmap='Reds') plt.colorbar() plt.xticks([i for i in range(0,mat.shape[0])]) plt.yticks([i for i in range(0,mat.shape[0])]) display(X.corr()) visualize_coeff_matrix(X.corr()) ``` From the correlation Matrix we can see that the first 3 features (0,1,2) are highly dependant/correlated, also the features (3,4) are highly correlated. That will give us hints to use some methods of dimensionality reduction. we will discuss that part also in the preprocessing part. ### Class Encoder we need to convert the class labels into numerical labels to be used later in the classification algroithms. We will use SciKit learn labelencoder class to help us perform this step. ``` from sklearn.preprocessing import LabelEncoder class_encoder = LabelEncoder() Y = class_encoder.fit_transform(Y) print(Y) ``` ## Dataset Split ``` from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.3, random_state=random_state, shuffle=True) print('Training set has {} samples'.format(len(X_train))) print('Testing set has {} samples'.format(len(X_test))) ``` ## Preprocessing ### 1) Feature Projection Using PCA We already have seen from the correlation matrix, there are some highly correlated features. So we will try to reduce the dimensionality as we can with no loss in the covered variance of the data. ``` from sklearn.decomposition import PCA def plot_pca(X): features_number = X.shape[1] pca = PCA(n_components=features_number, random_state=random_state) pca.fit(X) plt.figure(figsize=(20,8)) plt.title('PCA Components variance ratio') plt.xlabel('PCA Component') plt.ylabel('Variance Ratio') plt.xticks([i for i in range(1, features_number + 1)]) plt.plot([i for i in range(1, features_number + 1)], pca.explained_variance_ratio_, color='red', marker='o', linestyle='dashed', linewidth=2, markersize=12) plt.show() plt.figure(figsize=(20,8)) plt.title('Relation Between Number of PCA Components taken and Covered Variance Ratio') plt.xlabel('Number of Taken PCA Components') plt.ylabel('Covered Variance Ratio') plt.xticks([i for i in range(1, features_number + 1)]) plt.plot([i for i in range(1, features_number + 1)], pca.explained_variance_ratio_.cumsum(), color='red', marker='o', linestyle='dashed', linewidth=2, markersize=12) plt.show() plot_pca(X_train) ``` **We will choose to reduce the dimensionality to 7 dimensions which guarantees covering all the variance in the original data.** ``` pca = PCA(7, random_state=random_state) pca.fit(X_train) X_train_reduced = pd.DataFrame(pca.transform(X_train)) print("Training set after applying PCA Dimensionality Reduction") display(X_train_reduced) pca = PCA(7, random_state=random_state) pca.fit(X_test) X_test_reduced = pd.DataFrame(pca.transform(X_test)) print("Testing set after applying PCA Dimensionality Reduction") display(X_test_reduced) ``` ### 2) Z Score Normalization We have seen from the histograms that the data is distributed to nearly normal for some features. So we will try to normalize all the featues to be more useful later in the classification algorithms. ``` from scipy.stats import zscore X_train_reduced_normalized = X_train_reduced.apply(zscore) display(X_train_reduced_normalized) X_test_reduced_normalized = X_test_reduced.apply(zscore) display(X_test_reduced_normalized) ``` ### 3) Min Max Scaler We have seen also from the boxplot that many features have different ranges, so trying to scaling all the features to the same range such as [0,1] is often useful especially in the algorithms where distance between the sample points is highly considered such as KNN, and SVM. ``` from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler(feature_range=(0,1)) X_train_scaled = pd.DataFrame(data=scaler.fit_transform(X_train), columns=X_train.columns) X_test_scaled = pd.DataFrame(data=scaler.fit_transform(X_test), columns=X_test.columns) ``` ## Classification We will use several classifiers for our classification problem and evaluate them. This function will be used to get the result of any classifier easily. ``` from sklearn.metrics import accuracy_score, fbeta_score def train_predict(learner, X_train, y_train, X_test, y_test): ''' inputs: - learner: the learning algorithm to be trained and predicted on - sample_size: the size of samples (number) to be drawn from training set - X_train: features training set - y_train: income training set - X_test: features testing set - y_test: income testing set ''' results = {} start = time() # Get start time learner.fit(X_train, y_train) end = time() # Get end time results['train_time'] = end - start start = time() # Get start time predictions_test = learner.predict(X_test) predictions_train = learner.predict(X_train[:300]) end = time() # Get end time results['pred_time'] = end - start results['acc_train'] = accuracy_score(y_train[:300], predictions_train) results['acc_test'] = accuracy_score(y_test, predictions_test) results['f_train'] = fbeta_score(y_train[:300], predictions_train, beta=0.5) results['f_test'] = fbeta_score(y_test, predictions_test, beta=0.5) print("{} trained on {} samples, and tests predicted with accuracy {} and fscore {}".format(learner.__class__.__name__, len(X_train), results['acc_test'], results['f_test'])) # Return the results return results ``` This function will be used to compare between the different classifiers results. ``` def evaluate(results, title): """ Visualization code to display results of various learners. inputs: - learners: a list of supervised learners - stats: a list of dictionaries of the statistic results from 'train_predict()' - accuracy: The score for the naive predictor - f1: The score for the naive predictor """ # Create figure fig, ax = plt.subplots(2, 3, figsize = (15,10)) # Constants bar_width = 0.3 colors = ['#A00000','#00A0A0','#00AFFD','#00AB0A','#C0A0AA', '#ADA000'] # classifier for k, learner in enumerate(results.keys()): # metric for j, metric in enumerate(['train_time', 'acc_train', 'f_train', 'pred_time', 'acc_test', 'f_test']): # Creative plot code ax[int(j/3), j%3].bar(k*bar_width, results[learner][metric], width=bar_width, color=colors[k]) ax[int(j/3), j%3].set_xticks([0.45, 1.45, 2.45]) ax[int(j/3), j%3].set_xlabel("Classiifer Algorithm") ax[int(j/3), j%3].set_xlim((-0.1, 3.0)) # Add unique y-labels ax[0, 0].set_ylabel("Time (in seconds)") ax[0, 1].set_ylabel("Accuracy Score") ax[0, 2].set_ylabel("F-score") ax[1, 0].set_ylabel("Time (in seconds)") ax[1, 1].set_ylabel("Accuracy Score") ax[1, 2].set_ylabel("F-score") # Add titles ax[0, 0].set_title("Model Training") ax[0, 1].set_title("Accuracy Score on Training Subset") ax[0, 2].set_title("F-score on Training Subset") ax[1, 0].set_title("Model Predicting") ax[1, 1].set_title("Accuracy Score on Testing Set") ax[1, 2].set_title("F-score on Testing Set") # Set y-limits for score panels ax[0, 1].set_ylim((0, 1)) ax[0, 2].set_ylim((0, 1)) ax[1, 1].set_ylim((0, 1)) ax[1, 2].set_ylim((0, 1)) # Create patches for the legend patches = [] for i, learner in enumerate(results.keys()): patches.append(mpatches.Patch(color = colors[i], label = learner)) plt.legend(handles = patches, bbox_to_anchor=(-.80, 2.53), \ loc = 'upper center', borderaxespad = 0., ncol = 3, fontsize = 'x-large') # Aesthetics plt.suptitle(title, fontsize = 16, y = 1.02) plt.tight_layout() plt.show() ``` Here are our results which will be compared by plotting. ``` results = {} results_reduced = {} results_reduced_normalized = {} ``` ### 1) Using Decision Tree ``` from sklearn.tree import DecisionTreeClassifier clf = DecisionTreeClassifier(random_state=random_state) print('Before Preprocessing') results[clf.__class__.__name__] = train_predict(clf, X_train, y_train, X_test, y_test) print('After Applying PCA') results_reduced[clf.__class__.__name__] = train_predict(clf, X_train_reduced, y_train, X_test_reduced, y_test) print('After Applying PCA and Z Normalization') results_reduced_normalized[clf.__class__.__name__] = train_predict(clf, X_train_reduced_normalized, y_train, X_test_reduced_normalized, y_test) print('After Scaling Using MinMaxScaler') train_predict(clf, X_train_scaled, y_train, X_test_scaled, y_test); ``` ### 2) Using Naïve Bayes ``` from sklearn.naive_bayes import GaussianNB clf = GaussianNB() print('Before Preprocessing') results[clf.__class__.__name__] = train_predict(clf, X_train, y_train, X_test, y_test) print('After Applying PCA') results_reduced[clf.__class__.__name__] = train_predict(clf, X_train_reduced, y_train, X_test_reduced, y_test) print('After Applying PCA and Z Normalization') results_reduced_normalized[clf.__class__.__name__] = train_predict(clf, X_train_reduced_normalized, y_train, X_test_reduced_normalized, y_test) print('After Scaling Using MinMaxScaler') train_predict(clf, X_train_scaled, y_train, X_test_scaled, y_test); ``` ### 3) Support Vector Machines (SVM) ``` from sklearn.svm import SVC clf = SVC(random_state=random_state) print('Before Preprocessing') results[clf.__class__.__name__] = train_predict(clf, X_train, y_train, X_test, y_test) print('After Applying PCA') results_reduced[clf.__class__.__name__] = train_predict(clf, X_train_reduced, y_train, X_test_reduced, y_test) print('After Applying PCA and Z Normalization') results_reduced_normalized[clf.__class__.__name__] = train_predict(clf, X_train_reduced_normalized, y_train, X_test_reduced_normalized, y_test) print('After Scaling Using MinMaxScaler') train_predict(clf, X_train_scaled, y_train, X_test_scaled, y_test); ``` ### 4) K-Nearest Neighbor (K-NN) ``` from sklearn.neighbors import KNeighborsClassifier clf = KNeighborsClassifier(n_neighbors=3) print('Before Preprocessing') results[clf.__class__.__name__] = train_predict(clf, X_train, y_train, X_test, y_test) print('After Applying PCA') results_reduced[clf.__class__.__name__] = train_predict(clf, X_train_reduced, y_train, X_test_reduced, y_test) print('After Applying PCA and Z Normalization') results_reduced_normalized[clf.__class__.__name__] = train_predict(clf, X_train_reduced_normalized, y_train, X_test_reduced_normalized, y_test) print('After Scaling Using MinMaxScaler') train_predict(clf, X_train_scaled, y_train, X_test_scaled, y_test); ``` ### 5) Random Forests ``` from sklearn.ensemble import RandomForestClassifier clf = RandomForestClassifier(n_estimators=100, max_depth=2, random_state=random_state) print('Before Preprocessing') results[clf.__class__.__name__] = train_predict(clf, X_train, y_train, X_test, y_test) print('After Applying PCA') results_reduced[clf.__class__.__name__] = train_predict(clf, X_train_reduced, y_train, X_test_reduced, y_test) print('After Applying PCA and Z Normalization') results_reduced_normalized[clf.__class__.__name__] = train_predict(clf, X_train_reduced_normalized, y_train, X_test_reduced_normalized, y_test) print('After Scaling Using MinMaxScaler') train_predict(clf, X_train_scaled, y_train, X_test_scaled, y_test); ``` ### 6) AdaBoost ``` from sklearn.ensemble import AdaBoostClassifier clf = AdaBoostClassifier(base_estimator=DecisionTreeClassifier(max_depth=10), n_estimators=100, learning_rate=0.2, random_state=6) print('Before Preprocessing') results[clf.__class__.__name__] = train_predict(clf, X_train, y_train, X_test, y_test) print('After Applying PCA') results_reduced[clf.__class__.__name__] = train_predict(clf, X_train_reduced, y_train, X_test_reduced, y_test) print('After Applying PCA and Z Normalization') results_reduced_normalized[clf.__class__.__name__] = train_predict(clf, X_train_reduced_normalized, y_train, X_test_reduced_normalized, y_test) print('After Scaling Using MinMaxScaler') train_predict(clf, X_train_scaled, y_train, X_test_scaled, y_test); ``` ### Comparing Performance **Let's compare between the classifiers performance on the original data before preprocessing.** ``` evaluate(results, "Performance Metrics for Different Models Before Preprocessing") ``` **Let's compare between the classifiers performance on the original data after applying PCA** ``` evaluate(results_reduced, "Performance Metrics for Different Models After Applying PCA") ``` **Let's compare between the classifiers performance on the original data after applying PCA and Z Normalization.** ``` evaluate(results_reduced_normalized, "Performance Metrics for Different Models After Applying PCA and Z Normalization") ``` ### More Classifiers **Let's try more classifiers to test if we can gain more score on this dataset** ### 7) Gradient Boosting ``` from sklearn.ensemble import GradientBoostingClassifier clf = GradientBoostingClassifier(random_state=6) print('Before Preprocessing') train_predict(clf, X_train, y_train, X_test, y_test); print('After Applying PCA') train_predict(clf, X_train_reduced, y_train, X_test_reduced, y_test); print('After Applying PCA and Z Normalization') train_predict(clf, X_train_reduced_normalized, y_train, X_test_reduced_normalized, y_test); print('After Scaling Using MinMaxScaler') train_predict(clf, X_train_scaled, y_train, X_test_scaled, y_test); ``` ### 8) XGBoost ``` from xgboost import XGBClassifier from sklearn.metrics import fbeta_score clf = XGBClassifier() clf.fit(X_train, y_train) y_pred = clf.predict(X_test) predictions = [round(value) for value in y_pred] fscore = fbeta_score(y_test, predictions, beta=1) print("Fscore: %.5f" % (fscore)) ``` ### 9) Neural Network ``` from sklearn.neural_network import MLPClassifier clf = MLPClassifier(hidden_layer_sizes=(50,50,50), solver='adam', max_iter=300, shuffle=True, batch_size=50, random_state=29, learning_rate='adaptive',alpha=0.05, activation='relu') print('Before Preprocessing') train_predict(clf, X_train, y_train, X_test, y_test); print('After Applying PCA') train_predict(clf, X_train_reduced, y_train, X_test_reduced, y_test); print('After Applying PCA and Z Normalization') train_predict(clf, X_train_reduced_normalized, y_train, X_test_reduced_normalized, y_test); print('After Scaling Using MinMaxScaler') train_predict(clf, X_train_scaled, y_train, X_test_scaled, y_test); ``` ### 10) Quadratic Discriminant Analysis ``` from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis clf = QuadraticDiscriminantAnalysis() print('Before Preprocessing') train_predict(clf, X_train, y_train, X_test, y_test); print('After Applying PCA') train_predict(clf, X_train_reduced, y_train, X_test_reduced, y_test); print('After Applying PCA and Z Normalization') train_predict(clf, X_train_reduced_normalized, y_train, X_test_reduced_normalized, y_test); print('After Scaling Using MinMaxScaler') train_predict(clf, X_train_scaled, y_train, X_test_scaled, y_test); ``` ### 11) Logistic Regression ``` from sklearn.linear_model import LogisticRegression clf = LogisticRegression(random_state=random_state, n_jobs=-1) print('Before Preprocessing') train_predict(clf, X_train, y_train, X_test, y_test); print('After Applying PCA') train_predict(clf, X_train_reduced, y_train, X_test_reduced, y_test); print('After Applying PCA and Z Normalization') train_predict(clf, X_train_reduced_normalized, y_train, X_test_reduced_normalized, y_test); print('After Scaling Using MinMaxScaler') train_predict(clf, X_train_scaled, y_train, X_test_scaled, y_test); ``` ### 12) Bagging Ensemble Bagging on Neural Network ``` from sklearn.ensemble import BaggingClassifier clf = BaggingClassifier(MLPClassifier(hidden_layer_sizes=(50,50,50), solver='adam', max_iter=300, shuffle=True, batch_size=50, random_state=29, learning_rate='adaptive',alpha=0.05, activation='relu') , max_samples=0.9, max_features=0.8) print('Before Preprocessing') train_predict(clf, X_train, y_train, X_test, y_test); print('After Applying PCA') train_predict(clf, X_train_reduced, y_train, X_test_reduced, y_test); print('After Applying PCA and Z Normalization') train_predict(clf, X_train_reduced_normalized, y_train, X_test_reduced_normalized, y_test); print('After Scaling Using MinMaxScaler') train_predict(clf, X_train_scaled, y_train, X_test_scaled, y_test); ``` ### 13) Extra Trees ``` from sklearn.ensemble import ExtraTreesClassifier clf = ExtraTreesClassifier(n_estimators=900, random_state=6, max_depth=None, n_jobs=-1) print('Before Preprocessing') train_predict(clf, X_train, y_train, X_test, y_test); print('After Applying PCA') train_predict(clf, X_train_reduced, y_train, X_test_reduced, y_test); print('After Applying PCA and Z Normalization') train_predict(clf, X_train_reduced_normalized, y_train, X_test_reduced_normalized, y_test); print('After Scaling Using MinMaxScaler') train_predict(clf, X_train_scaled, y_train, X_test_scaled, y_test); ``` ### 14) Voting ``` from sklearn.ensemble import VotingClassifier clf1 = AdaBoostClassifier(base_estimator=DecisionTreeClassifier(max_depth=10), n_estimators=100, learning_rate=0.2, random_state=6) #0.86 clf2 = RandomForestClassifier(n_estimators=200, random_state=random_state, n_jobs=-1, max_depth=20) # 0.85 clf = VotingClassifier(estimators=[('clf2', clf2), ('clf1', clf1)], voting='hard', n_jobs=-1) train_predict(clf, X_train, y_train, X_test, y_test); ``` **The best Fscore we got is 0.88058 using Voting classiifer of AdaBoost and RandomForest** ``` from sklearn.ensemble import VotingClassifier clf1 = AdaBoostClassifier(base_estimator=DecisionTreeClassifier(max_depth=10), n_estimators=100, learning_rate=0.2, random_state=6) #0.86 clf2 = ExtraTreesClassifier(n_estimators=250, random_state=6, max_depth=20, n_jobs=-1) # 0.864 clf = VotingClassifier(estimators=[('clf1', clf1), ('clf2', clf2)], voting='hard', n_jobs=-1) train_predict(clf, X_train, y_train, X_test, y_test); ``` **The best Fscore we got is 0.8809 using Voting classiifer of AdaBoost and ExtraTrees** ## Model Parameter Tuning We will use this method to tune any model with the desired hyperparameters, it will return the model with the best hyperparameters ``` from sklearn.model_selection import GridSearchCV from sklearn.metrics import fbeta_score, make_scorer def tune_model(clf, parameters, X_train, y_train, X_test, y_test): scorer = make_scorer(fbeta_score, beta=1) grid_obj = GridSearchCV(estimator=clf, param_grid=parameters, scoring=scorer, n_jobs= -1) grid_fit = grid_obj.fit(X_train, y_train) # Get the best estimator best_clf = grid_fit.best_estimator_ # Get predictions predictions = (clf.fit(X_train, y_train)).predict(X_test) best_predictions = best_clf.predict(X_test) print("Untuned model") print("Accuracy score on testing data: {:.4f}".format(accuracy_score(y_test, predictions))) print("F-score on testing data: {:.4f}".format(fbeta_score(y_test, predictions, beta=1))) print('-------------------------------') print("Tuned Model") print("Best accuracy score on the testing data: {:.4f}".format(accuracy_score(y_test, best_predictions))) print("Best F-score on the testing data: {:.4f}".format(fbeta_score(y_test, best_predictions, beta=1))) print('-------------------------------') print("Best parameters found:", grid_fit.best_params_) print('-------------------------------') display(pd.DataFrame(grid_obj.grid_scores_)) return {'old_clf' : clf.fit(X_train, y_train), 'tuned_clf' : best_clf} ``` ### 1) Decision Tree ``` parameters = {'max_depth':range(5, 12), 'max_features':range(7,11), 'min_samples_split':[0.01, 0.1]} clf = DecisionTreeClassifier(random_state=random_state) tune_model(clf, parameters, X_train, y_train, X_test, y_test); ``` ### 2) Using Naïve Bayes No parameters to be tuned ### 3) Support Vector Machines (SVM) ``` parameters = {'C':[0.01, 0.1, 1, 10, 1000]} clf = SVC(random_state=random_state) tune_model(clf, parameters, X_train_reduced_normalized, y_train, X_test_reduced_normalized, y_test); ``` ### 4) K-Nearest Neighbor (K-NN) **I. Tuning on the original data** ``` parameters = {'n_neighbors':range(1,20), 'weights':['uniform', 'distance']} clf = KNeighborsClassifier() tune_model(clf, parameters, X_train, y_train, X_test, y_test); ``` **II. Tuning on the data after PCA and Z normalization** ``` parameters = {'n_neighbors':range(1,20), 'weights':['uniform', 'distance']} clf = KNeighborsClassifier() tune_model(clf, parameters, X_train_reduced_normalized, y_train, X_test_reduced_normalized, y_test); ``` ### 5) Random Forests ``` parameters = {'n_estimators':range(100,600,100)} clf = RandomForestClassifier(random_state=random_state, n_jobs=-1) tune_model(clf, parameters, X_train, y_train, X_test, y_test); ``` ### 6) AdaBoost ``` parameters = {'n_estimators':range(100, 500, 100)} clf = AdaBoostClassifier(base_estimator=DecisionTreeClassifier(max_depth=10), learning_rate=0.2, random_state=6) tune_model(clf, parameters, X_train, y_train, X_test, y_test); ``` ## Best Model After Tuning we can see that the best model after tuning is AdaBoost, So we will build that model and use it for testing on our dataset and find the model accuracy, precision, recall and F-measure. ``` from sklearn.metrics import classification_report, confusion_matrix final_model = AdaBoostClassifier(base_estimator=DecisionTreeClassifier(max_depth=10), n_estimators=100, learning_rate=0.2, random_state=6) final_model.fit(X_train, y_train) y_pred = final_model.predict(X_test) y_true = y_test print(classification_report(y_true, y_pred)) print(confusion_matrix(y_test, y_pred)) ``` ## Conclusion **We explored tha dataset and discovered it is imbalanced so we balanced it by using random downsampling, then we scaled the data using MinMaxScaler, reduced dimensionality using PCA, also we normalized dataset using Z Normalization. ** **We explored several classification algorithms to achieve the best results and ended with VotingClassifer which merges between AdaBoost and ExtraTrees. We achieved Fscore of 0.8809 on the testing dataset (30% of the whole dataset).**
github_jupyter
import numpy as np import pandas as pd import matplotlib.pyplot as plt from time import time import matplotlib.patches as mpatches def load_dataset(): url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/magic/magic04.data' attribute_names = ['fLength', 'fWidth', 'fSize', 'fConc', 'fConc1', 'fAsym', 'fM3Long', 'fM3Trans', 'fAlpha', 'fDist', 'class'] df = pd.read_csv(url, index_col=False, names=attribute_names) return df dataset_df = load_dataset() print("DataSet contains {} samples".format(dataset_df.shape[0])) dataset_df.head() dataset_df.describe() classes_cnt = dataset_df['class'].value_counts() print(classes_cnt) random_state = 42 random_samples = dataset_df[dataset_df['class'] == 'g'].sample(n=classes_cnt[0]-classes_cnt[1], random_state=random_state) display(random_samples) balanced_df = dataset_df.drop(random_samples.index); balanced_df['class'].value_counts() X = balanced_df.drop('class', axis=1) Y = balanced_df['class'] X.iloc[:,:].boxplot(grid=False, fontsize=10, rot=60, figsize=(10,20)) def plot_data(x_data, y_data, x_title, y_title, title, xticks): fig = plt.figure(figsize=(15,8)) plt.plot(x_data, y_data, 'bo') fig.suptitle(title, fontsize=16) plt.xlabel(x_title) plt.ylabel(y_title) plt.xticks(xticks) plt.show() return def plot_pretty_data(X, Y): classes_values = Y.unique() feature_names = list(X.columns) all_x = [] all_y = [] # plotting each class alone for class_val in classes_values: # making feature points x = [] y = [] for i in range(0, len(feature_names)): feature_values = list(X.loc[Y[Y == class_val].index].iloc[:, i]) y = y + feature_values x = x + [i] * len(feature_values) all_x = all_x + x all_y = all_y + y # plotting all classes together plot_data(all_x, all_y, 'Feature Number', 'Feature Value', 'All Classes', [i for i in range(0, len(feature_names))]) plot_pretty_data(X, Y) def plot_histogram(X, Y, bins=15, rwidth=0.5): colors = ['red', 'green', 'blue', 'olive', 'yellow', 'gray', 'black', 'gold', 'skyblue', 'teal'] classes = Y.unique() for class_val in classes: data = X.loc[Y[Y == class_val].index] plt.figure(figsize=(20,10)) plt.title("Class " + class_val ) plt.xlabel("Feature Value") plt.ylabel("Value Frequency") plt.hist(np.array(data), bins=bins, color=np.array(colors), label=classes, rwidth=rwidth) plt.legend() plt.show() plot_histogram(X, Y) def visualize_coeff_matrix(mat): fig = plt.figure(figsize = (12,12)) plt.imshow(mat, cmap='Reds') plt.colorbar() plt.xticks([i for i in range(0,mat.shape[0])]) plt.yticks([i for i in range(0,mat.shape[0])]) display(X.corr()) visualize_coeff_matrix(X.corr()) from sklearn.preprocessing import LabelEncoder class_encoder = LabelEncoder() Y = class_encoder.fit_transform(Y) print(Y) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.3, random_state=random_state, shuffle=True) print('Training set has {} samples'.format(len(X_train))) print('Testing set has {} samples'.format(len(X_test))) from sklearn.decomposition import PCA def plot_pca(X): features_number = X.shape[1] pca = PCA(n_components=features_number, random_state=random_state) pca.fit(X) plt.figure(figsize=(20,8)) plt.title('PCA Components variance ratio') plt.xlabel('PCA Component') plt.ylabel('Variance Ratio') plt.xticks([i for i in range(1, features_number + 1)]) plt.plot([i for i in range(1, features_number + 1)], pca.explained_variance_ratio_, color='red', marker='o', linestyle='dashed', linewidth=2, markersize=12) plt.show() plt.figure(figsize=(20,8)) plt.title('Relation Between Number of PCA Components taken and Covered Variance Ratio') plt.xlabel('Number of Taken PCA Components') plt.ylabel('Covered Variance Ratio') plt.xticks([i for i in range(1, features_number + 1)]) plt.plot([i for i in range(1, features_number + 1)], pca.explained_variance_ratio_.cumsum(), color='red', marker='o', linestyle='dashed', linewidth=2, markersize=12) plt.show() plot_pca(X_train) pca = PCA(7, random_state=random_state) pca.fit(X_train) X_train_reduced = pd.DataFrame(pca.transform(X_train)) print("Training set after applying PCA Dimensionality Reduction") display(X_train_reduced) pca = PCA(7, random_state=random_state) pca.fit(X_test) X_test_reduced = pd.DataFrame(pca.transform(X_test)) print("Testing set after applying PCA Dimensionality Reduction") display(X_test_reduced) from scipy.stats import zscore X_train_reduced_normalized = X_train_reduced.apply(zscore) display(X_train_reduced_normalized) X_test_reduced_normalized = X_test_reduced.apply(zscore) display(X_test_reduced_normalized) from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler(feature_range=(0,1)) X_train_scaled = pd.DataFrame(data=scaler.fit_transform(X_train), columns=X_train.columns) X_test_scaled = pd.DataFrame(data=scaler.fit_transform(X_test), columns=X_test.columns) from sklearn.metrics import accuracy_score, fbeta_score def train_predict(learner, X_train, y_train, X_test, y_test): ''' inputs: - learner: the learning algorithm to be trained and predicted on - sample_size: the size of samples (number) to be drawn from training set - X_train: features training set - y_train: income training set - X_test: features testing set - y_test: income testing set ''' results = {} start = time() # Get start time learner.fit(X_train, y_train) end = time() # Get end time results['train_time'] = end - start start = time() # Get start time predictions_test = learner.predict(X_test) predictions_train = learner.predict(X_train[:300]) end = time() # Get end time results['pred_time'] = end - start results['acc_train'] = accuracy_score(y_train[:300], predictions_train) results['acc_test'] = accuracy_score(y_test, predictions_test) results['f_train'] = fbeta_score(y_train[:300], predictions_train, beta=0.5) results['f_test'] = fbeta_score(y_test, predictions_test, beta=0.5) print("{} trained on {} samples, and tests predicted with accuracy {} and fscore {}".format(learner.__class__.__name__, len(X_train), results['acc_test'], results['f_test'])) # Return the results return results def evaluate(results, title): """ Visualization code to display results of various learners. inputs: - learners: a list of supervised learners - stats: a list of dictionaries of the statistic results from 'train_predict()' - accuracy: The score for the naive predictor - f1: The score for the naive predictor """ # Create figure fig, ax = plt.subplots(2, 3, figsize = (15,10)) # Constants bar_width = 0.3 colors = ['#A00000','#00A0A0','#00AFFD','#00AB0A','#C0A0AA', '#ADA000'] # classifier for k, learner in enumerate(results.keys()): # metric for j, metric in enumerate(['train_time', 'acc_train', 'f_train', 'pred_time', 'acc_test', 'f_test']): # Creative plot code ax[int(j/3), j%3].bar(k*bar_width, results[learner][metric], width=bar_width, color=colors[k]) ax[int(j/3), j%3].set_xticks([0.45, 1.45, 2.45]) ax[int(j/3), j%3].set_xlabel("Classiifer Algorithm") ax[int(j/3), j%3].set_xlim((-0.1, 3.0)) # Add unique y-labels ax[0, 0].set_ylabel("Time (in seconds)") ax[0, 1].set_ylabel("Accuracy Score") ax[0, 2].set_ylabel("F-score") ax[1, 0].set_ylabel("Time (in seconds)") ax[1, 1].set_ylabel("Accuracy Score") ax[1, 2].set_ylabel("F-score") # Add titles ax[0, 0].set_title("Model Training") ax[0, 1].set_title("Accuracy Score on Training Subset") ax[0, 2].set_title("F-score on Training Subset") ax[1, 0].set_title("Model Predicting") ax[1, 1].set_title("Accuracy Score on Testing Set") ax[1, 2].set_title("F-score on Testing Set") # Set y-limits for score panels ax[0, 1].set_ylim((0, 1)) ax[0, 2].set_ylim((0, 1)) ax[1, 1].set_ylim((0, 1)) ax[1, 2].set_ylim((0, 1)) # Create patches for the legend patches = [] for i, learner in enumerate(results.keys()): patches.append(mpatches.Patch(color = colors[i], label = learner)) plt.legend(handles = patches, bbox_to_anchor=(-.80, 2.53), \ loc = 'upper center', borderaxespad = 0., ncol = 3, fontsize = 'x-large') # Aesthetics plt.suptitle(title, fontsize = 16, y = 1.02) plt.tight_layout() plt.show() results = {} results_reduced = {} results_reduced_normalized = {} from sklearn.tree import DecisionTreeClassifier clf = DecisionTreeClassifier(random_state=random_state) print('Before Preprocessing') results[clf.__class__.__name__] = train_predict(clf, X_train, y_train, X_test, y_test) print('After Applying PCA') results_reduced[clf.__class__.__name__] = train_predict(clf, X_train_reduced, y_train, X_test_reduced, y_test) print('After Applying PCA and Z Normalization') results_reduced_normalized[clf.__class__.__name__] = train_predict(clf, X_train_reduced_normalized, y_train, X_test_reduced_normalized, y_test) print('After Scaling Using MinMaxScaler') train_predict(clf, X_train_scaled, y_train, X_test_scaled, y_test); from sklearn.naive_bayes import GaussianNB clf = GaussianNB() print('Before Preprocessing') results[clf.__class__.__name__] = train_predict(clf, X_train, y_train, X_test, y_test) print('After Applying PCA') results_reduced[clf.__class__.__name__] = train_predict(clf, X_train_reduced, y_train, X_test_reduced, y_test) print('After Applying PCA and Z Normalization') results_reduced_normalized[clf.__class__.__name__] = train_predict(clf, X_train_reduced_normalized, y_train, X_test_reduced_normalized, y_test) print('After Scaling Using MinMaxScaler') train_predict(clf, X_train_scaled, y_train, X_test_scaled, y_test); from sklearn.svm import SVC clf = SVC(random_state=random_state) print('Before Preprocessing') results[clf.__class__.__name__] = train_predict(clf, X_train, y_train, X_test, y_test) print('After Applying PCA') results_reduced[clf.__class__.__name__] = train_predict(clf, X_train_reduced, y_train, X_test_reduced, y_test) print('After Applying PCA and Z Normalization') results_reduced_normalized[clf.__class__.__name__] = train_predict(clf, X_train_reduced_normalized, y_train, X_test_reduced_normalized, y_test) print('After Scaling Using MinMaxScaler') train_predict(clf, X_train_scaled, y_train, X_test_scaled, y_test); from sklearn.neighbors import KNeighborsClassifier clf = KNeighborsClassifier(n_neighbors=3) print('Before Preprocessing') results[clf.__class__.__name__] = train_predict(clf, X_train, y_train, X_test, y_test) print('After Applying PCA') results_reduced[clf.__class__.__name__] = train_predict(clf, X_train_reduced, y_train, X_test_reduced, y_test) print('After Applying PCA and Z Normalization') results_reduced_normalized[clf.__class__.__name__] = train_predict(clf, X_train_reduced_normalized, y_train, X_test_reduced_normalized, y_test) print('After Scaling Using MinMaxScaler') train_predict(clf, X_train_scaled, y_train, X_test_scaled, y_test); from sklearn.ensemble import RandomForestClassifier clf = RandomForestClassifier(n_estimators=100, max_depth=2, random_state=random_state) print('Before Preprocessing') results[clf.__class__.__name__] = train_predict(clf, X_train, y_train, X_test, y_test) print('After Applying PCA') results_reduced[clf.__class__.__name__] = train_predict(clf, X_train_reduced, y_train, X_test_reduced, y_test) print('After Applying PCA and Z Normalization') results_reduced_normalized[clf.__class__.__name__] = train_predict(clf, X_train_reduced_normalized, y_train, X_test_reduced_normalized, y_test) print('After Scaling Using MinMaxScaler') train_predict(clf, X_train_scaled, y_train, X_test_scaled, y_test); from sklearn.ensemble import AdaBoostClassifier clf = AdaBoostClassifier(base_estimator=DecisionTreeClassifier(max_depth=10), n_estimators=100, learning_rate=0.2, random_state=6) print('Before Preprocessing') results[clf.__class__.__name__] = train_predict(clf, X_train, y_train, X_test, y_test) print('After Applying PCA') results_reduced[clf.__class__.__name__] = train_predict(clf, X_train_reduced, y_train, X_test_reduced, y_test) print('After Applying PCA and Z Normalization') results_reduced_normalized[clf.__class__.__name__] = train_predict(clf, X_train_reduced_normalized, y_train, X_test_reduced_normalized, y_test) print('After Scaling Using MinMaxScaler') train_predict(clf, X_train_scaled, y_train, X_test_scaled, y_test); evaluate(results, "Performance Metrics for Different Models Before Preprocessing") evaluate(results_reduced, "Performance Metrics for Different Models After Applying PCA") evaluate(results_reduced_normalized, "Performance Metrics for Different Models After Applying PCA and Z Normalization") from sklearn.ensemble import GradientBoostingClassifier clf = GradientBoostingClassifier(random_state=6) print('Before Preprocessing') train_predict(clf, X_train, y_train, X_test, y_test); print('After Applying PCA') train_predict(clf, X_train_reduced, y_train, X_test_reduced, y_test); print('After Applying PCA and Z Normalization') train_predict(clf, X_train_reduced_normalized, y_train, X_test_reduced_normalized, y_test); print('After Scaling Using MinMaxScaler') train_predict(clf, X_train_scaled, y_train, X_test_scaled, y_test); from xgboost import XGBClassifier from sklearn.metrics import fbeta_score clf = XGBClassifier() clf.fit(X_train, y_train) y_pred = clf.predict(X_test) predictions = [round(value) for value in y_pred] fscore = fbeta_score(y_test, predictions, beta=1) print("Fscore: %.5f" % (fscore)) from sklearn.neural_network import MLPClassifier clf = MLPClassifier(hidden_layer_sizes=(50,50,50), solver='adam', max_iter=300, shuffle=True, batch_size=50, random_state=29, learning_rate='adaptive',alpha=0.05, activation='relu') print('Before Preprocessing') train_predict(clf, X_train, y_train, X_test, y_test); print('After Applying PCA') train_predict(clf, X_train_reduced, y_train, X_test_reduced, y_test); print('After Applying PCA and Z Normalization') train_predict(clf, X_train_reduced_normalized, y_train, X_test_reduced_normalized, y_test); print('After Scaling Using MinMaxScaler') train_predict(clf, X_train_scaled, y_train, X_test_scaled, y_test); from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis clf = QuadraticDiscriminantAnalysis() print('Before Preprocessing') train_predict(clf, X_train, y_train, X_test, y_test); print('After Applying PCA') train_predict(clf, X_train_reduced, y_train, X_test_reduced, y_test); print('After Applying PCA and Z Normalization') train_predict(clf, X_train_reduced_normalized, y_train, X_test_reduced_normalized, y_test); print('After Scaling Using MinMaxScaler') train_predict(clf, X_train_scaled, y_train, X_test_scaled, y_test); from sklearn.linear_model import LogisticRegression clf = LogisticRegression(random_state=random_state, n_jobs=-1) print('Before Preprocessing') train_predict(clf, X_train, y_train, X_test, y_test); print('After Applying PCA') train_predict(clf, X_train_reduced, y_train, X_test_reduced, y_test); print('After Applying PCA and Z Normalization') train_predict(clf, X_train_reduced_normalized, y_train, X_test_reduced_normalized, y_test); print('After Scaling Using MinMaxScaler') train_predict(clf, X_train_scaled, y_train, X_test_scaled, y_test); from sklearn.ensemble import BaggingClassifier clf = BaggingClassifier(MLPClassifier(hidden_layer_sizes=(50,50,50), solver='adam', max_iter=300, shuffle=True, batch_size=50, random_state=29, learning_rate='adaptive',alpha=0.05, activation='relu') , max_samples=0.9, max_features=0.8) print('Before Preprocessing') train_predict(clf, X_train, y_train, X_test, y_test); print('After Applying PCA') train_predict(clf, X_train_reduced, y_train, X_test_reduced, y_test); print('After Applying PCA and Z Normalization') train_predict(clf, X_train_reduced_normalized, y_train, X_test_reduced_normalized, y_test); print('After Scaling Using MinMaxScaler') train_predict(clf, X_train_scaled, y_train, X_test_scaled, y_test); from sklearn.ensemble import ExtraTreesClassifier clf = ExtraTreesClassifier(n_estimators=900, random_state=6, max_depth=None, n_jobs=-1) print('Before Preprocessing') train_predict(clf, X_train, y_train, X_test, y_test); print('After Applying PCA') train_predict(clf, X_train_reduced, y_train, X_test_reduced, y_test); print('After Applying PCA and Z Normalization') train_predict(clf, X_train_reduced_normalized, y_train, X_test_reduced_normalized, y_test); print('After Scaling Using MinMaxScaler') train_predict(clf, X_train_scaled, y_train, X_test_scaled, y_test); from sklearn.ensemble import VotingClassifier clf1 = AdaBoostClassifier(base_estimator=DecisionTreeClassifier(max_depth=10), n_estimators=100, learning_rate=0.2, random_state=6) #0.86 clf2 = RandomForestClassifier(n_estimators=200, random_state=random_state, n_jobs=-1, max_depth=20) # 0.85 clf = VotingClassifier(estimators=[('clf2', clf2), ('clf1', clf1)], voting='hard', n_jobs=-1) train_predict(clf, X_train, y_train, X_test, y_test); from sklearn.ensemble import VotingClassifier clf1 = AdaBoostClassifier(base_estimator=DecisionTreeClassifier(max_depth=10), n_estimators=100, learning_rate=0.2, random_state=6) #0.86 clf2 = ExtraTreesClassifier(n_estimators=250, random_state=6, max_depth=20, n_jobs=-1) # 0.864 clf = VotingClassifier(estimators=[('clf1', clf1), ('clf2', clf2)], voting='hard', n_jobs=-1) train_predict(clf, X_train, y_train, X_test, y_test); from sklearn.model_selection import GridSearchCV from sklearn.metrics import fbeta_score, make_scorer def tune_model(clf, parameters, X_train, y_train, X_test, y_test): scorer = make_scorer(fbeta_score, beta=1) grid_obj = GridSearchCV(estimator=clf, param_grid=parameters, scoring=scorer, n_jobs= -1) grid_fit = grid_obj.fit(X_train, y_train) # Get the best estimator best_clf = grid_fit.best_estimator_ # Get predictions predictions = (clf.fit(X_train, y_train)).predict(X_test) best_predictions = best_clf.predict(X_test) print("Untuned model") print("Accuracy score on testing data: {:.4f}".format(accuracy_score(y_test, predictions))) print("F-score on testing data: {:.4f}".format(fbeta_score(y_test, predictions, beta=1))) print('-------------------------------') print("Tuned Model") print("Best accuracy score on the testing data: {:.4f}".format(accuracy_score(y_test, best_predictions))) print("Best F-score on the testing data: {:.4f}".format(fbeta_score(y_test, best_predictions, beta=1))) print('-------------------------------') print("Best parameters found:", grid_fit.best_params_) print('-------------------------------') display(pd.DataFrame(grid_obj.grid_scores_)) return {'old_clf' : clf.fit(X_train, y_train), 'tuned_clf' : best_clf} parameters = {'max_depth':range(5, 12), 'max_features':range(7,11), 'min_samples_split':[0.01, 0.1]} clf = DecisionTreeClassifier(random_state=random_state) tune_model(clf, parameters, X_train, y_train, X_test, y_test); parameters = {'C':[0.01, 0.1, 1, 10, 1000]} clf = SVC(random_state=random_state) tune_model(clf, parameters, X_train_reduced_normalized, y_train, X_test_reduced_normalized, y_test); parameters = {'n_neighbors':range(1,20), 'weights':['uniform', 'distance']} clf = KNeighborsClassifier() tune_model(clf, parameters, X_train, y_train, X_test, y_test); parameters = {'n_neighbors':range(1,20), 'weights':['uniform', 'distance']} clf = KNeighborsClassifier() tune_model(clf, parameters, X_train_reduced_normalized, y_train, X_test_reduced_normalized, y_test); parameters = {'n_estimators':range(100,600,100)} clf = RandomForestClassifier(random_state=random_state, n_jobs=-1) tune_model(clf, parameters, X_train, y_train, X_test, y_test); parameters = {'n_estimators':range(100, 500, 100)} clf = AdaBoostClassifier(base_estimator=DecisionTreeClassifier(max_depth=10), learning_rate=0.2, random_state=6) tune_model(clf, parameters, X_train, y_train, X_test, y_test); from sklearn.metrics import classification_report, confusion_matrix final_model = AdaBoostClassifier(base_estimator=DecisionTreeClassifier(max_depth=10), n_estimators=100, learning_rate=0.2, random_state=6) final_model.fit(X_train, y_train) y_pred = final_model.predict(X_test) y_true = y_test print(classification_report(y_true, y_pred)) print(confusion_matrix(y_test, y_pred))
0.59749
0.987326
4 fold * 6 epochs ---- I was trying to clean some of my code so I can add more models. However, this can never happen without the awesome kernels from other talented Kagglers. Forgive me if I missed any. * Based on SRK's kernel: https://www.kaggle.com/sudalairajkumar/a-look-at-different-embeddings * Vladimir Demidov's 2DCNN textClassifier: https://www.kaggle.com/yekenot/2dcnn-textclassifier * Attention layer from Khoi Ngyuen: https://www.kaggle.com/suicaokhoailang/lstm-attention-baseline-0-652-lb * LSTM model from Strideradu: https://www.kaggle.com/strideradu/word2vec-and-gensim-go-go-go * https://www.kaggle.com/danofer/different-embeddings-with-attention-fork * https://www.kaggle.com/ryanzhang/tfidf-naivebayes-logreg-baseline * Borrowed some idea from this model: https://www.kaggle.com/c/jigsaw-toxic-comment-classification-challenge/discussion/52644 * Sentence length seems to a good feature: https://www.kaggle.com/thebrownviking20/analyzing-quora-for-the-insinceres Some new things here: * Take average of embeddings (Unweighted DME) instead of blending predictions: https://arxiv.org/pdf/1804.07983.pdf * The original paper of this idea comes from: Frustratingly Easy Meta-Embedding – Computing Meta-Embeddings by Averaging Source Word Embeddings * Modified the code to choose best threshold * Robust method for blending weights: sort the val score and give the final weight Some thoughts: * Although I pulished a kernel on Transformer, I will not use it * Too much randomness in CuDNN. You may get different results by just rerunning this kernel * Blending rocks ``` # This Python 3 environment comes with many helpful analytics libraries installed # It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python # For example, here's several helpful packages to load in import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) # Input data files are available in the "../input/" directory. # For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory import os print(os.listdir("../input")) # Any results you write to the current directory are saved as output. ## some config values embed_size = 300 # how big is each word vector max_features = 95000 # how many unique words to use (i.e num rows in embedding vector) maxlen = 70 # max number of words in a question to use ``` **Load packages and data** ``` import os import time import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) from tqdm import tqdm import math from sklearn.model_selection import train_test_split from sklearn import metrics from sklearn.model_selection import GridSearchCV, StratifiedKFold from sklearn.metrics import f1_score, roc_auc_score from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.layers import Dense, Input, CuDNNLSTM, Embedding, Dropout, Activation, CuDNNGRU, Conv1D from keras.layers import Bidirectional, GlobalMaxPool1D, GlobalMaxPooling1D, GlobalAveragePooling1D from keras.layers import Input, Embedding, Dense, Conv2D, MaxPool2D, concatenate from keras.layers import Reshape, Flatten, Concatenate, Dropout, SpatialDropout1D from keras.optimizers import Adam from keras.models import Model from keras import backend as K from keras.engine.topology import Layer from keras import initializers, regularizers, constraints, optimizers, layers from keras.layers import concatenate def load_and_prec(): train_df = pd.read_csv("../input/train.csv") test_df = pd.read_csv("../input/test.csv") print("Train shape : ",train_df.shape) print("Test shape : ",test_df.shape) ## fill up the missing values train_X = train_df["question_text"].fillna("_##_").values test_X = test_df["question_text"].fillna("_##_").values ## Tokenize the sentences tokenizer = Tokenizer(num_words=max_features) tokenizer.fit_on_texts(list(train_X)) train_X = tokenizer.texts_to_sequences(train_X) test_X = tokenizer.texts_to_sequences(test_X) ## Pad the sentences train_X = pad_sequences(train_X, maxlen=maxlen) test_X = pad_sequences(test_X, maxlen=maxlen) ## Get the target values train_y = train_df['target'].values #shuffling the data np.random.seed(2018) trn_idx = np.random.permutation(len(train_X)) train_X = train_X[trn_idx] train_y = train_y[trn_idx] return train_X, test_X, train_y, tokenizer.word_index ``` **Load embeddings** ``` def load_glove(word_index): EMBEDDING_FILE = '../input/embeddings/glove.840B.300d/glove.840B.300d.txt' def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32') embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE)) all_embs = np.stack(embeddings_index.values()) emb_mean,emb_std = all_embs.mean(), all_embs.std() embed_size = all_embs.shape[1] # word_index = tokenizer.word_index nb_words = min(max_features, len(word_index)) embedding_matrix = np.random.normal(emb_mean, emb_std, (nb_words, embed_size)) for word, i in word_index.items(): if i >= max_features: continue embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector return embedding_matrix def load_fasttext(word_index): EMBEDDING_FILE = '../input/embeddings/wiki-news-300d-1M/wiki-news-300d-1M.vec' def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32') embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE) if len(o)>100) all_embs = np.stack(embeddings_index.values()) emb_mean,emb_std = all_embs.mean(), all_embs.std() embed_size = all_embs.shape[1] # word_index = tokenizer.word_index nb_words = min(max_features, len(word_index)) embedding_matrix = np.random.normal(emb_mean, emb_std, (nb_words, embed_size)) for word, i in word_index.items(): if i >= max_features: continue embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector return embedding_matrix def load_para(word_index): EMBEDDING_FILE = '../input/embeddings/paragram_300_sl999/paragram_300_sl999.txt' def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32') embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE, encoding="utf8", errors='ignore') if len(o)>100) all_embs = np.stack(embeddings_index.values()) emb_mean,emb_std = all_embs.mean(), all_embs.std() embed_size = all_embs.shape[1] # word_index = tokenizer.word_index nb_words = min(max_features, len(word_index)) embedding_matrix = np.random.normal(emb_mean, emb_std, (nb_words, embed_size)) for word, i in word_index.items(): if i >= max_features: continue embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector return embedding_matrix ``` **Attention layer** ``` # https://www.kaggle.com/suicaokhoailang/lstm-attention-baseline-0-652-lb class Attention(Layer): def __init__(self, step_dim, W_regularizer=None, b_regularizer=None, W_constraint=None, b_constraint=None, bias=True, **kwargs): self.supports_masking = True self.init = initializers.get('glorot_uniform') self.W_regularizer = regularizers.get(W_regularizer) self.b_regularizer = regularizers.get(b_regularizer) self.W_constraint = constraints.get(W_constraint) self.b_constraint = constraints.get(b_constraint) self.bias = bias self.step_dim = step_dim self.features_dim = 0 super(Attention, self).__init__(**kwargs) def build(self, input_shape): assert len(input_shape) == 3 self.W = self.add_weight((input_shape[-1],), initializer=self.init, name='{}_W'.format(self.name), regularizer=self.W_regularizer, constraint=self.W_constraint) self.features_dim = input_shape[-1] if self.bias: self.b = self.add_weight((input_shape[1],), initializer='zero', name='{}_b'.format(self.name), regularizer=self.b_regularizer, constraint=self.b_constraint) else: self.b = None self.built = True def compute_mask(self, input, input_mask=None): return None def call(self, x, mask=None): features_dim = self.features_dim step_dim = self.step_dim eij = K.reshape(K.dot(K.reshape(x, (-1, features_dim)), K.reshape(self.W, (features_dim, 1))), (-1, step_dim)) if self.bias: eij += self.b eij = K.tanh(eij) a = K.exp(eij) if mask is not None: a *= K.cast(mask, K.floatx()) a /= K.cast(K.sum(a, axis=1, keepdims=True) + K.epsilon(), K.floatx()) a = K.expand_dims(a) weighted_input = x * a return K.sum(weighted_input, axis=1) def compute_output_shape(self, input_shape): return input_shape[0], self.features_dim ``` **LSTM models** ``` def model_lstm_atten(embedding_matrix): inp = Input(shape=(maxlen,)) x = Embedding(max_features, embed_size, weights=[embedding_matrix], trainable=False)(inp) x = SpatialDropout1D(0.1)(x) x = Bidirectional(CuDNNLSTM(40, return_sequences=True))(x) y = Bidirectional(CuDNNGRU(40, return_sequences=True))(x) atten_1 = Attention(maxlen)(x) # skip connect atten_2 = Attention(maxlen)(y) avg_pool = GlobalAveragePooling1D()(y) max_pool = GlobalMaxPooling1D()(y) conc = concatenate([atten_1, atten_2, avg_pool, max_pool]) conc = Dense(16, activation="relu")(conc) conc = Dropout(0.1)(conc) outp = Dense(1, activation="sigmoid")(conc) model = Model(inputs=inp, outputs=outp) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) return model ``` **Train and predict** ``` # https://www.kaggle.com/strideradu/word2vec-and-gensim-go-go-go def train_pred(model, train_X, train_y, val_X, val_y, epochs=2): for e in range(epochs): model.fit(train_X, train_y, batch_size=512, epochs=1, validation_data=(val_X, val_y)) pred_val_y = model.predict([val_X], batch_size=1024, verbose=0) best_thresh = 0.5 best_score = 0.0 for thresh in np.arange(0.1, 0.501, 0.01): thresh = np.round(thresh, 2) score = metrics.f1_score(val_y, (pred_val_y > thresh).astype(int)) if score > best_score: best_thresh = thresh best_score = score print("Val F1 Score: {:.4f}".format(best_score)) pred_test_y = model.predict([test_X], batch_size=1024, verbose=0) print('='*100) return pred_val_y, pred_test_y, best_score ``` **Main part: load, train, pred and blend** ``` train_X, test_X, train_y, word_index = load_and_prec() embedding_matrix_1 = load_glove(word_index) # embedding_matrix_2 = load_fasttext(word_index) embedding_matrix_3 = load_para(word_index) ## Simple average: http://aclweb.org/anthology/N18-2031 # We have presented an argument for averaging as # a valid meta-embedding technique, and found experimental # performance to be close to, or in some cases # better than that of concatenation, with the # additional benefit of reduced dimensionality ## Unweighted DME in https://arxiv.org/pdf/1804.07983.pdf # “The downside of concatenating embeddings and # giving that as input to an RNN encoder, however, # is that the network then quickly becomes inefficient # as we combine more and more embeddings.” embedding_matrix = np.mean([embedding_matrix_1, embedding_matrix_3], axis = 0) np.shape(embedding_matrix) # https://www.kaggle.com/ryanzhang/tfidf-naivebayes-logreg-baseline def threshold_search(y_true, y_proba): best_threshold = 0 best_score = 0 for threshold in [i * 0.01 for i in range(100)]: score = f1_score(y_true=y_true, y_pred=y_proba > threshold) if score > best_score: best_threshold = threshold best_score = score search_result = {'threshold': best_threshold, 'f1': best_score} return search_result DATA_SPLIT_SEED = 2018 train_meta = np.zeros(train_y.shape) test_meta = np.zeros(test_X.shape[0]) splits = list(StratifiedKFold(n_splits=4, shuffle=True, random_state=DATA_SPLIT_SEED).split(train_X, train_y)) for idx, (train_idx, valid_idx) in enumerate(splits): X_train = train_X[train_idx] y_train = train_y[train_idx] X_val = train_X[valid_idx] y_val = train_y[valid_idx] model = model_lstm_atten(embedding_matrix) pred_val_y, pred_test_y, best_score = train_pred(model, X_train, y_train, X_val, y_val, epochs = 6) train_meta[valid_idx] = pred_val_y.reshape(-1) test_meta += pred_test_y.reshape(-1) / len(splits) search_result = threshold_search(train_y, train_meta) print(search_result) sub = pd.read_csv('../input/sample_submission.csv') sub.prediction = test_meta > search_result['threshold'] sub.to_csv("submission.csv", index=False) ```
github_jupyter
# This Python 3 environment comes with many helpful analytics libraries installed # It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python # For example, here's several helpful packages to load in import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) # Input data files are available in the "../input/" directory. # For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory import os print(os.listdir("../input")) # Any results you write to the current directory are saved as output. ## some config values embed_size = 300 # how big is each word vector max_features = 95000 # how many unique words to use (i.e num rows in embedding vector) maxlen = 70 # max number of words in a question to use import os import time import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) from tqdm import tqdm import math from sklearn.model_selection import train_test_split from sklearn import metrics from sklearn.model_selection import GridSearchCV, StratifiedKFold from sklearn.metrics import f1_score, roc_auc_score from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.layers import Dense, Input, CuDNNLSTM, Embedding, Dropout, Activation, CuDNNGRU, Conv1D from keras.layers import Bidirectional, GlobalMaxPool1D, GlobalMaxPooling1D, GlobalAveragePooling1D from keras.layers import Input, Embedding, Dense, Conv2D, MaxPool2D, concatenate from keras.layers import Reshape, Flatten, Concatenate, Dropout, SpatialDropout1D from keras.optimizers import Adam from keras.models import Model from keras import backend as K from keras.engine.topology import Layer from keras import initializers, regularizers, constraints, optimizers, layers from keras.layers import concatenate def load_and_prec(): train_df = pd.read_csv("../input/train.csv") test_df = pd.read_csv("../input/test.csv") print("Train shape : ",train_df.shape) print("Test shape : ",test_df.shape) ## fill up the missing values train_X = train_df["question_text"].fillna("_##_").values test_X = test_df["question_text"].fillna("_##_").values ## Tokenize the sentences tokenizer = Tokenizer(num_words=max_features) tokenizer.fit_on_texts(list(train_X)) train_X = tokenizer.texts_to_sequences(train_X) test_X = tokenizer.texts_to_sequences(test_X) ## Pad the sentences train_X = pad_sequences(train_X, maxlen=maxlen) test_X = pad_sequences(test_X, maxlen=maxlen) ## Get the target values train_y = train_df['target'].values #shuffling the data np.random.seed(2018) trn_idx = np.random.permutation(len(train_X)) train_X = train_X[trn_idx] train_y = train_y[trn_idx] return train_X, test_X, train_y, tokenizer.word_index def load_glove(word_index): EMBEDDING_FILE = '../input/embeddings/glove.840B.300d/glove.840B.300d.txt' def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32') embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE)) all_embs = np.stack(embeddings_index.values()) emb_mean,emb_std = all_embs.mean(), all_embs.std() embed_size = all_embs.shape[1] # word_index = tokenizer.word_index nb_words = min(max_features, len(word_index)) embedding_matrix = np.random.normal(emb_mean, emb_std, (nb_words, embed_size)) for word, i in word_index.items(): if i >= max_features: continue embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector return embedding_matrix def load_fasttext(word_index): EMBEDDING_FILE = '../input/embeddings/wiki-news-300d-1M/wiki-news-300d-1M.vec' def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32') embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE) if len(o)>100) all_embs = np.stack(embeddings_index.values()) emb_mean,emb_std = all_embs.mean(), all_embs.std() embed_size = all_embs.shape[1] # word_index = tokenizer.word_index nb_words = min(max_features, len(word_index)) embedding_matrix = np.random.normal(emb_mean, emb_std, (nb_words, embed_size)) for word, i in word_index.items(): if i >= max_features: continue embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector return embedding_matrix def load_para(word_index): EMBEDDING_FILE = '../input/embeddings/paragram_300_sl999/paragram_300_sl999.txt' def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32') embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE, encoding="utf8", errors='ignore') if len(o)>100) all_embs = np.stack(embeddings_index.values()) emb_mean,emb_std = all_embs.mean(), all_embs.std() embed_size = all_embs.shape[1] # word_index = tokenizer.word_index nb_words = min(max_features, len(word_index)) embedding_matrix = np.random.normal(emb_mean, emb_std, (nb_words, embed_size)) for word, i in word_index.items(): if i >= max_features: continue embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector return embedding_matrix # https://www.kaggle.com/suicaokhoailang/lstm-attention-baseline-0-652-lb class Attention(Layer): def __init__(self, step_dim, W_regularizer=None, b_regularizer=None, W_constraint=None, b_constraint=None, bias=True, **kwargs): self.supports_masking = True self.init = initializers.get('glorot_uniform') self.W_regularizer = regularizers.get(W_regularizer) self.b_regularizer = regularizers.get(b_regularizer) self.W_constraint = constraints.get(W_constraint) self.b_constraint = constraints.get(b_constraint) self.bias = bias self.step_dim = step_dim self.features_dim = 0 super(Attention, self).__init__(**kwargs) def build(self, input_shape): assert len(input_shape) == 3 self.W = self.add_weight((input_shape[-1],), initializer=self.init, name='{}_W'.format(self.name), regularizer=self.W_regularizer, constraint=self.W_constraint) self.features_dim = input_shape[-1] if self.bias: self.b = self.add_weight((input_shape[1],), initializer='zero', name='{}_b'.format(self.name), regularizer=self.b_regularizer, constraint=self.b_constraint) else: self.b = None self.built = True def compute_mask(self, input, input_mask=None): return None def call(self, x, mask=None): features_dim = self.features_dim step_dim = self.step_dim eij = K.reshape(K.dot(K.reshape(x, (-1, features_dim)), K.reshape(self.W, (features_dim, 1))), (-1, step_dim)) if self.bias: eij += self.b eij = K.tanh(eij) a = K.exp(eij) if mask is not None: a *= K.cast(mask, K.floatx()) a /= K.cast(K.sum(a, axis=1, keepdims=True) + K.epsilon(), K.floatx()) a = K.expand_dims(a) weighted_input = x * a return K.sum(weighted_input, axis=1) def compute_output_shape(self, input_shape): return input_shape[0], self.features_dim def model_lstm_atten(embedding_matrix): inp = Input(shape=(maxlen,)) x = Embedding(max_features, embed_size, weights=[embedding_matrix], trainable=False)(inp) x = SpatialDropout1D(0.1)(x) x = Bidirectional(CuDNNLSTM(40, return_sequences=True))(x) y = Bidirectional(CuDNNGRU(40, return_sequences=True))(x) atten_1 = Attention(maxlen)(x) # skip connect atten_2 = Attention(maxlen)(y) avg_pool = GlobalAveragePooling1D()(y) max_pool = GlobalMaxPooling1D()(y) conc = concatenate([atten_1, atten_2, avg_pool, max_pool]) conc = Dense(16, activation="relu")(conc) conc = Dropout(0.1)(conc) outp = Dense(1, activation="sigmoid")(conc) model = Model(inputs=inp, outputs=outp) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) return model # https://www.kaggle.com/strideradu/word2vec-and-gensim-go-go-go def train_pred(model, train_X, train_y, val_X, val_y, epochs=2): for e in range(epochs): model.fit(train_X, train_y, batch_size=512, epochs=1, validation_data=(val_X, val_y)) pred_val_y = model.predict([val_X], batch_size=1024, verbose=0) best_thresh = 0.5 best_score = 0.0 for thresh in np.arange(0.1, 0.501, 0.01): thresh = np.round(thresh, 2) score = metrics.f1_score(val_y, (pred_val_y > thresh).astype(int)) if score > best_score: best_thresh = thresh best_score = score print("Val F1 Score: {:.4f}".format(best_score)) pred_test_y = model.predict([test_X], batch_size=1024, verbose=0) print('='*100) return pred_val_y, pred_test_y, best_score train_X, test_X, train_y, word_index = load_and_prec() embedding_matrix_1 = load_glove(word_index) # embedding_matrix_2 = load_fasttext(word_index) embedding_matrix_3 = load_para(word_index) ## Simple average: http://aclweb.org/anthology/N18-2031 # We have presented an argument for averaging as # a valid meta-embedding technique, and found experimental # performance to be close to, or in some cases # better than that of concatenation, with the # additional benefit of reduced dimensionality ## Unweighted DME in https://arxiv.org/pdf/1804.07983.pdf # “The downside of concatenating embeddings and # giving that as input to an RNN encoder, however, # is that the network then quickly becomes inefficient # as we combine more and more embeddings.” embedding_matrix = np.mean([embedding_matrix_1, embedding_matrix_3], axis = 0) np.shape(embedding_matrix) # https://www.kaggle.com/ryanzhang/tfidf-naivebayes-logreg-baseline def threshold_search(y_true, y_proba): best_threshold = 0 best_score = 0 for threshold in [i * 0.01 for i in range(100)]: score = f1_score(y_true=y_true, y_pred=y_proba > threshold) if score > best_score: best_threshold = threshold best_score = score search_result = {'threshold': best_threshold, 'f1': best_score} return search_result DATA_SPLIT_SEED = 2018 train_meta = np.zeros(train_y.shape) test_meta = np.zeros(test_X.shape[0]) splits = list(StratifiedKFold(n_splits=4, shuffle=True, random_state=DATA_SPLIT_SEED).split(train_X, train_y)) for idx, (train_idx, valid_idx) in enumerate(splits): X_train = train_X[train_idx] y_train = train_y[train_idx] X_val = train_X[valid_idx] y_val = train_y[valid_idx] model = model_lstm_atten(embedding_matrix) pred_val_y, pred_test_y, best_score = train_pred(model, X_train, y_train, X_val, y_val, epochs = 6) train_meta[valid_idx] = pred_val_y.reshape(-1) test_meta += pred_test_y.reshape(-1) / len(splits) search_result = threshold_search(train_y, train_meta) print(search_result) sub = pd.read_csv('../input/sample_submission.csv') sub.prediction = test_meta > search_result['threshold'] sub.to_csv("submission.csv", index=False)
0.767777
0.599749
# Simulación Montecarlo > El método de Montecarlo es un método no determinista o estadístico numérico, usado para aproximar expresiones matemáticas complejas y costosas de evaluar con exactitud. El método se llamó así en referencia al Casino de Montecarlo (Mónaco) por ser “la capital del juego de azar”, al ser la ruleta un generador simple de números aleatorios. El nombre y el desarrollo sistemático de los métodos de Montecarlo datan aproximadamente de 1944 y se mejoraron enormemente con el desarrollo de la computadora. Referencia: - https://es.wikipedia.org/wiki/M%C3%A9todo_de_Montecarlo ___ ## 1. Introducción <img style="float: right; margin: 0px 0px 15px 15px;" src="https://upload.wikimedia.org/wikipedia/commons/5/54/Monte_carlo_method.svg" width="300px" height="100px" /> - Inventado por Stanislaw Ulam y a John von Neumann. Ulam ha explicado cómo se le ocurrió la idea mientras jugaba un solitario durante una enfermedad en 1946. - Advirtió que resulta mucho más simple tener una idea del resultado general del solitario haciendo pruebas múltiples con las cartas y contando las proporciones de los resultados que computar todas las posibilidades de combinación formalmente. - Se le ocurrió que esta misma observación debía aplicarse a su trabajo de Los Álamos sobre difusión de neutrones, para la cual resulta prácticamente imposible solucionar las ecuaciones íntegro-diferenciales que gobiernan la dispersión, la absorción y la fisión. - Dado que ya empezaban a estar disponibles máquinas de computación para efectuar las pruebas numéricas, el método cobró mucha fuerza. - El método de Montecarlo proporciona soluciones aproximadas a una gran variedad de problemas matemáticos posibilitando la realización de experimentos con muestreos de números pseudoaleatorios en una computadora. El método es aplicable a cualquier tipo de problema, ya sea estocástico o determinista. - El método de Montecarlo tiene un error absoluto de la estimación que decrece como $\frac{1}{\sqrt{N}}$ en virtud del teorema del límite central. ### Ejemplo Todos alguna vez hemos aplicado el método Montecarlo (inconscientemente). Como ejemplo, consideremos el juego de Astucia Naval. Normalmente, primero se realizan una serie de tiros a puntos aleatorios. Una vez se impacta en un barco, se puede utilizar un algoritmo determinista para identificar la posición del barco y así terminar de derrumbarlo. ___ ## 2. Caminata aleatoria <img style="float: right; margin: 0px 0px 15px 15px;" src="https://upload.wikimedia.org/wikipedia/commons/d/da/Random_Walk_example.svg" width="300px" height="100px" /> Una caminata aleatoria (*random walk* en inglés) es ua formalización matemática de la trayectoria que resulta al hacer pasos sucesivos aleatorios. Un ejemplo elemental de caminata aleatoria es la caminata aleatoria en la línea de números enteros $\mathbb{Z}$, la cual comienza en $0$ y en cada paso se mueve $+1$ o $-1$ con igual probabilidad. Otros ejemplos: - Trayectoria de una molécula al viajar en un fluido (líquido o gas). - El camino que sigue un animal en su búsqueda de comida. - El precio fluctuante de una acción. - La situación de un apostador en un juego de azar. Todos pueden ser aproximados por caminatas aleatorias, aunque no sean en verdad procesos aleatorios. **Este también es un ejemplo de caminata aleatoria** ``` from IPython.display import YouTubeVideo YouTubeVideo('Y77WnkLbT2Q') ``` ### Caminata aleatoria en una dimensión Como dijimos, un ejemplo elemental de caminata aleatoria es la caminata aleatoria en la línea de números enteros $\mathbb{Z}$, la cual comienza en $0$ y a cada paso se mueve , which starts at 0 and at each step moves $+1$ o $-1$ con igual probabilidad. Esta caminata se puede ilustrar como sigue: - Se posiciona en $0$ en la línea de números enteros y una moneda justa se tira. - Si cae en **sol** nos moveremos una unidad a la derecha. - Si cae en **águila** nos moveremos una unidad a la izquierda. Notemos que después de $5$ pasos podremos estar en 1, −1, 3, −3, 5, or −5. Las posibilidades son las siguientes: <img style="float: center; margin: 0px 0px 15px 15px;" src="https://upload.wikimedia.org/wikipedia/commons/0/05/Flips.svg" width="900px" height="300px" /> Referencia: - https://en.wikipedia.org/wiki/Random_walk **Importante:** librería random. Referencia: - https://docs.python.org/3/library/random.html ``` # Importar librería random import random help(random.choice) # Escribir una función que genere el resultado # de una caminata aleatoria de N pasos def caminata_aleatoria(N): s = [0] for i in range(N): Z = random.choice((-1,1)) s.append(s[-1] + Z) return s ``` **Actividad.** Graficar, en una misma ventana de gráficos, al menos ocho caminatas aleatorias de 100 pasos. ``` # Importar librería de gráficos 2d import matplotlib.pyplot as plt %matplotlib inline # Solucionar acá # Número de pasos N N = 100 # Ventana para graficar plt.figure(figsize=(8,6)) # Generar y graficar las caminatas de N pasos for i in range(8): plt.plot(caminata_aleatoria(N)) # Demás elementos del gráfico plt.xlabel('Pasos') plt.ylabel('Caminatas') plt.grid() ``` ### Usamos montecarlo para evaluar el resultado de la caminata aleatoria - Describir, de nuevo, el proceso de la caminata aleatoria en el pizarrón y ver el valor esperado de la caminata después de N pasos. - Luego, evaluar el proceso utilizando montecarlo y comparar resultados. ``` # Importamos numpy import numpy as np # Número de pasos N = 100 # Número de caminatas aleatorias n = 10000 # Inicializar lista con último valor de la # caminata aleatoria ultimo = [caminata_aleatoria(N)[-1]] # Realizar varias caminatas aleatorias y guardar # último valor for i in range(n): ultimo.append(caminata_aleatoria(N)[-1]) # Media del último valor print("La media muestral del ultimo valor de la caminata aleatoria es:", np.mean(ultimo)) ``` ## Ejemplo Ahora, para comprender el alcance de la simulación Montecarlo, tomaremos el ejemplo de un apostador básico. Referencia: - https://pythonprogramming.net/monte-carlo-simulator-python/ Supongamos que estamos en un casino especial, donde el usuario puede tirar un *dado metafórico* que puede dar como resultado del número uno (1) al número cien (100). Si el usuario tira cualquier número entre 1 y 50, el casino gana. Si el usuario tira cualquier número entre 51 y 99, el usuario gana. Si el usuario tira 100, pierde. Con esto, el casino mantiene un margen del 1%, el cual es mucho más pequeño que el margen típico en casinos, al igual que el margen de mercado cuando se incorporan costos por transacción. Por ejemplo, [Scottrade](https://www.scottrade.com/) cobra \$7 USD por transacción. Si se invierten \$1000 USD por acción, esto significa que tienes que pagar \$7 USD para entrar, y \$7 USD para salir, para un total de \$14 USD. Esto pone el margen en 1.4\%. Esto significa, que a largo plazo, las ganancias tienen que ser mayores a 1.4\% en promedio, de otra manera se estará perdiendo dinero. Aunque este porcentaje es pequeño, las probabilidades ya están en contra. La comercialización de acciones es un juego 50/50, especialmente en el corto plazo. De nuevo, con nuestro ejemplo en mente, 1-50, la casa gana. 51-99 el usuario gana. Un 100 significa que la casa gana. Ahora, comencemos. Primero tenemos que crear nuestro dado. ``` # Explorar función randint de la librería random y # crear una función que simule la tirada de un dado def tirar_dado(): return random.randint(1,100) # Tirar el dado 100 veces para comprobar que nuestra # función si trabaja correctamente (print) for i in range(100): print(tirar_dado()) ``` Sin embargo, el dado por si solo no nos es útil. Necesitamos una función que nos devuelva sólamente si ganamos o perdemos. ``` # Cambiar/usar la anterior función para obtener una # que devuelva simplemente ganar(true) o perder(false) def juego(): tirada = tirar_dado() if tirada<=50: return False elif tirada==100: return False else: return True # Probar la función creada para ver que funcione. # Crear contadores para ver la cantidad de veces que # ganamos y la cantidad de veces que perdemos cont_ganar = 0 cont_perder = 0 for i in range(100): jugada = juego() if jugada: cont_ganar+=1 else: cont_perder+=1 #print(jugada) print("Se ganaron ", cont_ganar, " veces, y se perdieron ", cont_perder, " veces.") ``` Ahora, necesitamos crear un apostador. Empezaremos con uno extremadamente básico por ahora. Veremos, que aún con un apostador muy básico, veremos cosas muy reveladoras usando un simulador montecarlo. ``` # Crearemos un apostador simple. Las caracterísitcas son: # se empieza con un capital inicial, # siempre se apuesta lo mismo, # y se va a apostar un número determinado de veces. # Si se gana, se añade la apuesta al capital, # si se pierde, se descuenta la apuesta del capital. # La función debe devolver un arreglo con el capital # al final de cada apuesta. def apostador(cap_ini, apuesta, n_apuestas): capital=[cap_ini] for i in range(n_apuestas): jugada = juego() if jugada: capital.append(capital[-1]+apuesta) else: capital.append(capital[-1]-apuesta) return capital # Ver como evolucionan los fondos de nuestro apostador # al jugar 100 veces, con un capital inicial de 10000 pesos # y con un monto de apuesta de 100 pesos. apostador(10000, 100, 100) ``` En realidad no nos importa tanto como evolucionan estos fondos. Nos importa más cuáles son los fondos al final (al largo plazo). Modificar la función anterior para ver esto. ``` # Función de apostador que devuelve los fondos # al final de apostar una cantidad determinadad de veces def apostador(cap_ini, apuesta, n_apuestas): capital=cap_ini for i in range(n_apuestas): jugada = juego() if jugada: capital+=apuesta else: capital-=apuesta return capital # (Montecarlo) Simular varios (100) escenarios # en que se apuestan 50, 100, 1000 y 10000 veces. ¿Qué pasa? for i in range(100): print(apostador(10000, 100, 10000)) ``` Vemos que al largo plazo la mayoría de los apostadores quebraron. Sin embargo, esta forma de visualizar los resultados no es adecuada. Utilicemos matplotlib. ``` # Modificar la función para que no devuelva los fondos al # final, sino que grafique los fondos a través del tiempo def apostador(cap_ini, apuesta, n_apuestas): capital=[cap_ini] for i in range(n_apuestas): jugada = juego() if jugada: capital.append(capital[-1]+apuesta) else: capital.append(capital[-1]-apuesta) plt.plot(capital) # (Montecarlo) Simular varios (100) escenarios # en que se apuestan 50, 100, 1000 y 10000 veces. ¿Qué pasa? plt.figure(figsize=(8,6)) for i in range(100): apostador(10000, 100, 10000) plt.xlabel('Numero de apuestas') plt.ylabel('Capital') plt.grid() ``` Por esto los apostadores pierden. Normalmente las probabilidades no están evidentemente muy en contra de ellos, solo un poco. Los casinos únicamente entienden psicología básica: ganar es extremadamente adictivo. Por ello, los casino se construyen para mantenerte jugando. En el corto plazo, la mayoría de los jugadores no se dan cuenta que son más propensos a perder. Las veces que ganan y pierden son muy parejas. Estadísticamente, casi la mitad de las personas terminarán con ganancias después de jugar unas pocas veces. El problema es la adicción, y que ellos continuarán apostando, y por ende perdiendo sus ganancias. Es matemática extremadamente básica, pero la psicología humana es débil. <script> $(document).ready(function(){ $('div.prompt').hide(); $('div.back-to-top').hide(); $('nav#menubar').hide(); $('.breadcrumb').hide(); $('.hidden-print').hide(); }); </script> <footer id="attribution" style="float:right; color:#808080; background:#fff;"> Created with Jupyter by Esteban Jiménez Rodríguez. </footer>
github_jupyter
from IPython.display import YouTubeVideo YouTubeVideo('Y77WnkLbT2Q') # Importar librería random import random help(random.choice) # Escribir una función que genere el resultado # de una caminata aleatoria de N pasos def caminata_aleatoria(N): s = [0] for i in range(N): Z = random.choice((-1,1)) s.append(s[-1] + Z) return s # Importar librería de gráficos 2d import matplotlib.pyplot as plt %matplotlib inline # Solucionar acá # Número de pasos N N = 100 # Ventana para graficar plt.figure(figsize=(8,6)) # Generar y graficar las caminatas de N pasos for i in range(8): plt.plot(caminata_aleatoria(N)) # Demás elementos del gráfico plt.xlabel('Pasos') plt.ylabel('Caminatas') plt.grid() # Importamos numpy import numpy as np # Número de pasos N = 100 # Número de caminatas aleatorias n = 10000 # Inicializar lista con último valor de la # caminata aleatoria ultimo = [caminata_aleatoria(N)[-1]] # Realizar varias caminatas aleatorias y guardar # último valor for i in range(n): ultimo.append(caminata_aleatoria(N)[-1]) # Media del último valor print("La media muestral del ultimo valor de la caminata aleatoria es:", np.mean(ultimo)) # Explorar función randint de la librería random y # crear una función que simule la tirada de un dado def tirar_dado(): return random.randint(1,100) # Tirar el dado 100 veces para comprobar que nuestra # función si trabaja correctamente (print) for i in range(100): print(tirar_dado()) # Cambiar/usar la anterior función para obtener una # que devuelva simplemente ganar(true) o perder(false) def juego(): tirada = tirar_dado() if tirada<=50: return False elif tirada==100: return False else: return True # Probar la función creada para ver que funcione. # Crear contadores para ver la cantidad de veces que # ganamos y la cantidad de veces que perdemos cont_ganar = 0 cont_perder = 0 for i in range(100): jugada = juego() if jugada: cont_ganar+=1 else: cont_perder+=1 #print(jugada) print("Se ganaron ", cont_ganar, " veces, y se perdieron ", cont_perder, " veces.") # Crearemos un apostador simple. Las caracterísitcas son: # se empieza con un capital inicial, # siempre se apuesta lo mismo, # y se va a apostar un número determinado de veces. # Si se gana, se añade la apuesta al capital, # si se pierde, se descuenta la apuesta del capital. # La función debe devolver un arreglo con el capital # al final de cada apuesta. def apostador(cap_ini, apuesta, n_apuestas): capital=[cap_ini] for i in range(n_apuestas): jugada = juego() if jugada: capital.append(capital[-1]+apuesta) else: capital.append(capital[-1]-apuesta) return capital # Ver como evolucionan los fondos de nuestro apostador # al jugar 100 veces, con un capital inicial de 10000 pesos # y con un monto de apuesta de 100 pesos. apostador(10000, 100, 100) # Función de apostador que devuelve los fondos # al final de apostar una cantidad determinadad de veces def apostador(cap_ini, apuesta, n_apuestas): capital=cap_ini for i in range(n_apuestas): jugada = juego() if jugada: capital+=apuesta else: capital-=apuesta return capital # (Montecarlo) Simular varios (100) escenarios # en que se apuestan 50, 100, 1000 y 10000 veces. ¿Qué pasa? for i in range(100): print(apostador(10000, 100, 10000)) # Modificar la función para que no devuelva los fondos al # final, sino que grafique los fondos a través del tiempo def apostador(cap_ini, apuesta, n_apuestas): capital=[cap_ini] for i in range(n_apuestas): jugada = juego() if jugada: capital.append(capital[-1]+apuesta) else: capital.append(capital[-1]-apuesta) plt.plot(capital) # (Montecarlo) Simular varios (100) escenarios # en que se apuestan 50, 100, 1000 y 10000 veces. ¿Qué pasa? plt.figure(figsize=(8,6)) for i in range(100): apostador(10000, 100, 10000) plt.xlabel('Numero de apuestas') plt.ylabel('Capital') plt.grid()
0.135032
0.980618
``` %load_ext autoreload %autoreload 2 import tensorflow as tf import numpy as np import random from tensorflow import keras from tensorflow.keras import utils as np_utils from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Flatten, Conv2D, AveragePooling2D, MaxPooling2D, Dropout, BatchNormalization, Softmax from tensorflow.keras import Model from tensorflow.keras.utils import to_categorical from tensorflow.keras.losses import categorical_crossentropy import datetime from time import time from matplotlib import pyplot as plt from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.python.keras.layers.pooling import GlobalAveragePooling2D import sys sys.path.append("/home/ecbm4040/Final_Project/e4040-2021Fall-Project-SCNN-as6430-as6456-vsk2123/src/") # Load and prepare data # CIFAR10 Dataset from modules.utils import load_data X_train, y_train = load_data(mode='train') num_training = 49000 num_validation = 1000 X_val = X_train[-num_validation:, :] y_val = y_train[-num_validation:] X_train = X_train[:num_training, :] y_train = y_train[:num_training] # Preprocessing: subtract the mean value across every dimension for training data, and reshape it to be RGB size mean_image = np.mean(X_train, axis=0) X_train = X_train.astype(np.float32) - mean_image.astype(np.float32) X_val = X_val.astype(np.float32) - mean_image X_train = X_train.reshape(-1,3,32,32).transpose(0,2,3,1) / 255 X_val = X_val.reshape(-1,3,32,32).transpose(0,2,3,1) / 255 print('Train data shape: ', X_train.shape) print('Train labels shape: ', y_train.shape) print('Validation data shape: ', X_val.shape) print('Validation labels shape: ', y_val.shape) y_train_dummy = tf.keras.utils.to_categorical(y_train) y_val_dummy = tf.keras.utils.to_categorical(y_val) print('Train labels shape (one-hot): ', y_train_dummy.shape) print('Validation labels shape (one-hot): ', y_val_dummy.shape) # Plot sample images before augmentation for i in range(0,9): plt.subplot(330 + 1 + i) plt.imshow(x_train[i]) plt.show() # Data augmentation code def HSV_perturbations(image): """ Takes an input image and returns it with either the randomly adjusted hue or saturation (or may be makes no HSV change at all) with a probability of 1/3 """ choice=random.randint(1,3) print(choice) image = np.array(image) if choice ==1: return tf.image.random_hue(image, 1/random.randint(1,10)) elif choice ==2: return tf.image.random_saturation(image, 5, 10) else: return image # so as to avoid not change hue for every image datagen = ImageDataGenerator( horizontal_flip=True, width_shift_range=0.1, height_shift_range=0.1, brightness_range=[0.5,1.5] ) datagen.fit(x_train) # Plot sample augmented images for X_batch, y_batch in datagen.flow(x_train, y_train, batch_size=9): for i in range(0, 9): plt.subplot(330 + 1 + i) plt.imshow(X_batch[i].astype(np.uint8)) plt.show() break # Creating Spectral CNN Layer class SpectralConvolution2D(tf.keras.layers.Layer): def __init__(self, filters, kernel_size,strides,padding,**kwargs): self.no_of_kernels = filters self.kernel_shape = kernel_size self.strides=strides if padding =="same": self.padding=kernel_size[0]-1 else: self.padding=0 super(SpectralConvolution2D, self).__init__(**kwargs) def build(self, input_shape): self.kernel = self.add_weight(shape=self.kernel_shape + (input_shape[-1], self.no_of_kernels),# (k_width,k_height,input channels, # kernels) (3,3,3,32) initializer='random_normal', trainable=True) self.bias = self.add_weight(shape=(self.no_of_kernels,),# 1 bias for each kernel initializer='random_normal', trainable=True) super(SpectralConvolution2D, self).build(input_shape) def call(self, inputs): out_shape = (inputs.get_shape().as_list()[1] - self.kernel.get_shape().as_list()[0] + self.padding)//self.strides[0] + 1 spatial_inputs = tf.transpose(inputs, perm=[0,3,1,2]) spatial_kernel = tf.transpose(self.kernel, perm=[3,2,0,1]) # Converting the inputs and kernel into spectral domain spectral_inputs = tf.signal.rfft2d(spatial_inputs, [out_shape, out_shape]) spectral_kernel = tf.signal.rfft2d(spatial_kernel, [out_shape, out_shape]) # Convolution in the spectral domain spectral_convolution_output = tf.einsum('imkl,jmkl->ijkl', spectral_inputs, spectral_kernel) # Converting the output in spectral domain back to spatial domain spatial_convolution_output = tf.signal.irfft2d(spectral_convolution_output, [out_shape, out_shape]) spatial_convolution_output = tf.transpose(spatial_convolution_output, perm=[0,2,3,1]) spatial_convolution_output = tf.nn.bias_add(spatial_convolution_output, self.bias) return spatial_convolution_output # Generic CNN architecture def spectralConvolutionCNN(): model = Sequential() model.add(SpectralConvolution2D(96, kernel_size=(3,3),padding="same", strides=(1,1), input_shape=input_shape)) model.add(MaxPooling2D(pool_size=(3,3),strides=(2,2))) model.add(SpectralConvolution2D(192, kernel_size=(3,3),padding="same",strides=(1,1))) model.add(MaxPooling2D(pool_size=(3,3),strides=(2,2))) model.add(Flatten()) model.add(Dense(1024)) model.add(Dense(512)) model.add(Dense(output_size, activation='softmax')) return model # Compiling and training the model batch_size=128 nb_epochs=50 train_generator = datagen.flow(x_train, y_train, batch_size=batch_size) valid_generator = datagen.flow(x_test, y_test, batch_size=batch_size) spectral_cnn_model = spectralConvolutionCNN() spectral_cnn_model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) history=spectral_cnn_model.fit_generator(train_generator,epochs=nb_epochs,steps_per_epoch=len(x_train)//batch_size, validation_data=valid_generator) ```
github_jupyter
%load_ext autoreload %autoreload 2 import tensorflow as tf import numpy as np import random from tensorflow import keras from tensorflow.keras import utils as np_utils from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Flatten, Conv2D, AveragePooling2D, MaxPooling2D, Dropout, BatchNormalization, Softmax from tensorflow.keras import Model from tensorflow.keras.utils import to_categorical from tensorflow.keras.losses import categorical_crossentropy import datetime from time import time from matplotlib import pyplot as plt from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.python.keras.layers.pooling import GlobalAveragePooling2D import sys sys.path.append("/home/ecbm4040/Final_Project/e4040-2021Fall-Project-SCNN-as6430-as6456-vsk2123/src/") # Load and prepare data # CIFAR10 Dataset from modules.utils import load_data X_train, y_train = load_data(mode='train') num_training = 49000 num_validation = 1000 X_val = X_train[-num_validation:, :] y_val = y_train[-num_validation:] X_train = X_train[:num_training, :] y_train = y_train[:num_training] # Preprocessing: subtract the mean value across every dimension for training data, and reshape it to be RGB size mean_image = np.mean(X_train, axis=0) X_train = X_train.astype(np.float32) - mean_image.astype(np.float32) X_val = X_val.astype(np.float32) - mean_image X_train = X_train.reshape(-1,3,32,32).transpose(0,2,3,1) / 255 X_val = X_val.reshape(-1,3,32,32).transpose(0,2,3,1) / 255 print('Train data shape: ', X_train.shape) print('Train labels shape: ', y_train.shape) print('Validation data shape: ', X_val.shape) print('Validation labels shape: ', y_val.shape) y_train_dummy = tf.keras.utils.to_categorical(y_train) y_val_dummy = tf.keras.utils.to_categorical(y_val) print('Train labels shape (one-hot): ', y_train_dummy.shape) print('Validation labels shape (one-hot): ', y_val_dummy.shape) # Plot sample images before augmentation for i in range(0,9): plt.subplot(330 + 1 + i) plt.imshow(x_train[i]) plt.show() # Data augmentation code def HSV_perturbations(image): """ Takes an input image and returns it with either the randomly adjusted hue or saturation (or may be makes no HSV change at all) with a probability of 1/3 """ choice=random.randint(1,3) print(choice) image = np.array(image) if choice ==1: return tf.image.random_hue(image, 1/random.randint(1,10)) elif choice ==2: return tf.image.random_saturation(image, 5, 10) else: return image # so as to avoid not change hue for every image datagen = ImageDataGenerator( horizontal_flip=True, width_shift_range=0.1, height_shift_range=0.1, brightness_range=[0.5,1.5] ) datagen.fit(x_train) # Plot sample augmented images for X_batch, y_batch in datagen.flow(x_train, y_train, batch_size=9): for i in range(0, 9): plt.subplot(330 + 1 + i) plt.imshow(X_batch[i].astype(np.uint8)) plt.show() break # Creating Spectral CNN Layer class SpectralConvolution2D(tf.keras.layers.Layer): def __init__(self, filters, kernel_size,strides,padding,**kwargs): self.no_of_kernels = filters self.kernel_shape = kernel_size self.strides=strides if padding =="same": self.padding=kernel_size[0]-1 else: self.padding=0 super(SpectralConvolution2D, self).__init__(**kwargs) def build(self, input_shape): self.kernel = self.add_weight(shape=self.kernel_shape + (input_shape[-1], self.no_of_kernels),# (k_width,k_height,input channels, # kernels) (3,3,3,32) initializer='random_normal', trainable=True) self.bias = self.add_weight(shape=(self.no_of_kernels,),# 1 bias for each kernel initializer='random_normal', trainable=True) super(SpectralConvolution2D, self).build(input_shape) def call(self, inputs): out_shape = (inputs.get_shape().as_list()[1] - self.kernel.get_shape().as_list()[0] + self.padding)//self.strides[0] + 1 spatial_inputs = tf.transpose(inputs, perm=[0,3,1,2]) spatial_kernel = tf.transpose(self.kernel, perm=[3,2,0,1]) # Converting the inputs and kernel into spectral domain spectral_inputs = tf.signal.rfft2d(spatial_inputs, [out_shape, out_shape]) spectral_kernel = tf.signal.rfft2d(spatial_kernel, [out_shape, out_shape]) # Convolution in the spectral domain spectral_convolution_output = tf.einsum('imkl,jmkl->ijkl', spectral_inputs, spectral_kernel) # Converting the output in spectral domain back to spatial domain spatial_convolution_output = tf.signal.irfft2d(spectral_convolution_output, [out_shape, out_shape]) spatial_convolution_output = tf.transpose(spatial_convolution_output, perm=[0,2,3,1]) spatial_convolution_output = tf.nn.bias_add(spatial_convolution_output, self.bias) return spatial_convolution_output # Generic CNN architecture def spectralConvolutionCNN(): model = Sequential() model.add(SpectralConvolution2D(96, kernel_size=(3,3),padding="same", strides=(1,1), input_shape=input_shape)) model.add(MaxPooling2D(pool_size=(3,3),strides=(2,2))) model.add(SpectralConvolution2D(192, kernel_size=(3,3),padding="same",strides=(1,1))) model.add(MaxPooling2D(pool_size=(3,3),strides=(2,2))) model.add(Flatten()) model.add(Dense(1024)) model.add(Dense(512)) model.add(Dense(output_size, activation='softmax')) return model # Compiling and training the model batch_size=128 nb_epochs=50 train_generator = datagen.flow(x_train, y_train, batch_size=batch_size) valid_generator = datagen.flow(x_test, y_test, batch_size=batch_size) spectral_cnn_model = spectralConvolutionCNN() spectral_cnn_model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) history=spectral_cnn_model.fit_generator(train_generator,epochs=nb_epochs,steps_per_epoch=len(x_train)//batch_size, validation_data=valid_generator)
0.795181
0.586079