code
stringlengths
38
801k
repo_path
stringlengths
6
263
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # + # small Austin Area import anuga import numpy cache = False verbose = True # Define Scenario # the final goal is to define a rainfall scenario # Here, in order to test, we follow the example to first have a fixed wave scenario scenario = 'fixed_wave' name_stem = 'aw_small' meshname = name_stem + '.msh' gage_file_name = 'aw_small_gauges.csv' # bounding polygon for study area bounding_polygon = anuga.read_polygon('aw_small_extent.csv') A = anuga.polygon_area(bounding_polygon) / 1000000.0 print 'Area of bounding polygon = %.2f km^2' % A # Read interior polygons #poly_river = anuga.read_polygon('aw_small_river.csv') # the greater the base_scale is the less the triangle it will be divided into just_fitting = False base_scale = 5000 background_res = 10000 river_res = base_scale city_res = base_scale #interior_regions = [[poly_river,river_res]] tide = 0.0
floodsimulation/GISdata&mesh/Untitled.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- import pandas as pd import seaborn as sns import matplotlib.pyplot as plt p2data = pd.read_csv("/Users/emmagueorguieva/git/pythontutorials/wageGenderEduAge.csv") display(p2data) plot = sns.displot(p2data, x="wage", hue="gender", kind="kde", fill= True, alpha= 0.2) plot.set(xlabel = "Wage") plt.title('Wage Distribution By Sex') sns.set_style("white") # This KDE plot is showing us that male and female pay distribution is not equal (if it would equal, they would overlap perfectly), and the slight right shift of the male distribution is showing that males receive higher wages. plot = sns.lmplot(data=p2data, x='education', y='wage', hue='gender') plot.set(xlabel = "Education") plot.set(ylabel = "Wage") plt.title('Education VS Wage By Sex') sns.set_style("white") # Looking at this plot comparing education level and wages between sexes, the linear models show that males make higher wages, even with less education. Consistently, no matter how many years of education they received, males made more than females. Females appear to catch up slightly at around 18 years, or at a graduate degree such as a pHD. However, according to this plot, while females may get closer to equal wages with more education they still consistently make less than males. plot = sns.lmplot(data=p2data, x='age', y='wage', hue='gender') plot.set(xlabel = "Age") plot.set(ylabel = "Wage") plt.title('Age VS Wage By Sex') sns.set_style("white") # Now looking at these second linear models comparing age and wage by sex doesn't look promising either. The lines are close together at first, indicating that males and females start off with almost the same wages at around age 20 (although still not totally equal, the male line is *still* above the female line which means males consistently are making more than females at all ages). However, the lines diverge fairly quickly, showing that males make more and more money as they age compared to females, who make a relatively stable wage even as they age. # All of these figures come together to show that there is a wage gap between sexes that favors men, which means that the world still has a lot of progress to make concerning sex equality. At the same age and education level, women make substantially less than men seemingly for only being...women. This is an extremely important issue that needs to be addressed.
Project2.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: 'Python 3.7.9 64-bit (''.venv'': venv)' # name: python3 # --- # + slideshow={"slide_type": "slide"} import course;course.header() # - course.display_topics(day=5) # + [markdown] slideshow={"slide_type": "slide"} # # Test Driven Development # - # # ## You all are already do some part of test driven development! # # <img style="right" src="./images/tdd_already.jpg"> # + [markdown] slideshow={"slide_type": "slide"} # ## TDD # Test driven development comes in three blocks. # # <img style="right" src="./images/tdd_explained.png" width=700> # # a) you start thinking about what you want to code, write a test that will fail and then start writing the code to make the test pass. At this stage you have a working prototype and leave the first block (blue dotted line) # # b) you will write more tests covering foreseeable corner cases. If the test fail you adjust your code. After the tests pass you will leave the second block behind having a real product with test. # # c) Finally you start refactoring your code into the bigger picture. The tests will give you confidence that nothing breaks while you refactor. This step becomes essential when you tackle a similar problem or consolidate functionality in your core package. After that, you leave the third block and your code is maintainable, reusable and generalized in a bigger context. # + [markdown] slideshow={"slide_type": "subslide"} # Advantages are # * think before coding. In a later stage you will think where the code will sit, how it wil work with the rest of your code base. # * you will write tests before actually start coding on the solution (ie you will have tests at the end of the dev phase) # * Forces you to write smaller functions that so TDD enforces the Zen of Python and general* coding philosophy # * Explicit is better than implicit. # * Simple is better than complex. # * Complex is better than complicated. # * a function should do one thing and one thing only # # # + [markdown] slideshow={"slide_type": "slide"} # In order to do so, we need to # * fork the advanced_python_repo (so you can commit you code to your repo) # * prepare some folders in your repo using this ... # * if you can, switch to terminal and activate our virtualenv # - # ### Create folder structure # + slideshow={"slide_type": "subslide"} """ <NAME> !mkdir ../peak_finder !mkdir ../tests !mkdir ../docs """ # - from pathlib import Path Path("../peak_finder").mkdir(exist_ok=True) Path("../tests").mkdir(exist_ok=True) Path("../docs").mkdir(exist_ok=True) # + [markdown] slideshow={"slide_type": "subslide"} # You should have a dir structure like this: # # ├── LICENSE # ├── README.md # ├── data # │   ├── ... # ├── docs # ├── notebooks # │   ├── ... # ├── peak_finder # └── tests # # - # ### Install pytest! # !pip install --upgrade pip # !pip install pytest # you need to restart VSCode :/ # ### Create basic peak_finder place holders # + slideshow={"slide_type": "slide"} # %%writefile ../peak_finder/__init__.py # __init__ py is required in a folder # to be recognized as a python module # otherwise the import statements won't work # the %%writefile magic allows the jupyter cell content to be stored as a file # lets load core into the name space as well from . import basic # - # %%writefile ../peak_finder/basic.py # # The first version of our function! # Write doc strings # def find_peaks(list_of_intensities): """Find peaks Find local maxima for a given list of intensities or tuples Intensities are defined as local maxima if the intensities of the elements in the list before and after are smaller than the peak we want to determine. For example given a list: 1 5 [6] 4 1 2 [3] 2 We expect 6 and 3 to be returned. Args: list_of_intensities (list of floats, ints or tuple of ints): a list of numeric values Returns: list of floats or tuples: list of the identified local maxima Note: This is just a place holder for the TDD part :) """ return # ### Write first test! # + # %%writefile ../tests/test_basic.py import sys from pathlib import Path # -------- START of inconvenient addon block -------- # This block is not necessary if you have installed your package # using e.g. pip install -e (requires setup.py) # or have a symbolic link in your sitepackages (my preferend way) sys.path.append( str(Path(__file__).parent.parent.resolve()) ) # It make import peak_finder possible # This is a demo hack for the course :) # -------- END of inconvenient addon block -------- import peak_finder def test_find_peaks(): peaks = peak_finder.basic.find_peaks([0, 2, 1]) assert peaks == [2] # - # <image src="./images/VSCode/tdd_first_fail.png"> # ## Fix it! # + [markdown] slideshow={"slide_type": "slide"} # ## Now let's go into the first (second) iterations # - # ### on the path to our first product # # <img style="right" src="images/tdd_explained.png" width=800> # + [markdown] slideshow={"slide_type": "slide"} # ## Now let's make it brilliant # - # # Let's say we are happy with our *product* and got "rich". # # Now why do we need to refactor? # # * Not to have our code exist in "peak_finder" but move it into our *work horse* package # * The moment the definition of list_of_intensities is altered, we would # * restart the TDD process at the start # * remember that both function do something similar so we could ultimately merge their code # + [markdown] slideshow={"slide_type": "slide"} # ## Lets go into the third iteration # - # # ### case find_peaks in a vector filled with colors # # Colors are defined as (e.g.) red-green-blue (RGB) tuples. So (0, 0, 0) is black and (255, 255, 255) is white. # # <img src="https://www.alanzucconi.com/wp-content/uploads/2015/09/colours.png"> # # And let's not go too deep into the beautiful world of [sorting colors by <NAME>](https://www.alanzucconi.com/2015/09/30/colour-sorting/) and let's just say # (20,0,0) > (0,19,0) so we sum-up the values in the tuples and feed it into our function, but this time we look for dark spots, that we want to identify as "peaks". # # ### Write a second function! # # ### What could refactoring look like ? # # Automation is key! # We want out test to run everytime a pull request is opened on github. # Github actions enable automatic tasks upon different actions to be triggered. Read more about it [here](https://github.com/features/actions) # # github actions are defined as yaml files and are placed under .github/workflows # # # !mkdir -p ../.github/workflows from pathlib import Path Path("../.github").mkdir(exist_ok = True) Path("../.github/workflows").mkdir(exist_ok = True) # + # %%writefile ../.github/workflows/pytest.yml name: pytest with codecov #wenn jemand pull request macht, dann mache on: pull_request: types: [opened, synchronize, reopened, edited] jobs: build: name: Run Python Tests runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 with: fetch-depth: 2 - name: Set up Python 3.9 uses: actions/setup-python@v2 with: python-version: 3.9 - name: Install Python dependencies run: | sudo apt install -y $(grep -o ^[^#][[:alnum:]-]* "packages.list") python3 -m pip install --upgrade pip pip3 install -r requirements.txt - name: Test with pytest run: | pytest --exitfirst --verbose --failed-first \ --cov=. --cov-report xml - name: Upload Coverage to Codecov uses: codecov/codecov-action@v2 with: token: ${{ secrets.CODECOV_TOKEN }} # not required for public repos # - # If you have a private repo, you need to add a settings > secrets name CODECOV_TOKEN, which you can get from codecov.io - register with your github account. # After you pushed to you repo, you should have new action! # + [markdown] slideshow={"slide_type": "slide"} # # Documentation to our peak_finder is important # - # ## Auto documentation using Sphinx! # # "Sphinx is a tool that makes it easy to create intelligent and beautiful documentation, written by <NAME> and licensed under the BSD license. # # It was originally created for the Python documentation, and it has excellent facilities for the documentation of software projects in a range of languages. Of course, this site is also created from reStructuredText sources using Sphinx! The following features should be highlighted:" # # [Website](http://www.sphinx-doc.org/en/master/) # !pip install sphinx # + [markdown] slideshow={"slide_type": "subslide"} # Quickstart, open terminal and # ``` bash # $ cd docs # ``` # # **NOTE:** Personally, I do not like the docs to clutter my project dir with different files but to have everything contained in the docs folder # # ``` bash # fu@mPro:~/dev/_teaching/advanced_python_2021-22_HD_pre/docs # 5 main $ sphinx-quickstart .venv [13:32:11] # Welcome to the Sphinx 4.2.0 quickstart utility. # # Please enter values for the following settings (just press Enter to # accept a default value, if one is given in brackets). # # Selected root path: . # # You have two options for placing the build directory for Sphinx output. # Either, you use a directory "_build" within the root path, or you separate # "source" and "build" directories within the root path. # > Separate source and build directories (y/n) [n]: y # # The project name will occur in several places in the built documentation. # > Project name: peak_finder # > Author name(s): <NAME> # > Project release []: alpha # # If the documents are to be written in a language other than English, # you can select a language here by its language code. Sphinx will then # translate text that it generates into that language. # # For a list of supported codes, see # https://www.sphinx-doc.org/en/master/usage/configuration.html#confval-language. # > Project language [en]: # # Creating file /Users/fu/dev/_teaching/advanced_python_2021-22_HD_pre/docs/source/conf.py. # Creating file /Users/fu/dev/_teaching/advanced_python_2021-22_HD_pre/docs/source/index.rst. # Creating file /Users/fu/dev/_teaching/advanced_python_2021-22_HD_pre/docs/Makefile. # Creating file /Users/fu/dev/_teaching/advanced_python_2021-22_HD_pre/docs/make.bat. # # Finished: An initial directory structure has been created. # # You should now populate your master file /Users/fu/dev/_teaching/advanced_python_2021-22_HD_pre/docs/source/index.rst and create other documentation # source files. Use the Makefile to build the docs, like so: # make builder # where "builder" is one of the supported builders, e.g. html, latex or linkcheck. # ``` # + [markdown] slideshow={"slide_type": "subslide"} # Now let's make the first documentation # ```bash # make html # open build/html/index.html # ``` # + [markdown] slideshow={"slide_type": "subslide"} # Sphinx does not know anything about our project yet so we have to edit # **docs/source/conf.py** you will find # - # # ``` python # # If extensions (or modules to document with autodoc) are in another directory, # # add these directories to sys.path here. If the directory is relative to the # # documentation root, use os.path.abspath to make it absolute, like shown here. # # # # import os # # import sys # # sys.path.insert(0, os.path.abspath('.')) # ``` # that block in the beginning of the conf file, uncomment it and edit the sys.path so the module can be found # ``` python # dir_path = os.path.join( # os.path.dirname(__file__), # os.pardir, # os.pardir, # ) # sys.path.insert(0, os.path.abspath(dir_path)) # ``` # + [markdown] slideshow={"slide_type": "subslide"} # Additionally, let's make sphinx understand google and numpy docstring! Edit # **docs/source/conf.py** again and add the napoleon extention to the extentions # ``` python # extensions = [ # 'sphinx.ext.napoleon', # ] # ``` # + [markdown] slideshow={"slide_type": "subslide"} # Wonder what so special about google's docstring ? # # *Regular* # ``` # :param path: The path of the file to wrap # :type path: str # :param field_storage: The :class:`FileStorage` instance to wrap # :type field_storage: FileStorage # :param temporary: Whether or not to delete the file when the File # instance is destructed # :type temporary: bool # :returns: A buffered writable file descriptor # :rtype: BufferedFileStorage # ``` # # *Google python style* # ``` # Args: # path (str): The path of the file to wrap # field_storage (FileStorage): The :class:`FileStorage` instance to wrap # temporary (bool): Whether or not to delete the file when the File # instance is destructed # # Returns: # BufferedFileStorage: A buffered writable file descriptor # ``` # # For more details, see [here](https://www.sphinx-doc.org/en/1.5/ext/example_google.html) # + [markdown] slideshow={"slide_type": "subslide"} # So now let's build again! # ```bash # make html # ``` # # # - # %pwd # %cd '/Users/fu/dev/teaching/advanced_python_2020-21_HD_pre/docs' # + slideshow={"slide_type": "subslide"} # !make html # + [markdown] slideshow={"slide_type": "subslide"} # ### Nothing to see because we have not added our module yet! # # Let's edit docs/source/index.rst # + [markdown] slideshow={"slide_type": "subslide"} # ``` # .. playground documentation master file, created by # sphinx-quickstart on Sun Oct 13 15:39:43 2019. # You can adapt this file completely to your liking, but it should at least # contain the root `toctree` directive. # # Welcome to playground's documentation! # ========================================= # # .. toctree:: # :maxdepth: 2 # :caption: Contents: # # core # # # Indices and tables # ================== # # * :ref:`genindex` # * :ref:`modindex` # * :ref:`search` # ``` # # **I added core to the toctree!** # # # + [markdown] slideshow={"slide_type": "subslide"} # and **docs/source/basic.rst** looks like: # ``` # .. _basic.rst: # # Basic module # ============ # # .. automodule:: peak_finder.basic # :members: # :undoc-members: # ``` # # This is sufficient to have all functions in this module to be parsed and included in this documentation. # # The *:undoc-members:* helps to find all functions, even the ones that have no documentation. # # # # + [markdown] slideshow={"slide_type": "subslide"} # Now rerun the documentation building procedure # ``` bash # make html # ``` # - # !make html;open build/html/index.html # # # Summary # # * Use test driven development! Because you do it already but you do not record it! # * Write good doc strings! Use Google style for clarity! # * Create a Sphinx documentation because it will help you not only to auto generate latest documentation but also create pdfs and have it hosted on readthedocs.org # * Automation is key # # # Exercise # # * Write tests to you Protein class # * Add actions to your github account that tests the Protein class # * Try to auto generate sphinx documentation using github actions #
notebooks/05.a.Test_driven_development.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Gerando informações para a apresentação (fotocorrente) # # Este notebook não possui nenhuma informação especial. # Serve apenas de auxílio na geração das imagens utilizadas para animação. # Só separamos por ser muito pesado. # + init_cell=true # python standard import os import time import re from multiprocessing import Pool, TimeoutError from datetime import datetime # third-party import numpy as np import pandas as pd import scipy.constants as cte from scipy.integrate import simps from scipy.sparse import diags from scipy.linalg import inv from scipy.fftpack import fft, ifft, fftfreq from scipy.stats import norm, skewnorm from scipy.spatial.distance import cdist from sklearn.preprocessing import StandardScaler from scipy.special import legendre, expit from scipy.signal import gaussian # locals from core.utilidades import * # + init_cell=true import locale locale.setlocale(locale.LC_NUMERIC, "pt_BR.UTF-8") import matplotlib.style import matplotlib as mpl mpl.style.use('classic') # %matplotlib inline import matplotlib.pyplot as plt from matplotlib.ticker import MultipleLocator plt.style.use('mestrado') # + init_cell=true # ## Constantes físicas au_l = cte.value('atomic unit of length') au_t = cte.value('atomic unit of time') au_e = cte.value('atomic unit of energy') au_v = cte.value('atomic unit of electric potential') au_ef = cte.value('atomic unit of electric field') me = cte.value('electron mass') c = cte.value('speed of light in vacuum') q = cte.value('elementary charge') hbar_ev = cte.value('Planck constant over 2 pi in eV s') hbar = cte.value('Planck constant over 2 pi') h = cte.value('Planck constant') ev = cte.value('electron volt') # outras relacoes de interesse au2ang = au_l / 1e-10 au2ev = au_e / ev hbar_au = 1.0 me_au = 1.0 # onda plana grid_tempo = np.linspace(0.0, 2.1739442773545673e-14, 20) alias = { 'Solucao Analitica': '', 'Pseudo-Espectral': 'pe', 'Crank-Nicolson': 'cn', 'Runge-Kutta': 'rk' } metodos = list(alias.keys()) parametros = { 'onda_plana_parametro_bom': { 'L': 100.0, 'N': 1024, 'dt': 1e-18 }, 'onda_plana_parametro_ruim': { 'L': 850.0, 'N': 256, 'dt': 1e-16 } } # - # # Gerando fotocorrente # + init_cell=true # dataframe de pandas com valores utilizados para calculos device = pd.DataFrame() N = 1024 # tamanho padrao do grid L = 1000.0 # tamanho padrao do sistema em angstrom dt = 1e-17 # incremento de tempo padrao em segundos device['z_ang'] = np.linspace(-L/2, L/2, N) # malha espacial em angstrom # + init_cell=true def algaas_gap(x): """Retorna o gap do material ja calculado em funcao da fracao de Aluminio utilizamos os valores exatos utilizados pelos referidos autores Params ------ x : float a fracao de aluminio, entre 0 e 1 Returns ------- O gap em eV """ if x == 0.2: return 0.0 elif x == 0.4: return 0.185897 return -0.185897 def algaas_meff(x): """Retorna a massa efetiva do AlGaAs em funcao da fracao de Aluminio assim como os referidos autores, utilizamos a massa efetiva do eletron no GaAs ao longo de todo o material Params ------ x : float a fracao de aluminio, entre 0 e 1 Returns ------- A massa efetiva do eletron no AlGaAs """ return 0.067 def x_shape(z): """Utilizamos a concentracao de Aluminio para determinar o perfil do potencial Params ------ z : float posicao no eixo z em angstrom Returns ------- A concentracao de Aluminio na posicao informada """ # concentracoes e larguras do sistema xd = 0.2 # concentracao no espaco entre poco e barreira xb = 0.4 # concentracao na barreira xw = 0.0 # concentracao no poco wl = 50.0 # largura do poco em angstrom bl = 50.0 # largura da barreira em angstrom dl = 40.0 # espacao entre poco e barreira em angstrom if np.abs(z) < wl/2: return xw elif np.abs(z) < wl/2+dl: return xd elif np.abs(z) < wl/2+dl+bl: return xb return xd # + init_cell=true device['x'] = device['z_ang'].apply(x_shape) device['v_ev'] = device['x'].apply(algaas_gap) device['meff'] = device['x'].apply(algaas_meff) pb = list(device['v_ev']).index(0.185897) # pontos antes do dispositivo pa = N-1-pb # pontos depois do dispositivo # - ax = device.plot(x='z_ang', y='v_ev', grid=True, legend=False) ax.set_xlabel(r'$z$ (\AA)') ax.set_ylabel(r'Energia (eV)') plt.savefig('figuras/poco_dupla_barreira_potencial_simples.png') # + z = np.linspace(-L/2,L/2,N) killer_1 = 0.175 * np.array([min(l,r) for l,r in zip(expit((450-z)/5), expit((z+450)/5))]) killer_2 = 0.175 * np.array([min(l,r) for l,r in zip(expit((250-z)/3), expit((z+250)/3))]) fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True) ax1.set_xlabel(r'$z (\AA)$') ax1.set_ylabel(r'Energia (eV)') ax1.plot(device.z_ang, killer_1) ax1.plot(device.z_ang, device.v_ev) # ax1.xaxis.set_minor_locator(MultipleLocator(50)) # ax1.yaxis.set_minor_locator(MultipleLocator(0.2)) # ax1.set_ylim([-0.05, 1.05]) # ax1.grid(which = 'minor') ax2.set_xlabel(r'$z (\AA)$') ax2.set_ylabel(r'Energia (eV)') ax2.plot(device.z_ang, killer_2) ax2.plot(device.z_ang, device.v_ev) # ax2.xaxis.set_minor_locator(MultipleLocator(50)) # ax2.yaxis.set_minor_locator(MultipleLocator(0.2)) # ax2.set_ylim([-0.05, 2.05]) # ax2.grid(which = 'minor') plt.grid(True) plt.savefig('figuras/poco_dupla_barreira_potencial_simples_com_absordedor.png') # + init_cell=true bias = 5.0 # KV/cm LIGAR NO CASO DE FOTOCORRENTE bias_v_cm = bias * 1e3 bias_v_m = 1e2 * bias_v_cm bias_j_m = bias_v_m * q def __constroi_bias(z): """constroi o potencial estatico usado como bias/vies, nao usar fora desta celula Params ------ z : float uma posicao no grid em angstrom Returns ------- O bias na posicao indicada """ border_left = device['z_ang'].values[pb] border_right = device['z_ang'].values[pa] def f_st_ev(z): return -(z*1e-10)*(bias_j_m)/ev if z <= border_left: return f_st_ev(border_left) elif z >= border_right: return f_st_ev(border_right) return f_st_ev(z) device['bias_ev'] = device['z_ang'].apply(__constroi_bias) device['v_st_ev'] = device['v_ev']+device['bias_ev'] # - ax = device.plot(x='z_ang', y='v_st_ev', grid=True, legend=False) ax.set_xlabel(r'$z$ (\AA)') ax.set_ylabel(r'Energia (eV)') plt.savefig('figuras/poco_dupla_barreira_potencial_com_bias.png') # + init_cell=true device['z_au'] = device['z_ang'].apply(lambda z: z / au2ang) device['v_au'] = device['v_st_ev'].apply(lambda z: z / au2ev) dt_au = dt / au_t # + init_cell=true def solve_eigenproblem(H): """ Solve an eigenproblem and return the eigenvalues and eigenvectors. """ vals, vecs = np.linalg.eig(H) idx = np.real(vals).argsort() vals = vals[idx] vecs = vecs.T[idx] return vals, vecs dev = device.copy() dz = dev['z_au'][1]-dev['z_au'][0] dz2 = dz**2 V = dev['v_au'].values m = dev['meff'].values z = dev['z_au'].values v_ev = V*au2ev z_ang = z*au2ang # Desloca o potencial do Hamiltoniano por shift sub_diag = np.zeros(N-1, dtype=np.complex_) main_diag = np.zeros(N, dtype=np.complex_) # constroi as diagnais da matriz, a principal e as duas semi # principais for i in range(N): try: main_diag[i] = (0.5/dz2)*(1.0/idf(m, i+0.5) + 1.0/idf(m, i-0.5))+(V[i]) except: main_diag[i] = 0.0 if i < N-1: sub_diag[i] = -(0.5/dz2)*(1.0/idf(m, i+0.5)) diagonals = [main_diag, sub_diag, sub_diag] A = diags(diagonals, [0, -1, 1]).toarray() res = solve_eigenproblem(A) # + autovalores = res[0][0:16] res2 = interacao_inversa(z, V, m, autovalores=autovalores, remover_repetidos=False) autovalores = np.copy(res2['autovalores']) autovetores = np.copy(res2['autovetores']) fig, ax = plt.subplots() ax.plot(z_ang, v_ev, label=r"$V(z)$") for i, vec in enumerate(autovetores): vec /= np.sqrt(simps(vec*vec.conj(),z_ang)) vec2 = 2*np.abs(vec)**2+autovalores[i]*au2ev ax.plot(z_ang, vec2) ax.set_xlabel(r'$z$ (\AA)') ax.set_ylabel(r'Energia (eV)') plt.legend() plt.savefig('figuras/poco_dupla_barreira_potencial_func_onda_tudo.png') plt.show() # - autovalores = res[0][[0,7,14]] res2 = interacao_inversa(z, V, m, autovalores=autovalores) autovalores = np.copy(res2['autovalores']) autovetores = np.copy(res2['autovetores']) # + fig, ax = plt.subplots() ax.plot(z_ang, v_ev, label=r"$V(z)$") for i, vec in enumerate(autovetores): vec /= np.sqrt(simps(vec*vec.conj(),z_ang)) vec2 = 2*np.abs(vec)**2+autovalores[i]*au2ev ax.plot(z_ang, vec2)#, label=r'$|\psi_{}(z)|^2$'.format(i)) ax.text(-400, autovalores[i]*au2ev+0.01, r'$|\psi_{}(z)|^2$'.format(i)) ax.set_xlabel(r'$z$ (\AA)') ax.set_ylabel(r'Energia (eV)') plt.legend() plt.savefig('figuras/poco_dupla_barreira_potencial_func_onda.png') plt.show() # + fig, ax = plt.subplots() ax.plot(z_ang, v_ev, label=r"$V(z)$") for i, vec in enumerate(autovetores[0:1]): vec /= np.sqrt(simps(vec*vec.conj(),z_ang)) vec2 = vec/2+autovalores[i]*au2ev ax.plot(z_ang, vec2)#, label=r'$|\psi_{}(z)|^2$'.format(i)) ax.text(-400, autovalores[i]*au2ev+0.01, r'$\psi(z,0) = \psi_{}(z)$'.format(i)) ax.set_xlabel(r'$z$ (\AA)') ax.set_ylabel(r'Energia (eV)') plt.legend() plt.savefig('figuras/poco_dupla_barreira_potencial_func_onda_inicial.png') plt.show() # + energy = 0.15317725752508362658 fosc=5.0 T=1e-12 fosc_j_m = fosc * 1e2 * 1e3 * q # KV/cm -> J/m T_au = T / au_t iters = int(T_au / dt_au) z_au = device.z_au.values t_grid_au = np.linspace(0.0, T_au, iters) psi = np.array(autovetores[0], dtype=np.complex_) psi /= np.sqrt(simps(psi*psi.conj(), device.z_au)) meff = device['meff'].values z_au = device['z_au'].values dz_au = z_au[1]-z_au[0] k_au = fftfreq(N, d=dz_au) j_t = np.zeros(iters) def j_p(p): """J=1/(2 i m*) (psi* d(psi)/dz - psi d(psi*)/dz) """ dzp = z_au[p+1]-z_au[p-1] pcdp = psi[p].conj() * (psi[p+1]-psi[p-1]) / dzp pdpc = psi[p] * (psi[p+1].conj()-psi[p-1].conj()) / dzp return ((-0.5j/(meff[p])) * (pcdp-pdpc)).real absorbing = device['z_ang'].apply( lambda z: min(expit((450-z)/5), expit((z+450)/5))) absorbing = absorbing.values z0_ang = device['z_ang'].values[0] fosc_j = device['z_ang'].apply(lambda z: (z0_ang-z) * 1e-10 * fosc_j_m) fosc_j = device['z_ang'].apply(lambda z: z * 1e-10 * fosc_j_m) fosc_ev = fosc_j / ev fosc_au = fosc_ev / au2ev omega_au = (energy / au2ev) / hbar_au v_au_ti = device['v_au'].values exp_t = np.exp(- 0.5j * (2 * np.pi * k_au) ** 2 * dt_au / meff) #exp_v2h = np.exp(- 0.5j * v_au_ti * dt_au) exp_v2h = np.exp(- 1.0j * v_au_ti * dt_au) #f_espec = - 0.5j * fosc_au * dt_au f_espec = - 1.0j * fosc_au * dt_au # - j = 1 for i, t_au in enumerate(t_grid_au[0:10000]): if i % 10 == 0 or i == len(t_grid_au) - 1: fig, ax = plt.subplots() pot = (v_au_ti + fosc_au * np.sin(omega_au * t_au))*au2ev ax.plot(z_ang, pot, label=r"$V'(z)+e F_\mathrm{osc} \sin(\omega t)$") ax.set_title(r"t = " + r"${}$ s".format(as_si(t_au * au_t, 2)), fontsize=16) ax.set_xlabel(r'$z$ (\AA)') ax.set_ylabel(r'Energia (eV)') ax.set_xlim(-600.0, 600.0) ax.set_ylim(-0.25, 0.2) plt.savefig('apresentacao/saidas/poco_dupla_barreira_potencial_osc_{0:04d}.png'.format(j)) plt.legend(loc='lower left') plt.close('all') j += 1 # + sub_diag = np.zeros(N-1, dtype=np.complex_) for i in range(N): if i < N-1: sub_diag[i] = -(0.5/dz2)*(1.0/idf(m, i+0.5)) j = 1 norma_0 = np.sqrt(simps(psi*psi.conj(),z_ang)).real for i, t_au in enumerate(t_grid_au): exp_v2 = exp_v2h * np.exp(f_espec * np.sin(omega_au*t_au)) psi = ifft(exp_t * fft(exp_v2 * psi)) * absorbing if i % 150 == 0 or i == len(t_grid_au) - 1: fig, ax = plt.subplots() pot = (v_au_ti + fosc_au * np.sin(omega_au * t_au)) ax.plot(z_ang, pot * au2ev, label=r"$V''(z, t)$") norma = np.sqrt(simps(psi*psi.conj(),z_ang)).real vec = psi / norma # Desloca o potencial do Hamiltoniano por shift main_diag = np.zeros(N, dtype=np.complex_) # constroi as diagnais da matriz, a principal e as duas semi # principais main_diag = np.array([(0.5/dz2)*(1.0/idf(m, i+0.5) + 1.0/idf(m, i-0.5))+(pot[i]) for i in range(N)], dtype=np.complex_) diagonals = [main_diag, sub_diag, sub_diag] H = diags(diagonals, [0, -1, 1]).toarray() autoval = simps(psi.conj() * (H.dot(psi)), z_au).real * au2ev vec2 = psi/2 + autoval ax.plot(z_ang, vec2, label=r"$\psi(z,t)$") ax.text(-550.0, 0.15, r"t = " + r"${}$ s".format(as_si(t_au * au_t, 2))) ax.text(-550.0, 0.10, r"$\int \, dz \, |\psi(z,t)|^2 = " + dummy_comma("{:.1f}$ %".format(100*norma/norma_0))) ax.text(-550.0, 0.05, r"$\langle E \rangle = " + dummy_comma("{:.5f}$ eV".format(autoval))) # ax.set_title(r"t = " + r"${}$ s".format(as_si(t_au * au_t, 2)), fontsize=16) ax.set_xlabel(r'$z$ (\AA)') ax.set_ylabel(r'Energia (eV)') ax.set_xlim(-600.0, 600.0) ax.set_ylim(-0.2, 0.2) plt.legend() plt.savefig('apresentacao/saidas/poco_dupla_barreira_evolucao_{0:04d}.png'.format(j)) plt.close('all') j += 1 # -
apresentacao-fotocorrente.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # <center><a href="https://www.featuretools.com/"><img src="img/featuretools-logo.png" width="400" height="200" /></a></center> # <h2> An Advanced Featuretools Approach with Custom Primitives</h2> # <p>The following tutorial illustrates an advanced featuretools model for the NYC Taxi Trip Duration competition on Kaggle using our custom primitive API. You will need to download the following five files into a `data` folder in this repository.</p> # # <h2>Step 1: Download raw data </h2> # <a href="https://www.kaggle.com/c/nyc-taxi-trip-duration/data">test.csv and train.csv</a> # # The functions used here don't appear until Featuretools version 0.1.9. If you're using a lower version you will get an error. import featuretools as ft import pandas as pd import numpy as np import taxi_utils ft.__version__ # <h2>Step 2: Prepare the Data </h2> # + TRAIN_DIR = "data/train.csv" TEST_DIR = "data/test.csv" data_train, data_test = taxi_utils.read_data(TRAIN_DIR, TEST_DIR) # - # The `fastest_routes` dataset has information on the shortest path between two coordinates in NYC. We can merge it in with our dataset here and then merge together our test and train datasets after marking them as such. # + # Make a train/test column data_train['test_data'] = False data_test['test_data'] = True # Combine the data and convert some strings data = pd.concat([data_train, data_test], sort=True) data.head(5) # - # ## Step 3: Custom Primitives # The custom primitive API is new to Featuretools version 0.1.9. Our workflow will be as follows: # 1. Make a new LatLong class which is a tuple of a latitude and longitude # 2. Define some functions for LatLong # 3. Make new primitives from those functions # # For the first step, we'll make new columns for the pickup and dropoff locations which are tuples. data["pickup_latlong"] = data[['pickup_latitude', 'pickup_longitude']].apply(tuple, axis=1) data["dropoff_latlong"] = data[['dropoff_latitude', 'dropoff_longitude']].apply(tuple, axis=1) data = data.drop(["pickup_latitude", "pickup_longitude", "dropoff_latitude", "dropoff_longitude"], axis = 1) # We can define the `pickup_latlong` to be a `LatLong` type. This is a way to tell DFS that certain primitives are only important in one direction, from the beginning of a trip to the end. # + from featuretools import variable_types as vtypes from featuretools.variable_types import LatLong trip_variable_types = { 'passenger_count': vtypes.Ordinal, 'vendor_id': vtypes.Categorical, 'pickup_latlong': LatLong, 'dropoff_latlong': LatLong, } es = ft.EntitySet("taxi") es.entity_from_dataframe(entity_id="trips", dataframe=data, index="id", time_index='pickup_datetime', variable_types=trip_variable_types) es.normalize_entity(base_entity_id="trips", new_entity_id="vendors", index="vendor_id") es.normalize_entity(base_entity_id="trips", new_entity_id="passenger_cnt", index="passenger_count") cutoff_time = es['trips'].df[['id', 'pickup_datetime']] # - # ## Visualize EntitySet es.plot() # Next, we can create primitives for our new `pickup_latlong` and `dropoff_latlong` which are of type `LatLong`. # # The distance between two `LatLong` types is most accurately represented by the Haversine distance: the nearest length along a sphere. We can also define the Cityblock distance (also called the taxicab metric), which takes into account that we can't move diagonally through buildings in Manhattan. # + from featuretools.primitives import make_agg_primitive, make_trans_primitive def haversine(latlong1, latlong2): lat_1s = np.array([x[0] for x in latlong1]) lon_1s = np.array([x[1] for x in latlong1]) lat_2s = np.array([x[0] for x in latlong2]) lon_2s = np.array([x[1] for x in latlong2]) lon1, lat1, lon2, lat2 = map(np.radians, [lon_1s, lat_1s, lon_2s, lat_2s]) dlon = lon2 - lon1 dlat = lat2 - lat1 a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2 km = 6367 * 2 * np.arcsin(np.sqrt(a)) return km def cityblock(latlong1, latlong2): lon_dis = haversine(latlong1, latlong2) lat_dist = haversine(latlong1, latlong2) return lon_dis + lat_dist def bearing(latlong1, latlong2): lat1 = np.array([x[0] for x in latlong1]) lon1 = np.array([x[1] for x in latlong1]) lat2 = np.array([x[0] for x in latlong2]) lon2 = np.array([x[1] for x in latlong2]) delta_lon = np.radians(lon2 - lon1) lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2]) x = np.cos(lat2) * np.sin(delta_lon) y = np.cos(lat1) * np.sin(lat2) - np.sin(lat1) * np.cos(lat2) * np.cos(delta_lon) return np.degrees(np.arctan2(x, y)) # - # We can also make some primitives directly from `LatLong` types. In particular, we'll almost certainly want to extract the Latitude, the Longitude and the central point between two such coordinates. # <p>Now lets make primitives from those functions!</p> # + Bearing = make_trans_primitive(function=bearing, input_types=[LatLong, LatLong], commutative=True, return_type=vtypes.Numeric) Cityblock = make_trans_primitive(function=cityblock, input_types=[LatLong, LatLong], commutative=True, return_type=vtypes.Numeric) # + def is_rush_hour(datetime): hour = pd.DatetimeIndex(datetime).hour return (hour >= 7) & (hour <= 11) def is_noon_hour(datetime): hour = pd.DatetimeIndex(datetime).hour return (hour >= 11) & (hour <= 13) def is_night_hour(datetime): hour = pd.DatetimeIndex(datetime).hour return (hour >= 18) & (hour <= 23) RushHour = make_trans_primitive(function=is_rush_hour, input_types=[vtypes.Datetime], return_type = vtypes.Boolean) NoonHour = make_trans_primitive(function=is_noon_hour, input_types=[vtypes.Datetime], return_type = vtypes.Boolean) NightHour = make_trans_primitive(function=is_night_hour, input_types=[vtypes.Datetime], return_type = vtypes.Boolean) # - # We have grouped together some times of day with `RushHour`, `NoonHour` and `NightHour`. # + from featuretools.primitives import TransformPrimitive from featuretools.variable_types import Boolean, LatLong class GeoBox(TransformPrimitive): name = "GeoBox" input_types=[LatLong] return_type=Boolean def __init__(self, bottomleft, topright): self.bottomleft = bottomleft self.topright = topright def get_function(self): def geobox(latlong, bottomleft=self.bottomleft, topright=self.topright): lat = np.array([x[0] for x in latlong]) lon = np.array([x[1] for x in latlong]) boxlats = [bottomleft[0],topright[0]] boxlongs = [bottomleft[1], topright[1]] output = [] for i, name in enumerate(lat): if (min(boxlats) <= lat[i] and lat[i] <= max(boxlats) and min(boxlongs) <= lon[i] and lon[i] <= max(boxlongs)): output.append(True) else: output.append(False) return output return geobox def generate_name(self, base_feature_names): return u"GEOBOX({}, {}, {})".format(base_feature_names[0], str(self.bottomleft), str(self.topright)) # - # The feature `Geobox` finds if a latlong is in a rectangle defined by two coordinate pairs. # ## Step 4: Using custom primitives in DFS # Let's see what features are created if we run DFS now: # + agg_primitives = [] trans_primitives = [Bearing, Cityblock, GeoBox(bottomleft=(40.62, -73.85), topright=(40.70, -73.75)), GeoBox(bottomleft=(40.70, -73.97), topright=(40.77, -73.9)), RushHour, NoonHour, NightHour] # calculate feature_matrix using deep feature synthesis features = ft.dfs(entityset=es, target_entity="trips", trans_primitives=trans_primitives, agg_primitives=agg_primitives, drop_contains=['trips.test_data'], verbose=True, cutoff_time=cutoff_time, approximate='36d', max_depth=3, max_features=40, features_only=True) features # - # Our new features were applied exactly where they should be! The distances were only calcuated between the pickup_latlong and the dropoff_latlong, while primitives like `LATITUDE` were calculated on both latlong columns. # # For this dataset, we have approximately 2 million distinct cutoff times, times at which DFS will have to recalculate aggregation primitives. Calculating those features at specific times every hour and using that number instead will save computation time and perhaps not lose too much information. The `approximate` parameter in DFS lets you specify a window size to use when approximating. # # With the features from before, we calculate the whole feature matrix: # + agg_primitives = ['Sum', 'Mean', 'Median', 'Std', 'Count', 'Min', 'Max', 'Num_Unique', 'Skew'] trans_primitives = [Bearing, Cityblock, GeoBox(bottomleft=(40.62, -73.85), topright=(40.70, -73.75)), GeoBox(bottomleft=(40.70, -73.97), topright=(40.77, -73.9)), RushHour, NoonHour, NightHour, 'Day', 'Hour', 'Minute', 'Month', 'Weekday', 'Week', 'Is_weekend'] # this allows us to create features that are conditioned on a second value before we calculate. es.add_interesting_values() # calculate feature_matrix using deep feature synthesis feature_matrix, features = ft.dfs(entityset=es, target_entity="trips", trans_primitives=trans_primitives, agg_primitives=agg_primitives, drop_contains=['trips.test_data'], verbose=True, cutoff_time=cutoff_time, approximate='36d', max_depth=4) feature_matrix.head() # - # ## Step 5: Build the Model # <p>As before, we need to retrieve our labels for the train dataset, so we should merge our current feature matrix with the original dataset. </p> # # <p>We use the `log` of the trip duration since that measure is better at distinguishing distances within the city</p> # separates the whole feature matrix into train data feature matrix, train data labels, and test data feature matrix X_train, labels, X_test = taxi_utils.get_train_test_fm(feature_matrix) labels = np.log(labels.values + 1) model = taxi_utils.train_xgb(X_train, labels) submission = taxi_utils.predict_xgb(model, X_test) submission.head(5) submission.to_csv('trip_duration_ft_custom_primitives.csv', index=True, index_label='id') # <dl> # <dt>This solution:</dt> # <dd>&nbsp; &nbsp; Received a score of 0.39256 on the Kaggle competition.</dd> # <dd>&nbsp; &nbsp; Placed 416 out of 1257.</dd> # <dd>&nbsp; &nbsp; Beat 67% of competitors on the Kaggle competition.</dd> # <dd>&nbsp; &nbsp; Had a modeling RMSLE of 0.33454</dd> # </dl> # # December 27, 2017. # # <h2>Additional Analysis</h2> # <p>Lets look at how important the features we created were for the model.</p> feature_names = X_train.columns.values ft_importances = taxi_utils.feature_importances(model, feature_names) ft_importances[:50] # + # Save output files import os try: os.mkdir("output") except: pass feature_matrix.to_csv('output/feature_matrix.csv') cutoff_time.to_csv('output/cutoff_times.csv') # - # <p> # <img src="https://www.featurelabs.com/wp-content/uploads/2017/12/logo.png" alt="Featuretools" /> # </p> # # Featuretools was created by the developers at [Feature Labs](https://www.featurelabs.com/). If building impactful data science pipelines is important to you or your business, please [get in touch](https://www.featurelabs.com/contact/).
NYC Taxi 4 - Custom Featuretools Primitives.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + id="pr2mSxr1YyxY" from sklearn.datasets import load_files import numpy as np train_dir = '../input/fruits/Fruits_1/Training' test_dir = '../input/fruits/Fruits_1/Test' def load_dataset(path): data = load_files(path) files = np.array(data['filenames']) targets = np.array(data['target']) target_labels = np.array(data['target_names']) return files,targets,target_labels x_train, y_train,target_labels = load_dataset(train_dir) x_test, y_test,_ = load_dataset(test_dir) print('Loading complete!') print('Training set size : ' , x_train.shape[0]) print('Testing set size : ', x_test.shape[0]) # + id="qM6hJfMzYzx6" no_of_classes = len(np.unique(y_train)) no_of_classes # + id="Vfu2NweUY2XM" print(y_train[0:10]) # + id="EzqEE2QIY5OW" from keras.utils import np_utils y_train = np_utils.to_categorical(y_train,no_of_classes) y_test = np_utils.to_categorical(y_test,no_of_classes) y_train[0] # + id="OHuNydniY7mf" x_test,x_valid = x_test[3500:],x_test[:3500] y_test,y_vaild = y_test[3500:],y_test[:3500] print('Vaildation X : ',x_valid.shape) print('Vaildation y :',y_vaild.shape) print('Test X : ',x_test.shape) print('Test y : ',y_test.shape) # + id="cDBXHJVhY-fG" from keras.preprocessing.image import array_to_img, img_to_array, load_img def convert_image_to_array(files): images_as_array=[] for file in files: # Convert to Numpy Array images_as_array.append(img_to_array(load_img(file))) return images_as_array x_train = np.array(convert_image_to_array(x_train)) print('Training set shape : ',x_train.shape) x_valid = np.array(convert_image_to_array(x_valid)) print('Validation set shape : ',x_valid.shape) x_test = np.array(convert_image_to_array(x_test)) print('Test set shape : ',x_test.shape) print('1st training image shape ',x_train[0].shape) # + id="-ZPCcxC3ZBvM" from keras.applications.resnet_v2 import ResNet50V2 model=ResNet50V2(include_top=True, weights=None, input_tensor=None, input_shape=(100,100,3),classes=41) model.summary() # + id="0AiKcVgwZE1L" model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) print('Compiled!') # + id="qc15-t5vaLOc" from keras.models import Sequential from keras.layers import Conv2D,MaxPooling2D from keras.layers import Activation, Dense, Flatten, Dropout from keras.preprocessing.image import ImageDataGenerator from keras.callbacks import ModelCheckpoint from keras import backend as K batch_size = 50 checkpointer = ModelCheckpoint(filepath = 'cnn_from_scratch_fruits.hdf5', save_best_only = True) history = model.fit(x_train,y_train, batch_size = 50, epochs=15, validation_data=(x_valid, y_vaild), callbacks = [checkpointer], shuffle=True ) # + id="6VT6Ncz_aMLE" model.load_weights('cnn.hdf5') # + id="SXtGBjEzaTB3" score = model.evaluate(x_test, y_test, verbose=0) print('\n', 'Test accuracy:', score[1]) # + id="sIGqQnH7aVmT" import matplotlib.pyplot as plt # Plot training & validation accuracy values plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('Model accuracy') plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.legend(['Train', 'Test'], loc='upper left') plt.show() # Plot training & validation loss values plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Model loss') plt.ylabel('Loss') plt.xlabel('Epoch') plt.legend(['Train', 'Test'], loc='upper left') plt.show()
ResNet50 V2/resnet50_v2.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # # Amazon Instruments # Author: <NAME> # + import time import numpy as np import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt import seaborn as sns sns.set() sns.set_style("white") sns.set_palette("mako_r") # + # Import the dataset df = pd.read_csv("Musical_instruments_reviews.csv") # The json file contains the same info as the csv: # reviews = pd.read_json("Musical_Instruments_5.json") # - df.head() df.info() df.isna().sum() # It can be seen that we have several missing names. Clearly, names are not relevant to the kind of analysis that we want to perform and, therefore, we can drop that column and forget about the nulls. On the other hand, we have a few missing reviews. df.reviewerName.fillna(df.reviewerID, inplace=True) df.reviewText.fillna("", inplace=True) # + # It would be interesting to take a look at the general look of the reviews # The next function prints n random comments import random def printRandomComments(df, number=10): for i in range(0,number): j = random.randint(0, df.shape[0]) print(str(i+1)+") "+df["reviewText"][j]+"\n") i=i+1 printRandomComments(df, 5) # - # ## Sentiment Analysis from textblob import TextBlob from wordcloud import WordCloud # We are going to use textblob to get the subjectivity and polarity values of each review text, and we are going to use those values to clasify them as positive, neutral or negative # + # We define a function for each value an create add them to new columns def getSubjectivity(text): return TextBlob(text).sentiment.subjectivity def getPolatiry(text): return TextBlob(text).sentiment.polarity # Getting all the values takes time so the next lines help with anxiety start_time = time.time() print("Performing analysis...") # Get the values and fill the columns df["Subjectivity"] = df["reviewText"].apply(getSubjectivity) df["Polarity"] = df["reviewText"].apply(getPolatiry) print("Analysis concluded in "+"%s seconds" % (time.time() - start_time)) df[["reviewText", "Subjectivity","Polarity"]].head() # + # Now let's clasify the reviews based on ther polarity score # This function asigns a label based on the score # If no limits are pased, positive and negative labels will be based on the sign # if ranges are pased, values within those ranges are going to be consider neutral def assignSentiment(score, thresholds=[0,0]): if score < thresholds[0]: return "Negative" elif score > thresholds[1]: return "Positive" else: return "Neutral" df["Sentiment"] = df["Polarity"].apply(lambda x: assignSentiment(x, [-0.1,0.1])) # - pd.DataFrame(df["Sentiment"].value_counts()).rename(columns={"Sentiment":"Reviews"}) # ### Most positive and negative Reviews best = df[["Sentiment","Polarity","Subjectivity","reviewText"]].sort_values(["Polarity"], ascending=False).head() best # Let's take a better look at the best comments for txt in best["reviewText"]: print("\n_" + txt) worst = df[["Sentiment","Polarity","Subjectivity","reviewText"]].sort_values(["Polarity"], ascending=True).head() worst # Let's take a better look at the worst comments for txt in worst["reviewText"]: print("\n_" + txt) # We can see that the algorithm is pretty good at identifying good comments, but we have some clear false identifications among the negative ones. # ### WordCloud # + # Let's create some filters based on the asigned sentiments pos = df["Sentiment"] == "Positive" neu = df["Sentiment"] == "Neutral" neg = df["Sentiment"] == "Negative" # we define a function to give as a wordcloud from a given text def showWordCloud(text): wordCloud = WordCloud(width=500, height=300, random_state=42, max_font_size=120).generate(text) plt.imshow(wordCloud) plt.axis("off") plt.show() # - # All Reviews allReviews = "".join(msgs for msgs in df["reviewText"]) showWordCloud(allReviews) # + # Positive Reviews posReviews = "".join(msgs for msgs in df[pos]["reviewText"]) showWordCloud(posReviews) # Negative negReviews = "".join(msgs for msgs in df[neg]["reviewText"]) showWordCloud(negReviews) # + # It seems tha "guitar", "one" is pretty prevalent, let's remove those words def removeSubstrings(text,substrings=[""]): text = text.lower() for substr in substrings: text = text.replace(substr.lower(),"") return text # + to_remove = ["guitar", "one","use"] posReviews = removeSubstrings(posReviews, to_remove) negReviews = removeSubstrings(negReviews, to_remove) showWordCloud(posReviews) showWordCloud(negReviews) # -
exploratory-data-analysis.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ##### tf-idf를 통해 벡터화해보고, k-fold를 사용해서 cross_validation을 진행해보자 train = pd.read_csv("../../labeledTrainData.tsv", delimiter='\t', quoting=3) test = pd.read_csv("../../testData.tsv", delimiter='\t', quoting=3) # + # 데이터 전처리는 html코드 제거까지만 # 여기에 병렬처리하도록 멀티프로세싱 코드 추가 from KaggleWord2VecUtility import KaggleWord2VecUtility from bs4 import BeautifulSoup def review_to_words(raw_review): review_text = BeautifulSoup(raw_review, 'html.parser').get_text() return review_text # - train['review_clean'] = train['review'].map(review_to_words) test['review_clean'] = test['review'].map(review_to_words) x_train = train['review_clean'] x_test = test['review_clean'] import nltk nltk.download('words') # + from sklearn.feature_extraction.text import TfidfTransformer from sklearn.feature_extraction.text import CountVectorizer from sklearn.pipeline import Pipeline from nltk.corpus import words vectorizer = CountVectorizer(analyzer='word', lowercase= True, tokenizer = None, preprocessor = None, stop_words = 'english', min_df = 2, ngram_range = (1,3), vocabulary = set(words.words()), max_features = 90000) # - pipeline = Pipeline([('vect', vectorizer),('tfidf', TfidfTransformer(smooth_idf= False))]) pipeline x_train_tfidf_vector = pipeline.fit_transform(x_train) vocab = vectorizer.get_feature_names() print(len(vocab)) vocab[:10] x_test_tfidf_vector = pipeline.fit_transform(x_test) from sklearn.ensemble import RandomForestClassifier forest = RandomForestClassifier(n_estimators=100, random_state=2018) forest.fit(x_train_tfidf_vector, train['sentiment']) # + from sklearn.model_selection import KFold from sklearn.model_selection import cross_val_score k_fold = KFold(n_splits=5, shuffle=True, random_state=2018) score = np.mean(cross_val_score(forest, x_train_tfidf_vector, train['sentiment'], cv=k_fold, scoring='roc_auc', n_jobs=-1)) # - score result = forest.predict(x_test_tfidf_vector) output = pd.DataFrame(data={'id':test['id'], "sentiment":result}) output.tail() output.to_csv("tutorial4_tfidf_{0:.5f}".format(score), index=False, quoting=3)
part4/TF-IDF_K-fold.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- ## This makes figures in a separate python window # #%matplotlib ## This makes static figures as .png files in the notebook: recommended # %matplotlib inline ## This makes figures "live" in the notebook # #%matplotlib notebook ## Standard imports for working in python import matplotlib.pyplot as plt import numpy as np ## It is highly recommended that you do NOT import * from any library ## Otherwise you can run into bad function name overlaps ## For instance, both numpy and python define "sum" # The matplotlib example gallery has good examples of how to do almost everything needed in matplotlib. When in doubt, you can take a look through here. # # https://matplotlib.org/stable/gallery/index.html # # A somewhat advanced but useful set of cheat sheets: # # https://github.com/rougier/matplotlib-cheatsheet # # Basic Plotting # # https://matplotlib.org/gallery/pyplots/pyplot_formatstr.html#sphx-glr-gallery-pyplots-pyplot-formatstr-py # # * plot a line https://matplotlib.org/gallery/lines_bars_and_markers/simple_plot.html#sphx-glr-gallery-lines-bars-and-markers-simple-plot-py # * plot a scatterplot with plt.plot: `plt.plot(x, y, 'o')` # * plot a scatterplot with plt.scatter: `plt.scatter(x, y)` # * plot errorbars: `plt.errorbar(x, y, fmt='o', yerr=y_err)` https://matplotlib.org/gallery/statistics/errorbar.html#sphx-glr-gallery-statistics-errorbar-py https://matplotlib.org/gallery/statistics/errorbar_features.html#sphx-glr-gallery-statistics-errorbar-features-py # # * Get the current figure or axis: `fig = plt.gcf()` and `ax = plt.gca()` # # * colors, line styles, markers, marker styles: https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot # # # * axis labels: `plt.xlabel('my label')` or `ax.set_xlabel('my label')` # * axis limits: `plt.xlim(xmin, xmax)` or `ax.set_xlim(xmin, xmax)` # * axis titles: `plt.title('my title')` or `ax.set_title('my title')` # * axis tick marks: see `matplotlib.ticker.MultipleLocator` https://matplotlib.org/api/ticker_api.html, e.g. `ax.xaxis.set_major_locator(MultipleLocator(1))` or `ax.yaxis.set_minor_locator(MultipleLocator(0.1))` # * inverting axes: set the axis limits in the reverse direction, or `ax.invert_xaxis()` https://matplotlib.org/gallery/subplots_axes_and_figures/invert_axes.html#sphx-glr-gallery-subplots-axes-and-figures-invert-axes-py # * axis fonts https://matplotlib.org/gallery/text_labels_and_annotations/fonts_demo_kw.html#sphx-glr-gallery-text-labels-and-annotations-fonts-demo-kw-py https://matplotlib.org/gallery/text_labels_and_annotations/text_fontdict.html#sphx-glr-gallery-text-labels-and-annotations-text-fontdict-py # * TeX in text: `plt.xlabel(r"$\sqrt{N}$")` # * legends https://matplotlib.org/gallery/text_labels_and_annotations/legend_demo.html#sphx-glr-gallery-text-labels-and-annotations-legend-demo-py https://matplotlib.org/gallery/recipes/transparent_legends.html#sphx-glr-gallery-recipes-transparent-legends-py # https://matplotlib.org/gallery/text_labels_and_annotations/custom_legends.html#sphx-glr-gallery-text-labels-and-annotations-custom-legends-py # * log scale: `ax.set_xscale('log')` https://matplotlib.org/2.0.0/examples/pylab_examples/log_demo.html # # # # * annotating and labeling figures: `plt.text`, `plt.figtext`, `plt.annotate` # # # * figure of certain size: `fig = plt.figure(figsize=(8,11))` (in inches) # * multi-panel figures: `fig, axes = plt.subplots(4, 2, figsize=(8,11))` # # # * 1D histograms (`plt.hist`, `plt.step` and `np.histogram`) # # * saving figures `fig = plt.gcf(); fig.savefig("myname.png", bbox_inches='tight', dpi=300)` (can also do .pdf, .eps, ...) # # * string formatting (e.g. when printing numbers): https://pyformat.info/ # One confusing thing about matplotlib is that there are always at least 2 ways to do the same thing: # The "pyplot" (or matlab-like) interface, and the "object-oriented" interface. # # The pyplot interface is usually better for making quick/interactive plots, while the object-oriented interface is usually better for making scripted plots. # https://matplotlib.org/gallery/misc/pythonic_matplotlib.html#sphx-glr-gallery-misc-pythonic-matplotlib-py # # I usually default to the object-oriented interface, meaning I start making every plot with something like: # # `fig, ax = plt.subplots(figsize=(8,8))` # # Example # # Here we generate a bunch of random data from a line to make a scatterplot, then also plot some lines. # # I've used the "object-oriented" interface (i.e. `ax.<stuff>` instead of `plt.<stuff>`) def line_model(m, b, x): """ Returns a line """ return m*x + b # + ## Generate some data m0 = 1 b0 = 0.5 np.random.seed(512) xdata = np.random.uniform(-1, 1, size=100) ydata = line_model(m0, b0, xdata) # + fig, ax = plt.subplots(figsize=(5,5)) # Plot the data ax.plot(xdata, ydata, 'ko', label="whoo data") # The above is a common shorthand, which is short for this: # ax.plot(xdata, ydata, marker='o', linestyle='none', color='black', label="whoo data") # the quick colors are "rgbcmyk" for red/green/blue/cyan/magenta/yellow/black # you can also specify colors using their hex codes, e.g. from here: https://xkcd.com/color/rgb/ # Plot a dashed line xplot = np.linspace(-1, 1, 101) # evenly spaced points between -1 and 1 (inclusive) yplot = line_model(m0, b0, xplot) ax.plot(xplot, yplot, 'r--', label="m={:.1f} b={:.1f}".format(m0, b0)) # Plot a dotted line at a different point m, b = m0, b0+0.5 yplot = line_model(m, b, xplot) # #ff028d is hot pink from the XKCD site ax.plot(xplot, yplot, ':', color="#ff028d", label="m={:.1f} b={:.1f}".format(m, b), lw=2) # Here's also adding a transparent wide line # Consider looking up ax.fill_between if you want to do fancier things ax.plot(xplot, yplot, '-', color="k", label="m={:.1f} b={:.1f} transparent".format(m, b), lw=9, alpha=.2) # Set axis limits ax.set_xlim(-1, 1) # Label your axes, with whatever fontsize you want ax.set_xlabel("xdata", fontsize=10) ax.set_ylabel("ydata", fontsize=10) ax.set_title("My Figure Title!", fontsize=15) ax.tick_params(axis='x', labelsize=8) ax.tick_params(axis='y', labelsize=8) # Add a legend ax.legend(loc="upper left", fontsize=10) # Set where you want the ticks to be ax.xaxis.set_major_locator(plt.MultipleLocator(0.25)) ax.yaxis.set_major_locator(plt.MultipleLocator(0.25)) # I often like to draw a grid ax.grid() # You can add text this way at a specific coordinate ax.text(-1.0, 1.0, "Some text", fontsize=10, ha='left', va='bottom') # You can also add text relative to the axis coordinates ax.text(0.95, 0.05, "More text", fontsize=10, ha='right', va='top', transform=ax.transAxes) # You can draw horizontal and vertical lines, e.g. here to highlight y=0 and x=0 ax.axhline(0, color='k', ls='-') # y=0 ax.axvline(0, color='k', ls='-') # x=0 # This squeezes the margins of the figure fig.tight_layout() # You can save figures in different formats like this: # fig.savefig("my_figure.png") # fig.savefig("my_figure.pdf") # - # If you want to look up what something does, you can always use the `?` # ?ax.tick_params # ?ax.plot # + ## The exact same thing but using the `plt` interface plt.figure(figsize=(5,5)) # Plot the data plt.plot(xdata, ydata, 'ko', label="whoo data") # Plot a dashed line xplot = np.linspace(-1, 1, 101) # evenly spaced points between -1 and 1 (inclusive) yplot = line_model(m0, b0, xplot) plt.plot(xplot, yplot, 'r--', label="m={:.1f} b={:.1f}".format(m0, b0)) # Plot a dotted line at a different point m, b = m0, b0+0.5 yplot = line_model(m, b, xplot) plt.plot(xplot, yplot, ':', color="#ff028d", label="m={:.1f} b={:.1f}".format(m, b), lw=2) # Here's also adding a transparent wide line plt.plot(xplot, yplot, '-', color="k", label="m={:.1f} b={:.1f} transparent".format(m, b), lw=9, alpha=.2) # Set axis limits: DIFFERENT! No "set_" plt.xlim(-1, 1) # Label your axes, with whatever fontsize you want # DIFFERENT! plt.xlabel("xdata", fontsize=10) plt.ylabel("ydata", fontsize=10) plt.title("My Figure Title!", fontsize=15) plt.xticks(fontsize=8) plt.yticks(fontsize=8) # Add a legend plt.legend(loc="upper left", fontsize=10) # Set where you want the ticks to be. Have to get the axis with plt.gca() plt.gca().xaxis.set_major_locator(plt.MultipleLocator(0.25)) plt.gca().yaxis.set_major_locator(plt.MultipleLocator(0.25)) plt.grid() # You can add text this way at a specific coordinate plt.text(-1.0, 1.0, "Some text", fontsize=10, ha='left', va='bottom') # You can also add text relative to the axis coordinates plt.text(0.95, 0.05, "More text", fontsize=10, ha='right', va='top', transform=plt.gca().transAxes) # You can draw horizontal and vertical lines, e.g. here to highlight y=0 and x=0 plt.axhline(0, color='k', ls='-') # y=0 plt.axvline(0, color='k', ls='-') # x=0 # This squeezes the margins of the figure fig = plt.gcf() # gcf = get current figure, gca = get current axis fig.tight_layout() # -
PythonPlotting.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/New-Languages-for-NLP/repo-template/blob/main/New_Language_Training_(Colab).ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="061ba15a" # <img width=50% src="https://github.com/New-Languages-for-NLP/course-materials/raw/main/w2/using-inception-data/newnlp_notebook.png" /> # # For full documentation on this project, see [here](https://new-languages-for-nlp.github.io/course-materials/w2/using-inception-data/New%20Language%20Training.html) # # + [markdown] id="psP7JdcRLR7n" # # 1 Prepare the Notebook Environment # + id="a0ba9e5a" cellView="form" #@title The Colab runtime comes with spaCy v2 and needs to be upgraded to v3. #@markdown This project uses the GPU by default, if you need to use just the CPU, just uncheck the box below. GPU = True #@param {type:"boolean"} # Install spaCy v3 and libraries for GPUs and transformers # !pip install spacy --upgrade --quiet if GPU: # !pip install 'spacy[transformers,cuda111]' --quiet # #!pip install wandb spacy-huggingface-hub --quiet # + [markdown] id="WfsEKZv6ErlG" # The notebook will pull project files from your GitHub repository. # # Note that you need to set the langugage (lang), treebank (same as the repo name), test_size and package name in the project.yml file in your repository. # + cellView="form" id="7c0bda8e" #@title Enter your language's repository name. #@markdown If the repo is private, please check the "private_repo" box and include an [access token](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token). private_repo = False #@param {type:"boolean"} repo_name = "repo-template" #@param {type:"string"} branch = "main" #@param {type:"string"} # !rm -rf /content/newlang_project # !rm -rf $repo_name if private_repo: git_access_token = "<KEY>" #@param {type:"string"} git_url = f"https://{git_access_token}@github.com/New-Languages-for-NLP/{repo_name}/" # !git clone $git_url -b $branch # !cp -r ./$repo_name/newlang_project . # !mkdir newlang_project/assets/ # !mkdir newlang_project/configs/ # !mkdir newlang_project/corpus/ # !mkdir newlang_project/metrics/ # !mkdir newlang_project/packages/ # !mkdir newlang_project/training/ # !mkdir newlang_project/assets/$repo_name # !cp -r ./$repo_name/* newlang_project/assets/$repo_name/ # !rm -rf ./$repo_name else: # !python -m spacy project clone newlang_project --repo https://github.com/New-Languages-for-NLP/$repo_name --branch $branch # !python -m spacy project assets /content/newlang_project # + id="4dc13741" # Install the custom language object from Cadet # !python -m spacy project run install /content/newlang_project # + [markdown] id="qU_AqRK6LZrF" # # 2 Prepare the Data for Training # + cellView="form" colab={"base_uri": "https://localhost:8080/"} id="HPjD0SN6iAvc" outputId="04e7fed1-7613-423a-ce0f-7aaf73ae6953" #@title (optional) cell to correct a problem when your tokens have no pos value # %%writefile /usr/local/lib/python3.7/dist-packages/spacy/training/converters/conllu_to_docs.py import re from .conll_ner_to_docs import n_sents_info from ...training import iob_to_biluo, biluo_tags_to_spans from ...tokens import Doc, Token, Span from ...vocab import Vocab from wasabi import Printer def conllu_to_docs( input_data, n_sents=10, append_morphology=False, ner_map=None, merge_subtokens=False, no_print=False, **_ ): """ Convert conllu files into JSON format for use with train cli. append_morphology parameter enables appending morphology to tags, which is useful for languages such as Spanish, where UD tags are not so rich. Extract NER tags if available and convert them so that they follow BILUO and the Wikipedia scheme """ MISC_NER_PATTERN = "^((?:name|NE)=)?([BILU])-([A-Z_]+)|O$" msg = Printer(no_print=no_print) n_sents_info(msg, n_sents) sent_docs = read_conllx( input_data, append_morphology=append_morphology, ner_tag_pattern=MISC_NER_PATTERN, ner_map=ner_map, merge_subtokens=merge_subtokens, ) sent_docs_to_merge = [] for sent_doc in sent_docs: sent_docs_to_merge.append(sent_doc) if len(sent_docs_to_merge) % n_sents == 0: yield Doc.from_docs(sent_docs_to_merge) sent_docs_to_merge = [] if sent_docs_to_merge: yield Doc.from_docs(sent_docs_to_merge) def has_ner(input_data, ner_tag_pattern): """ Check the MISC column for NER tags. """ for sent in input_data.strip().split("\n\n"): lines = sent.strip().split("\n") if lines: while lines[0].startswith("#"): lines.pop(0) for line in lines: parts = line.split("\t") id_, word, lemma, pos, tag, morph, head, dep, _1, misc = parts for misc_part in misc.split("|"): if re.match(ner_tag_pattern, misc_part): return True return False def read_conllx( input_data, append_morphology=False, merge_subtokens=False, ner_tag_pattern="", ner_map=None, ): """Yield docs, one for each sentence""" vocab = Vocab() # need vocab to make a minimal Doc for sent in input_data.strip().split("\n\n"): lines = sent.strip().split("\n") if lines: while lines[0].startswith("#"): lines.pop(0) doc = conllu_sentence_to_doc( vocab, lines, ner_tag_pattern, merge_subtokens=merge_subtokens, append_morphology=append_morphology, ner_map=ner_map, ) yield doc def get_entities(lines, tag_pattern, ner_map=None): """Find entities in the MISC column according to the pattern and map to final entity type with `ner_map` if mapping present. Entity tag is 'O' if the pattern is not matched. lines (str): CONLL-U lines for one sentences tag_pattern (str): Regex pattern for entity tag ner_map (dict): Map old NER tag names to new ones, '' maps to O. RETURNS (list): List of BILUO entity tags """ miscs = [] for line in lines: parts = line.split("\t") id_, word, lemma, pos, tag, morph, head, dep, _1, misc = parts if "-" in id_ or "." in id_: continue miscs.append(misc) iob = [] for misc in miscs: iob_tag = "O" for misc_part in misc.split("|"): tag_match = re.match(tag_pattern, misc_part) if tag_match: prefix = tag_match.group(2) suffix = tag_match.group(3) if prefix and suffix: iob_tag = prefix + "-" + suffix if ner_map: suffix = ner_map.get(suffix, suffix) if suffix == "": iob_tag = "O" else: iob_tag = prefix + "-" + suffix break iob.append(iob_tag) return iob_to_biluo(iob) def conllu_sentence_to_doc( vocab, lines, ner_tag_pattern, merge_subtokens=False, append_morphology=False, ner_map=None, ): """Create an Example from the lines for one CoNLL-U sentence, merging subtokens and appending morphology to tags if required. lines (str): The non-comment lines for a CoNLL-U sentence ner_tag_pattern (str): The regex pattern for matching NER in MISC col RETURNS (Example): An example containing the annotation """ # create a Doc with each subtoken as its own token # if merging subtokens, each subtoken orth is the merged subtoken form if not Token.has_extension("merged_orth"): Token.set_extension("merged_orth", default="") if not Token.has_extension("merged_lemma"): Token.set_extension("merged_lemma", default="") if not Token.has_extension("merged_morph"): Token.set_extension("merged_morph", default="") if not Token.has_extension("merged_spaceafter"): Token.set_extension("merged_spaceafter", default="") words, spaces, tags, poses, morphs, lemmas = [], [], [], [], [], [] heads, deps = [], [] subtok_word = "" in_subtok = False for i in range(len(lines)): line = lines[i] parts = line.split("\t") id_, word, lemma, pos, tag, morph, head, dep, _1, misc = parts if "." in id_: continue if "-" in id_: in_subtok = True if "-" in id_: in_subtok = True subtok_word = word subtok_start, subtok_end = id_.split("-") subtok_spaceafter = "SpaceAfter=No" not in misc continue if merge_subtokens and in_subtok: words.append(subtok_word) else: words.append(word) if in_subtok: if id_ == subtok_end: spaces.append(subtok_spaceafter) else: spaces.append(False) elif "SpaceAfter=No" in misc: spaces.append(False) else: spaces.append(True) if in_subtok and id_ == subtok_end: subtok_word = "" in_subtok = False id_ = int(id_) - 1 head = (int(head) - 1) if head not in ("0", "_") else id_ tag = pos if tag == "_" else tag morph = morph if morph != "_" else "" dep = "ROOT" if dep == "root" else dep lemmas.append(lemma) if pos == "_": pos = "" poses.append(pos) tags.append(tag) morphs.append(morph) heads.append(head) deps.append(dep) doc = Doc( vocab, words=words, spaces=spaces, tags=tags, pos=poses, deps=deps, lemmas=lemmas, morphs=morphs, heads=heads, ) for i in range(len(doc)): doc[i]._.merged_orth = words[i] doc[i]._.merged_morph = morphs[i] doc[i]._.merged_lemma = lemmas[i] doc[i]._.merged_spaceafter = spaces[i] ents = get_entities(lines, ner_tag_pattern, ner_map) doc.ents = biluo_tags_to_spans(doc, ents) if merge_subtokens: doc = merge_conllu_subtokens(lines, doc) # create final Doc from custom Doc annotation words, spaces, tags, morphs, lemmas, poses = [], [], [], [], [], [] heads, deps = [], [] for i, t in enumerate(doc): words.append(t._.merged_orth) lemmas.append(t._.merged_lemma) spaces.append(t._.merged_spaceafter) morphs.append(t._.merged_morph) if append_morphology and t._.merged_morph: tags.append(t.tag_ + "__" + t._.merged_morph) else: tags.append(t.tag_) poses.append(t.pos_) heads.append(t.head.i) deps.append(t.dep_) doc_x = Doc( vocab, words=words, spaces=spaces, tags=tags, morphs=morphs, lemmas=lemmas, pos=poses, deps=deps, heads=heads, ) doc_x.ents = [Span(doc_x, ent.start, ent.end, label=ent.label) for ent in doc.ents] return doc_x def merge_conllu_subtokens(lines, doc): # identify and process all subtoken spans to prepare attrs for merging subtok_spans = [] for line in lines: parts = line.split("\t") id_, word, lemma, pos, tag, morph, head, dep, _1, misc = parts if "-" in id_: subtok_start, subtok_end = id_.split("-") subtok_span = doc[int(subtok_start) - 1 : int(subtok_end)] subtok_spans.append(subtok_span) # create merged tag, morph, and lemma values tags = [] morphs = {} lemmas = [] for token in subtok_span: tags.append(token.tag_) lemmas.append(token.lemma_) if token._.merged_morph: for feature in token._.merged_morph.split("|"): field, values = feature.split("=", 1) if field not in morphs: morphs[field] = set() for value in values.split(","): morphs[field].add(value) # create merged features for each morph field for field, values in morphs.items(): morphs[field] = field + "=" + ",".join(sorted(values)) # set the same attrs on all subtok tokens so that whatever head the # retokenizer chooses, the final attrs are available on that token for token in subtok_span: token._.merged_orth = token.orth_ token._.merged_lemma = " ".join(lemmas) token.tag_ = "_".join(tags) token._.merged_morph = "|".join(sorted(morphs.values())) token._.merged_spaceafter = ( True if subtok_span[-1].whitespace_ else False ) with doc.retokenize() as retokenizer: for span in subtok_spans: retokenizer.merge(span) return doc # + id="563fdc94" # Convert the conllu files from inception to spaCy binary format # Read the conll files with ner data and as ents to spaCy docs # !python -m spacy project run convert /content/newlang_project # + id="9519c858" # test/train split # !python -m spacy project run split /content/newlang_project # + id="4feefe6f" # Debug the data # !python -m spacy project run debug /content/newlang_project # + [markdown] id="151-cj1dLgAD" # # 3 Model Training # + [markdown] id="KKW2QGPTJ_CZ" # If your project file uses Weights and Biases to monitor model training (`vars.wanb: true`), you'll need to create an account at [wandb.ai](https://wandb.ai/site) and get an API key. # + id="38b490a4" # train the model # !python -m spacy project run train /content/newlang_project # + [markdown] id="ynXr8vlXqCxv" # If you get `ValueError: Could not find gold transition - see logs above.` # You may not have sufficent data to train on: https://github.com/explosion/spaCy/discussions/7282 # + id="018362d8" # Evaluate the model using the test data # !python -m spacy project run evaluate /content/newlang_project # + id="gg1sLlVrgiyu" # Find the path for your meta.json file # You'll need to add newlang_project/ + the path from the training step just after "✔ Saved pipeline to output directory" # !ls newlang_project/training/urban-giggle/model-last # + id="3zGCTURr9JE6" #Update meta.json import spacy import srsly # Change path to match that from the training cell where it says "✔ Saved pipeline to output directory" meta_path = "newlang_project/training/urban-giggle/model-last/meta.json" # Replace values below for your project my_meta = { "lang":"yi", "name":"yiddish_sm", "version":"0.0.1", "description":"Yiddish pipeline optimized for CPU. Components: tok2vec, tagger, parser, senter, lemmatizer.", "author":"New Languages for NLP", "email":"<EMAIL>", "url":"https://newnlp.princeton.edu", "license":"MIT", } meta = spacy.util.load_meta(meta_path) meta.update(my_meta) srsly.write_json(meta_path, meta) # + [markdown] id="JM309FhNVAeb" # ### Download the trained model to your computer. # # + id="8e1d6f36" # Save the model to disk in a format that can be easily downloaded and re-used. # !python -m spacy package newlang_project/training/urban-giggle/model-last newlang_project/export # + colab={"base_uri": "https://localhost:8080/", "height": 17} id="8d32abf2" outputId="70bdb4ba-a62b-4601-ef2c-5f03a35ee1ce" from google.colab import files # replace with the path in the previous cell under "✔ Successfully created zipped Python package" files.download('newlang_project/export/yi_yiddish_sm-0.0.1/dist/yi_yiddish_sm-0.0.1.tar.gz') # once on your computer, you can pip install yi_yiddish_sm-0.0.1.tar.gz # Be sure to add the file to the 4_trained_models folder in GitHub
New_Language_Training_(Colab).ipynb
// --- // jupyter: // jupytext: // text_representation: // extension: .cpp // format_name: light // format_version: '1.5' // jupytext_version: 1.14.4 // kernelspec: // display_name: C++17 // language: C++17 // name: xcpp17 // --- // # Advanced OOP // # Inheritance #include <iostream> // + class Vehicle { public: std::string color = "white"; bool areLightsTurnOn() const { return lightsStatus; } // Accessor void switchLights() { lightsStatus = !lightsStatus; } // Mutator private: bool lightsStatus{false}; }; // - // Car inherits from Vehicle class Car : public Vehicle { public: std::string color = "blue"; int wheelsNum{4}; }; // Motorcycle inherits from Vehicle class Motorcycle : public Vehicle { public: std::string color = "red"; int wheelsNum{2}; }; // + Car car; Motorcycle moto; std::cout << "Number of wheels of the Car: " << car.wheelsNum << std::endl; std::cout << "Color of the Car: " << car.color << std::endl; std::cout << "Number of wheels of the Motorcycle: " << moto.wheelsNum << std::endl; std::cout << "Color of the Motorcycle: " << moto.color << std::endl; // - // ### Access modifiers #include <iostream> #include <string> using std::string; class Vehicle { public: int wheels = 0; string color = "blue"; void Print() const { std::cout << "This " << color << " vehicle has " << wheels << " wheels!\n"; } }; class Car : public Vehicle { public: bool sunroof = false; }; class Bicycle : protected Vehicle { public: bool kickstand = true; void Wheels(int w) { wheels = w; } }; class Scooter : private Vehicle { public: bool electric = false; void Wheels(int w) { wheels = w; } }; Car car; car.wheels = 4; Bicycle bike; // bike.wheels = 2; will throw us an error because in inherits // wheels from Car as a protected member. bike.Wheels(2); // however, this works correctly! Scooter scooter; // scooter.wheels = 2; also won't work scooter.Wheels(2); // ## Composition #include <iostream> #include <string> #include <vector> class Wheel { public: Wheel() : diameter(50) {} int diameter; }; // Class Car is composed of wheels class Car { public: // wheels is declared as a vector of 4 Wheels Car() : wheels(4, Wheel()) {} std::vector<Wheel> wheels; }; Car car; std::cout << "Number of wheels: " << car.wheels.size() << std::endl; std::cout << "Diameter of each wheel: " << car.wheels[0].diameter << std::endl;
2.Object-Oriented-Programming/2.Advanced-OOP.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [default] # language: python # name: python3 # --- import matplotlib.pyplot as plt from astroduet.zodi import load_zodi import matplotlib.pyplot as plt import numpy as np import astropy.units as u from astroduet.duet_telescope import load_qe from astroduet.duet_filters import make_red_filter from astroduet.apply_transmission import apply_trans # Load low Zodi scale = 75 zodi = load_zodi(scale=scale) # + wave = zodi['wavelength'] flux = zodi['flux'] # Make the red filter and loda the qe low_wave = 180*u.nm high_wave = 220*u.nm rejection = 1e-3 qe_wave, qe = load_qe(low_wave =low_wave, high_wave = high_wave, rejection=rejection) red_filter = make_red_filter(wave, diag=True) # + # Apply red filter and the QE curve red_flux = apply_trans(wave, flux, wave, red_filter) qe_flux = apply_trans(wave, red_flux, qe_wave, qe/100.) # - plt.plot(zodi['wavelength'], zodi['flux'], label='Input') plt.plot(zodi['wavelength'], red_flux, label = 'Red Filter') plt.plot(zodi['wavelength'], qe_flux, label='QE Filter') plt.xlabel('Wavelength (Ang)') plt.ylabel(qe_flux.unit) plt.yscale('Log') plt.ylim([1e-4, 1e6]) plt.xlim([1200, 12000]) plt.legend() plt.show() dlambda = wave[1] - wave[0] received_fluence = (dlambda * qe_flux).sum() print('Received Sky Background: {}'.format(received_fluence)) de = wave[1] - wave[0] ph_flux = ((de*qe_flux).cgs).to(1 / ((u.cm**2 * u.arcsec**2 * u.s))) fluence = ph_flux.sum() print('Zodi fluence: {}'.format(fluence)) plt.plot(zodi['wavelength'], ph_flux) plt.yscale('Log') plt.xlabel('Wavelength (nm)') plt.ylabel(ph_flux.unit) plt.xlim([1200, 10000]) plt.legend() plt.show()
notebooks/out_of_date/zodi_calculator.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # <h1>Table of Contents<span class="tocSkip"></span></h1> # <div class="toc"><ul class="toc-item"><li><span><a href="#uberduck_ml_dev.exec.split_train_val" data-toc-modified-id="uberduck_ml_dev.exec.split_train_val-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>uberduck_ml_dev.exec.split_train_val</a></span></li></ul></div> # <h1>Table of Contents<span class="tocSkip"></span></h1> # <div class="toc"><ul class="toc-item"><li><span><a href="#uberduck_ml_dev.exec.split_train_val" data-toc-modified-id="uberduck_ml_dev.exec.split_train_val-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>uberduck_ml_dev.exec.split_train_val</a></span></li></ul></div> # # uberduck_ml_dev.exec.split_train_val # + # default_exp exec.split_train_val # + # export import os from pathlib import Path import numpy as np from sklearn.model_selection import train_test_split def write_filenames(filenames, output_dir, output_filename): """ Writes a list of filenames of as each line of a .txt file specified by output_filename. """ with open(os.path.join(output_dir, output_filename), "w") as f: for item in filenames: f.write(f"{item}\n") def run( path, val_percent=0.2, val_num=None, train_file="train.txt", val_file="val.txt", ): """Split file in t Default behavior only creates a training and validation set (not test set). """ with open(path) as f: lines = [l.strip("\n") for l in f.readlines()] train, val = train_test_split(lines, test_size=val_num if val_num else val_percent) write_filenames(train, Path(os.path.dirname(path)), train_file) write_filenames(val, Path(os.path.dirname(path)), val_file) # + from pathlib import Path p = Path("foo/bar/baz") import os os.path.dirname(p) # + # export import argparse import sys def parse_args(args): parser = argparse.ArgumentParser() parser.add_argument( "-i", "--in", dest="input_path", help="Path to input file list", required=True ) parser.add_argument("-n", "--num_val", dest="num_val", type=float, default=0.1) args = parser.parse_args(args) return args try: from nbdev.imports import IN_NOTEBOOK except: IN_NOTEBOOK = False if __name__ == "__main__" and not IN_NOTEBOOK: args = parse_args(sys.argv[1:]) if args.num_val > 1: run(args.input_path, val_num=int(args.num_val)) else: run(args.input_path, val_percent=args.num_val) # -
nbs/exec.split_train_val.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + colab_type="code" id="3Hx5hS8-nfdK" colab={"base_uri": "https://localhost:8080/", "height": 52} outputId="27620524-7480-42f7-ed48-0dd7856ceb6f" import numpy as np import pandas_datareader as web import pandas as pd import tensorflow as tf import matplotlib.pyplot as plt # + colab_type="code" id="yxVxL1X6nfd7" colab={"base_uri": "https://localhost:8080/", "height": 238} outputId="91c4e3f5-6ca5-4156-df68-e5296d04232e" # using JD as its not as stable df=web.DataReader('AAPL',data_source='yahoo',start='04-01-2003',end='07-15-2020') df.head() # + colab_type="code" id="HbCQgpcNnffr" colab={"base_uri": "https://localhost:8080/", "height": 336} outputId="dfc9b36f-8fcf-4802-b3b6-2cf23a4e7015" plt.figure(figsize=(20,5)) plt.plot(df.Close) plt.title("AAPL") plt.grid() # + colab_type="code" id="sPXxlg3WnfgL" colab={} from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler(feature_range=(0,0.75)) # 0.75 so it's easier for relu to reach # closing valueŝ ser = df.Close.values ser = ser.reshape(-1,1) # scaled series series = scaler.fit_transform(ser) # + id="0kYsog3xnk-R" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="1c3fc859-662c-492c-8d6a-73e99f531b6c" int(series.shape[0]*0.9) # + colab_type="code" id="CX29emFtjb4x" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="17d0750b-8691-4d9b-e40f-ba3bb2aded4a" # fixed input size to model, last 30 days Window = 30 Predday = 7 # To split the data into 90:10 Trainsplit = 0.9 cut = int(series.shape[0]*Trainsplit) # train closetrain = series[:cut] # test closetest = series[cut:-(Window+Predday)] # forecast for future 7 days closeforecast = series[-(Window+Predday):] closetrain.shape, closetest.shape , closeforecast.shape # + colab_type="code" id="yljo-o1Cnfgb" colab={} def windowed_dataset(series, window_size = 31,predday = 7, batch_size = 32, shuffle_buffer= 1000): ds = tf.data.Dataset.from_tensor_slices(series) ds = ds.window(window_size + predday, shift=1, drop_remainder=True) ds = ds.flat_map(lambda w: w.batch(window_size + predday)) ds = ds.shuffle(shuffle_buffer) ds = ds.map(lambda w: (w[:-7], tf.squeeze(w[-7:]))) return ds.batch(batch_size).prefetch(3) trainbatches = windowed_dataset(closetrain) testbatches = windowed_dataset(closetest,batch_size=8) # + id="zRiZQ-rNnk-y" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="becb8a6a-ad71-46d0-f8d4-fb227efe102e" testbatches # + id="5SPTdNPEoFvT" colab_type="code" colab={} from google.colab import drive drive.mount('/content/drive') # + colab_type="code" id="diIbGKvanfiR" colab={"base_uri": "https://localhost:8080/", "height": 399} outputId="146ecc44-c319-4913-eab7-6a4f742835e9" from tensorflow.keras.models import load_model path=r'/content/drive/My Drive/LSTM MODEL STOCK/Model1_pred_7days.h5' new_model=load_model(path) new_model.summary() # + colab_type="code" id="NLF6pyRL66LY" colab={"base_uri": "https://localhost:8080/", "height": 364} outputId="009e6df3-bb40-482a-d511-31d52850d359" h = new_model.fit(trainbatches,epochs=10,validation_data=testbatches,verbose=1) hist = h.history # + colab_type="code" id="0wdjtxegkttj" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="0ada9d3e-348c-40c4-985a-31ec9d211912" hist.keys() # + colab_type="code" id="hBaRe7nIGTev" colab={"base_uri": "https://localhost:8080/", "height": 513} outputId="aefd314b-3d85-4e78-e0b6-7d0ca9461392" for i in ["loss","mean_squared_error"]: plt.plot(hist[i],label = i) plt.plot(hist["val_"+i],label = "val_"+i) plt.legend() plt.show() # + id="qX7JTJAXnk_r" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="ee1795f6-64e9-4a15-dc9e-2f851259de6a" x1,y1 = next(iter(testbatches)) output = new_model.predict(x1) output.shape # + id="_inPRtNynk_0" colab_type="code" colab={} outputId="9cd0ab89-43e2-478e-e361-156d937c8f17" testbatches # + colab_type="code" id="-4tCKJgJIaIJ" colab={"base_uri": "https://localhost:8080/", "height": 1000} outputId="ebd524e4-9d92-4a3c-df54-3a6b5eb57be5" def visualplotloss(dataset): x,y = next(iter(dataset)) output = new_model.predict(x) timecorr =list(range(30,37)) for j in range(8): plt.ylim(0,0.75) plt.plot(x[j]) plt.plot(timecorr,output[j],"--") plt.plot(timecorr,y[j]) plt.legend(["Input of 30 days","Prediction","Truth Value"]) plt.show() visualplotloss(testbatches) # + colab_type="code" id="7b95NR3XHfgt" colab={"base_uri": "https://localhost:8080/", "height": 52} outputId="facadbac-8b10-448b-847a-4fbbe49f821c" new_model.evaluate(testbatches) # + id="rQf42hT8nlAg" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 1000} outputId="9b4d13f0-c0bf-4270-f219-c7e2f3f187b7" def visualplotloss(dataset): x,y = next(iter(dataset)) output = new_model.predict(x) timecorr =list(range(30,37)) for j in range(8): plt.ylim(0,0.75) plt.plot(x[j]) plt.plot(timecorr,output[j],"--") plt.plot(timecorr,y[j]) plt.legend(["Input of 30 days","Prediction","Truth Value"]) plt.show() visualplotloss(testbatches) # + [markdown] id="2bUODWCvq3ys" colab_type="text" # **<H2>Issues** # # Model Performance is weird although the predictions are good.
Experiments NB/Transfer_Learning_Apple(1).ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + id="JcWMYg4bWvj2" executionInfo={"status": "ok", "timestamp": 1615702748511, "user_tz": 300, "elapsed": 725, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjHn5A5nCXb4FsIfIBdin6XTbj6u54lww1hF6ECkT8=s64", "userId": "12308918870841825745"}} # This cell is used to load the hints and solutions, if needed from IPython.display import Pretty as disp hint = 'https://raw.githubusercontent.com/soltaniehha/Business-Analytics/master/docs/hints/' # path to hints on GitHub # + [markdown] id="CsZjroUuWGmg" # # Exercise - A Preview of Data Science Tools # In the following cell two lists of weight (in lbs) and height (in inches) of 6 basketball players are given: # + id="vpVHH7zUWGmh" executionInfo={"status": "ok", "timestamp": 1615702748724, "user_tz": 300, "elapsed": 277, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/<KEY>", "userId": "12308918870841825745"}} height_in = [73, 74, 71, 75, 74, 72, 70, 71, 68, 69, 72, 71] weight_lb = [170 , 215, 210 , 204, 189, 195, 190, 194, 200, 178, 199, 202] # + [markdown] id="H5aHHSQkWGmi" # Import the numpy package as np # + id="VCUyBYukWGmi" executionInfo={"status": "ok", "timestamp": 1615702755804, "user_tz": 300, "elapsed": 503, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjHn5A5nCXb4FsIfIBdin6XTbj6u54lww1hF6ECkT8=s64", "userId": "12308918870841825745"}} # Your answer goes here # + colab={"base_uri": "https://localhost:8080/"} id="xh99XF75WqDN" executionInfo={"status": "ok", "timestamp": 1615702751714, "user_tz": 300, "elapsed": 640, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjHn5A5nCXb4FsIfIBdin6XTbj6u54lww1hF6ECkT8=s64", "userId": "12308918870841825745"}} outputId="07d63542-5401-4097-9c9b-9aff0e7dc4c1" # SOLUTION: Uncomment and execute the cell below to get help #disp(hint + '02-03-ex01-a') # + [markdown] id="iTN8_z3BWGmi" # Create 2 numpy arrays, `np_height_in` & `np_weight_lb`, from height and weight. Hint: one can make a numpy array from a python list, L, by `np.array(L)`. # + id="nwTFZ1jEWGmi" executionInfo={"status": "ok", "timestamp": 1615702773248, "user_tz": 300, "elapsed": 393, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjHn5A5nCXb4FsIfIBdin6XTbj6u54lww1hF6ECkT8=s64", "userId": "12308918870841825745"}} # Your answer goes here np_height_in = np.array(height_in) np_weight_lb = np.array(weight_lb) # + id="SQlfaRSeXY4V" executionInfo={"status": "ok", "timestamp": 1615702770970, "user_tz": 300, "elapsed": 463, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjHn5A5nCXb4FsIfIBdin6XTbj6u54lww1hF6ECkT8=s64", "userId": "12308918870841825745"}} # SOLUTION: Uncomment and execute the cell below to get help #disp(hint + '02-03-ex01-b') # + [markdown] id="eql8pP-nWGmj" # Checkout the type of np_weight_lb: # + id="_6EOALD-WGmj" outputId="b7c17a31-5f65-4544-d876-499e6a2586e8" # Your answer goes here # + id="UWaVqiAcXdkb" # SOLUTION: Uncomment and execute the cell below to get help #disp(hint + '02-03-ex01-c') # + [markdown] id="FL0lzCSHWGmj" # This is how `np_weight_lb` will look like after the conversion: # + colab={"base_uri": "https://localhost:8080/"} id="HyOH2jS4WGmj" executionInfo={"status": "ok", "timestamp": 1615702782138, "user_tz": 300, "elapsed": 491, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjHn5A5nCXb4FsIfIBdin6XTbj6u54lww1hF6ECkT8=s64", "userId": "12308918870841825745"}} outputId="83a0e2c6-7b72-491a-8dba-f6e1981c3f74" np_weight_lb # + [markdown] id="viHsBjYJWGmk" # Convert `np_height_in` to meters and call it `np_height_m`, then print it. Hint: Use the formula $height(m) = height(in) * 2.54\ /\ 100$. # + colab={"base_uri": "https://localhost:8080/"} id="CvNeshPdWGmk" executionInfo={"status": "ok", "timestamp": 1615702792582, "user_tz": 300, "elapsed": 406, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjHn5A5nCXb4FsIfIBdin6XTbj6u54lww1hF6ECkT8=s64", "userId": "12308918870841825745"}} outputId="76b61e04-0733-442b-c265-32b3fbd76970" # Your answer goes here # + id="xxshnkE6XjoY" executionInfo={"status": "ok", "timestamp": 1615702795926, "user_tz": 300, "elapsed": 531, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjHn5A5nCXb4FsIfIBdin6XTbj6u54lww1hF6ECkT8=s64", "userId": "12308918870841825745"}} # SOLUTION: Uncomment and execute the cell below to get help #disp(hint + '02-03-ex01-d') # + [markdown] id="bQnHjgljWGmk" # Convert `np_weight_lb` to Kgs and call it `np_weight_kg`, then print it. Hint: Use the formula $weight(kg) = weight(lb) \ /\ 2.2$. # + colab={"base_uri": "https://localhost:8080/"} id="WF_1mhRzWGmk" executionInfo={"status": "ok", "timestamp": 1615702805614, "user_tz": 300, "elapsed": 385, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjHn5A5nCXb4FsIfIBdin6XTbj6u54lww1hF6ECkT8=s64", "userId": "12308918870841825745"}} outputId="b1bdc742-964a-43cc-d586-e06a9f9ee60a" # Your answer goes here # + id="aINv1KbEXpZq" executionInfo={"status": "ok", "timestamp": 1615702808508, "user_tz": 300, "elapsed": 434, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjHn5A5nCXb4FsIfIBdin6XTbj6u54lww1hF6ECkT8=s64", "userId": "12308918870841825745"}} # SOLUTION: Uncomment and execute the cell below to get help #disp(hint + '02-03-ex01-e') # + [markdown] id="xGrsEFdYWGml" # Using `np_weight_kg` and `np_height_m` create a simple scatter plot. # Hint: to do this you have several options, here are two of them: 1) use `plt.plot(x, y, 'o')`. The option 'o' here creates a scatter plot with circles; checkout help `plt.plot?` to find out about other symbols. 2) use `plt.scatter(x, y)` function. # + colab={"base_uri": "https://localhost:8080/", "height": 265} id="Z5kJwy_RWGml" executionInfo={"status": "ok", "timestamp": 1615702820583, "user_tz": 300, "elapsed": 652, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjHn5A5nCXb4FsIfIBdin6XTbj6u54lww1hF6ECkT8=s64", "userId": "12308918870841825745"}} outputId="c8554124-1c2b-4c3a-a76d-57765fdb3f72" # Your answer goes here # + id="ZOPLgZXEXvIZ" executionInfo={"status": "ok", "timestamp": 1615702818484, "user_tz": 300, "elapsed": 458, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjHn5A5nCXb4FsIfIBdin6XTbj6u54lww1hF6ECkT8=s64", "userId": "12308918870841825745"}} # SOLUTION: Uncomment and execute the cell below to get help #disp(hint + '02-03-ex01-f') # + [markdown] id="K-Mq2tL3WGml" # Now try to use the second option. But this time also use `plt.xlabel("X-label")` & ``plt.ylabel("Y-label")`` to give the axis appropriate names: # + colab={"base_uri": "https://localhost:8080/", "height": 279} id="SyOJdIJFWGml" executionInfo={"status": "ok", "timestamp": 1615702835944, "user_tz": 300, "elapsed": 816, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjHn5A5nCXb4FsIfIBdin6XTbj6u54lww1hF6ECkT8=s64", "userId": "12308918870841825745"}} outputId="fca967e9-09e4-4f38-8629-351724ebae12" # Your answer goes here # + id="QdinwNZXX01J" executionInfo={"status": "ok", "timestamp": 1615702838505, "user_tz": 300, "elapsed": 453, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjHn5A5nCXb4FsIfIBdin6XTbj6u54lww1hF6ECkT8=s64", "userId": "12308918870841825745"}} # SOLUTION: Uncomment and execute the cell below to get help #disp(hint + '02-03-ex01-g') # + [markdown] id="iC79wPf-WGml" # Calculate bmi and call it `bmi`, round it to 2 digits and print it. Hint: $bmi = weight(kg)\ /\ height ^ 2(m)$. # + colab={"base_uri": "https://localhost:8080/"} id="A3HijiX6WGmm" executionInfo={"status": "ok", "timestamp": 1615702846406, "user_tz": 300, "elapsed": 413, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjHn5A5nCXb4FsIfIBdin6XTbj6u54lww1hF6ECkT8=s64", "userId": "12308918870841825745"}} outputId="c32d42b8-b32a-410e-a9d3-bd33bd804d88" # Your answer goes here # + id="mu7gIz-cYGbw" executionInfo={"status": "ok", "timestamp": 1615702850468, "user_tz": 300, "elapsed": 440, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjHn5A5nCXb4FsIfIBdin6XTbj6u54lww1hF6ECkT8=s64", "userId": "12308918870841825745"}} # SOLUTION: Uncomment and execute the cell below to get help #disp(hint + '02-03-ex01-h') # + [markdown] id="FLAkIxXSWGmm" # Checkout the type of `bmi`: # + id="vUPBLMMNWGmm" outputId="4605fa75-465b-43d4-a924-4e3ac190fe58" # Your answer goes here # + id="orpMdpfuYNs6" # SOLUTION: Uncomment and execute the cell below to get help #disp(hint + '02-03-ex01-i') # + [markdown] id="E_LydGmCWGmm" # Create a Pandas dafaframe from np_weight_kg, np_height_m, bmi with the column names `weight`, `height`, `bmi`. Call this dataframe `players`: # + colab={"base_uri": "https://localhost:8080/", "height": 421} id="I20WHI9sWGmm" executionInfo={"status": "ok", "timestamp": 1615702863386, "user_tz": 300, "elapsed": 435, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjHn5A5nCXb4FsIfIBdin6XTbj6u54lww1hF6ECkT8=s64", "userId": "12308918870841825745"}} outputId="5b31e6f3-5d1b-4b14-de89-d263bc6cfb04" # Your answer goes here # + id="TVyRbLWcYUKl" executionInfo={"status": "ok", "timestamp": 1615702861201, "user_tz": 300, "elapsed": 425, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjHn5A5nCXb4FsIfIBdin6XTbj6u54lww1hF6ECkT8=s64", "userId": "12308918870841825745"}} # SOLUTION: Uncomment and execute the cell below to get help #disp(hint + '02-03-ex01-j') # + [markdown] id="dlERuZRAWGmn" # See if you can reproduce the above plot by using DataFrame method `.plot.scatter()` on `players` DataFrame: # + colab={"base_uri": "https://localhost:8080/", "height": 279} id="Re3GxeejWGmn" executionInfo={"status": "ok", "timestamp": 1615702873261, "user_tz": 300, "elapsed": 586, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjHn5A5nCXb4FsIfIBdin6XTbj6u54lww1hF6ECkT8=s64", "userId": "12308918870841825745"}} outputId="ea81fcb0-c688-4906-9d71-e520107febd7" # Your answer goes here # + id="a4fGv2VAYbW5" executionInfo={"status": "ok", "timestamp": 1615702875962, "user_tz": 300, "elapsed": 429, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjHn5A5nCXb4FsIfIBdin6XTbj6u54lww1hF6ECkT8=s64", "userId": "12308918870841825745"}} # SOLUTION: Uncomment and execute the cell below to get help #disp(hint + '02-03-ex01-k') # + [markdown] id="pj0UCJnMWGmn" # Now with ggplot style: # + colab={"base_uri": "https://localhost:8080/", "height": 282} id="L_TkgDqgWGmo" executionInfo={"status": "ok", "timestamp": 1615702887250, "user_tz": 300, "elapsed": 635, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjHn5A5nCXb4FsIfIBdin6XTbj6u54lww1hF6ECkT8=s64", "userId": "12308918870841825745"}} outputId="7caf1adb-9492-498b-ce8b-54b6687d5fff" # Your answer goes here # + id="EH7wtwcqYiUR" executionInfo={"status": "ok", "timestamp": 1615702885154, "user_tz": 300, "elapsed": 449, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjHn5A5nCXb4FsIfIBdin6XTbj6u54lww1hF6ECkT8=s64", "userId": "12308918870841825745"}} # SOLUTION: Uncomment and execute the cell below to get help #disp(hint + '02-03-ex01-l') # + [markdown] id="ICOgI0FxYrDS" # Notice that pandas way has the advantage that x and y axis automatically get populated by the column names.
03-Data-Import-Export/Exercise-01-Preview-of-Data-Science-Tools.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import os, sys sys.path.insert(1, os.path.abspath("../../../")) # for dowhy source code # + import numpy as np import pandas as pd import logging import dowhy from dowhy import CausalModel import dowhy.datasets import econml import warnings warnings.filterwarnings('ignore') # - data = dowhy.datasets.linear_dataset(10, num_common_causes=4, num_samples=10000, num_instruments=0, num_effect_modifiers=0, treatment_is_binary=False) df=data['df'] df.head() model = CausalModel(data=data["df"], treatment=data["treatment_name"], outcome=data["outcome_name"], graph=data["gml_graph"]) model.view_model() from IPython.display import Image, display display(Image(filename="causal_model.png")) identified_estimand= model.identify_effect() print(identified_estimand) from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LassoCV from sklearn.ensemble import GradientBoostingRegressor econml_estimate = model.estimate_effect(identified_estimand, method_name="backdoor.econml.dml.DMLCate", target_units = lambda df: df["X0"]>1, confidence_intervals=False, method_params={"init_params":{'model_y':GradientBoostingRegressor(), 'model_t': GradientBoostingRegressor(), "model_final":LassoCV(), 'featurizer':PolynomialFeatures(degree=1, include_bias=True)}, "fit_params":{}}) print(econml_estimate) print("True causal estimate is", data["ate"]) # ### Linear Model linear_estimate = model.estimate_effect(identified_estimand, method_name="backdoor.linear_regression") print(linear_estimate) # ## Refuting the estimate # ### Random res_random=model.refute_estimate(identified_estimand, econml_estimate, method_name="random_common_cause") print(res_random) # ### Adding an unobserved common cause variable res_unobserved=model.refute_estimate(identified_estimand, econml_estimate, method_name="add_unobserved_common_cause", confounders_effect_on_treatment="binary_flip", confounders_effect_on_outcome="linear", effect_strength_on_treatment=0.01, effect_strength_on_outcome=0.02) print(res_unobserved) # #### Replacing treatment with a random (placebo) variable res_placebo=model.refute_estimate(identified_estimand, econml_estimate, method_name="placebo_treatment_refuter", placebo_type="permute") print(res_placebo) # #### Removing a random subset of the data res_subset=model.refute_estimate(identified_estimand, econml_estimate, method_name="data_subset_refuter", subset_fraction=0.8) print(res_subset)
docs/source/example_notebooks/dowhy-conditional-treatment-effects.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # ## Video Game Sales # oqla alrefai 11/15/2021 # import pandas as pd # #%matplotlib_inline #import matplotlib.pyplot as plt df = pd.read_csv("vgsales.csv") df.head(3) # #### the most common video game publisher df['Publisher'].mode() # #### the most common platform df['Platform'].mode() # #### the most common genre df['Genre'].mode() # #### the top 20 highest grossing games # + df.sort_values('Global_Sales',ascending=False).head(20) # - # #### the median of North American video game sales df[['Name', 'NA_Sales']].median()[0] df[df['NA_Sales'] == df[['Name', 'NA_Sales']].median()[0]].head() x = (df['NA_Sales'].head(1)) meanValue = df["NA_Sales"].mean() standardDeviation = (x - meanValue)/df["NA_Sales"].std() standardDeviation[0] df[df['Platform']== 'Wii'].Global_Sales.mean() # ### Come up with 3 more questions that can be answered with this data set. # # #### what is the most recent game produced ? x = df['Year'].max() data = df[df['Year'] == x].head(1) data['Name'] # #### find top 5 games in 2015? data = df[df['Year'] == 2010] data[['Name','Rank']].head(5) # #### display the top sport games in rank ? # sportGames = df[df['Genre']=='Sports'] sportGames.sort_values('Rank',ascending=True).head(5)
vg-stats.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .jl # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Julia 1.2.0 # language: julia # name: julia-1.2 # --- # # Notes: # # * fuck I lost my notes argh # # * we have to multiply density, $f(x)$ by some interval $dx$ because the probability of getting an exact value is vanishingly small # * we are essentially summing up a bunch of small distributions about each data point to create an overall distribution # * KDE is useful for estimating data points that may not be in the data set # # + using CSV using DataFrames using PyPlot using ScikitLearn using Statistics using Random using LaTeXStrings using Printf # (optional) check out all of the styles! https://matplotlib.org/3.1.1/gallery/style_sheets/style_sheets_reference.html PyPlot.matplotlib.style.use("bmh") # (optional)change settings for all plots at once, e.g. font size rcParams = PyPlot.PyDict(PyPlot.matplotlib."rcParams") rcParams["font.size"] = 16; # - df = CSV.read("apples.csv", copycols=true) first(df, 6) # # Histograms aren't great for estimating densities # * data is jagged/discontinuous # * apparent density depends on bin size and location # * qualitative features in underlying data generating distribution can be hidden depending on how bins are chosen, including small shifts in bins even if they are the same width # * as dimensionality increases, the # of bins grow exponentially and most will end up empty in a higher dimensional histogram in the absence of a shitload of data bins = range(0.0, stop=130, length=8) offsets = range(0.0, 50.0, length=5) for offset in offsets figure() xlabel("Apple Mass (g)", weight="bold") scatter(df[!, :mass], [-0.001 for _ = 1:nrow(df)], marker="+", alpha=0.3, color="C1") hist(df[!, :mass], alpha=0.6, bins=bins.+offset, normed=true) xlim([0, 170]) ylim([-0.002, maximum(ylim())]) ylabel(L"Density $\mathbf{f(m)}$", weight="bold") end # ## kernel functions # (see $\hat{f}(x)$ eqn) # # A kernel function $K_{\lambda}(m, m_{i})$ is a weighting function that assigns a weight to $m_{i}$ based on its distance from $m$. Kernel functions are typically indexed by $\lambda$, the mandwidth that determines the neighborhood around $m$ where teh kernel for $m_{i}$ is sizeable.
In-Class Notes/Kernel Density Estimation/.ipynb_checkpoints/kernel density estimation-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: RAPIDS Stable # language: python # name: rapids-stable # --- # # BlazingContext API # ## Storage Plugins # ### AWS S3 # [Docs](https://docs.blazingdb.com/docs/s3) | [BlazingSQL Notebooks](https://app.blazingsql.com/jupyter/user-redirect/lab/workspaces/auto-b/tree/Welcome_to_BlazingSQL_Notebooks/docs/blazingsql.ipynb#AWS-S3) from blazingsql import BlazingContext bc = BlazingContext() # Register public AWS S3 bucket. bc.s3('bsql', bucket_name='blazingsql-colab') # Create a table from an S3 bucket. bc.create_table('taxi', 's3://bsql/yellow_taxi/taxi_data.parquet') # ### Dask Remote Data # [Docs](https://docs.blazingdb.com/docs/dask) | [BlazingSQL Notebooks](https://app.blazingsql.com/jupyter/user-redirect/lab/workspaces/auto-b/tree/Welcome_to_BlazingSQL_Notebooks/docs/blazingsql.ipynb#AWS-S3) # #### Dask Remote Data - AWS from blazingsql import BlazingContext bc = BlazingContext() # + import dask.dataframe as dd df = dd.read_csv('s3://nyc-tlc/trip data/yellow_tripdata_2018-04.csv', storage_options={'anon': True, 'use_ssl': False}) bc.create_table('taxi', df.compute()) # - # #### Dask Remote Data - URL # + from dask_cuda import LocalCUDACluster from dask.distributed import Client cluster = LocalCUDACluster() client = Client(cluster) from blazingsql import BlazingContext bc = BlazingContext(dask_client=client, network_interface='lo') # + import dask.dataframe as dd df = dd.read_csv('https://s3.amazonaws.com/nyc-tlc/trip+data/yellow_tripdata_2015-01.csv') bc.create_table('taxi', df.compute()) # - # ### MinIo S3 # [Docs](https://docs.blazingdb.com/docs/minio) | [BlazingSQL Notebooks](https://app.blazingsql.com/jupyter/user-redirect/lab/workspaces/auto-b/tree/Welcome_to_BlazingSQL_Notebooks/blog_posts/querying_minio_with_blazingsql.ipynb) # Learn how to query MinIO with our blog post "[Querying MinIO with BlazingSQL](https://blog.blazingdb.com/querying-minio-with-blazingsql-91b6b3485027?source=friends_link&sk=a30c725b5bd3e9394801e21fbf954283)" or try out the [querying_minio_with_blazingsql.ipynb demo here](https://app.blazingsql.com/jupyter/user-redirect/lab/workspaces/auto-b/tree/Welcome_to_BlazingSQL_Notebooks/blog_posts/querying_minio_with_blazingsql.ipynb). # # BlazingSQL Docs # **[Table of Contents](../TABLE_OF_CONTENTS.ipynb) | [Issues (GitHub)](https://github.com/BlazingDB/Welcome_to_BlazingSQL_Notebooks/issues)**
docs/blazingsql/blazingcontext_api/storage_plugins.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import pandas as pd from nltk.tokenize import word_tokenize from nltk.corpus import stopwords from nltk.stem import PorterStemmer import nltk import re from gensim.models import Word2Vec from nltk.corpus import stopwords from nltk.tokenize import word_tokenize,sent_tokenize from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from sklearn.model_selection import train_test_split from sklearn.decomposition import PCA import matplotlib.pyplot as plt # - plt.rcParams['figure.figsize'] = [10, 10] data = pd.read_csv('../../chapter 8/data/movie_reviews.csv', encoding='latin-1') data.shape data.SentimentText = data.SentimentText.str.lower() def clean_str(string): string = re.sub(r"https?\://\S+", '', string) string = re.sub(r'\<a href', ' ', string) string = re.sub(r'&amp;', '', string) string = re.sub(r'<br />', ' ', string) string = re.sub(r'[_"\-;%()|+&=*%.,!?:#$@\[\]/]', ' ', string) string = re.sub('\d','', string) string = re.sub(r"can\'t", "cannot", string) string = re.sub(r"it\'s", "it is", string) return string data.SentimentText = data.SentimentText.apply(lambda x: clean_str(str(x))) pd.Series(' '.join(data['SentimentText']).split()).value_counts().head(10) stop_words = stopwords.words('english') + ['movie', 'film', 'time'] stop_words = set(stop_words) remove_stop_words = lambda r: [[word for word in word_tokenize(sente) if word not in stop_words] for sente in sent_tokenize(r)] data['SentimentText'] = data['SentimentText'].apply(remove_stop_words) data['SentimentText'][0] data['SentimentText'] = data['SentimentText'].apply(lambda x: x[0]) model = Word2Vec( data['SentimentText'], iter=10, size=100, window=5, min_count=5, workers=10) vocab = list(model.wv.vocab) len(vocab) model.wv.most_similar('insight') model.wv.similarity(w1='happy', w2='sad') model.wv.similarity(w1='violent', w2='brutal') # + word_limit = 200 X = model[model.wv.vocab][:word_limit] pca = PCA(n_components=2) result = pca.fit_transform(X) plt.scatter(result[:, 0], result[:, 1]) words = list(model.wv.vocab)[:word_limit] for i, word in enumerate(words): plt.annotate(word, xy=(result[i, 0], result[i, 1])) plt.show() # - model.wv.save_word2vec_format('movie_embedding.txt', binary=False)
Chapter07/Exercise 56.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- from sklearn.feature_extraction.text import TfidfVectorizer def get_tf_idf_vectors(corpus): tfidf_model = TfidfVectorizer() vector_list = tfidf_model.fit_transform(corpus).todense() return vector_list corpus = [ 'Data Science is an overlap between Arts and Science', 'Generally, Arts graduates are right-brained and Science graduates are left-brained', 'Excelling in both Arts and Science at a time becomes difficult', 'Natural Language Processing is a part of Data Science' ] vector_list = get_tf_idf_vectors(corpus) print(vector_list)
Chapter02/Exercise2.15/Exercise 2.15.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # # Monte Carlo Techniques # ## Part 1: Examples # ### Example: coin flip # Let's check how to use the random number generator in numpy # ?np.random # Alternatively, we can look at the documentation on the numpy site: https://numpy.org/doc/stable/reference/random/generated/numpy.random.rand.html # + # standard preamble import numpy as np import scipy as sp from scipy import stats import matplotlib.pyplot as plt # %matplotlib inline outcomes = ('Heads','Tails') def flip(): if np.random.random() > 0.5: return outcomes[1] return outcomes[0] for i in range(5): print (flip()) # - print(flip()) # ### Example: dice roll # + def dice(): return int(np.random.random()*6)+1 print (dice()) # - for i in range(5): print (dice()) x = [dice() for i in range(10000)] n, bins, patches = plt.hist(x,6,(0.5,6.5)) plt.xlabel('Dice Number') plt.ylabel('Number of Values') # ### Example: deck of cards import random import itertools SUITS = 'cdhs' RANKS = '23456789TJQKA' DECK = tuple(''.join(card) for card in itertools.product(RANKS, SUITS)) hand = random.sample(DECK, 5) print (hand) # Let's take a brief look at the documentation for itertools: https://docs.python.org/3/library/itertools.html # ## Part 2 # ### Example: Linear Congruential Generator # + #set the seed for random number generation myRandomSeed = 504 # define function to calculate random number def myRandom(a=65539, b=0, c=int(2**31-1)): global myRandomSeed x = (a*myRandomSeed+b) % c myRandomSeed = x return x # print out the random numbers in a string out = "" for i in range(5): out += str(myRandom()) out += " " print (out) out = "" # now, choose a very particular value for the random seed myRandomSeed = 1 for i in range(20): out += str(myRandom(a=5, b=3, c=8)) out += " " print (out) # + ## Part 3: Random numbers in python # - # ### Example: Python random numbers # integer random number between [a..b] print (np.random.randint(0,6)+1) # float random number between [0..1) print (np.random.random()) x01 = np.random.random() # [0..1) x05 = x01*5 # [0..5) x510 = x05+5 # [5..10) print(x510) # float random number between [a..b) print (np.random.uniform(5,10)) # Choose a random element print (np.random.choice(['a','b','c','d','e','f','g','h','i','j'])) # plot distribution ds = np.random.uniform(5,10,size=10000000) print('Mean = {0:5.3f}'.format(np.mean(ds))) print('Std. dev. = {0:5.3f}'.format(np.std(ds))) plt.hist(ds,50,density=True) plt.show() # ### Example: Python random number generators ds = np.random.exponential(scale=2.2,size=1000) # generate life time of a muon (in usec) print('Mean = {0:5.3f}'.format(np.mean(ds))) print('Std. dev. = {0:5.3f}'.format(np.std(ds))) plt.hist(ds,50,density=True) plt.show() # See discussion of the [Cauchy distribution](https://en.wikipedia.org/wiki/Cauchy_distribution) in wikipedia for further information. ds = np.random.standard_cauchy(size=10000) print('Mean = {0:5.3f}'.format(np.mean(ds))) print('Std. dev. = {0:5.3f}'.format(np.std(ds))) plt.hist(ds,20,density=True) plt.show() ds = np.random.triangular(5,10,15,size=10000000) print('Mean = {0:5.3f}'.format(sp.mean(ds))) print('Std. dev. = {0:5.3f}'.format(sp.std(ds))) plt.hist(ds,50,density=True) plt.show()
Week08/L07/Lecture07.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: 'Python 3.7.9 64-bit (''myenv'': conda)' # name: python379jvsc74a57bd00989d4cb382ec003e6ad9ee0079fe5a34620af18f47069c43c62ee5030c1ec77 # --- # # Recommender System # importing the libraries import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt # %matplotlib inline # importing the dataset and converting it into DataFrame df = pd.read_csv('D:/Data Science Stuff/Python for Data Science/3. Jupyter Overview/Refactored_Py_DS_ML_Bootcamp-master/19-Recommender-Systems/u.data', sep='\t', names= ['user_id', 'item_id', 'rating', 'timestamp']) #checking first few rows of the data df.head() #seems like this is a tab separated data, we can use sep="\t" while reading the file # The data we have imported is called as the movie lens data # But we don't have movie titles in it, we have it in a separate file, we will import that too.. movie_titles = pd.read_csv('D:/Data Science Stuff/Python for Data Science/3. Jupyter Overview/Refactored_Py_DS_ML_Bootcamp-master/19-Recommender-Systems/Movie_Id_Titles') movie_titles[:5] # Now we will merge this movie_titles to the original dataframe based on the item_id df = pd.merge(df, movie_titles, on='item_id') df.head() df.shape # Number of unique movies present in the data df['title'].nunique() # now let's find the mean ratings for every movie df.groupby('title')['rating'].mean().sort_values(ascending= False).head() # * What we did here is that, we had ratings given from individual users and recorded in a dataset. # * So now we grouped the movies and calculated their average ratings given from all the users to a movie. # * the data shown above might not be correct because, these might be those movies where only 1 user might have watched it rated them a 5 star # Movies with the most ratings df.groupby('title')['rating'].count().sort_values(ascending= False).head() # * as we can see here that these are the popular movies and they have high number of reviews/ ratings from the users # * From this data we can see that these are the popular movies from the entire collection of dataset # We create a separate dataframe off average ratings from this data ratings = pd.DataFrame(df.groupby('title')['rating'].mean()) ratings.head() # Now let's add a column to this ratings dataframe which tells us about the number of ratings based off the title ratings['num_of_ratings'] = pd.DataFrame(df.groupby('title')['rating'].count()) ratings.head() # *TIME FOR SOME EDA* # A histogram which tells us about the distribution of number of ratings sns.set_style('whitegrid') sns.displot(ratings.num_of_ratings, bins=70, color= 'green') # * Here, we can see that there are lot of movies where only one of the user has rated the movie # A histogram which tells us about the distribution of ratings sns.set_style('darkgrid') sns.displot(ratings.rating, color= 'red') # * From this visualisation, we see that the distribution is normally distributed # * Except, for the outliers at 1, which clearly states that many movies have been rated poor # * We see another intreseting fact that the frequency of the ratings is more on whole numbered ratings which shows how the users rate the movies in the scale of 1-5 # Let's have a look at bi-variate analysis between ratings and number of ratings sns.set_style('whitegrid') sns.jointplot(x='rating', y='num_of_ratings', data=ratings, alpha= 0.5, color='red') # * From this visualisation we can make out that, there are many number of ratings for some of the popular movies maybe # * As expected, there are few movies which are rated 5 and 1 and not many users have rated them, so we have to filter this items in the further process. # **Now building a recommendation engine based on item** # Create a matrix that has user user_Id one one axis and the movie titles on the another axis movie_matrix = df.pivot_table(index='user_id', columns='title', values= 'rating') movie_matrix.head() # we see that there are many null values present which is obvious that a single user might have not watched all the movies and have rated them. # Listing out the popular movies ratings.sort_values(by='num_of_ratings', ascending= False).head() # We filter out 2 from the popular movies and compare them to the correaltion between them with other movies starwars_ratings = movie_matrix['Star Wars (1977)'] liarliar_ratings = movie_matrix['Liar Liar (1997)'] # Now, we group the movies which are similar to starwars similar_to_starwars = movie_matrix.corrwith(starwars_ratings) similar_to_starwars[:10] corr_starwars = pd.DataFrame(similar_to_starwars, columns= ['Correlation']) corr_starwars.dropna(inplace=True) corr_starwars[:5] # * This tells us that how correlated this movies user ratings were to the use ratings of star wars movies. # * But there are some movies which doesn't give the result we are expecting, because there might be some users who might have watched only one movie and would have rated similar to Star wars. corr_starwars.sort_values(by='Correlation', ascending= False).head(10) # So we can set a threshold/ minimum number of ratings necessary in order to consider it for our recommendation model # # So we filter out the movies which has <100 num_of_rating corr_starwars = corr_starwars.join(ratings.num_of_ratings) corr_starwars.sort_values(by='Correlation', ascending= False)[:10] corr_starwars[corr_starwars.num_of_ratings > 100].sort_values(by='Correlation', ascending= False)[1:10] # * So from this data we conclude saying that the user who liked Star Wars can get item based recommendation based on the above mentioned matrix. # * In other words, he is likely to get recommendations of these movies which are popular like Star Wars and are also having high correlation compared to Star Wars.
Machine Learning/Recommender Systems/Recommender.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # T9 Regression analysis # ## Linear and polynomial regression # We are given two generic data-sets consisting of observations at diffferent values of x. The task is to determine whether there exists a relationship between the independent variable x and the variable y? In other words, perform a regression analysis on the data-sets and determine whether changes in the independent variable predict changes in the dependent variable. # # We will use linear regression which assumes a linear (geometrically speaking: a line) relationship between the inpependent and dependent variable. Linear regression estimates the offset and the slope as predictors for the relationship. # # Polynomial regression extends the linear model by adding extra predictors, obtained by raising each of the original predictors to a power. For example, a cubic regression uses three variables $X^1$, $X^2$, $X^3$, as predictors. This approach provides a simple way to provide a non-linear fit to data. # # # The data is provided in the two files `data1-regression.npy` and `data2-regression.npy`. Remember that numpy binary files can loaded with `np.load([name of file])`. # # # # #### Performing regression analysis 'by hand' # # Let's start by performing the regression analysis 'by hand', which means that we will successively perform the steps. # # 1. Let's start by plotting both data-sets. Based on visual inspection, do you expect none, one or both data-sets to exhibit a relationship? # 1. Let's fit at line to the data using the numpy `polyfit()` function. This function takes, x, y and the degree of the polynomial function as input arguments and returns the polynomial coefficients. # * Calculate the predicted values based on the linear fit. The numpy `polyval()` function can be used for that, it takes the polynomial coefficients and the x values as input arguments. # * Plot both, the cloud of data and the fitted line. # * Calculate the $R^2$ value. Note that this requires to calculate the total sum of squares $SS_{tot}$ and the residual sum of squares $SS_{res}$. Check the formula for $R^2$ from the lecture. # * Plot the residual of both data-sets. What can you say about the statistics of the residuals? # * Perform the regression now using polynomials of higher order (2,4,8,16) to predict the relationship betweeen x and y. How does $R^2$ change for both data-sets when using high-order polynomials? Plot $R^2$ as a function of the polynomial order. import numpy as np import matplotlib.pyplot as plt # your code # #### Performing regression using precompiled scipy function # # Let's now perform the regression analysis using the `scipy.stats` function : `linregress()`. This function takes the x and the y values as input arguments. Compare the results of `linregress()` with the polynomial coefficients and the $R^2$ values caluclated above. from scipy.stats import linregress # ## Logistic regression # We have a data-set (stored in the variable `data3`) which contains data on how students passed a test. The x values are hours spent preparing for an exam and the y-values inform whether or not the student passed the exam. In turn, the y-values are # binary taking either 0 - the student didn't pass the test - or 1 - the student passed the test - as values. Let's perform a logistic regression on this data-set. The result will help us decide how much time we should spend preparing the exam in order to have a good chance succeeding. data3 = np.array(([12,12.5,13.2,14,14.7,15.5,15.9,16.5,16.8,17,17.1,17.7,17.9,18.1,18.2,18.8,19.8,20.3,20.8,21,22], [0,0,0,0,0,0,0,1,0,1,0,0,1,1,1,1,1,1,1,1,1])) # #### Perform logistic regression using scikit-learn function # # 1. Plot the data. Based on visual inspection, how much time should you invest to have a good chance of passing the exam? # + # your code # - # 2. Perfrom the logistic regression using the code below. # + from sklearn.linear_model import LogisticRegression displacement = np.mean(data3[0]) logRegression = LogisticRegression(solver='lbfgs') logRegression.fit(data3[0].reshape(len(data3[0]),1)-displacement,data3[1]) x_pred = np.linspace(data3[0].min()-displacement,data3[0].max()-displacement,1000) y_pred = logRegression.predict_proba(x_pred.reshape(len(x_pred),1)) plt.plot(data3[0],data3[1],'o') plt.plot(x_pred+displacement,y_pred[:,1]) plt.show() # - # 3. Based on the logistic regression, how much time should you invest preparing the exam in order to have a 50 % change or more to pass the test? # + # your code # - # ## The end
tutorials/T09_Regression-analysis-Empty.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # # A mesh class for a tesseroid relief # # There is a `PrismRelief` mesh class in [Fatiando a Terra](http://www.fatiando.org/) but we still need a `TesseroidRelief` for this inversion. This is a mesh of tesseroids distributed along an area. They undulate below and above a reference level, describing the relief of an interface. Tesseroids have either the top of bottom fixed to a reference height. The other end undulates along a relief. The `TesseroidRelief` class is defined in the [`mohoinv.py`](mohoinv.py) module. This notebook will show some of the features of the mesh and how to use it. # ## Package imports # Insert plots into the notebook # %matplotlib inline from __future__ import division, unicode_literals import numpy as np import matplotlib.pyplot as plt from IPython.display import Image import multiprocessing import seaborn # Makes the default style of the plots nicer # Load the required modules from Fatiando a Terra and show the specific version of the library used. from fatiando import gridder, utils from fatiando.gravmag import tesseroid import fatiando print("Using Fatiando a Terra version: {}".format(fatiando.__version__)) from mohoinv import TesseroidRelief # ## Create some synthetic relief # Define a regular grid. # shape is nlat, nlon = the number of points in the grid shape = (41, 31) # Make a regular grid inside an area = (s, n, w, e) area = (20, 60, -40, 40) lat, lon, h = gridder.regular(area, shape, z=250e3) # The model area is slightly larger because the points generated above are in the center of each cell. dlat, dlon = gridder.spacing(area, shape) s, n, w, e = area modelarea = (s - dlat/2, n + dlat/2, w - dlon/2, e + dlon/2) # Make a checker board relief undulating along a specified height reference. f = 0.2 reference = -35e3 relief = 10e3*np.sin(0.5*f*lon)*np.cos(f*lat) + reference plt.figure(figsize=(7, 3)) plt.title('Synthetic relief') plt.axis('scaled') plt.pcolormesh(lon.reshape(shape), lat.reshape(shape), relief.reshape(shape), cmap="RdYlBu_r") plt.colorbar(pad=0.01).set_label('meters') plt.xlim(lon.min(), lon.max()) plt.ylim(lat.min(), lat.max()) plt.tight_layout() # Set a density contrast for the relief. The density contrast is negative if the relief is below the reference and positive otherwise. density = 600*np.ones_like(relief) density[relief < reference] *= -1 plt.figure(figsize=(7, 3)) plt.title('Relief density contrast') plt.axis('scaled') plt.pcolormesh(lon.reshape(shape), lat.reshape(shape), density.reshape(shape), cmap="RdBu_r") plt.colorbar(pad=0.01).set_label(u'kg/m³') plt.xlim(lon.min(), lon.max()) plt.ylim(lat.min(), lat.max()) plt.tight_layout() # Now we can create a mesh. sample_mesh = TesseroidRelief(modelarea, shape, relief, reference, {'density': density}) # ## Calculate the gravitational effect of this mesh # # The mesh behaves like a list of `Tesseroid` objects. So we can pass it to any function in Fatiando a Terra that takes such list as input. # # Below, we'll show an example of using the forward modeling functions in Fatiando to calculate the gravitational effect of the above relief. ncpu = multiprocessing.cpu_count() print('Number of cores: {}'.format(ncpu)) # Forward model the data on the grid generated above using all available cores of the processor. data = tesseroid.gz(lon, lat, h, sample_mesh, njobs=ncpu) # The warnings above are because some small tesseroids (below 10 cm dimensions) are ignored to avoid numerical issues. plt.figure(figsize=(7, 3)) plt.title('Relief gravity anomaly') plt.axis('scaled') plt.tricontourf(lon, lat, data, 40, cmap="RdBu_r") plt.colorbar(pad=0.01).set_label(u'mGal') plt.xlim(lon.min(), lon.max()) plt.ylim(lat.min(), lat.max()) plt.tight_layout()
code/tesseroid-relief-example.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # This notebook was prepared by [<NAME>](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/system-design-primer-primer). # # Design a call center # ## Constraints and assumptions # # * What levels of employees are in the call center? # * Operator, supervisor, director # * Can we assume operators always get the initial calls? # * Yes # * If there is no free operators or the operator can't handle the call, does the call go to the supervisors? # * Yes # * If there is no free supervisors or the supervisor can't handle the call, does the call go to the directors? # * Yes # * Can we assume the directors can handle all calls? # * Yes # * What happens if nobody can answer the call? # * It gets queued # * Do we need to handle 'VIP' calls where we put someone to the front of the line? # * No # * Can we assume inputs are valid or do we have to validate them? # * Assume they're valid # ## Solution # + # %%writefile call_center.py from abc import ABCMeta, abstractmethod from collections import deque from enum import Enum class Rank(Enum): OPERATOR = 0 SUPERVISOR = 1 DIRECTOR = 2 class Employee(metaclass=ABCMeta): def __init__(self, employee_id, name, rank, call_center): self.employee_id = employee_id self.name = name self.rank = rank self.call = None self.call_center = call_center def take_call(self, call): """Assume the employee will always successfully take the call.""" self.call = call self.call.employee = self self.call.state = CallState.IN_PROGRESS def complete_call(self): self.call.state = CallState.COMPLETE self.call_center.notify_call_completed(self.call) @abstractmethod def escalate_call(self): pass def _escalate_call(self): self.call.state = CallState.READY call = self.call self.call = None self.call_center.notify_call_escalated(call) class Operator(Employee): def __init__(self, employee_id, name): super(Operator, self).__init__(employee_id, name, Rank.OPERATOR) def escalate_call(self): self.call.level = Rank.SUPERVISOR self._escalate_call() class Supervisor(Employee): def __init__(self, employee_id, name): super(Operator, self).__init__(employee_id, name, Rank.SUPERVISOR) def escalate_call(self): self.call.level = Rank.DIRECTOR self._escalate_call() class Director(Employee): def __init__(self, employee_id, name): super(Operator, self).__init__(employee_id, name, Rank.DIRECTOR) def escalate_call(self): raise NotImplemented('Directors must be able to handle any call') class CallState(Enum): READY = 0 IN_PROGRESS = 1 COMPLETE = 2 class Call(object): def __init__(self, rank): self.state = CallState.READY self.rank = rank self.employee = None class CallCenter(object): def __init__(self, operators, supervisors, directors): self.operators = operators self.supervisors = supervisors self.directors = directors self.queued_calls = deque() def dispatch_call(self, call): if call.rank not in (Rank.OPERATOR, Rank.SUPERVISOR, Rank.DIRECTOR): raise ValueError('Invalid call rank: {}'.format(call.rank)) employee = None if call.rank == Rank.OPERATOR: employee = self._dispatch_call(call, self.operators) if call.rank == Rank.SUPERVISOR or employee is None: employee = self._dispatch_call(call, self.supervisors) if call.rank == Rank.DIRECTOR or employee is None: employee = self._dispatch_call(call, self.directors) if employee is None: self.queued_calls.append(call) def _dispatch_call(self, call, employees): for employee in employees: if employee.call is None: employee.take_call(call) return employee return None def notify_call_escalated(self, call): # ... def notify_call_completed(self, call): # ... def dispatch_queued_call_to_newly_freed_employee(self, call, employee): # ...
solutions/object_oriented_design/call_center/call_center.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Face Recognition with OpenCV and Python # ## Introduction # What is face recognition? Or what is recognition? When you look at an apple fruit, your mind immediately tells you that this is an apple fruit. This process, your mind telling you that this is an apple fruit is recognition in simple words. So what is face recognition then? I am sure you have guessed it right. When you look at your friend walking down the street or a picture of him, you recognize that he is your friend Paulo. Interestingly when you look at your friend or a picture of him you look at his face first before looking at anything else. Ever wondered why you do that? This is so that you can recognize him by looking at his face. Well, this is you doing face recognition. # # But the real question is how does face recognition works? It is quite simple and intuitive. Take a real life example, when you meet someone first time in your life you don't recognize him, right? While he talks or shakes hands with you, you look at his face, eyes, nose, mouth, color and overall look. This is your mind learning or training for the face recognition of that person by gathering face data. Then he tells you that his name is Paulo. At this point your mind knows that the face data it just learned belongs to Paulo. Now your mind is trained and ready to do face recognition on Paulo's face. Next time when you will see Paulo or his face in a picture you will immediately recognize him. This is how face recognition work. The more you will meet Paulo, the more data your mind will collect about Paulo and especially his face and the better you will become at recognizing him. # # Now the next question is how to code face recognition with OpenCV, after all this is the only reason why you are reading this article, right? OK then. You might say that our mind can do these things easily but to actually code them into a computer is difficult? Don't worry, it is not. Thanks to OpenCV, coding face recognition is as easier as it feels. The coding steps for face recognition are same as we discussed it in real life example above. # # - **Training Data Gathering:** Gather face data (face images in this case) of the persons you want to recognize # - **Training of Recognizer:** Feed that face data (and respective names of each face) to the face recognizer so that it can learn. # - **Recognition:** Feed new faces of the persons and see if the face recognizer you just trained recognizes them. # # OpenCV comes equipped with built in face recognizer, all you have to do is feed it the face data. It's that simple and this how it will look once we are done coding it. # # ![visualization](output/output.png) # ## OpenCV Face Recognizers # OpenCV has three built in face recognizers and thanks to OpenCV's clean coding, you can use any of them by just changing a single line of code. Below are the names of those face recognizers and their OpenCV calls. # # 1. EigenFaces Face Recognizer Recognizer - `cv2.face.createEigenFaceRecognizer()` # 2. FisherFaces Face Recognizer Recognizer - `cv2.face.createFisherFaceRecognizer()` # 3. Local Binary Patterns Histograms (LBPH) Face Recognizer - `cv2.face.createLBPHFaceRecognizer()` # # We have got three face recognizers but do you know which one to use and when? Or which one is better? I guess not. So why not go through a brief summary of each, what you say? I am assuming you said yes :) So let's dive into the theory of each. # ### EigenFaces Face Recognizer # This algorithm considers the fact that not all parts of a face are equally important and equally useful. When you look at some one you recognize him/her by his distinct features like eyes, nose, cheeks, forehead and how they vary with respect to each other. So you are actually focusing on the areas of maximum change (mathematically speaking, this change is variance) of the face. For example, from eyes to nose there is a significant change and same is the case from nose to mouth. When you look at multiple faces you compare them by looking at these parts of the faces because these parts are the most useful and important components of a face. Important because they catch the maximum change among faces, change that helps you differentiate one face from the other. This is exactly how EigenFaces face recognizer works. # # EigenFaces face recognizer looks at all the training images of all the persons as a whole and try to extract the components which are important and useful (the components that catch the maximum variance/change) and discards the rest of the components. This way it not only extracts the important components from the training data but also saves memory by discarding the less important components. These important components it extracts are called **principal components**. # # I will use the terms **principal components**, **variance**, **areas of high change**, **useful features** interchangably a they basically are same thing. # # # Below is an image showing the principal components extracted from a list of faces. # # **Principal Components** # # ![eigenfaces_opencv](visualization/eigenfaces_opencv.png) # # **[source](http://docs.opencv.org/2.4/modules/contrib/doc/facerec/facerec_tutorial.html)** # # You can see that principal components actually represent faces and these faces are called **eigen faces** and hence the name of the algorithm. # # So this is how EigenFaces face recognizer trains itself (by extracting principal components). Remember, it also keeps a record of which principal component belongs to which person. One thing to note in above image is that **Eigenfaces algorithm also considers illumination as an important component**. # # Later during recognition, when you feed a new image to the algorithm, it repeats the same process on that image as well. It extracts the principal component from that new image and compares that component with the list of components it stored during training and finds the component with the best match and returns the person label associated with that best match component. # # Easy peasy, right? Next one is even easier than this one. # ### FisherFaces Face Recognizer # This algorithm is an improved version of EigenFaces face recognizer. Eigenfaces face recognizer looks at all the training faces of all the persons at once and finds principal components from all of them combined. By capturing principal components from all of faces combined you are not focusing on the features that discriminate one person from the other but the features that represent all the faces of all the persons in the training data as a whole. # # This approach has a drawback. For example, consider the illumination changes in following faces. # # ![Illumination changes](visualization/illumination-changes.png) # # You know that the EigenFaces face recognizer also considers illumination as an important component, right? So imagine a scenario in which all the faces of one person has very high illuminiation changes (really dark or really light etc.). EigenFaces face recognizer will consider those illumination changes very useful features and may discard the features of the other persons' faces considering them less useful. Now the features EigenFaces has extracted represent just one person's facial features and not all the persons' facial features. # # How to fix this? We can fix this by tunning EigenFaces face recognizer so that it extracts useful features from faces of each person separately instead of extracting useful features of all the faces combined. This way, even if one person has high illumination changes it will not affect the other persons features extraction process. This is exactly what FisherFaces face recognizer algorithm does. # # Fisherfaces algorithm, instead of extracting useful features that represent all the faces of all the persons, it extracts useful features that discriminate one person from the others. This way features of one person do not dominate (considered more useful features) over the others and you have the features that discriminate one person from the others. # # Below is an image of features extracted using Fisherfaces algorithm. # # **Fisher Faces** # # ![eigenfaces_opencv](visualization/fisherfaces_opencv.png) # # **[source](http://docs.opencv.org/2.4/modules/contrib/doc/facerec/facerec_tutorial.html)** # # You can see that features extracted actually represent faces and these faces are called **fisher faces** and hence the name of the algorithm. # # One thing to note here is that Fisherfaces face recognizer only prevents features of one person from dominating over features of the other persons but it still considers illumination changes as useful features. We know that illumination change is not a useful feature to extract as it is not part of the actual face. Then, wow to get rid of this illumination problem? This is where our next face recognizer comes in. # ### Local Binary Patterns Histograms (LBPH) Face Recognizer # I wrote a detailed explaination on Local Binary Patterns Histograms in my previous article on [face detection](https://www.superdatascience.com/opencv-face-detection/) using local binary patterns histograms. So here I will just give a brief overview of how it works. # # We know that Eigenfaces and Fisherfaces are both affected by light and in real life we can't guarantee perfect light conditions. LBPH face recognizer is an improvement to overcome this drawback. # # Idea is to not look at the image as a whole instead find the local features of an image. LBPH alogrithm try to find the local structure of an image and it does that by comparing each pixel with its neighboring pixels. # # Take a 3x3 window and move it one image, at each move (each local part of an image), compare the pixel at the center with its neighbor pixels. The neighbors with intensity value less than or equal to center pixel are denoted by 1 and others by 0. Then you read these 0/1 values under 3x3 window in a clockwise order and you will have a binary pattern like 11100011 and this pattern is local to a specific area of the image. You do this on whole image and you will have a list of local binary patterns. # # # **LBP Labeling** # # ![LBP labeling](visualization/lbp-labeling.png) # # Now you get why this algorithm has Local Binary Patterns in its name? Because you get a list of local binary patterns. Now you may be wondering, what about the histogram part of the LBPH? Well after you get a list of local binary patterns, you convert each binary pattern into a decimal number using [binary to decimal conversion](https://www.mathsisfun.com/binary-number-system.html) (as shown in above image) and then you make a [histogram](https://www.mathsisfun.com/data/histograms.html) of all of those decimal values. A sample histogram looks like this. # # # **Sample Histogram** # # ![LBP labeling](visualization/histogram.png) # # # # I guess this answers the question about histogram part. So in the end you will have **one histogram for each face** image in the training data set. That means if there were 100 images in training data set then LBPH will extract 100 histograms after training and store them for later recognition. Remember, **algorithm also keeps track of which histogram belongs to which person**. # # Later during recognition, when you will feed a new image to the recognizer for recognition it will generate a histogram for that new image, compare that histogram with the histograms it already has, find the best match histogram and return the person label associated with that best match histogram. # # Below is a list of faces and their respective local binary patterns images. You can see that the LBP images are not affected by changes in light conditions. # # # **LBP Faces** # # ![LBP faces](visualization/lbph-faces.jpg) # # **[source](http://docs.opencv.org/2.4/modules/contrib/doc/facerec/facerec_tutorial.html)** # # The theory part is over and now comes the coding part! Ready to dive into coding? Let's get into it then. # # Coding Face Recognition with OpenCV # The Face Recognition process in this tutorial is divided into three steps. # # 1. **Prepare training data:** In this step we will read training images for each person/subject along with their labels, detect faces from each image and assign each detected face an integer label of the person it belongs to. # 2. **Train Face Recognizer:** In this step we will train OpenCV's LBPH face recognizer by feeding it the data we prepared in step 1. # 3. **Testing:** In this step we will pass some test images to face recognizer and see if it predicts them correctly. # # To detect faces, I will use the code from my previous article on [face detection](https://www.superdatascience.com/opencv-face-detection/). So if you have not read it, I encourage you to do so to understand how face detection works and its Python coding. # ### Code Dependencies # 1. [OpenCV 3.2.0](http://opencv.org/releases.html). # 2. [Python v3.5](https://www.python.org/downloads/). # 3. [NumPy](http://www.numpy.org/) Numpy makes computing in Python easy. Amont other things it contains a powerful implementation of N-dimensional arrays which we will use for feeding data as input to OpenCV functions. # ### Import Required Modules # Before starting the actual coding we need to import the required modules for coding. So let's import them first. # # - **cv2:** is _OpenCV_ module for Python which we will use for face detection and face recognition. # - **os:** We will use this Python module to read our training directories and file names. # - **numpy:** We will use this module to convert Python lists to numpy arrays as OpenCV face recognizers accept numpy arrays. #import OpenCV module import cv2 #import os module for reading training data directories and paths import os #import numpy to convert python lists to numpy arrays as #it is needed by OpenCV face recognizers import numpy as np # ### Training Data # The more images used in training the better. Normally a lot of images are used for training a face recognizer so that it can learn different looks of the same person, for example with glasses, without glasses, laughing, sad, happy, crying, with beard, without beard etc. To keep our tutorial simple we are going to use only 12 images for each person. # # So our training data consists of total 2 persons with 12 images of each person. All training data is inside _`training-data`_ folder. _`training-data`_ folder contains one folder for each person and **each folder is named with format `sLabel (e.g. s1, s2)` where label is actually the integer label assigned to that person**. For example folder named s1 means that this folder contains images for person 1. The directory structure tree for training data is as follows: # # ``` # training-data # |-------------- s1 # | |-- 1.jpg # | |-- ... # | |-- 12.jpg # |-------------- s2 # | |-- 1.jpg # | |-- ... # | |-- 12.jpg # ``` # # The _`test-data`_ folder contains images that we will use to test our face recognizer after it has been successfully trained. # As OpenCV face recognizer accepts labels as integers so we need to define a mapping between integer labels and persons actual names so below I am defining a mapping of persons integer labels and their respective names. # # **Note:** As we have not assigned `label 0` to any person so **the mapping for label 0 is empty**. #there is no label 0 in our training data so subject name for index/label 0 is empty subjects = ["", "<NAME>", "<NAME>"] # ### Prepare training data # You may be wondering why data preparation, right? Well, OpenCV face recognizer accepts data in a specific format. It accepts two vectors, one vector is of faces of all the persons and the second vector is of integer labels for each face so that when processing a face the face recognizer knows which person that particular face belongs too. # # For example, if we had 2 persons and 2 images for each person. # # ``` # PERSON-1 PERSON-2 # # img1 img1 # img2 img2 # ``` # # Then the prepare data step will produce following face and label vectors. # # ``` # FACES LABELS # # person1_img1_face 1 # person1_img2_face 1 # person2_img1_face 2 # person2_img2_face 2 # ``` # # # Preparing data step can be further divided into following sub-steps. # # 1. Read all the folder names of subjects/persons provided in training data folder. So for example, in this tutorial we have folder names: `s1, s2`. # 2. For each subject, extract label number. **Do you remember that our folders have a special naming convention?** Folder names follow the format `sLabel` where `Label` is an integer representing the label we have assigned to that subject. So for example, folder name `s1` means that the subject has label 1, s2 means subject label is 2 and so on. The label extracted in this step is assigned to each face detected in the next step. # 3. Read all the images of the subject, detect face from each image. # 4. Add each face to faces vector with corresponding subject label (extracted in above step) added to labels vector. # Did you read my last article on [face detection](https://www.superdatascience.com/opencv-face-detection/)? No? Then you better do so right now because to detect faces, I am going to use the code from my previous article on [face detection](https://www.superdatascience.com/opencv-face-detection/). So if you have not read it, I encourage you to do so to understand how face detection works and its coding. Below is the same code. #function to detect face using OpenCV def detect_face(img): #convert the test image to gray image as opencv face detector expects gray images gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #load OpenCV face detector, I am using LBP which is fast #there is also a more accurate but slow Haar classifier face_cascade = cv2.CascadeClassifier('opencv-files/lbpcascade_frontalface.xml') #let's detect multiscale (some images may be closer to camera than others) images #result is a list of faces faces = face_cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5); #if no faces are detected then return original img if (len(faces) == 0): return None, None #under the assumption that there will be only one face, #extract the face area (x, y, w, h) = faces[0] #return only the face part of the image return gray[y:y+w, x:x+h], faces[0] # I am using OpenCV's **LBP face detector**. On _line 4_, I convert the image to grayscale because most operations in OpenCV are performed in gray scale, then on _line 8_ I load LBP face detector using `cv2.CascadeClassifier` class. After that on _line 12_ I use `cv2.CascadeClassifier` class' `detectMultiScale` method to detect all the faces in the image. on _line 20_, from detected faces I only pick the first face because in one image there will be only one face (under the assumption that there will be only one prominent face). As faces returned by `detectMultiScale` method are actually rectangles (x, y, width, height) and not actual faces images so we have to extract face image area from the main image. So on _line 23_ I extract face area from gray image and return both the face image area and face rectangle. # # Now you have got a face detector and you know the 4 steps to prepare the data, so are you ready to code the prepare data step? Yes? So let's do it. #this function will read all persons' training images, detect face from each image #and will return two lists of exactly same size, one list # of faces and another list of labels for each face def prepare_training_data(data_folder_path): #------STEP-1-------- #get the directories (one directory for each subject) in data folder dirs = os.listdir(data_folder_path) #list to hold all subject faces faces = [] #list to hold labels for all subjects labels = [] #let's go through each directory and read images within it for dir_name in dirs: #our subject directories start with letter 's' so #ignore any non-relevant directories if any if not dir_name.startswith("s"): continue; #------STEP-2-------- #extract label number of subject from dir_name #format of dir name = slabel #, so removing letter 's' from dir_name will give us label label = int(dir_name.replace("s", "")) #build path of directory containin images for current subject subject #sample subject_dir_path = "training-data/s1" subject_dir_path = data_folder_path + "/" + dir_name #get the images names that are inside the given subject directory subject_images_names = os.listdir(subject_dir_path) #------STEP-3-------- #go through each image name, read image, #detect face and add face to list of faces for image_name in subject_images_names: #ignore system files like .DS_Store if image_name.startswith("."): continue; #build image path #sample image path = training-data/s1/1.pgm image_path = subject_dir_path + "/" + image_name #read image image = cv2.imread(image_path) #display an image window to show the image cv2.imshow("Training on image...", image) cv2.waitKey(100) #detect face face, rect = detect_face(image) #------STEP-4-------- #for the purpose of this tutorial #we will ignore faces that are not detected if face is not None: #add face to list of faces faces.append(face) #add label for this face labels.append(label) cv2.destroyAllWindows() cv2.waitKey(1) cv2.destroyAllWindows() return faces, labels # I have defined a function that takes the path, where training subjects' folders are stored, as parameter. This function follows the same 4 prepare data substeps mentioned above. # # **(step-1)** On _line 8_ I am using `os.listdir` method to read names of all folders stored on path passed to function as parameter. On _line 10-13_ I am defining labels and faces vectors. # # **(step-2)** After that I traverse through all subjects' folder names and from each subject's folder name on _line 27_ I am extracting the label information. As folder names follow the `sLabel` naming convention so removing the letter `s` from folder name will give us the label assigned to that subject. # # **(step-3)** On _line 34_, I read all the images names of of the current subject being traversed and on _line 39-66_ I traverse those images one by one. On _line 53-54_ I am using OpenCV's `imshow(window_title, image)` along with OpenCV's `waitKey(interval)` method to display the current image being traveresed. The `waitKey(interval)` method pauses the code flow for the given interval (milliseconds), I am using it with 100ms interval so that we can view the image window for 100ms. On _line 57_, I detect face from the current image being traversed. # # **(step-4)** On _line 62-66_, I add the detected face and label to their respective vectors. # But a function can't do anything unless we call it on some data that it has to prepare, right? Don't worry, I have got data for two faces. I am sure you will recognize at least one of them! # # ![training-data](visualization/test-images.png) # # Let's call this function on images of these beautiful celebrities to prepare data for training of our Face Recognizer. Below is a simple code to do that. # + #let's first prepare our training data #data will be in two lists of same size #one list will contain all the faces #and other list will contain respective labels for each face print("Preparing data...") faces, labels = prepare_training_data("training-data") print("Data prepared") #print total faces and labels print("Total faces: ", len(faces)) print("Total labels: ", len(labels)) # - # This was probably the boring part, right? Don't worry, the fun stuff is coming up next. It's time to train our own face recognizer so that once trained it can recognize new faces of the persons it was trained on. Read? Ok then let's train our face recognizer. # ### Train Face Recognizer # As we know, OpenCV comes equipped with three face recognizers. # # 1. EigenFace Recognizer: This can be created with `cv2.face.createEigenFaceRecognizer()` # 2. FisherFace Recognizer: This can be created with `cv2.face.createFisherFaceRecognizer()` # 3. Local Binary Patterns Histogram (LBPH): This can be created with `cv2.face.LBPHFisherFaceRecognizer()` # # I am going to use LBPH face recognizer but you can use any face recognizer of your choice. No matter which of the OpenCV's face recognizer you use the code will remain the same. You just have to change one line, the face recognizer initialization line given below. # + #create our LBPH face recognizer face_recognizer = cv2.face.createLBPHFaceRecognizer() #or use EigenFaceRecognizer by replacing above line with #face_recognizer = cv2.face.createEigenFaceRecognizer() #or use FisherFaceRecognizer by replacing above line with #face_recognizer = cv2.face.createFisherFaceRecognizer() # - # Now that we have initialized our face recognizer and we also have prepared our training data, it's time to train the face recognizer. We will do that by calling the `train(faces-vector, labels-vector)` method of face recognizer. #train our face recognizer of our training faces face_recognizer.train(faces, np.array(labels)) # **Did you notice** that instead of passing `labels` vector directly to face recognizer I am first converting it to **numpy** array? This is because OpenCV expects labels vector to be a `numpy` array. # # Still not satisfied? Want to see some action? Next step is the real action, I promise! # ### Prediction # Now comes my favorite part, the prediction part. This is where we actually get to see if our algorithm is actually recognizing our trained subjects's faces or not. We will take two test images of our celeberities, detect faces from each of them and then pass those faces to our trained face recognizer to see if it recognizes them. # # Below are some utility functions that we will use for drawing bounding box (rectangle) around face and putting celeberity name near the face bounding box. # + #function to draw rectangle on image #according to given (x, y) coordinates and #given width and heigh def draw_rectangle(img, rect): (x, y, w, h) = rect cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2) #function to draw text on give image starting from #passed (x, y) coordinates. def draw_text(img, text, x, y): cv2.putText(img, text, (x, y), cv2.FONT_HERSHEY_PLAIN, 1.5, (0, 255, 0), 2) # - # First function `draw_rectangle` draws a rectangle on image based on passed rectangle coordinates. It uses OpenCV's built in function `cv2.rectangle(img, topLeftPoint, bottomRightPoint, rgbColor, lineWidth)` to draw rectangle. We will use it to draw a rectangle around the face detected in test image. # # Second function `draw_text` uses OpenCV's built in function `cv2.putText(img, text, startPoint, font, fontSize, rgbColor, lineWidth)` to draw text on image. # # Now that we have the drawing functions, we just need to call the face recognizer's `predict(face)` method to test our face recognizer on test images. Following function does the prediction for us. #this function recognizes the person in image passed #and draws a rectangle around detected face with name of the #subject def predict(test_img): #make a copy of the image as we don't want to chang original image img = test_img.copy() #detect face from the image face, rect = detect_face(img) #predict the image using our face recognizer label= face_recognizer.predict(face) #get name of respective label returned by face recognizer label_text = subjects[label] #draw a rectangle around face detected draw_rectangle(img, rect) #draw name of predicted person draw_text(img, label_text, rect[0], rect[1]-5) return img # * **line-6** read the test image # * **line-7** detect face from test image # * **line-11** recognize the face by calling face recognizer's `predict(face)` method. This method will return a lable # * **line-12** get the name associated with the label # * **line-16** draw rectangle around the detected face # * **line-18** draw name of predicted subject above face rectangle # # Now that we have the prediction function well defined, next step is to actually call this function on our test images and display those test images to see if our face recognizer correctly recognized them. So let's do it. This is what we have been waiting for. # + print("Predicting images...") #load test images test_img1 = cv2.imread("test-data/test1.jpg") test_img2 = cv2.imread("test-data/test2.jpg") #perform a prediction predicted_img1 = predict(test_img1) predicted_img2 = predict(test_img2) print("Prediction complete") #display both images cv2.imshow(subjects[1], predicted_img1) cv2.imshow(subjects[2], predicted_img2) cv2.waitKey(0) cv2.destroyAllWindows() # - # wohooo! Is'nt it beautiful? Indeed, it is! # ## End Notes # You can download the complete code and relevant files from this Github [repo](https://github.com/informramiz/opencv-face-recognition-python). # # Face Recognition is a fascinating idea to work on and OpenCV has made it extremely simple and easy for us to code it. It takes just a few lines of code to have a fully working face recognition application and we can switch between all three face recognizers with a single line of code change. It's that simple. # # Although EigenFaces, FisherFaces and LBPH face recognizers are good but there are even better ways to perform face recognition like using Histogram of Oriented Gradients (HOGs) and Neural Networks. So the more advanced face recognition algorithms are now a days implemented using a combination of OpenCV and Machine learning. I have plans to write some articles on those more advanced methods as well, so stay tuned!
OpenCV-Face-Recognition-Python.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Pegasus Tutorial # # Author: [<NAME>](https://github.com/yihming)<br /> # Date: 2020-02-01 <br /> # Notebook Source: [pegasus_analysis.ipynb](https://raw.githubusercontent.com/klarman-cell-observatory/pegasus/master/notebooks/pegasus_analysis.ipynb) import pegasus as pg # ## Count Matrix File # # For this tutorial, we provide a count matrix dataset on Human Bone Marrow with 8 donors stored in zarr format (with file extension ".zarr.zip"). # # You can download the data at https://storage.googleapis.com/terra-featured-workspaces/Cumulus/MantonBM_nonmix_subset.zarr.zip. # # This file is achieved by aggregating gene-count matrices of the 8 10X channels using PegasusIO, and further filtering out cells with fewer than $100$ genes expressed. Please see [here](https://pegasusio.readthedocs.io/en/latest/_static/tutorials/pegasusio_tutorial.html#Case-5:-Data-aggregation-with-filtering) for how to do it interactively. # # Now load the file using pegasus `read_input` function: data = pg.read_input("MantonBM_nonmix_subset.zarr.zip") data # The count matrix is managed as a UnimodalData object defined in [PegasusIO](https://pegasusio.readthedocs.io) module, and users can manipulate the data from top level via MultimodalData structure, which can contain multiple UnimodalData objects as members. # # For this example, as show above, `data` is a MultimodalData object, with only one UnimodalData member of key `"GRCh38-rna"`, which is its default UnimodalData. Any operation on `data` will be applied to this default UnimodalData object. # # UnimodalData has the following structure: # # <img src="https://raw.githubusercontent.com/klarman-cell-observatory/pegasus/master/notebooks/unidata.png" width="50%" /> # # It has 6 major parts: # * Raw count matrix: `data.X`, a [Scipy sparse matrix](https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html) (sometimes can be a dense matrix), with rows the cell barcodes, columns the genes/features: data.X # This dataset contains $48,219$ barcodes and $36,601$ genes. # # * Cell barcode attributes: `data.obs`, a [Pandas data frame](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html) with barcode as the index. For now, there is only one attribute `"Channel"` referring to the donor from which the cell comes from: data.obs.head() data.obs['Channel'].value_counts() # * Gene attributes: `data.var`, also a Pandas data frame, with gene name as the index. For now, it only has one attribute `"gene_ids"` referring to the unique gene ID in the experiment: data.var.head() # * Unstructured information: `data.uns`, a Python [hashed dictionary](https://docs.python.org/3/library/collections.html#collections.OrderedDict). It usually stores information not restricted to barcodes or features, but about the whole dataset, such as its genome reference and modality type: data.uns['genome'] data.uns['modality'] # * Finally, embedding attributes on cell barcodes: `data.obsm`; as well as on genes, `data.varm`. We'll see it in later sections. # ## Preprocessing # # ### Filtration # # The first step in preprocessing is to perform the quality control analysis, and remove cells and genes of low quality. # # We can generate QC metrics using the following method with default settings: pg.qc_metrics(data, percent_mito=10) # The metrics considered are: # * **Number of genes**: keep cells with $500 \leq \text{# Genes} < 6000$ *(Default)*; # * **Number of UMIs**: don't filter cells due to UMI bounds *(Default)*; # * **Percent of Mitochondrial genes**: keep cells with percent $< 10\%$. # # For details on customizing your own thresholds, see [documentation](https://pegasus.readthedocs.io/en/stable/api/pegasus.qc_metrics.html). # # Numeric summaries on filtration on cell barcodes and genes can be achieved by `get_filter_stats` method: df_qc = pg.get_filter_stats(data) df_qc # The results is a Pandas data frame on samples. # # You can also check the QC stats via plots. Below is on number of genes: pg.qcviolin(data, plot_type='gene', dpi=100) # Then on number of UMIs: pg.qcviolin(data, plot_type='count', dpi=100) # On number of percentage of mitochondrial genes: pg.qcviolin(data, plot_type='mito', dpi=100) # Now filter cells based on QC metrics set in `qc_metrics`: pg.filter_data(data) # You can see that $35,465$ cells ($73.55\%$) are kept. # # Moreover, for genes, only those with no cell expression are removed. After that, we identify **robust** genes for downstream analysis: pg.identify_robust_genes(data) # The metric is the following: # * Gene is expressed in at least $0.05\%$ of cells, i.e. among every 6000 cells, there are at least 3 cells expressing this gene. # # Please see [its documentation](https://pegasus.readthedocs.io/en/stable/api/pegasus.identify_robust_genes.html) for details. # # As a result, $25,653$ ($70.09\%$) genes are kept. Among them, $17,516$ are robust. # # We can now view the cells of each sample after filtration: data.obs['Channel'].value_counts() # ### Normalization and Logarithmic Transformation # # After filtration, we need to first normalize the distribution of counts w.r.t. each cell to have the same sum (default is $10^5$, see [documentation](https://pegasus.readthedocs.io/en/stable/api/pegasus.log_norm.html)), and then transform into logarithmic space by $log(x + 1)$ to avoid number explosion: pg.log_norm(data) # For the downstream analysis, we may need to make a copy of the count matrix, in case of coming back to this step and redo the analysis: data_trial = data.copy() # ### Highly Variable Gene Selection # # **Highly Variable Genes (HVG)** are more likely to convey information discriminating different cell types and states. # Thus, rather than considering all genes, people usually focus on selected HVGs for downstream analyses. # # You need to set `consider_batch` flag to consider or not consider batch effect. At this step, set it to `False`: pg.highly_variable_features(data_trial, consider_batch=False) # By default, we select 2000 HVGs using the pegasus selection method. Alternative, you can also choose the traditional method that both *Seurat* and *SCANPY* use, by setting `flavor='Seurat'`. See [documentation](https://pegasus.readthedocs.io/en/stable/api/pegasus.highly_variable_features.html) for details. # # We can view HVGs by ranking them from top: data_trial.var.loc[data_trial.var['highly_variable_features']].sort_values(by='hvf_rank') # We can also view HVGs in a scatterplot: pg.hvfplot(data_trial, dpi=200) # In this plot, each point stands for one gene. Blue points are selected to be HVGs, which account for the majority of variation of the dataset. # ### Principal Component Analysis # # To reduce the dimension of data, Principal Component Analysis (PCA) is widely used. Briefly speaking, PCA transforms the data from original dimensions into a new set of Principal Components (PC) of a much smaller size. In the transformed data, dimension is reduced, while PCs still cover a majority of the variation of data. Moreover, the new dimensions (i.e. PCs) are independent with each other. # # `pegasus` uses the following method to perform PCA: pg.pca(data_trial) # By default, `pca` uses: # * Before PCA, scale the data to standard Normal distribution $N(0, 1)$, and truncate them with max value $10$; # * Number of PCs to compute: 50; # * Apply PCA only to highly variable features. # # See [its documentation](https://pegasus.readthedocs.io/en/stable/api/pegasus.pca.html) for customization. # # To explain the meaning of PCs, let's look at the first PC (denoted as $PC_1$), which covers the most of variation: coord_pc1 = data_trial.uns['PCs'][:, 0] coord_pc1 # This is an array of 2000 elements, each of which is a coefficient corresponding to one HVG. # # With the HVGs as the following: data_trial.var.loc[data_trial.var['highly_variable_features']].index.values # $PC_1$ is computed by # # \begin{equation*} # PC_1 = \text{coord_pc1}[0] \cdot \text{HES4} + \text{coord_pc1}[1] \cdot \text{ISG15} + \text{coord_pc1}[2] \cdot \text{TNFRSF18} + \cdots + \text{coord_pc1}[1997] \cdot \text{RPS4Y2} + \text{coord_pc1}[1998] \cdot \text{MT-CO1} + \text{coord_pc1}[1999] \cdot \text{MT-CO3} # \end{equation*} # # Therefore, all the 50 PCs are the linear combinations of the 2000 HVGs. # # The calculated PCA count matrix is stored in the `obsm` field, which is the first embedding object we have data_trial.obsm['X_pca'].shape # For each of the $35,465$ cells, its count is now w.r.t. 50 PCs, instead of 2000 HVGs. # ## Nearest Neighbors # # All the downstream analysis, including clustering and visualization, needs to construct a k-Nearest-Neighbor (kNN) graph on cells. We can build such a graph using `neighbors` method: pg.neighbors(data_trial) # It uses the default setting: # * For each cell, calculate its 100 nearest neighbors; # * Use PCA matrix for calculation; # * Use L2 distance as the metric; # * Use [hnswlib](https://github.com/nmslib/hnswlib) search algorithm to calculate the approximated nearest neighbors in a really short time. # # See [its documentation](https://pegasus.readthedocs.io/en/stable/api/pegasus.neighbors.html) for customization. # # Below is the result: print(f"Get {data_trial.uns['pca_knn_indices'].shape[1]} nearest neighbors (excluding itself) for each cell.") data_trial.uns['pca_knn_indices'] data_trial.uns['pca_knn_distances'] # Each row corresponds to one cell, listing its neighbors (not including itself) from nearest to farthest. `data_trial.uns['pca_knn_indices']` stores their indices, and `data_trial.uns['pca_knn_distances']` stores distances. # ## Clustering and Visualization # # Now we are ready to cluster the data for cell type detection. `pegasus` provides 4 clustering algorithms to use: # * `louvain`: Louvain algorithm, using [louvain](https://github.com/vtraag/louvain-igraph) package. # * `leiden`: Leiden algorithm, using [leidenalg](https://github.com/vtraag/leidenalg) package. # * `spectral_louvain`: Spectral Louvain algorithm, which requires Diffusion Map. # * `spectral_leiden`: Spectral Leiden algorithm, which requires Diffusion Map. # # See [this documentation](https://pegasus.readthedocs.io/en/stable/api/index.html#cluster-algorithms) for details. # # In this tutorial, we use the Louvain algorithm: pg.louvain(data_trial) # As a result, Louvain algorithm finds 19 clusters: data_trial.obs['louvain_labels'].value_counts() # We can check each cluster's composition regarding donors via a composition plot: pg.compo_plot(data_trial, 'louvain_labels', 'Channel') # However, we can see a clear batch effect in the plot: e.g. Cluster 11 and 14 have most cells from Donor 3. # # We can see it more clearly in its FIt-SNE plot (a visualization algorithm which we will talk about later): pg.tsne(data_trial) pg.scatter(data_trial, attrs=['louvain_labels', 'Channel'], basis='tsne') # ## Batch Correction # # Batch effect occurs when data samples are generated in different conditions, such as date, weather, lab setting, equipment, etc. Unless informed that all the samples were generated under the similar condition, people may suspect presumable batch effects if they see a visualization graph with samples kind-of isolated from each other. # # For this dataset, we need the batch correction step to reduce such a batch effect, which is observed in the plot above. # # In this tutorial, we use [Harmony](https://www.nature.com/articles/s41592-019-0619-0) algorithm for batch correction. It requires redo HVG selection, calculate new PCA coordinates, and apply the correction: pg.highly_variable_features(data, consider_batch=True) pg.pca(data) pca_key = pg.run_harmony(data) # The corrected PCA coordinates are stored in `data.obsm`: data.obsm['X_pca_harmony'].shape # `pca_key` is the representation key returned by `run_harmony` function, which is equivalent to string `"pca_harmony"`. In the following sections, you can use either `pca_key` or `"pca_harmony"` to specify `rep` parameter in Pegasus functions whenever applicable. # ## Repeat Previous Steps on the Corrected Data # # As the count matrix is changed by batch correction, we need to recalculate nearest neighbors and perform clustering. Don't forget to use the corrected PCA coordinates as the representation: pg.neighbors(data, rep=pca_key) pg.louvain(data, rep=pca_key) # Let's check the composition plot now: pg.compo_plot(data, 'louvain_labels', 'Channel') # If everything goes properly, you should be able to see that no cluster has a dominant donor cells. Also notice that Louvain algorithm on the corrected data finds 16 clusters, instead of the original 19 ones. # # Also, FIt-SNE plot is different: pg.tsne(data, rep=pca_key) pg.scatter(data, attrs=['louvain_labels', 'Channel'], basis='tsne') # You can see that the right-hand-side plot has a much better mixture of cells from different donors. # ## Visualization # ### tSNE Plot # # In previous sections, we have seen data visualization using FIt-SNE. FIt-SNE is a fast implementation on tSNE algorithm, and Pegasus uses it for the tSNE embedding calculation. [See details](https://pegasus.readthedocs.io/en/stable/api/pegasus.tsne.html) # ### UMAP Plot # # Besides tSNE, `pegasus` also provides UMAP plotting methods: # # * `umap`: UMAP plot, using [umap-learn](https://github.com/lmcinnes/umap) package. [See details](https://pegasus.readthedocs.io/en/stable/api/pegasus.umap.html) # * `net_umap`: Approximated UMAP plot with DNN model based speed up. [See details](https://pegasus.readthedocs.io/en/stable/api/pegasus.net_umap.html) # # Below is the UMAP plot of the data using `umap` method: pg.umap(data, rep=pca_key) pg.scatter(data, attrs=['louvain_labels', 'Channel'], basis='umap') # ## Differential Expression Analysis # # With the clusters ready, we can now perform Differential Expression (DE) Analysis. DE analysis is to discover cluster-specific marker genes. For each cluster, it compares cells within the cluster with all the others, then finds genes significantly highly expressed (up-regulated) and lowly expressed (down-regulated) for the cluster. # Now use `de_analysis` method to run DE analysis. We use Louvain result here. pg.de_analysis(data, cluster='louvain_labels') # By default, DE analysis runs Mann-Whitney U (MWU) test. # # Alternatively, you can also run the follow tests by setting their corresponding parameters to be `True`: # * `fisher`: Fisher’s exact test. # * `t`: Welch’s T test. # # DE analysis result is stored with key `"de_res"` (by default) in `varm` field of data. See [documentation](https://pegasus.readthedocs.io/en/stable/api/pegasus.de_analysis.html) for more details. # # To load the result in a human-readable format, use `markers` method: marker_dict = pg.markers(data) # By default, `markers`: # * Sort genes by Area under ROC curve (AUROC) in descending order; # * Use $\alpha = 0.05$ significance level on q-values for inference. # # See [documentation](https://pegasus.readthedocs.io/en/stable/api/pegasus.markers.html) for customizing these parameters. # # Let's see the up-regulated genes for Cluster 1, and rank them in descending order with respect to log fold change: marker_dict['1']['up'].sort_values(by='log2FC', ascending=False) # Among them, **TRAC** worth notification. It is a critical marker for T cells. # We can also use Volcano plot to see the DE result. Below is such a plot w.r.t. Cluster 1 with MWU test results (by default): pg.volcano(data, cluster_id = '1', dpi=200) # The plot above uses the default thresholds: log fold change at $1$ (i.e. fold change at $2$), and q-value at $0.05$. Each point stands for a gene. Red ones are significant marker genes: those at right-hand side are up-regulated genes for Cluster 1, while those at left-hand side are down-regulated genes. # # We can see that gene **TRAC** is the second to rightmost point, which is a significant up-regulated gene for Cluster 1. # # To store a specific DE analysis result to file, you can `write_results_to_excel` methods in `pegasus`: pg.write_results_to_excel(marker_dict, "MantonBM_subset.de.xlsx") # ## Cell Type Annotation # # After done with DE analysis, we can use the test result to annotate the clusters. celltype_dict = pg.infer_cell_types(data, markers = 'human_immune') cluster_names = pg.infer_cluster_names(celltype_dict) # `infer_cell_types` has 2 critical parameters to set: # * `markers`: Either `'human_immune'`, `'mouse_immune'`, `'human_brain'`, `'mouse_brain'`, `'human_lung'`, or a user-specified marker dictionary. # * `de_test`: Decide which DE analysis test to be used for cell type inference. It can be either `'t'`, `'fisher'`, or `'mwu'`. Its default is `'mwu'`. # # `infer_cluster_names` by default uses `threshold = 0.5` to filter out candidate cell types of scores lower than 0.5. # # See [documentation](https://pegasus.readthedocs.io/en/stable/api/pegasus.infer_cell_types.html) for details. # # Below is the cell type annotation report for Cluster 1: celltype_dict['1'] # The report has a list of predicted cell types along with their scores and support genes for users to decide. # # Next, substitute the inferred cluster names in data using `annotate` function: pg.annotate(data, name='anno', based_on='louvain_labels', anno_dict=cluster_names) data.obs['anno'].value_counts() # So the cluster-specific cell type information is stored in `data.obs['anno']`. # # The `anno_dict` can be either a list or a dictionary. If provided a list (which is the case here), Pegasus will match cell types with cluster labels in the same order. Alternatively, you can create an annotation dictionary with keys being cluster labels and cell types being values. # # In practice, users may want to manually create this annotation structure by reading the report in `celltype_dict`. In this tutorial, we'll just use the output of `infer_cluster_names` function for demonstration. # # Now plot the data with cell types: pg.scatter(data, attrs='anno', basis='tsne', dpi=100) pg.scatter(data, attrs='anno', basis='umap', legend_loc='on data', dpi=150) # ## Raw Count vs Log-norm Count # # Now let's check the count matrix: data # You can see that besides `X`, there is another matrix `raw.X` generated for this analysis. As the key name indicates, `raw.X` stores the raw count matrix, which is the one after loading from the original Zarr file; while `X` stores the log-normalized counts. # # `data` currently binds to matrix `X`. To use the raw count instead, type: data.select_matrix('raw.X') data # Now `data` binds to raw counts. # # We still need log-normalized counts for the following sections, so reset the default count matrix: data.select_matrix('X') # ## Cell Development Trajectory and Diffusion Map # # Alternative, pegasus provides cell development trajectory plots using Force-directed Layout (FLE) algorithm: # # * `pg.fle`: FLE plot, using Force-Atlas 2 algorithm in [forceatlas2-python](https://github.com/klarman-cell-observatory/forceatlas2-python) package. [See details](https://pegasus.readthedocs.io/en/stable/api/pegasus.fle.html) # * `pg.net_fle`: Approximated FLE plot with DNN model based speed up. [See details](https://pegasus.readthedocs.io/en/stable/api/pegasus.net_fle.html) # # Moreover, calculation of FLE plots is on Diffusion Map of the data, rather than directly on data points, in order to achieve a better efficiency. Thus, we need to first compute the diffusion map structure: pg.diffmap(data, rep=pca_key) # By default, diffmap method uses: # # * Number of Diffusion Components = 100 # * Compute diffusion map from PCA matrix. # # In this tutorial, we should use the corrected PCA matrix, which is specified in `pca_key`. The resulting diffusion map is in `data.obsm` with key `"X_diffmap"`: data.obsm['X_diffmap'].shape # Now we are ready to calculate the pseudo-temporal trajectories of cell development. We use `fle` here: pg.fle(data) # And show FLE plot regarding cell type annotations: pg.scatter(data, attrs='anno', basis='fle') # ## Save Result to File # # Use `write_output` function to save analysis result `data` to file: pg.write_output(data, "result.zarr.zip") # It's stored in `zarr` format, because this is the default file format in Pegasus. # # Alternatively, you can also save it in `h5ad`, `mtx`, or `loom` format. See [its documentation](https://pegasus.readthedocs.io/en/stable/api/pegasus.write_output.html) for instructions. # ## Read More... # # * Read [Plotting Tutorial](https://pegasus.readthedocs.io/en/stable/_static/tutorials/plotting_tutorial.html) for more plotting functions provided by Pegasus. # # * Read [Pegasus API](https://pegasus.readthedocs.io/en/stable/api/index.html) documentation for details on Pegasus functions.
notebooks/pegasus_analysis.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns sns.set() plt.rcParams["figure.figsize"] = (10, 6) df = pd.read_csv('crawler/data/data.csv') df = df[df['published_date'] < '2020-01-23'] # an article age more than 1 month (to stable ratings) df['published_date'] = pd.to_datetime(df['published_date']) df['published_dayofweek'] = df['published_date'].dt.dayofweek # 0 - Monday df['published_dayname'] = df['published_date'].dt.day_name() df['published_year'] = df['published_date'].dt.year df['published_hour'] = df['published_time'].apply(lambda x: int(x[:2])) print(df.shape) df[['link', 'title', 'published_date', 'published_time']].head() # #### Counters by day of week (expect different behav. on weekends) sample = df[['published_dayofweek', 'published_dayname', 'rating', 'comments', 'views']].groupby(['published_dayofweek', 'published_dayname']).agg('mean').reset_index() width = 0.35 x = np.arange(len(sample)) fig, ax = plt.subplots() rects1 = ax.bar(x - width/2, sample['rating'], width, label='rating') rects2 = ax.bar(x + width/2, sample['comments'], width, label='comments') ax.set_ylabel('stats') ax.set_title('Counters by day of week') ax.set_xticks(x) ax.set_xticklabels(sample['published_dayname']) ax.legend() plt.show() # #### Counters by hour sample = df[['published_hour', 'rating', 'comments', 'views']].groupby(['published_hour']).agg('mean').reset_index() width = 0.35 x = np.arange(len(sample)) fig, ax = plt.subplots() rects1 = ax.bar(x - width/2, sample['rating'], width, label='rating') rects2 = ax.bar(x + width/2, sample['comments'], width, label='comments') ax.set_ylabel('stats') ax.set_title('Counters by hour') ax.set_xticks(x) ax.set_xticklabels(sample['published_hour']) ax.legend() plt.show() # #### Counters by year sample = df[['published_year', 'rating', 'comments']].groupby(['published_year']).agg('mean').reset_index() width = 0.35 x = np.arange(len(sample)) fig, ax = plt.subplots() rects1 = ax.bar(x - width/2, sample['rating'], width, label='rating') rects2 = ax.bar(x + width/2, sample['comments'], width, label='comments') ax.set_ylabel('stats') ax.set_title('Counters by year') ax.set_xticks(x) ax.set_xticklabels(sample['published_year']) ax.legend() plt.show() # it's some approx, because it doesn't contain all articles sample = df[['published_year', 'rating', 'comments']].groupby(['published_year']).agg('sum').reset_index() width = 0.35 x = np.arange(len(sample)) fig, ax = plt.subplots() rects1 = ax.bar(x - width/2, sample['rating'], width, label='rating') rects2 = ax.bar(x + width/2, sample['comments'], width, label='comments') ax.set_ylabel('stats') ax.set_title('Activity by year') ax.set_xticks(x) ax.set_xticklabels(sample['published_year']) ax.legend() plt.show() # #### Most common categories from collections import Counter c = Counter(', '.join(list(df['article_categories'][~df['article_categories'].isnull()])).split(', ')) most_common_article_categs = c.most_common(10) most_common_article_categs # #### Most common tags c = Counter(', '.join(list(df['tags'][~df['tags'].isnull()])).split(', ')) most_common_tags = c.most_common(10) most_common_tags # #### Views distribution. Supposed to be ~lognormal plt.hist(df['views'], bins=100, color='#0504aa') plt.show() plt.hist(np.log(df['views']+1), bins=100, color='#0504aa') plt.show() # #### Article lengths plt.hist(df['sentences_count'], bins=100, color='#0504aa') plt.show() plt.hist(np.log(df['sentences_count']+1), bins=100, color='#0504aa') plt.show() # #### Is there a dependency between an article length and rating (define a new rating as: positive / (positive+negative)) df_sample = df[(df['positive_votes'] + df['negative_votes']) > 10].copy() print(len(df_sample)) df_sample['rating_2'] = df_sample['positive_votes'] / (df_sample['positive_votes'] + df_sample['negative_votes']) # #### Check if a new rating correlates with dayofweek sample = df_sample[['published_dayofweek', 'published_dayname', 'rating_2']].groupby(['published_dayofweek', 'published_dayname']).agg('mean').reset_index() plt.bar(range(len(sample)), sample['rating_2']) plt.xticks(range(len(sample)), sample['published_dayname']) plt.title('Rating_2 by dayofweek') plt.ylabel('stats') plt.show() plt.hist(df_sample['rating_2'], bins=100, color='#0504aa') plt.title('rating_2 distrib') plt.xlabel('rating_2') plt.ylabel('count') plt.show() # + df_sample['rating_2_round'] = df_sample['rating_2'].apply(lambda x: round(x*10)/10) sample = df_sample[['rating_2_round', 'sentences_count']].groupby('rating_2_round').agg('mean').reset_index() plt.bar(range(len(sample)), sample['sentences_count']) plt.xticks(range(len(sample)), sample['rating_2_round']) plt.title('Sent length rating_2 dependency') plt.xlabel('rating_2') plt.ylabel('sentences count') plt.show() # - # #### Of course there is a correlation between rating and how long article is # #### Let's build a model to predict this 'normalized' rating (but there is still a room to normalize it (through time, for example) most_common_article_categs = set([x[0] for x in most_common_article_categs]) most_common_tags = set([x[0] for x in most_common_tags]) most_common_article_categs, most_common_tags # + def is_article_categ_most_common(article_categ_line): if pd.isnull(article_categ_line): return 0 categs = article_categ_line.split(', ') return int(any([categ in most_common_article_categs for categ in categs])) def is_tag_most_common(tags_line): if pd.isnull(tags_line): return 0 tags = tags_line.split(', ') return int(any([tag in most_common_tags for tag in tags])) # - df_sample['title_len'] = df_sample['title'].apply(len) df_sample['article_categ_cnt'] = df_sample['article_categories'].apply(lambda x: x.count(',') if pd.notnull(x) else 0) df_sample['tags_cnt'] = df_sample['tags'].apply(lambda x: x.count(',') if pd.notnull(x) else 0) df_sample['weekend'] = df_sample['published_dayofweek'].apply(lambda x: int(x in [5, 6])) df_sample['most_common_article_categ'] = df_sample['article_categories'].apply(is_article_categ_most_common) df_sample['most_common_tag'] = df_sample['tags'].apply(is_tag_most_common) df_sample['weight'] = df_sample['negative_votes'] + df_sample['positive_votes'] # + features = [ 'title_len', 'article_categ_cnt', 'href_count', 'img_count', 'tags_cnt', 'h3_count', 'i_count', 'spoiler_count', 'text_len', 'lines_count', 'sentences_count', 'max_sentence_len', 'min_sentence_len', 'mean_sentence_len', 'median_sentence_len', 'tokens_count', 'max_token_len', 'mean_token_len', 'median_token_len', 'alphabetic_tokens_count', 'words_count', 'words_mean', 'published_dayofweek', 'published_hour', 'weekend', 'most_common_article_categ', 'most_common_tag', 'weight' ] y = df_sample['rating_2'] X = df_sample[features] y.shape, X.shape # - # #### target distribution plt.hist(np.log(1.1-y), bins=40) plt.show() # #### Translations # 1. target = log(1.1 - rating) # 2. rating = 1.1 - exp(target) from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) train_weights = X_train['weight'] X_train.drop(['weight'], axis=1, inplace=True) X_test.drop(['weight'], axis=1, inplace=True) import lightgbm as lgb # + gbm = lgb.LGBMRegressor(num_leaves=31, learning_rate=0.04, n_estimators=100) gbm.fit(X_train, np.log(1.1 - y_train), sample_weight=train_weights, eval_set=[(X_test, np.log(1.1 - y_test))], eval_metric='l2', early_stopping_rounds=20) y_pred = gbm.predict(X_test, num_iteration=gbm.best_iteration_) # - mean_squared_error(y_test, 1.1 - np.exp(y_pred)) ** 0.5 plt.hist(1.1 - np.exp(y_pred), bins=10, label='pred') plt.hist(y_test, bins=10, label='true', alpha=0.8) plt.show() np.corrcoef(y_test, 1.1 - np.exp(y_pred)) sample = X_test.copy() sample['pred'] = y_pred sample = sample.sort_values('pred') # + articles_cnt = 10 best_articles = [row for _, row in df_sample.loc[list(sample.index[:articles_cnt])].iterrows()] worst_articles = [row for _, row in df_sample.loc[list(sample.index[-articles_cnt:])].iterrows()] print('best articles') for article in best_articles: print(f' {article["title"]} {article["positive_votes"]} {article["negative_votes"]}\n {article["rating_2"]}\n {article["link"]}') print('worst articles') for article in worst_articles: print(f' {article["title"]} {article["positive_votes"]} {article["negative_votes"]}\n {article["rating_2"]}\n {article["link"]}') # - # #### Although the model is weak, it can help to find more serious and thoughtful articles
data_stats.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Prediction and Performance Evaluation # # Previously, we learned about the three-step process in scikit-learn to do machine learning. Once our model is trained, it's time to put it to use. We will learn how to make predictions with it and then to evaluate its performance by calculating $R^2$. # # ## Repeating the three step machine learning process # # Let's repeat the three step machine learning process to build a linear regression model that uses above ground living area to predict sale price. Let's read in our sample housing dataset and select the single feature `GrLivArea` as our input. import pandas as pd import numpy as np housing = pd.read_csv('../data/housing_sample.csv') X = housing[['GrLivArea']] y = housing['SalePrice'] # ### Import, Instantiate, Fit # # Let's complete the three-step process in a single cell by importing our estimator, instantiating, and training it with the `fit` method. from sklearn.linear_model import LinearRegression lr = LinearRegression() lr.fit(X, y) # ### Make predictions with the `predict` method # Now that our model is trained, we can use the `predict` method to make predictions. We must pass it a 2-dimensional numpy array (or single-column DataFrame) with the same number of columns as the one it was trained on. We used one feature during training, so we need a one-column array. Let's make predictions for houses with square footage of 500, 1,000, 3,000, and 5,000. new_data = np.array([[500], [1000], [3000], [5000]]) new_data # Pass this two-dimensional array to the `predict` method to get the predicted sale price. lr.predict(new_data) # All those decimal places are excessive and make it difficult to read. Let's round our result to the nearest thousand. lr.predict(new_data).round(-3) # ### Could have used a DataFrame or list of lists # # Instead of using a numpy array to hold the new data, we could have used a single-column DataFrame or a list of lists. We begin by creating a DataFrame. df_new_data = pd.DataFrame({'GrLivArea': [500, 1000, 3000, 5000]}) df_new_data # Passing it to the `predict` method returns the same exact values as above. lr.predict(df_new_data).round(-3) # Using a list of lists where the inner list contains the value for the single feature also works and again returns the same predicted values. new_data_list = [[500], [1000], [3000], [5000]] lr.predict(new_data_list).round(-3) # ### Write our own function to calculate predictions # # We know the coefficients of our trained model and can build our own `predict` function with them. def predict(x): return lr.intercept_ + lr.coef_ * x # Let's verify that the values are the same. predict(new_data).round(-3) # ## Evaluating the performance of our predictions # # It's only possible to evaluate the performance of our predictions if they are labeled with the ground truth. The only labeled observations we have are the ones we built the model from and are currently stored in variables `X` and `y`. # # ### Evaluating on the training data is bad, but we will do it anyways # # The data that is used to train the model is called the **training data**. Typically, we would not use this same data to evaluate our model performance and instead choose labeled data that the model has not seen. We will learn formal processes for model evaluation later. For now, we will evaluate our model on the training data with the `score` method which returns $R^2$. lr.score(X, y) # ### Explanation of the `score` method # # The `score` method uses the model built during the call to the `fit` method. It makes a prediction for each observation in `X`. It then calculates $R^2$ between this predicted value and the actual sale price $y$. Our linear regression model with a single feature obtained a score of .5 meaning that the sum of squared error from the model was 50% less than the sum of squared error produced by guessing the mean. In other words, our model explains 50% of the inherent variance in the data. # ## Exercises # # ### Exercise 1 # # <span style="color:green; font-size:16px">Use the garage area to build a simple linear regression model. What is the value of $R^2$ when scoring with the training data? What does the model predict for garage areas of size 100, 500, and 1000 square feet? Repeat this process for the other numeric features. Create your own arrays with new data to make predictions with.</span>
jupyter_notebooks/machine_learning/mastering_machine_learning/02. Linear Regression/04. Prediction and Performance Evaluation.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: 'Python 3.8.12 64-bit (''skillNer-dev-env'': conda)' # name: python3 # --- # + # # !pip install skillNer # # !python -m spacy download en_core_web_lg # + # imports import spacy import en_core_web_lg from spacy.matcher import PhraseMatcher # import skill extractor from skillNer.skill_extractor_class import SkillExtractor from skillNer.general_params import SKILL_DB # init params of skill extractor nlp = en_core_web_lg.load() # init skill extractor skill_extractor = SkillExtractor(nlp, SKILL_DB, PhraseMatcher) # + # extract skills from job_description job_description = """ You are a Python developer with a solid experience in web development and can manage projects. You quickly adapt to new environments and speak fluently English and French """ annotations = skill_extractor.annotate(job_description) # - # inspect annotations skill_extractor.describe(annotations) print(annotations)
Tutorials/sandbox.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/komo135/tradingrl/blob/master/dist_sac.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + id="cBVV8hQizHTI" colab_type="code" outputId="cd170def-3749-482a-fb95-5b6b905a6c75" colab={"base_uri": "https://localhost:8080/", "height": 54} # Google ドライブをマウントするには、このセルを実行してください。 from google.colab import drive from google.colab import files drive.mount('/content/drive') # %cd drive/My Drive # + id="yXQj6liny0Sd" colab_type="code" colab={} from ape_x import * import os import multiprocessing as mp import tensorflow as tf import numpy as np import time import shutil df = "audpred60.csv" _ = shutil.copy("/content/drive/My Drive/"+df,"/content") restore = True if restore == True: _ = shutil.copy("/content/drive/My Drive/sac_one_step.ckpt.data-00000-of-00001","/content") _ = shutil.copy("/content/drive/My Drive/sac_one_step.ckpt.index","/content") _ = shutil.copy("/content/drive/My Drive/checkpoint","/content") output_size = 3 # 短いステップサイズを使用することでポジションを長期保有することによって得られるアクション選択を是正し、fxという明確は有限がない状態での総報酬を最大化する # という目的を制限し、短期報酬を高めることができる。また、長すぎるステップサイズは制御することが困難になる。オーバーフィット対策に頻繁に状態の分布を変えることで # 対処する。よって、すべての状態で最善の行動を生み出すことができるエージェントを開発する。 def actor_work(queues,epsilon, num): sess = tf.InteractiveSession() actor = Actor(df, 5, num, epsilon, sess,STEP_SIZE=120,OUTPUT_SIZE=output_size, save=True, saver_path="sac_one_step.ckpt", restore=restore) actor.run(queues, 10, 1000,200,24,n=4) def leaner_work(queues): sess = tf.InteractiveSession() leaner = Leaner(df, 5, sess,output_size,'/gpu:0', save=True, saver_path="sac_one_step.ckpt", restore=restore) leaner.leaner(queues,files) # + id="1FBIJ0z4zKf7" colab_type="code" outputId="4530b597-e537-4f63-f386-85e2b8ac0371" colab={"base_uri": "https://localhost:8080/", "height": 1000} # %cd /content queue = mp.Queue() ps = [mp.Process(target=leaner_work, args=(queue,))] for i in range(3): epsilon = 0.0 if i == 0 else np.random.rand() true = True while true: if epsilon >= 0.2 or i == 0: true = False else: epsilon = np.random.rand() epsilon = 1.0 if i == 1 else epsilon ps.append(mp.Process(target=actor_work, args=(queue,epsilon,i))) for p in ps: p.start() time.sleep(1) for p in ps: p.join() # + id="QoY9bXh69UtJ" colab_type="code" colab={} from multiprocessing import Process, Queue def f(q): for i in range(100): rand = np.random.RandomState() if rand.rand() < 0.2: action = rand.choice(3, p=(0.2,0.3,0.5)) print(i) print(action) if __name__ == '__main__': q = Queue() p = Process(target=f, args=(q,)) p.start() p.join() # + id="bfAKRJrCaZFi" colab_type="code" colab={} a = np.asanyarray([[1,1,1,1],[0,0,0,0]]) # + id="IABToLrT_8YF" colab_type="code" colab={} b = [i[0][0] for i in a] # + id="PuA8kBwRAVBW" colab_type="code" colab={} import urllib.request import urllib.parse url = 'https://www.googleapis.com/drive/v2/files/trash' f = urllib.request.urlopen(url)
dist_sac.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %load_ext autoreload # %autoreload 2 # + from collections import namedtuple from itertools import product import numpy as np from pyqumo.random import Exponential, HyperExponential, Erlang from pyqumo.cqumo.sim import simulate_tandem # - Params = namedtuple('Params', [ 'arrival_avg', 'arrival_std', 'service_avg', 'service_std', 'num_stations', 'queue_capacity' ]) # + ARRIVAL_AVG = np.asarray([10, 20]) ARRIVAL_STD = np.asarray([1, 5, 10]) SERVICE_AVG = np.asarray([2.5, 5]) SERVICE_STD = np.asarray([1, 2.5, 5, 7.5, 10]) NUM_STATIONS = np.asarray([5]) QUEUE_CAPACITY = np.asarray([10]) # Build the parameters grid: parameters = [ Params(arrival_avg, arrival_std, service_avg, service_std, num_stations, queue_capacity) for (arrival_avg, arrival_std, service_avg, service_std, num_stations, queue_capacity) in product(ARRIVAL_AVG, ARRIVAL_STD, SERVICE_AVG, SERVICE_STD, NUM_STATIONS, QUEUE_CAPACITY) ] print(f"Defined {len(parameters)} parameters grid points") # + # Run the simulation results = [] # store (params, ret), where `ret` is an instance of `pyqumo.sim.tandem.Result` NUM_PACKETS = 100000 # This function returns the most appropriate distribution: def get_distribution(avg, std): cv = std / avg if cv == 1: return Exponential(avg) if cv > 1: return HyperExponential.fit(avg, std) return Erlang.fit(avg, std) for params in parameters: arrival = get_distribution(params.arrival_avg, params.arrival_std) services = [ get_distribution(params.service_avg, params.service_std) for _ in range(params.num_stations) ] ret = simulate_tandem(arrival, services, params.queue_capacity, NUM_PACKETS) results.append((params, ret)) # + # Build a table: from tabulate import tabulate rows = [] for (param, ret) in results: rows.append((param.arrival_avg, param.arrival_std, param.service_avg, param.service_std, param.queue_capacity, param.num_stations, ret.delivery_delays[0].avg, ret.delivery_delays[0].std, ret.delivery_prob[0])) print(tabulate(rows, headers=( 'Arr.avg.', 'Arr.std.', 'Srv.avg.', 'Srv. std.', 'Queue capacity', 'Num. stations', 'Delay avg.', 'Delay std.', 'Delivery P.' ))) # -
src/pyqumo/experiments/tandem_exeuctions.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # This notebook demonstrates how to perform standard (Kronecker) multitask regression with kernels.IndexKernel. # # This differs from the [hadamard_multitask_gp_regression example notebook](https://github.com/cornellius-gp/gpytorch/blob/master/examples/hadamard_multitask_gp_regression.ipynb) in one key way: # - Here, we assume that we want to learn **all tasks per input**. (The kernel that we learn is expressed as a Kronecker product of an input kernel and a task kernel). # - In the other notebook, we assume that we want to learn one tasks per input. For each input, we specify the task of the input that we care about. (The kernel in that notebook is the Hadamard product of an input kernel and a task kernel). # # Multitask regression, first introduced in [this paper](https://papers.nips.cc/paper/3189-multi-task-gaussian-process-prediction.pdf) learns similarities in the outputs simultaneously. It's useful when you are performing regression on multiple functions that share the same inputs, especially if they have similarities (such as being sinusodial). # + import math import torch import gpytorch from matplotlib import pyplot as plt # %matplotlib inline # %load_ext autoreload # %autoreload 2 # + # Training points are every 0.1 in [0,1] (note that they're the same for both tasks) train_x = torch.linspace(0, 1, 100) # y1 function is sin(2*pi*x) with noise N(0, 0.04) train_y1 = torch.sin(train_x.data * (2 * math.pi)) + torch.randn(train_x.size()) * 0.2 # y2 function is cos(2*pi*x) with noise N(0, 0.04) train_y2 = torch.cos(train_x.data * (2 * math.pi)) + torch.randn(train_x.size()) * 0.2 # Create a train_y which interleaves the two train_y = torch.stack([train_y1, train_y2], -1) # - from torch import optim from gpytorch.kernels import RBFKernel, MultitaskKernel from gpytorch.means import ConstantMean, MultitaskMean from gpytorch.likelihoods import MultitaskGaussianLikelihood from gpytorch.random_variables import MultitaskGaussianRandomVariable # + class MultitaskGPModel(gpytorch.models.ExactGP): def __init__(self, train_x, train_y, likelihood): super(MultitaskGPModel, self).__init__(train_x, train_y, likelihood) self.mean_module = MultitaskMean(ConstantMean(), n_tasks=2) self.data_covar_module = RBFKernel() self.covar_module = MultitaskKernel(self.data_covar_module, n_tasks=2, rank=1) def forward(self, x): mean_x = self.mean_module(x) covar_x = self.covar_module(x) return MultitaskGaussianRandomVariable(mean_x, covar_x) # Gaussian likelihood is used for regression to give predictive mean+variance # and learn noise likelihood = MultitaskGaussianLikelihood(n_tasks=2) model = MultitaskGPModel(train_x, train_y, likelihood) # + # Find optimal model hyperparameters model.train() likelihood.train() # Use the adam optimizer optimizer = torch.optim.Adam([ {'params': model.parameters()}, # Includes GaussianLikelihood parameters ], lr=0.1) # "Loss" for GPs - the marginal log likelihood mll = gpytorch.mlls.ExactMarginalLogLikelihood(likelihood, model) n_iter = 50 for i in range(n_iter): # Zero prev backpropped gradients optimizer.zero_grad() # Make predictions from training data # Again, note feeding duplicated x_data and indices indicating which task output = model(train_x) # TODO: Fix this view call!! loss = -mll(output, train_y) loss.backward() print('Iter %d/%d - Loss: %.3f' % (i + 1, n_iter, loss.item())) optimizer.step() # + # Set into eval mode model.eval() likelihood.eval() # Initialize plots f, (y1_ax, y2_ax) = plt.subplots(1, 2, figsize=(8, 3)) # Test points every 0.02 in [0,1] # Make predictions with torch.no_grad(): test_x = torch.linspace(0, 1, 51) observed_pred = likelihood(model(test_x)) # Get mean mean = observed_pred.mean() # Get lower and upper confidence bounds lower, upper = observed_pred.confidence_region() # This contains predictions for both tasks, flattened out # The first half of the predictions is for the first task # The second half is for the second task # Define plotting function def ax_plot(): # Plot training data as black stars y1_ax.plot(train_x.detach().numpy(), train_y1.detach().numpy(), 'k*') # Predictive mean as blue line y1_ax.plot(test_x.numpy(), mean[:, 0].numpy(), 'b') # Shade in confidence y1_ax.fill_between(test_x.numpy(), lower[:, 0].numpy(), upper[:, 0].numpy(), alpha=0.5) y1_ax.set_ylim([-3, 3]) y1_ax.legend(['Observed Data', 'Mean', 'Confidence']) y1_ax.set_title('Observed Values (Likelihood)') # Plot training data as black stars y2_ax.plot(train_x.detach().numpy(), train_y2.detach().numpy(), 'k*') # Predictive mean as blue line y2_ax.plot(test_x.numpy(), mean[:, 1].numpy(), 'b') # Shade in confidence y2_ax.fill_between(test_x.numpy(), lower[:, 1].numpy(), upper[:, 1].numpy(), alpha=0.5) y2_ax.set_ylim([-3, 3]) y2_ax.legend(['Observed Data', 'Mean', 'Confidence']) y2_ax.set_title('Observed Values (Likelihood)') # Plot both tasks ax_plot() # -
examples/multitask_gp_regression.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ## Airtable Python Wrapper # # This Notebook shows typical usage for the airtable client. # It requires `jupyter`, `pandas`, and and env var `AIRTABLE_KEY` # # The `base_key` included is a reference to [this base](https://airtable.com/shrREAyVIxHiBEZOF) # + # %load_ext autoreload # %autoreload import os from pprint import pprint from airtable import Airtable base_key = '<KEY>' table_name = 'table' airtable = Airtable(base_key, table_name, api_key=os.environ['AIRTABLE_API_KEY']) print(airtable) # + # Get Iter with Max Records pages = airtable.get_iter(maxRecords=2) for page in pages: for record in page: pprint(record) # + # Get All with Max Records records = airtable.get_all(maxRecords=2) df = pd.DataFrame.from_records((r['fields'] for r in records)) df.head() # - # Get All on a View - View has only One Record records = airtable.get_all(view='Artists on display') # pprint(records) df = pd.DataFrame.from_records((r['fields'] for r in records)) df.head(3) # + # Get All with Max Records, Fields records = airtable.get_all(fields='Name', max_records=1) for record in records[0:2]: pprint(record) # - records = airtable.search('Name', "<NAME>") pprint([r['fields'] for r in records]) records = airtable.search('On Display?', "1") pprint([r['fields'] for r in records]) # Sort Implicit records = airtable.get_all(maxRecords=2, sort=["-Name"], fields='Name') pprint(records) # Sort Explicit records = airtable.get_all(maxRecords=2, sort=[("Name", 'desc')]) pprint(records[0]['fields']['Name']) # + # Replace - If Field is not included, it will be set to null # records = airtable.replace_by_field("COLUMN_ID", '4', {'COLUMN_ID': '4', 'COLUMN_UPDATE':'A'}) # print(records) # + # Update - Only included fields are updated. Rest is left as is. # records = airtable.update_by_field("COLUMN_INT", '4', {'COLUMN_UPDATE':'B'}) # print(records) # + # Insert # airtable.insert({'text': 'A', 'number': 1}) # airtable.batch_insert([{'text': 'A', 'number': 1}, {'text': 'B', 'number': 2}]) # + # Delete # rec = airtable.get_all()[0] # rec2 = airtable.get_all()[1] # airtable.batch_delete([rec['id'], rec2['id']])
Airtable.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # DATA QUALITY ASSESSMENT - TASK_1 # ### importing relevant libraries #removes warnings import warnings warnings.filterwarnings('ignore') # + #for Data wrangling and analysis import pandas as pd import numpy as np #for data visualations import seaborn as sns from sklearn.impute import SimpleImputer import matplotlib.pyplot as plt # %matplotlib inline # to read files from pandas import ExcelWriter from pandas import ExcelFile # for dates import datetime # - # ### Loading data transactions = pd.read_excel(r"C:\Users\User\Downloads\KPMG Related\KPMG_VI_New_raw_data_update_final .xlsx", sheet_name='Transactions') new_customer_lists = pd.read_excel(r"C:\Users\User\Downloads\KPMG Related\KPMG_VI_New_raw_data_update_final .xlsx", sheet_name='NewCustomerList') customer_demographic = pd.read_excel(r"C:\Users\User\Downloads\KPMG Related\KPMG_VI_New_raw_data_update_final .xlsx", sheet_name='CustomerDemographic') customer_address = pd.read_excel(r"C:\Users\User\Downloads\KPMG Related\KPMG_VI_New_raw_data_update_final .xlsx", sheet_name='CustomerAddress') # ### EXPLORATION OF TRANSACTION DATASET transactions.head() # checking the data type type(transactions) transactions.info() # ### DATA MANIPULATIONS #converting date columns from integer to datetime transactions['transaction_date'] = pd.to_datetime(transactions['transaction_date'], unit='s') transactions['transaction_date'].head() # + # converting integers to datetime transactions['product_first_sold_date'] = pd.to_datetime(transactions['product_first_sold_date'], unit='s') # - transactions['product_first_sold_date'].head() # ### OBSERVATION # There is need for more clarity on the dataset. The integers in the date columns are not correct, there is inconsistency. #### checking the statistical summary of transactions dataset. transactions.describe() # ## CHECKING FOR AND TREATING MISSING VALUES #identifying missing values transactions.isnull().sum() # ### OBSERVATIONS # There are two many missing values in the transaction dataset. # # we may decide to drop columns with missing values depending on the purpose of analysis. # + # lets further explore the columns to know what is really going on. transactions.columns transactions['online_order'].value_counts() transactions['online_order'] = transactions['online_order'].fillna(method='ffill') transactions['brand'].value_counts() transactions['brand'] = transactions['brand'].fillna(method='ffill') transactions['product_line'].value_counts() transactions['product_line'] = transactions['product_line'].fillna(method='bfill') transactions['product_class'].value_counts() transactions['product_class'].fillna(transactions['product_class'].mode()[0], inplace=True) # - transactions['product_size'].value_counts() # + from sklearn.impute import SimpleImputer imputer = SimpleImputer(strategy='most_frequent') transactions['product_size'] = imputer.fit_transform(transactions[['product_class']]) transactions['product_size'].value_counts() transactions['standard_cost'].value_counts() from sklearn.impute import KNNImputer # - imputer = KNNImputer() transactions['standard_cost'] = transactions['standard_cost'].fillna(method='ffill') transactions['product_first_sold_date'].value_counts() transactions['product_first_sold_date'].fillna(transactions['product_first_sold_date'].mean(), inplace=True) #CHECKS transactions.isnull().sum() transactions.drop(transactions.loc[transactions['order_status']=='Cancelled'].index, inplace=True) transactions['order_status'].value_counts() sns.boxplot(x='brand', y='list_price', data=transactions) sns.countplot(x='product_line', data=transactions) # ## CHECKING FOR DUPLICATE duplicates = transactions.duplicated() transactions[duplicates].sum() # ### OBSERVATIONS # The data looks consistent and there are no duplicate values. # ## EXPLORATION OF new_customer_lists DATASET # + new_customer_lists.head() # - new_customer_lists.info() # #### OBSERVATIONS # There are unnamed columns in the data,the unnamed columns should be drop. # Dropping all Unnamed Column unnamed_columns = ['Unnamed: 16','Unnamed: 17','Unnamed: 18','Unnamed: 19','Unnamed: 20'] new_customer_lists = new_customer_lists.drop(unnamed_columns, axis=1) # + #new_customer_lists.info() # - # ### STATISTICAL SUMMARY # checking the statistical summary of new_customer_lists.describe() # ### TREATING MISSING VALUES # Checking for missing values new_customer_lists.isnull().sum() # ### OBSERVATIONS # There are missing values. There two columns relevant to these analysis that are having missing values. # ### DUPLICATES CHECK # + ##Checking for duplicates new_customer_lists.duplicated().sum() # - # ### OBSERVATION # There are no duplicate value in new_customer_lists dataset # ### EXPLORING COLUMNS AND SHAPE OF THE DATA new_customer_lists.shape # + new_customer_lists['gender'].value_counts() # Replace 'U' with 'not declaredN' new_customer_lists['gender'].str.replace('U','not declared') new_customer_lists['DOB'].describe() # - # ### EXPLORING CUSTOMER DEMOGRAPHIC DATASET sns.set(rc={'figure.figsize':[10,10]},font_scale=1.3) customer_demographic.isnull().sum() customer_demographic.describe() # + customer_demographic.head() # + customer_demographic.head() customer_demographic['defaults'].value_counts() # - # ### OBSERVATIONS # There are lots of incorrect values, we would however drop the column # + # dropping columns with incorrect values and printing the first five records to check; customer_demographic = customer_demographic.drop('defaults', axis=1) # - customer_demographic.head() # Replace 'U' with 'not declared' customer_demographic['gender'].str.replace('U','not declared') customer_demographic['DOB'].describe() customer_demographic.info() customer_demographic['gender'].value_counts() # ### OBSERVATION # There are some contraditions that needs to be replaced # Replace inconsistent values with appropriate values customer_demographic['gender'] = customer_demographic['gender'].replace('F','Female').replace('M','Male').replace('Femal','Female').replace('U','not declared') customer_demographic['gender'].value_counts() # ## EXPLORING CUSTOMER ADDRESS # + customer_address.info() # - customer_address.isnull().sum() customer_address.describe() customer_address['address'].value_counts() customer_address['state'].value_counts() # + customer_address.loc[customer_address['state'] == 'New South Wales', 'state'] = 'NSW' customer_address.loc[customer_address['state'] == 'Victoria', 'state'] = 'VIC' customer_address['state'].value_counts() # - customer_address['country'].value_counts() customer_address['property_valuation'].value_counts() sns.countplot(x='state', data=customer_address, palette=("flare")) sns.countplot(x='property_valuation', data=customer_address) # ## DATA AGGREGATION # since all the tables have common relationship to customer, it is useful to merge them for the purpose of analysis. new_customer_lists.head() customer_demographic['customer_id'].iloc[-1] new_customer_lists.insert(0, 'customer_id', range(4001, 4001 + len(new_customer_lists))) new_customer_lists.head() customer_demographic.head() # Merging the Customer Demographic with the Customer Address table before joining with New Customer List customer_add.head() # Merge dataframes using the customer_id column customer_demographic = pd.merge(customer_demographic, customer_address, how='left', on='customer_id') # + #customer_demographic = customer_demographic.drop(['address_x','postcode_x','state_x','country_x','property_valuation_x'], axis=1) # + customer_demographic.head() # - new_customer_lists.head() final_df = pd.concat([customer_demographic, new_customer_lists], ignore_index=True, sort=False) final_df final_df.to_csv('finalTransactions.csv') final_df.head() # + from sklearn.impute import KNNImputer imputer = KNNImputer() final_df['job_title'] = final_df['job_title'].fillna(method='ffill') final_df['job_industry_category'] = final_df['job_industry_category'].fillna(method='ffill') # - final_df.head()
DATA QUALITY ASSESSMENT - TASK_1.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # 1. Importing Packages and Collecting Data # # + import pandas as pd import numpy as np from scipy import stats '''Customize visualization Seaborn and matplotlib visualization.''' import matplotlib.pyplot as plt import seaborn as sns sns.set_style("whitegrid") # %matplotlib inline '''Plotly visualization .''' import plotly.offline as py from plotly.offline import iplot, init_notebook_mode import plotly.graph_objs as go init_notebook_mode(connected = True) # Required to use plotly offline in jupyter notebook '''Display markdown formatted output like bold, italic bold etc.''' from IPython.display import Markdown def bold(string): display(Markdown(string)) # - '''Read in export and import data from CSV file''' df_train = pd.read_csv('../input/bigquery-geotab-intersection-congestion/train.csv') df_test = pd.read_csv('../input/bigquery-geotab-intersection-congestion/test.csv') # # 4. Feature Engineering # # ## <span style='color:darkgreen;background:yellow'>4.1. Intersection ID # # Making a new columns of IntersectionId with city name. df_train['Intersection'] = df_train['IntersectionId'].astype(str) + df_train['City'] df_test['Intersection'] = df_test['IntersectionId'].astype(str) + df_test['City'] print(df_train['Intersection'].sample(6).values) from sklearn.preprocessing import LabelEncoder le = LabelEncoder() le.fit(pd.concat([df_train['Intersection'], df_test['Intersection']]).drop_duplicates().values) df_train['Intersection'] = le.transform(df_train['Intersection']) df_test['Intersection'] = le.transform(df_test['Intersection']) print(df_train['Intersection'].sample(6).values) # ## <span style='color:darkgreen;background:yellow'>4.2. Encoding Street Names # We are encode the street name according to its road type. # + # Reference: https://www.kaggle.com/bgmello/how-one-percentile-affect-the-others '''Let's use the following road types: Street, Avenue, Road, Boulevard, Broad and Drive''' road_encoding = { 'Road': 1, 'Street': 2, 'Avenue': 2, 'Drive': 3, 'Broad': 3, 'Boulevard': 4 } # - def encode(x): if pd.isna(x): return 0 for road in road_encoding.keys(): if road in x: return road_encoding[road] return 0 df_train['EntryTypeStreet'] = df_train['EntryStreetName'].apply(encode) df_train['ExitTypeStreet'] = df_train['ExitStreetName'].apply(encode) df_test['EntryTypeStreet'] = df_test['EntryStreetName'].apply(encode) df_test['ExitTypeStreent'] = df_test['ExitStreetName'].apply(encode) print(df_train['EntryTypeStreet'].sample(10).values) df_train["same_street_exact"] = (df_train["EntryStreetName"] == df_train["ExitStreetName"]).astype(int) df_test["same_street_exact"] = (df_test["EntryStreetName"] == df_test["ExitStreetName"]).astype(int) # ## <span style='color:darkgreen;background:yellow'>4.3. Encoding Cordinal Direction # Turn Direction: # # The cardinal directions can be expressed using the equation: $$ \frac{\theta}{\pi} $$ # # Where $\theta$ is the angle between the direction we want to encode and the north compass direction, measured clockwise. # # # Reference: # * https://www.kaggle.com/danofer/baseline-feature-engineering-geotab-69-5-lb # * This is an important feature, as shown by janlauge here : https://www.kaggle.com/janlauge/intersection-congestion-eda # # * We can fill in this code in python (e.g. based on: https://www.analytics-link.com/single-post/2018/08/21/Calculating-the-compass-direction-between-two-points-in-Python , https://rosettacode.org/wiki/Angle_difference_between_two_bearings#Python , https://gist.github.com/RobertSudwarts/acf8df23a16afdb5837f ) '''Defineing the directions''' directions = { 'N': 0, 'NE': 1/4, 'E': 1/2, 'SE': 3/4, 'S': 1, 'SW': 5/4, 'W': 3/2, 'NW': 7/4 } # + df_train['EntryHeading'] = df_train['EntryHeading'].map(directions) df_train['ExitHeading'] = df_train['ExitHeading'].map(directions) df_test['EntryHeading'] = df_test['EntryHeading'].map(directions) df_test['ExitHeading'] = df_test['ExitHeading'].map(directions) df_train['diffHeading'] = df_train['EntryHeading']- df_train['ExitHeading'] df_test['diffHeading'] = df_test['EntryHeading']- df_test['ExitHeading'] display(df_train[['ExitHeading','EntryHeading','diffHeading']].drop_duplicates().head(5)) # - # ## <span style='color:darkgreen;background:yellow'>4.5 standardizing of lat-long from sklearn.preprocessing import StandardScaler scaler = StandardScaler() lat_long = ['Latitude', 'Longitude'] for col in lat_long: df_train[col] = (scaler.fit_transform(df_train[col].values.reshape(-1, 1))) df_test[col] = (scaler.fit_transform(df_test[col].values.reshape(-1, 1))) # ## <span style='color:darkgreen;background:yellow'>4.6 Droping the variables """Let's see the columns of data""" df_train.columns.values """Let's drop the unwanted variables from test and train dataset""" df_train.drop(['RowId', 'IntersectionId', 'EntryStreetName', 'ExitStreetName', 'Path', 'City'], axis=1, inplace=True) df_test.drop(['RowId', 'IntersectionId', 'EntryStreetName', 'ExitStreetName', 'Path', 'City'], axis=1, inplace=True) # # 5. Seting X and Y # + '''Function to reduce the DF size''' # source: https://www.kaggle.com/kernels/scriptcontent/3684066/download def reduce_mem_usage(df): """ iterate through all the columns of a dataframe and modify the data type to reduce memory usage. """ start_mem = df.memory_usage().sum() / 1024**2 print('Memory usage of dataframe is {:.2f} MB'.format(start_mem)) for col in df.columns: col_type = df[col].dtype if col_type != object: c_min = df[col].min() c_max = df[col].max() if str(col_type)[:3] == 'int': if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max: df[col] = df[col].astype(np.int8) elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max: df[col] = df[col].astype(np.int16) elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max: df[col] = df[col].astype(np.int32) elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max: df[col] = df[col].astype(np.int64) else: if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max: df[col] = df[col].astype(np.float16) elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max: df[col] = df[col].astype(np.float32) else: df[col] = df[col].astype(np.float64) else: df[col] = df[col].astype('category') end_mem = df.memory_usage().sum() / 1024**2 print('Memory usage after optimization is: {:.2f} MB'.format(end_mem)) print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) / start_mem)) return df # - df_train = reduce_mem_usage(df_train) df_test = reduce_mem_usage(df_test) # + '''Seting X and Y''' target_var = df_train.iloc[:, 7:22] X_train = df_train.drop(target_var,axis = 1) y1_train = df_train["TotalTimeStopped_p20"] y2_train = df_train["TotalTimeStopped_p50"] y3_train = df_train["TotalTimeStopped_p80"] y4_train = df_train["DistanceToFirstStop_p20"] y5_train = df_train["DistanceToFirstStop_p50"] y6_train = df_train["DistanceToFirstStop_p80"] X_test = df_test # - """Let's have a final look at our data""" bold('**Data Dimension for Model Building:**') print('Input matrix dimension:', X_train.shape) print('Output vector dimension:',y1_train.shape) print('Test data dimension:', X_test.shape) # # 6. Model Building & Evaluation X_train.describe() """pecifying categorical features""" cat_feat = ['Hour', 'Weekend','Month', 'same_street_exact', 'Intersection', 'EntryTypeStreet', 'ExitTypeStreet'] all_preds ={0:[],1:[],2:[],3:[],4:[],5:[]} all_target = [y1_train, y2_train, y3_train, y4_train, y5_train, y6_train] # + # Reference: # https://medium.com/analytics-vidhya/hyperparameters-optimization-for-lightgbm-catboost-and-xgboost-regressors-using-bayesian-6e7c495947a9 # https://lightgbm.readthedocs.io/en/latest/Parameters-Tuning.html#for-faster-speed '''Importing Libraries''' import lightgbm as lgb from bayes_opt import BayesianOptimization dtrain = lgb.Dataset(data=X_train, label=y1_train) '''Define objective function''' def hyp_lgbm(num_leaves, feature_fraction, bagging_fraction, max_depth, min_split_gain, min_child_weight, lambda_l1, lambda_l2): params = {'application':'regression','num_iterations': 10, 'learning_rate':0.01, 'metric':'rmse'} # Default parameters params["num_leaves"] = int(round(num_leaves)) params['feature_fraction'] = max(min(feature_fraction, 1), 0) params['bagging_fraction'] = max(min(bagging_fraction, 1), 0) params['max_depth'] = int(round(max_depth)) params['min_split_gain'] = min_split_gain params['min_child_weight'] = min_child_weight params['lambda_l1'] = lambda_l1 params['lambda_l2'] = lambda_l2 cv_results = lgb.cv(params, dtrain, nfold=5, seed=44, categorical_feature=cat_feat, stratified=False, verbose_eval =None) # print(cv_results) return -np.min(cv_results['rmse-mean']) # - ''' Define search space of hyperparameters''' pds = {'num_leaves': (100, 230), 'feature_fraction': (0.1, 0.5), 'bagging_fraction': (0.8, 1), 'lambda_l1': (0,3), 'lambda_l2': (0,5), 'max_depth': (8, 19), 'min_split_gain': (0.001, 0.1), 'min_child_weight': (1, 20) } # + '''Define a surrogate model of the objective function and call it.''' optimizer = BayesianOptimization(hyp_lgbm,pds,random_state=44) # Optimize optimizer.maximize(init_points=5, n_iter=12) # - # ## 6.1 Retrain and Predict Using Optimized Hyperparameters '''Best parameters after optimization''' optimizer.max p = optimizer.max['params'] param = {'num_leaves': int(round(p['num_leaves'])), 'feature_fraction': p['feature_fraction'], 'bagging_fraction': p['bagging_fraction'], 'max_depth': int(round(p['max_depth'])), 'lambda_l1': p['lambda_l1'], 'lambda_l2':p['lambda_l2'], 'min_split_gain': p['min_split_gain'], 'min_child_weight': p['min_child_weight'], 'learing_rate':0.05, 'objective': 'regression', 'boosting_type': 'gbdt', 'verbose': 1, 'seed': 44, 'metric': 'rmse' } param # + '''Instantiate the models with optimized hyperparameters.''' train = X_train test = X_test from sklearn.model_selection import train_test_split for i in range(len(all_preds)): print('Training and predicting for target {}'.format(i+1)) X_train,X_test,y_train,y_test=train_test_split(train,all_target[i], test_size=0.2, random_state=31) xg_train = lgb.Dataset(X_train, label = y_train ) xg_valid = lgb.Dataset(X_test, label = y_test ) clf = lgb.train(param, xg_train, 10000, valid_sets = [xg_valid],categorical_feature=cat_feat, verbose_eval=100, early_stopping_rounds = 200) all_preds[i] = clf.predict(test, num_iteration=clf.best_iteration) # - submission = pd.read_csv('../input/bigquery-geotab-intersection-congestion/sample_submission.csv') #submission.head() dt = pd.DataFrame(all_preds).stack() dt = pd.DataFrame(dt) submission['Target'] = dt[0].values submission.head() submission.to_csv('lgbm2_submission.csv', index=False)
thoughtful-eda-feature-engineering-and-lightgbm.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [conda env:.conda-gaussflow-gpu] # language: python # name: conda-env-.conda-gaussflow-gpu-py # --- # + [markdown] colab_type="text" id="view-in-github" # <a href="https://colab.research.google.com/github/IPL-UV/gaussflow/blob/master/docs/assets/demo/pytorch_nf_freia.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="QMV_fJikDPKT" # # Freia - Linear Transforms # # This is my notebook where I play around with all things PyTorch. I use the following packages: # # * PyTorch # * Pyro # * GPyTorch # * PyTorch Lightning # # - # @title Install Packages # # %%capture try: import sys, os from pyprojroot import here # spyder up to find the root root = here(project_files=[".here"]) # append to path sys.path.append(str(root)) except ModuleNotFoundError: import os # !pip install --upgrade pyro-ppl gpytorch pytorch-lightning tqdm wandb corner nflows # !pip install git+https://github.com/VLL-HD/FrEIA.git # + colab={"base_uri": "https://localhost:8080/"} id="NUiHU3HWBa3o" outputId="ab02a9f0-ecb9-40a5-af55-d863c9fb5cbe" #@title Load Packages # TYPE HINTS from typing import Tuple, Optional, Dict, Callable, Union # PyTorch Settings import torch import torch.nn as nn from torch.utils.data import TensorDataset, DataLoader import torch.distributions as dist # PyTorch Lightning Settings import pytorch_lightning as pl from pytorch_lightning import Trainer from pytorch_lightning.loggers import WandbLogger from pytorch_lightning import seed_everything # NUMPY SETTINGS import numpy as np np.set_printoptions(precision=3, suppress=True) # MATPLOTLIB Settings import corner import matplotlib as mpl import matplotlib.pyplot as plt # %matplotlib inline # %config InlineBackend.figure_format = 'retina' # SEABORN SETTINGS import seaborn as sns sns.set_context(context='talk',font_scale=0.7) # sns.set(rc={'figure.figsize': (12, 9.)}) # sns.set_style("whitegrid") # PANDAS SETTINGS import pandas as pd pd.set_option("display.max_rows", 120) pd.set_option("display.max_columns", 120) # LOGGING SETTINGS import ml_collections import wandb device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') print("Using device: {}".format(device)) #logger.setLevel(logging.INFO) # %load_ext autoreload # %autoreload 2 # - # ## Logging # + cfg = ml_collections.ConfigDict() # Logger cfg.wandb_project = "gf2_0" cfg.wandb_entity = "ipl_uv" cfg.batch_size = 256 cfg.num_workers = 8 cfg.seed = 123 # Data cfg.n_train = 5_000 cfg.n_valid = 1_000 cfg.n_test = 2_000 cfg.noise = 0.05 # Model cfg.n_layers = 8 cfg.n_features = 2 cfg.n_reflections = 2 cfg.coupling = "glow" # Training cfg.num_epochs = 100 cfg.learning_rate = 1e-2 cfg.n_total_steps = cfg.num_epochs * cfg.n_train cfg.loss_fn = "inn" # - seed_everything(cfg.seed) # wandb_logger = WandbLogger(project=cfg.wandb_project, entity=cfg.wandb_entity) # wandb_logger.experiment.config.update(cfg) # + [markdown] id="fJSHSGzGeKLU" # ## Data # + id="-b_R70f2FFPE" from sklearn.datasets import make_moons data, label = make_moons(n_samples=cfg.n_train, noise=cfg.noise) # + colab={"base_uri": "https://localhost:8080/", "height": 367} id="xbN-qgbwJbtG" outputId="fa1bf8ca-3572-45a8-82dd-7f34262ef2fc" fig = corner.corner(data, hist_factor=2, color="blue") # - # #### DataLoader # + data_train, label = make_moons(n_samples=cfg.n_train, noise=cfg.noise, random_state=123) data_valid, label = make_moons(n_samples=cfg.n_valid, noise=cfg.noise, random_state=42) X_train = torch.FloatTensor(data_train) X_valid = torch.FloatTensor(data_valid) # make into dataset train_ds = TensorDataset(X_train) valid_ds = TensorDataset(X_valid) # make dataloader shuffle = True train_dl = DataLoader(train_ds, batch_size=cfg.batch_size, shuffle=shuffle, num_workers=cfg.num_workers) valid_dl = DataLoader(valid_ds, batch_size=cfg.batch_size, shuffle=False, num_workers=cfg.num_workers) # - from src.data.utils import tensor2numpy, numpy2tensor # + [markdown] id="1HkZk7qTeLJY" # ## Model # - # ### Lightning Module from src.lit_plane import FlowLearnerPlane from src.models.layers.linear import LinearLayer # ### Standard RVP # + id="JxjR2n8BJrHi" # FrEIA imports import FrEIA.framework as Ff import FrEIA.modules as Fm from src.models.layers.coupling import get_coupling_layer from src.models.layers.linear import create_linear_transform from src.models.layers.linear import LinearLayer # we define a subnet for use inside an affine coupling block # for more detailed information see the full tutorial hidden_dim = 512 def subnet_fc(dims_in, dims_out): return nn.Sequential(nn.Linear(dims_in, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, dims_out)) # a simple chain of operations is collected by ReversibleSequential inn = Ff.SequenceINN(cfg.n_features) for k in range(cfg.n_layers): # coupling transform (GLOW) coupling_transform = get_coupling_layer(coupling="glow") # create coupling transform inn.append( coupling_transform, subnet_constructor=subnet_fc, ) # # linear transform (orthogonal) # inn.append(Fm.HouseholderPerm, n_reflections=cfg.n_reflections) # linear transformation (NFlows Layers) inn.append( LinearLayer, transform="svd", num_householder=cfg.n_reflections, with_permutations=False ) base_dist = dist.Normal(torch.tensor([0.0]), torch.tensor([1.0])) # + [markdown] id="GP9Y0CogKDrh" # #### Initial Transformation # + colab={"base_uri": "https://localhost:8080/", "height": 367} id="TDDP_hTbJ32_" outputId="7ab26f3e-bdfc-4936-fd2a-b18315080a98" x = torch.Tensor(data) z, log_jac_det = inn(x) fig = corner.corner(z.detach().numpy(), hist_factor=2, color="blue") # + [markdown] id="54bG45mKKGW6" # ## Training # - learn = FlowLearnerPlane(inn, base_dist, cfg) trainer = pl.Trainer( # epochs min_epochs=5, max_epochs=100, #cfg.num_epochs, # progress bar progress_bar_refresh_rate=100, # device gpus=0, # gradient norm gradient_clip_val=1.0, gradient_clip_algorithm='norm', # logger=wandb_logger ) trainer.fit(learn, train_dataloader=train_dl, val_dataloaders=valid_dl) # + colab={"base_uri": "https://localhost:8080/", "height": 359} id="T_O1CQ_iK9ws" outputId="20fa5ef0-b799-474f-ef1e-fb914a06050c" z, log_jac_det = learn.model(X_train) fig = corner.corner(z.detach().numpy(), hist_factor=2, color="red") # wandb_logger.experiment.log({"latent_trained": wandb.Image(fig)}) # + [markdown] id="9h1FZD_VaM5S" # #### Inverse Transform # + colab={"base_uri": "https://localhost:8080/", "height": 367} id="j9rabhl-MNnv" outputId="aad12229-7eae-4d4f-a454-e0c6036dec3c" x_ori, _ = learn.model(z, rev=True) fig = corner.corner(x_ori.detach().numpy(), hist_factor=2, color="green") # wandb_logger.experiment.log({"latent_trained_inv": wandb.Image(fig)}) # - # #### Density Estimation # + from src.viz.bivariate import generate_2d_grid # Read data X_plot, _ = make_moons(n_samples=100_000, shuffle=True, noise=0.05, random_state=123 + 2) # # sampled data data_plot, label = make_moons(n_samples=100, noise=0.05) xyinput = generate_2d_grid(data_plot, 500, buffer=0.1) # + z, log_jac_det = learn.model(torch.Tensor(xyinput)) X_log_prob = base_dist.log_prob(z).sum(1) + log_jac_det X_log_prob = X_log_prob.detach().numpy() # + from matplotlib import cm # # Original Density # n_samples = 1_000_000 # n_features = 2 # X_plot = load_data(n_samples, 42) # X_plot = StandardScaler().fit_transform(X_plot) # Estimated Density cmap = cm.magma # "Reds" probs = np.exp(X_log_prob) # probs = np.clip(probs, 0.0, 1.0) # probs = np.clip(probs, None, 0.0) cmap = cm.magma # "Reds" # cmap = "Reds" fig, ax = plt.subplots(ncols=2, figsize=(12, 5)) h = ax[0].hist2d( X_plot[:, 0], X_plot[:, 1], bins=512, cmap=cmap, density=True, vmin=0.0, vmax=1.0 ) ax[0].set_title("True Density") ax[0].set( xlim=[X_plot[:, 0].min(), X_plot[:, 0].max()], ylim=[X_plot[:, 1].min(), X_plot[:, 1].max()], ) h1 = ax[1].scatter( xyinput[:, 0], xyinput[:, 1], s=1, c=probs, cmap=cmap, vmin=0.0, #vmax=1.0 ) ax[1].set( xlim=[xyinput[:, 0].min(), xyinput[:, 0].max()], ylim=[xyinput[:, 1].min(), xyinput[:, 1].max()], ) plt.colorbar(h1) ax[1].set_title("Estimated Density") plt.tight_layout() plt.show() # wandb_logger.experiment.log({"density": wandb.Image(fig)}) # + [markdown] id="sjOLEynNaWYy" # #### Sampling # + colab={"base_uri": "https://localhost:8080/", "height": 367} id="i5LfuaNDaXi9" outputId="eae2e7c2-1eaf-45d9-abd3-76894fc81798" # %%time # sample from the INN by sampling from a standard normal and transforming # it in the reverse direction n_samples = 100_000 z = torch.randn(n_samples, cfg.n_features) samples, _ = learn.model(z, rev=True) # - fig = corner.corner(samples.detach().numpy(), hist_factor=2, color="red") # wandb_logger.experiment.log({"sampling_trained": wandb.Image(fig)})
docs/assets/demo/freia_plane_linear.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # --- # # Production Performance - Near Real-Time Analysis # <h2><span style="color: #117d30;"> Using Azure Cosmos DB - Azure Synapse Link </span></h2> # # # Overview # Consider a typical industry scenario in which a conveyor belt scans or checks the quality of manufactured products and categorizes them into three categories viz. $Good$ OR $Snag$ OR $Reject$. The product quality whole process gets saved to a local database and gets pushed to the Synapse SQL server instance every night. # # Normally, we create an ETL pipeline that runs every night on the above data and creates meaningful insights out of it. So in such a case, to see the overall performance of machines, we need to wait for 24 hours. # # But, what if we can get this analysis in near real-time, say every 30 minutes or so, then this will make a huge difference, and can also derive many possibilities for changes. # # Here, in this notebook we will showcase the capability of Azure Cosmos DB with Azure Synapse Link and how we can achieve near real time analytics on data. See the workflow below. # # # Workflow # # ![Image alt text](https://#DATA_LAKE_NAME#.blob.core.windows.net/mfgdemocontainer/notebook-images/htap2.png) # # ### Scenario # Let's consider where we are getting telemetry data every 15 minutes from 5 machines into our Azure Cosmos DB with the following information : # - Overall Good / Snag / Reject # - Overall Average of Good / (Good + Snag + Reject) # - Timestamp # # **Dataset**: Above Quality data coming every 15 minutes from 5 machines, describing the number of items that were Good / Snag / Reject and what is the average production quality. # # Total records a day per machine = 1440/15 = 96 # # 5 Machines, 96 * 5 = 480 # # Records per day = 480 # # ***Database contains data from 24th June 2019 to 30th June 2019.*** # # Total records in database = 480 * 7 = **3360 records** # # # ### Tools/Techniques: # - Azure Cosmos DB Analytical store feature and Azure Synapse Link # - Visualization Using Matplotlib # # # ### Notebook Organization # # This notebook uses Azure Synapse Link functionality and retrieves near real-time data from Azure Cosmos DB Analytical Store and performs near real-time analytics on data. Following are key things achieved in the notebook : # # + How to read data from Azure Cosmos DB Analytical Store # - Container Name: mfg-mes-quality # - Azure Cosmos DB Linked Service Name : MESQuality # # + Aggregate data for each machine over a day. # # + Find out which machine's performance is degrading in near real-time. # ## Load data from Azure Cosmos DB Analytical Store into a Spark DataFrame # # + diagram={"activateDiagramType": 1, "aggData": "{\"ProductionMonth\":{\"2019-06-24T00:00:00.000Z\":8,\"2019-06-25T00:00:00.000Z\":8,\"2019-06-26T00:00:00.000Z\":8,\"2019-06-27T00:00:00.000Z\":8,\"2019-06-28T00:00:00.000Z\":8,\"2019-06-29T00:00:00.000Z\":8,\"2019-06-30T00:00:00.000Z\":8}}", "chartConfig": {"aggByBackend": false, "aggregation": "COUNT", "category": "bar", "keys": ["ProductionMonth"], "values": ["ProductionMonth"], "xLabel": "ProductionMonth", "yLabel": "ProductionMonth"}, "isSql": false, "isSummary": false, "previewData": {"filter": null}} # Let's load near-real time data from Telemetry storage - Azure Cosmos DB. To do the same, we use modern # syntax of connecting to Azure Cosmos DB Analytical Store. # In this code block, we are connecting to Azure Cosmos DB via Linked Service Connection. You can find # the same in Synapse Studio -> Data -> Linked (Tab) -> Cosmos DB -> Your linked service name. # We also specify Cosmos DB Container, which is mfg-mes-quality in this case. df_ProductionPerformance = spark.read\ .format("cosmos.olap")\ .option("spark.synapse.linkedService", "#COSMOS_LINKED_SERVICE#")\ .option("spark.cosmos.container", "mfg-mes-quality1")\ .load() # + # To proceed further for performing analysis in the Notebook, we need to import few of Python's data processing # libraries. Additionally, we will use matplotlib library to plot the required charts. import pandas as pd import numpy as np import matplotlib.pyplot as plt; plt.rcdefaults() from datetime import datetime # - # ## Data Transformation # # + # Let's load data into Python DataFrame. Here, we convert Spark DataFrame into Pandas DataFrame, which # in combination with Matplotlib provides an extensive set of tools for creating visualizations. # Once we have fetched Telemetry data we convert raw Timestamp values in String to datetime object. # This allows us perform aggregation as needed over the Time Series. # converting Spark DataFrame to Pandas for data exploration and visualization df_ProductionQuality = df_ProductionPerformance.toPandas() # converting a column datetime object column df_ProductionQuality['ProductionMonth'] = pd.to_datetime(df_ProductionQuality['ProductionMonth']) # - # ## Data Aggregation # # - We will **aggregate data for each day** grouped by machines. # + diagram={"activateDiagramType": 1, "aggData": "{\"_ts\":{\"ST_20_041\":7961369501.9375}}", "chartConfig": {"aggByBackend": false, "aggregation": "SUM", "category": "bar", "keys": ["MachineInstance"], "values": ["_ts"], "xLabel": "MachineInstance", "yLabel": "_ts"}, "isSql": false, "isSummary": false, "previewData": {"filter": null}} # We receive Quality data from MES System at regular interval. To better understand this data, we perform grouping on basis of: # 1. Date # 2. Machine Instance # Post grouping, let's see how data looks by displaying entire Aggregated DataFrame. # setting datetime index on Pandas DataFrame df_ProductionQuality.set_index(df_ProductionQuality["ProductionMonth"],inplace=True) # grouping data by machine and aggregating using daily mean df_AggProductionQuality = df_ProductionQuality.groupby(["MachineInstance"], sort=False).resample('D').mean().reset_index() display(df_AggProductionQuality.head()) # - # ## Tabulating the daywise averages for machines # - The above dataFrame (df_ProdPerfBatch) has aggregated data per day for each machine. # # - We will showcase this using a Table. # # - Lets keep a **threshold of 95%**. whenever a machine's daily average falls below 95% it will be marked as critical. # + diagram={"activateDiagramType": 1, "aggData": "{\"2019-06-24 00:00:00\":{\"94.88\":95.4,\"95.66\":96.65,\"95.9\":96.48,\"96.98\":95.44,\"97.23\":96.8}}", "chartConfig": {"aggByBackend": false, "aggregation": "SUM", "category": "bar", "keys": ["2019-06-25 00:00:00"], "values": ["2019-06-24 00:00:00"], "xLabel": "2019-06-25 00:00:00", "yLabel": "2019-06-24 00:00:00"}, "isSql": false, "isSummary": false, "previewData": {"filter": null}} # It's time to visualize our DataFrame and identify what fits our requirements from a business perspective. # As a business rule, threshold of 95% is minimum acceptable Quality. # Lower than 95% threshold indicates a problem which may need further inspection. # For visualizing data, we use matplotlib to draw a table # with yellow background indicating a problem. # plotting a table to see percentage of daily quality data for each machine cols = df_AggProductionQuality['ProductionMonth'].unique() index = df_AggProductionQuality['MachineInstance'].unique() index.sort() df_AvgMachineProduction = pd.DataFrame(index=index,columns=cols) df_TableColors = pd.DataFrame(index=index,columns=cols) rgb_normal = '#01B8AA' rgb_alert = '#E2B803' for i,row in df_AggProductionQuality.iterrows(): r = row['MachineInstance'] c = row['ProductionMonth'] avg_str = str(round(row['Avg'],2))[:5] if len(avg_str) < 5: avg_str+='0' df_AvgMachineProduction.loc[r,c] = avg_str if(row['Avg']<95): df_TableColors.loc[r,c]=rgb_alert else: df_TableColors.loc[r,c]=rgb_normal fig, ax = plt.subplots(figsize = (4,4)) ax.axis('off') ax.axis('tight') colNames = [dt.strftime("%d %b") for dt in pd.to_datetime(cols)] the_table = ax.table(cellText=np.array(df_AvgMachineProduction),cellColours=np.array(df_TableColors), cellLoc ='center', colWidths=[0.15]*len(cols) ,rowLabels=index,colLabels=colNames,loc='center') the_table.auto_set_font_size(False) the_table.set_fontsize(12) the_table.scale(3,2) fig.tight_layout() plt.show() # - # ## Horizontal Stacked Bar Chart Visualization # - Quality data contains number of items processed into three categories : # - Good # - Snag # - Reject # - We will plot it as a Stack chart. # + # Once we have plotted Quality averages, we need to see distribution between elements of Quality, viz, Good, Snag and Reject. # To plot elements of Quality, we use Horizontally Stacked Bar Charts, with customized starting point to see all values. # Plotting a horizontal stacked bar chart to show daily 'Good', 'Snag', and 'Reject' outputs for each machine # Note: These numbers represent the production calculated by averaging each batch in a day and summed across all machines df_stackPlot = df_ProductionQuality.resample('D').sum().reset_index() y = df_stackPlot['ProductionMonth'] df_Good = df_stackPlot['Good'] df_Snag = df_stackPlot['Snag'] df_Reject = df_stackPlot['Reject'] #Horizontal Stack Bar Plot fig, axs = plt.subplots(figsize=(13,7)) y_index = np.arange(len(y)) color_good = ["#02B480"] color_snag= ["#E2B803"] color_reject = ["#FD6C53"] colNames = [dt.strftime("%d-%b") for dt in pd.to_datetime(y)] bar1 = axs.barh(y_index, df_Good, alpha=0.7, color = color_good, linewidth = 2, edgecolor = color_good, tick_label=colNames) bar2 = axs.barh(y_index, df_Snag,left=df_Good, alpha=0.7, color = color_snag,linewidth= 2,edgecolor=color_snag,tick_label=colNames) bar3 = axs.barh(y_index, df_Reject, left =(df_Snag+df_Good), alpha=0.7, color = color_reject,linewidth= 2,edgecolor=color_reject,tick_label=colNames) # setting x limit min_val = min(df_Good) max_val = max(df_Good+df_Snag+df_Reject) diff = max_val - min_val x_min = 2000 # min_val-diff/2 x_max = 11000 #max_val+diff/2 axs.set_xlim(x_min, x_max) # writing text inside bars for i, patch in enumerate(bar1.get_children()): bl = patch.get_xy() x_cord = x_min/2 + 0.5*patch.get_width() + bl[0] y_cord = 0.5*patch.get_height() + bl[1] axs.text(x_cord,y_cord, str(int(round(df_Good[i]))), ha='center',va='center') axs.set_xlabel('Production') axs.set_ylabel('Date') fig.suptitle('Overall Production') plt.legend((bar1[0], bar2[0], bar3[0]), ('Good', 'Snag', 'Reject')) plt.show() # - # ## Horizontal Bar Chart Visualization # - To get an insight of which machine is behaving abnormaly or showing poor performance, lets compare all of them using a bar chart. # - We are calculating mean of each machine's production AVG for all seven days. # + # Up until now, we have been visualizing daily metrics. To interprete exact problem, # we also need to see how each machine Quality output looks like. By combining data from both # sides, we can pinpoint a specific machine that appears to be under performing. # plotting bar graph chart to show total quality of production for each machine #Bar Chart df_MachineTotalAvg = df_ProductionQuality.groupby(["MachineInstance"], sort=True).mean() # creating a list of avg production of each machine performance = df_MachineTotalAvg['Avg'] names= df_MachineTotalAvg.index.tolist() # plotting bar graph plt.figure(figsize=(13,7)) y_pos = np.arange(len(names)) edge_colour = ["#FFA132"] color_map = ['#FFA132', '#FFAA46', '#FFB35A', '#FFBC6D', '#FFC581', '#FFCE94', '#FFD7A8'] plt.barh(y_pos, performance, align='center', alpha=1, color = color_map, edgecolor=color_map) plt.yticks(y_pos, names) perf_min = min(performance) perf_max = max(performance) perf_diff = (perf_max - perf_min)/2 plt.xlim(perf_min-perf_diff, perf_max+perf_diff) plt.xlabel('Percentage') plt.ylabel('Machines') plt.title('Production Performance of Machines') plt.show() # + # Let's visualize correlation between Quality of production of all machines per day against number of Good pieces produced per day. # For doing the same, we are going to use Date on X-Axis. Stackbars will represent Average quality output of all machines. # Line overlapped over Stackbars will represent number of Good pieces produced across all machines for that day. # plotting graph to show the correlation between daily overall quality and average quality of all batches in a day df_barPlot = df_AggProductionQuality.set_index(df_AggProductionQuality["ProductionMonth"]).resample('D').mean().reset_index() df_linePlot = df_AggProductionQuality.set_index(df_AggProductionQuality["ProductionMonth"]).resample('D').sum().reset_index() x = df_barPlot['ProductionMonth'].tolist() x_Names = [dt.strftime("%d-%b") for dt in pd.to_datetime(x)] x_pos = np.arange(len(x)) y = df_barPlot['Avg'].tolist() y_min = min(y) y_max = max(y) y_diff = (y_max - y_min) y2 = df_linePlot['Good'].tolist() # plotting graph fig, ax1 = plt.subplots(figsize=(13,7)) color_map = ['#FFA132', '#FFAA46', '#FFB35A', '#FFBC6D', '#FFC581', '#FFCE94', '#FFD7A8'] # bar plot p1 = ax1.bar(x_pos, y, align='center', alpha=1, color = color_map,tick_label=x_Names) ax1.set_xticks(x_pos,x_Names) ax1.set_ylim(y_min-y_diff, y_max+y_diff/2) # line plot line_color = '#02C480' ax2 = ax1.twinx() p2 = ax2.plot(x_pos,y2,color = line_color) ax2.set_ylabel('Quality') ax1.set_ylabel('Average Percentage of Availability') ax1.set_xlabel('Date') fig.suptitle("Overall Quality") plt.legend((p1[0], p2[0]), ('Quality', 'Good')) plt.show() # - # ## Visualizing Average Availability for all Machines till 30th June 7:00 AM # # # + # Let's see what is happening currently. Through Azure Synapse Link feature, we can # perform near-real time analytics on data. # Let's plot a graph showing average Quality output of all machines for the last few hours. df_AvailabilityChartData = df_ProductionPerformance.toPandas() df_AvailabilityChartData.sort_values('ProductionMonth', inplace=True) df_RecentRecords = df_AvailabilityChartData.tail(60) df_RecentRecords = df_RecentRecords.groupby(["ProductionMonth"], sort=True).mean() performance = df_RecentRecords['Avg'].tolist() names = df_RecentRecords.index.tolist() perf_min = min(performance) perf_max = max(performance) perf_diff = (perf_max - perf_min)/2 # performance = [x for x in performance] # plotting bar graph plt.figure(figsize=(13,7)) y_pos = np.arange(len(names)) colNames = [dt.strftime("%H:%M") for dt in pd.to_datetime(names)] color_map=['#02B480','#02B480','#02B480','#E2B803','#02B480','#02B480','#02B480','#F4B71C','#F6A629','#F79537','#F98444','#FB7351'] plt.bar(y_pos, performance, align='center', alpha=1, color = color_map, edgecolor=color_map) plt.xticks(y_pos, colNames) plt.ylim(perf_min-perf_diff, perf_max+perf_diff) plt.ylabel('Average Percentage of Quality') plt.xlabel('Time of the day ({})'.format(pd.to_datetime(names)[0].strftime("%d-%b"))) plt.title("Machines Average Quality (Till 30th June 7:00 AM)") plt.show()
Manufacturing/automation/artifacts/notebooks/13 MFG_WITH_HTAP.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # *Accompanying code examples of the book "Introduction to Artificial Neural Networks and Deep Learning: A Practical Guide with Applications in Python" by [<NAME>](https://sebastianraschka.com). All code examples are released under the [MIT license](https://github.com/rasbt/deep-learning-book/blob/master/LICENSE). If you find this content useful, please consider supporting the work by buying a [copy of the book](https://leanpub.com/ann-and-deeplearning).* # # Other code examples and content are available on [GitHub](https://github.com/rasbt/deep-learning-book). The PDF and ebook versions of the book are available through [Leanpub](https://leanpub.com/ann-and-deeplearning). # %load_ext watermark # %watermark -a '<NAME>' -v -p torch # # Model Zoo -- Getting Gradients of an Intermediate Variable in PyTorch # This notebook illustrates how we can fetch the intermediate gradients of a function that is composed of multiple inputs and multiple computation steps in PyTorch. Note that gradient is simply a vector listing the derivatives of a function with respect # to each argument of the function. So, strictly speaking, we are discussing how to obtain the partial derivatives here. # Assume we have this simple toy graph: # # ![](images/manual-gradients/graph_1.png) # Now, we provide the following values to b, x, and w; the red numbers indicate the intermediate values of the computation and the end result: # # ![](images/manual-gradients/graph_2.png) # Now, the next image shows the partial derivatives of the output node, a, with respect to the input nodes (b, x, and w) as well as all the intermediate partial derivatives: # # # ![](images/manual-gradients/graph_3.png) # (The images were taken from my PyData Talk in August 2017, for more information of how to arrive at these derivatives, please see the talk/slides at https://github.com/rasbt/pydata-annarbor2017-dl-tutorial; also, I put up a little calculus and differentiation primer if helpful: https://sebastianraschka.com/pdf/books/dlb/appendix_d_calculus.pdf) # # # For instance, if we are interested in obtaining the partial derivative of the output a with respect to each of the input and intermediate nodes, we could do the following in TensorFlow, where `d_a_b` denotes "partial derivative of a with respect to b" and so forth: # + import tensorflow as tf g = tf.Graph() with g.as_default() as g: x = tf.placeholder(dtype=tf.float32, shape=None, name='x') w = tf.Variable(initial_value=2, dtype=tf.float32, name='w') b = tf.Variable(initial_value=1, dtype=tf.float32, name='b') u = x * w v = u + b a = tf.nn.relu(v) d_a_x = tf.gradients(a, x) d_a_w = tf.gradients(a, w) d_a_b = tf.gradients(a, b) d_a_u = tf.gradients(a, u) d_a_v = tf.gradients(a, v) with tf.Session(graph=g) as sess: sess.run(tf.global_variables_initializer()) grads = sess.run([d_a_x, d_a_w, d_a_b, d_a_u, d_a_v], feed_dict={'x:0': 3}) print(grads) # - # ## Intermediate Gradients in PyTorch via autograd's `grad` # In PyTorch, there are multiple ways to compute partial derivatives or gradients. If the goal is to just compute partial derivatives, the most straight-forward way would be using autograd's `grad` function. By default, the `retain_graph` parameter of the `grad` function is set to `False`, which will free the graph after computing the partial derivative. Thus, if we want to obtain multiple partial derivatives, we need to set `retain_graph=True`. Note that this is a very inefficient solution though, as multiple passes over the graph are being made where intermediate results are being recalculated: # + import torch import torch.nn.functional as F from torch.autograd import grad x = torch.tensor([3.], requires_grad=True) w = torch.tensor([2.], requires_grad=True) b = torch.tensor([1.], requires_grad=True) u = x * w v = u + b a = F.relu(v) d_a_b = grad(a, b, retain_graph=True) d_a_u = grad(a, u, retain_graph=True) d_a_v = grad(a, v, retain_graph=True) d_a_w = grad(a, w, retain_graph=True) d_a_x = grad(a, x) for name, grad in zip("xwbuv", (d_a_x, d_a_w, d_a_b, d_a_u, d_a_v)): print('d_a_%s:' % name, grad) # - # As suggested by <NAME>, this can be made rewritten in a more efficient manner by passing a tuple to the `grad` function so that it can reuse intermediate results and only require one pass over the graph: # + import torch import torch.nn.functional as F from torch.autograd import grad x = torch.tensor([3.], requires_grad=True) w = torch.tensor([2.], requires_grad=True) b = torch.tensor([1.], requires_grad=True) u = x * w v = u + b a = F.relu(v) partial_derivatives = grad(a, (x, w, b, u, v)) for name, grad in zip("xwbuv", (partial_derivatives)): print('d_a_%s:' % name, grad) # - # ## Intermediate Gradients in PyTorch via `retain_grad` # In PyTorch, we most often use the `backward()` method on an output variable to compute its partial derivative (or gradient) with respect to its inputs (typically, the weights and bias units of a neural network). By default, PyTorch only stores the gradients of the leaf variables (e.g., the weights and biases) via their `grad` attribute to save memory. So, if we are interested in the intermediate results in a computational graph, we can use the `retain_grad` method to store gradients of non-leaf variables as follows: # + import torch import torch.nn.functional as F from torch.autograd import Variable x = torch.tensor([3.], requires_grad=True) w = torch.tensor([2.], requires_grad=True) b = torch.tensor([1.], requires_grad=True) u = x * w v = u + b a = F.relu(v) u.retain_grad() v.retain_grad() a.backward() for name, var in zip("xwbuv", (x, w, b, u, v)): print('d_a_%s:' % name, var.grad) # - # ## Intermediate Gradients in PyTorch Using Hooks # Finally, and this is a not-recommended workaround, we can use hooks to obtain intermediate gradients. While the two other approaches explained above should be preferred, this approach highlights the use of hooks, which may come in handy in certain situations. # # > The hook will be called every time a gradient with respect to the variable is computed. (http://pytorch.org/docs/master/autograd.html#torch.autograd.Variable.register_hook) # Based on the suggestion by <NAME> (https://discuss.pytorch.org/t/why-cant-i-see-grad-of-an-intermediate-variable/94/7?u=rasbt), we can use these hooks in a combintation with a little helper function, `save_grad` and a `hook` closure writing the partial derivatives or gradients to a global variable `grads`. So, if we invoke the `backward` method on the output node `a`, all the intermediate results will be collected in `grads`, as illustrated below: # + import torch import torch.nn.functional as F grads = {} def save_grad(name): def hook(grad): grads[name] = grad return hook x = torch.tensor([3.], requires_grad=True) w = torch.tensor([2.], requires_grad=True) b = torch.tensor([1.], requires_grad=True) u = x * w v = u + b x.register_hook(save_grad('d_a_x')) w.register_hook(save_grad('d_a_w')) b.register_hook(save_grad('d_a_b')) u.register_hook(save_grad('d_a_u')) v.register_hook(save_grad('d_a_v')) a = F.relu(v) a.backward() grads # - # %watermark -iv
code/model_zoo/pytorch_ipynb/manual-gradients.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [default] # language: python # name: python3 # --- # %pylab inline import pandas as pd import tensorflow as tf import glob from tensorflow.contrib.tensor_forest.python import tensor_forest from tensorflow.python.ops import resources from tqdm import tqdm_notebook from multiprocessing import Pool import os os.environ["CUDA_VISIBLE_DEVICES"] = "" np.random.seed(42) df = pd.read_table('normal_tumor_segmented_df.tsv') FEATURE_KEYS = df.columns df = pd.read_csv('normal_tumor_segmented_df_with_label.csv') BUFFER_SIZE = len(df.index) BUFFER_SIZE # + # Parameters num_steps = 500 # Total steps to train batch_size = 1024 # The number of samples per batch num_classes = 2 # The 10 digits num_features = 46 # Each image is 28x28 pixels num_trees = 100 max_nodes = 10000 # + X = tf.placeholder(tf.float32, shape=[None, num_features]) # For random forest, labels must be integers (the class id) Y = tf.placeholder(tf.int32, shape=[None]) # Random Forest Parameters hparams = tensor_forest.ForestHParams(num_classes=num_classes, num_features=num_features, num_trees=num_trees, max_nodes=max_nodes).fill() # Build the Random Forest forest_graph = tensor_forest.RandomForestGraphs(hparams) # Get training graph and loss train_op = forest_graph.training_graph(X, Y) loss_op = forest_graph.training_loss(X, Y) # Measure the accuracy infer_op, _, _ = forest_graph.inference_graph(X) correct_prediction = tf.equal(tf.argmax(infer_op, 1), tf.cast(Y, tf.int64)) accuracy_op = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # Initialize the variables (i.e. assign their default value) and forest resources init_vars = tf.group(tf.global_variables_initializer(), resources.initialize_resources(resources.shared_resources())) # Start TensorFlow session sess = tf.Session() # Run the initializer sess.run(init_vars) # + def _parse_csv(rows_string_tensor): """Takes the string input tensor and returns tuple of (features, labels).""" # Last dim is the label. num_features = len(FEATURE_KEYS) num_columns = num_features + 1 columns = tf.decode_csv(rows_string_tensor, record_defaults=[[0.0]] * num_features + [[0]], field_delim=',') return tf.cast(tf.stack(columns[:-1]), tf.float32), tf.cast(columns[-1], tf.int32) def input_fn(file_names, batch_size): """The input_fn.""" dataset = tf.data.TextLineDataset(file_names).skip(1) # Skip the first line (which does not have data). dataset = dataset.map(_parse_csv) dataset = dataset.shuffle(buffer_size=BUFFER_SIZE) dataset = dataset.batch(batch_size) iterator = tf.data.Iterator.from_structure(dataset.output_types, dataset.output_shapes) next_batch = iterator.get_next() init_op = iterator.make_initializer(dataset) return init_op, next_batch # - training_init_op, training_next_batch = input_fn(['normal_tumor_segmented_df_with_label.csv'], 1024) for epoch in range(num_steps): sess.run(training_init_op) while True: try: training_features_batch, training_label_batch = sess.run(training_next_batch) except tf.errors.OutOfRangeError: break _, l = sess.run([train_op, loss_op], feed_dict={X: training_features_batch, Y: training_label_batch}) acc = sess.run(accuracy_op, feed_dict={X: training_features_batch, Y: training_label_batch}) print('Step %i, Loss: %f, Acc: %f' % (epoch, l, acc)) len(training_label_batch) len(training_features_batch) testing_init_op, testing_next_batch = input_fn(['test_normal_tumor_segmened_with_labels.csv'], 1024) test_acc = [] sess.run(testing_init_op) while True: try: testing_features_batch, testing_label_batch = sess.run(testing_next_batch) except tf.errors.OutOfRangeError: break acc = sess.run(accuracy_op, feed_dict={X: testing_features_batch, Y: testing_label_batch}) test_acc.append(acc) test_acc
notebooks/RandomForest-128px.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- #import bs4 the beautifulsoup library from bs4 import BeautifulSoup #create employee html document employee_html_doc ="""<employee> <employee class="accountant"> <firstName>John</firstName> <lastName>Doe</lastName> </employee> <employee class="manager"> firstName>Anna</firstName> <lastName>Smith</lastName> </employee> <employee class="developer"> firstName>Peter</firstName> <lastName>Jones</lastName> </employee> </employees>""" #create soup object soup_emp = BeautifulSoup(employee_html_doc,'html.parser') #access and view the tag tag = soup_emp.employee tag #modify the tag tag['class']='manager' #view the tag to see the modification tag #view the soup object to verify the modification soup_emp #add a tag tag = soup_emp.new_tag('rank') tag.string = 'Manager 1' #modify using insert_after_method soup_emp.employees.employee.insert_after(tag)
WebScrapping_ModifyDATA.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %matplotlib inline # # # Logistic function # # # Shown in the plot is how the logistic regression would, in this # synthetic dataset, classify values as either 0 or 1, # i.e. class one or two, using the logistic curve. # # # # + print(__doc__) # Code source: <NAME> # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model from scipy.special import expit # General a toy dataset:s it's just a straight line with some Gaussian noise: xmin, xmax = -5, 5 n_samples = 100 np.random.seed(0) X = np.random.normal(size=n_samples) y = (X > 0).astype(np.float) X[X > 0] *= 4 X += .3 * np.random.normal(size=n_samples) X = X[:, np.newaxis] # Fit the classifier clf = linear_model.LogisticRegression(C=1e5, solver='lbfgs') clf.fit(X, y) # and plot the result plt.figure(1, figsize=(4, 3)) plt.clf() plt.scatter(X.ravel(), y, color='black', zorder=20) X_test = np.linspace(-5, 10, 300) loss = expit(X_test * clf.coef_ + clf.intercept_).ravel() plt.plot(X_test, loss, color='red', linewidth=3) ols = linear_model.LinearRegression() ols.fit(X, y) plt.plot(X_test, ols.coef_ * X_test + ols.intercept_, linewidth=1) plt.axhline(.5, color='.5') plt.ylabel('y') plt.xlabel('X') plt.xticks(range(-5, 10)) plt.yticks([0, 0.5, 1]) plt.ylim(-.25, 1.25) plt.xlim(-4, 10) plt.legend(('Logistic Regression Model', 'Linear Regression Model'), loc="lower right", fontsize='small') plt.tight_layout() plt.show()
01 Machine Learning/scikit_examples_jupyter/linear_model/plot_logistic.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ## Python Modules # %%writefile weather.py def prognosis(): print("It will rain today") import weather weather.prognosis() # ## How does Python know from where to import packages/modules from? # + # Python imports work by searching the directories listed in sys.path. # - import sys sys.path # + ## "__main__" usage # A module can discover whether or not it is running in the main scope by checking its own __name__, # which allows a common idiom for conditionally executing code in a module when it is run as a script or with python -m # but not when it is imported: # + # %%writefile hw.py # #!/usr/bin/env python def hw(): print("Running Main") def hw2(): print("Hello 2") if __name__ == "__main__": # execute only if run as a script print("Running as script") hw() hw2() # - import main import hw main.main() hw.hw2() # + # Running on all 3 OSes from command line: python main.py # - # ## Make main.py self running on Linux (also should work on MacOS): # # Add # # #!/usr/bin/env python to first line of script # # mark it executable using # # ### need to change permissions too! # $ chmod +x main.py # ## Making Standalone .EXEs for Python in Windows # # * http://www.py2exe.org/ used to be for Python 2 , now supposedly Python 3 as well # * http://www.pyinstaller.org/ # Tutorial: https://medium.com/dreamcatcher-its-blog/making-an-stand-alone-executable-from-a-python-script-using-pyinstaller-d1df9170e263 # # Need to create exe on a similar system as target system! # Exercise Write a function which returns a list of fibonacci numbers up to starting with 1, 1, 2, 3, 5 up to the nth. So Fib(4) would return [1,1,2,3] # ![Fibo](https://upload.wikimedia.org/wikipedia/commons/thumb/d/db/34%2A21-FibonacciBlocks.png/450px-34%2A21-FibonacciBlocks.png) # ![Fibonacci](https://upload.wikimedia.org/wikipedia/commons/thumb/8/8e/Leonardo_da_Pisa.jpg/330px-Leonardo_da_Pisa.jpg) # + # %%writefile fibo.py # Fibonacci numbers module def fib(n): # write Fibonacci series up to n a, b = 1 1 while b < n: print(b, end=' ') a, b = b, a+b print() def fib2(n): # return Fibonacci series up to n result = [] a, b = 1, 1 while b < n: result.append(b) a, b = b, a+b return result # - import fibo fibo.fib(100) fibo.fib2(100) fib=fibo.fib # If you intend to use a function often you can assign it to a local name: fib(300) # #### There is a variant of the import statement that imports names from a module directly into the importing module’s symbol table. from fibo import fib, fib2 # we overwrote fib=fibo.fib fib(100) fib2(200) # This does not introduce the module name from which the imports are taken in the local symbol table (so in the example, fibo is not defined). # There is even a variant to import all names that a module defines: **NOT RECOMMENDED** # + ## DO not do this Namespace collission possible!! # - from fibo import * fib(400) # ### If the module name is followed by as, then the name following as is bound directly to the imported module. import fibo as fib dir(fib) fib.fib(50) # + ### It can also be used when utilising from with similar effects: # - from fibo import fib as fibonacci fibonacci(200) # ### Executing modules as scripts¶ # When you run a Python module with # # python fibo.py <arguments> # # the code in the module will be executed, just as if you imported it, but with the \_\_name\_\_ set to "\_\_main\_\_". That means that by adding this code at the end of your module: # + # %%writefile fibbo.py # Fibonacci numbers module def fib(n): # write Fibonacci series up to n a, b = 0, 1 while b < n: print(b, end=' ') a, b = b, a+b print() def fib2(n): # return Fibonacci series up to n result = [] a, b = 0, 1 while b < n: result.append(b) a, b = b, a+b return result if __name__ == "__main__": import sys fib(int(sys.argv[1], 10)) # - import fibbo as fi fi.fib(200) # #### This is often used either to provide a convenient user interface to a module, or for testing purposes (running the module as a script executes a test suite). # ### The Module Search Path # # When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations: # # * The directory containing the input script (or the current directory when no file is specified). # * PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH). # * The installation-dependent default. # Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A. Just like the use of modules saves the authors of different modules from having to worry about each other’s global variable names, the use of dotted module names saves the authors of multi-module packages like NumPy or Pillow from having to worry about each other’s module names. sound/ Top-level package __init__.py Initialize the sound package formats/ Subpackage for file format conversions __init__.py wavread.py wavwrite.py aiffread.py aiffwrite.py auread.py auwrite.py ... effects/ Subpackage for sound effects __init__.py echo.py surround.py reverse.py ... filters/ Subpackage for filters __init__.py equalizer.py vocoder.py karaoke.py ... # The \_\_init\_\_.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, \_\_init\_\_.py can just be an empty file
Python Modules and Imports.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # + # Comparison of booleans # see if True equals False print(True == False) # Comparison of integers print(-5 * 15 != 75) # Comparison of strings print("pyscript" == "PyScript") # Compare a boolean with a numeric print(True == 1) # + # Comparison of integers x = -3 * 6 print(x >= -10) # Comparison of strings y = "test" print("test" <= y) # Comparison of booleans print(True > False) # + # Create arrays import numpy as np my_house = np.array([18.0, 20.0, 10.75, 9.50]) your_house = np.array([14.0, 24.0, 14.25, 9.0]) # my_house greater than or equal to 18 print(my_house >= 18) # my_house less than your_house print(my_house < your_house)
Pandas/2_Operators.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # <p style='color:red'>Introdução sobre projeto.... preguiça de escrever agora</p> # # ## 1. Repository Structure # # The package is structured in repository as follows: # # jp_notebook_visuals/ # | LICENSE # | README.md >>>you are here<<< # | Visuals/ # | | __init__.py # | | FastMatplot.py # | | LaTex.py # | | # | | _base_/ # | | | __init__.py # | | | _axes_base.py # | | | _graph_base.py # | | # | | _utils_/ # | | | __init__.py # | | | _exceptions.py # | | | _type_definitions.py # | | | _functions.py # # # # ## 2. Installation # # To install Visuals module, two main options are available # # #### 2.1 via pip install # # The simplest way is to install the package is achieved via PIP, the __package installer for python__ used to download packages from <a href='https://pypi.org/'>PyPI</a>, the Python Package Index. The package url in PyPI can be found <a href='https://pypi.org/project/jp-notebook-utils/'>here</a> # # To install the package, simply open a terminal or kernel and run the following command: # # `pip install jp_notebook_visuals` # # #### 2.2 via github # # It is also possible to clone a public github repository or simply download zip file where the source code is located. In case you are reading this readme.md file from anywhere but github, Visuals package source code can be found in github <a href='https://github.com/rodrigodoering/jp_notebook_visuals'>here</a> # # # #### 2.3 Installation requirements # # At the moment, as a pre-alpha stage code, jp_notebook_visuals package requires a strict set of public python libraries with a minimum obligatory version, which can be found at `setup.py` script: # # python >= 3.5.2 # matplotlib >= 3.3.0 # numpy >= 1.19.2 # pandas >= 1.1.3 # # If any of the above requirements is not satisfied and jp_notebook_visuals package is installed via __pip__ ina terminal, installation will be cancalled. It can however works perfectly if installation occurred via repository clone since it wont evaluate install requirements set in `setup.py`. # # __Important Note__: # # Although these requirements might stop installation in the middle if not fulfilled, they are not strictly mandatory for the package to work. During setup configuration and package development, code has been tested only in two specific python environments, so the requirerments are, at least for now, simply based on the least up to date environment where the modules were tested in first place. In general terms, what the package strictly requires for running is a python 3.5 environment since the modules make use of __type hinting__ which was only introduced to python by that version. Type hints allow a more readable code with better documentation which is exactly what we are looking for here. In special, its possible to study the existing user-defined types <a href='https://github.com/rodrigodoering/jp_notebook_visuals/blob/main/Visuals/_utils_/_type_definitions.py'>here</a>, making it easier to use the functions. # # # ## 3 Importing # # Once....something # # # <p style='color:red'> # PRECISO CONTINUAR AQUI DEPOIS, MAS SI PA NÃO VOU PRECISAR DESSA PARTE... # CÉLULA DE CÓDIGO ABAIXO É APENAS PARA CARREGAR O DIRETÓRIO LOCAL NO PC - NÃO ESQUECER DE # EXCLUIR NA VERSÃO FINAL # # </p> import sys sys.path.append('C:\\Users\\rodri\\github\\jp_notebook_visuals_git') # <p style='color:red'>Seguindo...</p> # ## 4 LaTex Module # # LaTex module contains functions for displaying LaTex language expressions in a nice fashion in jupyter notebook presentations. Three main functions are declared within the module: # # - display_expression # - display_vec # - display_matrix # # `display_expression` function is the principal one, responsible for actually displaying latex code in stdout. The other two, `display_vec` and `display_matrix` are adaptations for structuring specific latex code for displaying matrices and vectors, but internally use `display_expression` function as well. # # For more information about latex expressions, a good option is __Overleaf__, where you can find a good and complete documentation about what LaTex is and how to use it (specially in the context of writing scientific papers that require mathematical formulations). The following <a href='https://www.overleaf.com/learn/latex/Learn_LaTeX_in_30_minutes'>link</a> is a 30 minutes tutorial in Overleaf, where you can read more about it. # # To import LaTex module we can run the following: from Visuals import LaTex # Other options to import the module with an alias: # # from Visuals import LaTex as lx # # Or to import directly the existing functions: # # from Visuals.LaTex import display_expression # from Visuals.LaTex import display_matrix # from Visuals.LaTex import display_vec # # Lets create a example latex expression using the famous __sigmoid function__ (a popular activation function used by many algorithms in machine learning and statistical modelling fields): sigmoid = 'f(x) = \\frac{1}{1 + e^{-(x)}}' type(sigmoid) # If we simply print this variable, it will appear as a simple string in stdout: # # print(sigmoid) # >>> 'f(x) = \frac{1}{1 + e^{-(x)}}' # # Now, by passing this same expression to __LaTex.display_expression__ function, it will properly display the latex equation: # LaTex.display_expression(sigmoid) # There are a few customizable parameters the function supports, all related to LaTex native keywords: `size`, `style` and `font`. Please refer to the following documentations in Overleaf for more information about: # # - <a href='https://www.overleaf.com/learn/latex/Font_sizes,_families,_and_styles'>font sizes</a> # - <a href='https://www.overleaf.com/learn/latex/Display_style_in_math_mode'>display styles</a> # - <a href='https://www.overleaf.com/learn/latex/Mathematical_fonts'>Math fonts</a> # # The available options are stored as list variables inside the module `Visuals.LaTex`itself, and we can even access this variables if needed: print('Available styles', LaTex.available_styles) # The parameters here are integers since they work as index for the desired value. Lets run an example with math fonts to see how the function select the desired preset and display the sigmoid function with different values for `font`parameter: # Interate over the first three available fonts # For the example it's not necessary to use all available fonts for i, font in enumerate(LaTex.available_fonts[:3]): # print selected index and respective font print('\nIndex %d, Font: %s' % (i, font)) # display expression with selected font LaTex.display_expression(sigmoid, size=5, font=i) # Now, suppose we want to implement and run the sigmoid function, we can display the data easily with the other two functions in the module. First we create a vector with $x$ values as input for the sigmoid function: # + import numpy as np X = np.linspace(0,1,5) # - # Now, we must define a simple sigmoid function to pass the $x$ input and compute $f(x)$ values # + def sigmoid(x): """ Implements sigmoid function """ return 1 / (1 + np.e**(-x)) f_x = [sigmoid(x) for x in X] # - # Lets view the vector produced in LaTex display by calling `display_vec`function: LaTex.display_vec(f_x, label='f(x)', size=3) # A few interesting things above: # - both `display_vec`and `display_matrix` functions supports a `label` parameter where you can name and identify the matrix or vector. It supports Latex display as well and we can even pass more elaborated LaTex expressions as labels for the visualization. # # - we are passing once again the `size` parameter, only now this is a __kwarg__ argunment. As mentioned before, both `display_vec`and `display_matrix` functions are calling `display_expression`internally, thus allowing the user to personalize LaTex keywords by passing kwargs internally to `display_expression` call. # # - In both functions, there is a boolean parameter `info` with default value of `True`. If true, it will display stylish information formated in LaTex as well about the vector or matrix dimensions. # # To test the other function, `display_matrix`, lets simply stack both vectors and compose a 5x2 matrix called $S$: S = np.vstack((x,y)).T LaTex.display_matrix(aug_matrix, label='S') # One very import thing to always keep in mind is that displaying LaTex is __memory consuming__. Often in fields such as data science and machine learning engineering we will be presented to huge datasets with millions of rows or columns (or both depending on the application), and displaying those as latex might cause memory crashs and __very__ slow execution times. Turns out, you can define a limit value for rows or columns (or both) with `n_rows` and `n_cols` arguments prior to be shown. In case of matrices, you can use both parameters. As for vectors, since they are uni-dimensional, usa only `n_rows`. Bellow I run an example by creating a $100 \times 10$ matrix and display it: LaTex.display_matrix(np.random.rand(100,10), n_rows=10, n_cols=3) # So, there are $1000$ values stored in that matrix, but I decided to limit the visualization to only 30 values (10 rows with 3 columns each). However, observe that the information displayed at the bottom holds the original dimensions of the matrix. The operation of "cropping" the matrix happens after storing the matrix dimensions. Take note that in the current version of the module, by default all the existing values __will be displayed__, there is __not__ a code block inside this functions evaluating the size of the input prior to displaying it eventhough the option of cropping is available for both functions. However, we do intend to create such behaviour inside the functions in future updates # #
Visuals/LaTex Module User Guide .ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + #### Get Feature Vector ##### import librosa from librosa import feature import numpy as np fn_list_i = [ feature.chroma_stft, feature.spectral_centroid, feature.spectral_bandwidth, feature.spectral_rolloff ] fn_list_ii = [ feature.rmse, feature.zero_crossing_rate ] def get_feature_vector(y,sr): feat_vect_i = [ np.mean(funct(y,sr)) for funct in fn_list_i] feat_vect_ii = [ np.mean(funct(y)) for funct in fn_list_ii] feature_vector = feat_vect_i + feat_vect_ii return feature_vector # + #### MULTITHREADING technique for Feature Extraction from Audio Files concurrently and save them into Different output folder import IPython.display as ipd import librosa import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.io import wavfile as wav from sklearn import metrics from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split import threading import os from glob import glob def task1(): print("Task 1 assigned to thread: {}".format(threading.current_thread().name)) print("ID of process running task 1: {}".format(os.getpid())) #directories of normal audios #norm_data_dir = ‘./audio-processing-files/normals/’ norm_data_dir = 'F:/sensez9/Audio_ML/data/cats_dogs/train/cat/' #'F:/sensez9/Audio_ML/data/cats_dogs/train/cat/' norm_audio_files = glob(norm_data_dir + '*.wav') ### Feature Extraction From Audios #### norm_audios_feat = [] for file in norm_audio_files: y , sr = librosa.load(file,sr=None) feature_vector = get_feature_vector(y, sr) norm_audios_feat.append(feature_vector) feature_train_cat_df = pd.DataFrame(norm_audios_feat) print(feature_train_cat_df.shape) df1 = [norm_audios_feat] df1= pd.DataFrame(df1) df1_arr = df1.values df1_t = df1_arr.transpose() train_cat = pd.DataFrame(df1_t) train_cat['label'] = 'cat' train_cat.to_csv(r'E:\sensez9\output\train_cat_features.csv') def task2(): print("Task 2 assigned to thread: {}".format(threading.current_thread().name)) print("ID of process running task 2: {}".format(os.getpid())) #directories of normal audios #norm_data_dir = ‘./audio-processing-files/normals/’ norm_data_dir2 = 'F:/sensez9/Audio_ML/data/cats_dogs/train/dog/' #'F:/sensez9/Audio_ML/data/cats_dogs/train/cat/' norm_audio_files2 = glob(norm_data_dir2 + '*.wav') norm_audios_feat2 = [] for file in norm_audio_files2: y , sr = librosa.load(file,sr=None) feature_vector = get_feature_vector(y, sr) norm_audios_feat2.append(feature_vector) feature_train_dog_df = pd.DataFrame(norm_audios_feat2) print(feature_train_dog_df.shape) df2 = [norm_audios_feat2] df2= pd.DataFrame(df2) df2_arr = df2.values df2_t = df2_arr.transpose() train_dog = pd.DataFrame(df2_t) train_dog['label'] = 'dog' train_dog.to_csv(r'E:\sensez9\output\train_dog_features.csv') if __name__ == "__main__": # print ID of current process print("ID of process running main program: {}".format(os.getpid())) # print name of main thread print("Main thread name: {}".format(threading.current_thread().name)) # creating threads t1 = threading.Thread(target=task1, name='t1') t2 = threading.Thread(target=task2, name='t2') # starting threads t1.start() t2.start() # wait until all threads finish t1.join() t2.join() #### perform Librosa Code through multithreading process ##### # -
Multithreading_feature_extraction.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import joblib print(joblib.__version__) def func(i): return i result = joblib.Parallel(n_jobs=-1)(joblib.delayed(func)(i) for i in range(5)) print(result) result = joblib.Parallel(n_jobs=-1, verbose=1)(joblib.delayed(func)(i) for i in range(5)) result = joblib.Parallel(n_jobs=-1, verbose=11)(joblib.delayed(func)(i) for i in range(5)) result = joblib.Parallel(n_jobs=2, verbose=1)(joblib.delayed(func)(i) for i in range(5)) result = joblib.Parallel(n_jobs=-2, verbose=1)(joblib.delayed(func)(i) for i in range(5)) def func_multi(i): return i, i**2, i**3 results = joblib.Parallel(n_jobs=-1)(joblib.delayed(func_multi)(i) for i in range(5)) print(results) a, b, c = zip(*results) print(a) print(b) print(c) def func_multi2(i, j, k): return i, j, k results = joblib.Parallel(n_jobs=-1)( joblib.delayed(func_multi2)(i, j, k) for i, j, k in zip(range(5), range(5, 10), range(10, 15)) ) print(results) def func_none(): # do something pass results = joblib.Parallel(n_jobs=-1)(joblib.delayed(func_none)() for i in range(5)) print(results) joblib.Parallel(n_jobs=-1)(joblib.delayed(func_none)() for i in range(5)) _ = joblib.Parallel(n_jobs=-1)(joblib.delayed(func_none)() for i in range(5))
notebook/joblib_parallel_usage.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # plotting libraries import matplotlib import matplotlib.pyplot as plt # numpy (math) libary import numpy as np from scipy.optimize import fsolve, root #from scipy.optimize import root import math # + # CONSTANTS and PARAMETERS # general physics ε0 = 8.85418782e-12 # [F/m] vacuum permittivity epsilon_0 c0 = 299792458 # [m/s] speed of light in vacuum c_0 ħ = 1.05457180e-34 # [J/s] Planck constant # geometrical parameters R = 9.0e-6 # [m ] radius w = 500e-9 # [m ] width h = 200e-9 # [m ] height wga = w*h # [m²] core area L = 2*np.pi*R # [m ] core length V = L*wga # [m³] ~ core volume Veff = V # [m³] effective mode volume Γ = 0.9 ρSi = 2.3290e3 # [kg/m³] Mring = ρSi*V # [kg] mass of the microring Cp = 0.7e3 # [J/kg/K] # parameters λ0 = 1.550e-6 # [m] ω0 = c0/λ0 # ~ 193.1 e12 [Hz] or e0 [THz] print('resonance:') print('wavelength λ_0 = %.4f' % (λ0*1.0e06), 'µm') print('frequency ω_0 = %.4f' % (ω0/1.0e12), 'THz') λp = 1.5505e-6 # [m] ωp = c0/λp # ~ 193.1 e12 [Hz] or e0 [THz] print('resonance:') print('wavelength λ_P = %.4f' % (λp*1.0e06), 'µm') print('frequency ω_P = %.4f' % (ωp/1.0e12), 'THz') 𝛾TH = 7.5e6 # [Hz] 𝛾FC = 250e6 # [Hz] or 250 µs-¹ # refractive index nSi = 3.48 # Silicon refractive index n0 = nSi # standard refractive index nT = 1.8e-4 # [1/K] at 300 K. dTdP = 1e-6 # [K/(W/cm^2)] n2 = 5e-14 # [1/(W/cm²)] intensity-dependent refractive index n2 = 4.5e-18 # [1/(W/m²)] intensity-dependent refractive index dndT = 1.86e-4 # [1/K] dndN = -1.73e-27 # [m³] dαdN = 1.1e-15 # [m²] βtpa = 0.7e-11 # [m/W] vg = c0/4 # [m/s] κa = 0.15 κb = κa τa = L / (κa**2 * vg) τb = τa τ0 = 3.0e-9 # [Hz] ~ 1 / (α * vg) σ = np.sqrt(0.5*c0*ε0*n0*wga) # [ W / (V/m) ] Ep = np.power( 0.000, 0.5) # [ σ * (V/m) ] Es = np.power( 100, 0.5) # [ σ * (V/m) ] #ω, ωp, ω0, Ep, Es, τa, τb, τ0, 𝛾TH, 𝛾FC, Mring, Cp, n0, n2, dndT, dndN, dαdN, βtpa, Γ, V, Veff = par # - # print(1550e-9**2/(L*20e-9)) print(L) # + # greek letters and other symbols (Ctrl+Shift+u): # Γ = u0393 # Δ = u0394 # Ω = u03a9 # α = u03b1 # β = u03b2 # γ = u03b3, 𝛾 = u1D6FE # δ = u03b4 # ε = u03b5 # λ = u03bb # σ = u03c3 # τ = u03c4 # ψ = u03c8 # ω = u03c9 # + # Constant normalized to the main quantities, i.e. Power, Energy, Temperature, Population # + # useful functions def wlen_to_freq(wlen): return c0/wlen # returns the frequency [Hz] from the wavelength [m] def freq_to_wlen(freq): return c0/freq # returns the wavelength [m] from the frequency [Hz] # + # Energy inside the cavity due to # pump field: def U_internal(ω, E, ω0, τa, τb, τ0): return np.sqrt(2/τa)*E/( (ω-ω0)-1J*(1/τa+1/τb+1/τ0) ) def get_initial_conditions(ωs, ωp, ω0, Ep, Es, τa, τb, τ0): # UpR, UpI tmp1 = np.real( U_internal(ωp, Ep, ω0, τa, τb, τ0) ) tmp2 = np.imag( U_internal(ωp, Ep, ω0, τa, τb, τ0) ) # UsR, UsI tmp3 = np.real( U_internal(ωs, Es, ω0, τa, τb, τ0) ) tmp4 = np.imag( U_internal(ωs, Es, ω0, τa, τb, τ0) ) # Utot tmp5 = tmp1**2+tmp2**2 + tmp3**2+tmp3**2 # ΔN, ΔT, ΔωR, ΔωI tmp6 = 1.0e3 tmp7 = 0.0 tmp8 = 0.0 tmp9 = 0.0 return (tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7, tmp8, tmp9, ) # #def fU2([U1, U2, Utot, ΔT, ΔN, Δω], ωp, E2, ω0, Δω, τa, τb, τ0): # return ( -1J*(ωp-ω0-Δω)-(1/τa+1/τb+1/τ0) )*U2 + 1J*np.sqrt(2/τa)*E2 # #def fUint([U1, U2, Utot, ΔT, ΔN, Δω]): # return Utot - np.power(U1,2) - np.power(U2,2) # #def fΔT([U1, U2, Utot, ΔT, ΔN, Δω], 𝛾TH, Mring, Cp, τ0, dαdN, Γ, n0, βtpa, Veff): # return 1/( 𝛾TH*Mring*Cp ) * (2/τ0 + dαdN*c0*Γ/n0*ΔN + ( c0**2*βtpa )/( np.power(n0,2)*Veff ) *Utot ) * Utot # #def fΔN([U1, U2, Utot, ΔT, ΔN, Δω], βtpa, ωp, V, Veff, 𝛾FC): # return ( c0**2*βtpa ) / ( 𝛾FC*2*ħ*ωp*V*Veff*np.power(n0,2) ) * np.power(Utot,2) # #def fΔω([U1, U2, Utot, ΔT, ΔN, Δω], ω0, n0, n2, Γ, dndT, dndN, dαdN, βtpa, Veff): # return Δω + 2*ω0/n0*dndT*Γ*ΔT + ( 2*ω0/n0*dndN - 1J*dαdN*c0/n0 )*Γ*ΔN + ( 2*ω0*c0*n2 + 1J*c0**2*βtpa )/( np.power(n0,2)*Veff )*Utot # - def equations(var, *par): # variables xUpR, xUpI, xUsR, xUsI, xUtot, xΔN, xΔT, xΔωR, xΔωI = var # parameters pωs, pωp, pω0, pEp, pEs, pτa, pτb, pτ0, p𝛾TH, p𝛾FC, pMring, pCp, pn0, pn2, pdndT, pdndN, pdαdN, pβtpa, pΓ, pV, pVeff = par # constants # c0, ħ f1R = +(pωp-pω0+xΔωR)*xUpI +(1/pτa+1/pτb+1/pτ0+xΔωI)*xUpR f1I = -(pωp-pω0+xΔωR)*xUpR +(1/pτa+1/pτb+1/pτ0+xΔωI)*xUpI + np.sqrt(2/pτa)*pEp f2R = +(pωs-pω0+xΔωR)*xUsI +(1/pτa+1/pτb+1/pτ0+xΔωI)*xUsR f2I = -(pωs-pω0+xΔωR)*xUsR +(1/pτa+1/pτb+1/pτ0+xΔωI)*xUsI + np.sqrt(2/pτa)*pEs f3R = xUtot - (np.power(xUpR,2)+np.power(xUpI,2) +np.power(xUsR,2)+np.power(xUsI,2)) f4R = -p𝛾FC*xΔN + c0**2*pβtpa / ( 2*ħ*pωp*pV*pVeff*np.power(pn0,2) ) *np.power(xUtot,2) f5R = -p𝛾TH*xΔT + 1/( pMring*pCp ) * (2/pτ0 + pdαdN*c0*pΓ/pn0*xΔN + ( np.power(c0/pn0,2)*pβtpa )/pVeff *xUtot ) * xUtot f6R = xΔωR - ( -2*pω0/pn0*pdndT*pΓ*xΔT -2*pω0/pn0*pdndN*pΓ*xΔN -2*pω0*c0*pn2/( np.power(pn0,2)*pVeff )*xUtot ) f6I = xΔωI - ( pdαdN*c0/pn0*pΓ*xΔN +np.power(c0/pn0,2)*pβtpa/pVeff*xUtot ) return (f1R, f1I, f2R, f2I, f3R, f4R, f5R, f6R, f6I) if False: # The starting estimate for the roots of func(x) = 0. # UpR, UpI, UsR, UsI, Utot, ΔN, ΔT, ΔωR, ΔωI x0 = (1e3, 1e3, 1e3, 1e3, 1e3, 0.0, 0.0, 1.0e3, 1.0e3) # extra arguments to func in fsolve(func, ). #ωs = 1.53e-6 ω_range = np.linspace(wlen_to_freq(1.551e-6), wlen_to_freq(1.5495e-6), 500) dataP = [] dataS = [] for ωs in ω_range: # The starting estimate for the roots of func(x) = 0. x0 = get_initial_conditions(ωs, ωp, ω0, Ep, Es, τa, τb, τ0) # extra arguments to func in fsolve(func, ... ). params = (ωs, ωp, ω0, Ep, Es, τa, τb, τ0, 𝛾TH, 𝛾FC, Mring, Cp, n0, n2, dndT, dndN, dαdN, βtpa, Γ, V, Veff) UpR, UpI, UsR, UsI, Utot, ΔN, ΔT, ΔωR, ΔωI = fsolve(equations, x0, args=params) if False: print(UpR, UpI, UsR, UsI, Utot, ΔN, ΔT, ΔωR, ΔωI) print( equations((UpR, UpI, UsR, UsI, Utot, ΔT, ΔN, ΔωR, ΔωI), *params) ) print() dataP.append(UpR**2+UpI**2) dataS.append(UsR**2+UsI**2) if True: # The starting estimate for the roots of func(x) = 0. # UpR, UpI, UsR, UsI, Utot, ΔN, ΔT, ΔωR, ΔωI x0 = (1e3, 1e3, 1e3, 1e3, 1e3, 0.0, 0.0, 1.0e3, 1.0e3) # extra arguments to func in fsolve(func, ). #ωs = 1.53e-6 ω_range = np.linspace(wlen_to_freq(1.554e-6), wlen_to_freq(1.546e-6), 500) dataP = [] dataS = [] data3 = [] data4 = [] for ωs in ω_range: # The starting estimate for the roots of func(x) = 0. x0 = get_initial_conditions(ωs, ωp, ω0, Ep, Es, τa, τb, τ0) # extra arguments to func in fsolve(func, ... ). #params = (ωs, ωp, ω0, Ep, Es, τa, τb, τ0, 𝛾TH, 𝛾FC, Mring, Cp, n0, n2, dndT, dndN, dαdN, βtpa, Γ, V, Veff) params = (ωs, ωp, ω0, Ep, Es, τa, τb, τ0, 𝛾TH, 0.0, Mring, Cp, n0, 0.0, dndT, 0.0, 0.0, 0.0, 1.0, V, Veff) UpR, UpI, UsR, UsI, Utot, ΔN, ΔT, ΔωR, ΔωI = fsolve(equations, x0, args=params) if False: print(UpR, UpI, UsR, UsI, Utot, ΔN, ΔT, ΔωR, ΔωI) print( equations((UpR, UpI, UsR, UsI, Utot, ΔT, ΔN, ΔωR, ΔωI), *params) ) print() dataP.append(UpR**2+UpI**2) dataS.append(UsR**2+UsI**2) data3.append(ΔωR) data4.append(ΔωI) # + linear = True plt.show() plt.close() fig = plt.figure(figsize=(3*6.4, 2*4.8)) # default = 6.4, 4.8 ax1 = fig.add_subplot(111) if not linear: ax1.set_yscale('log') ax1.set_ylim([1e-20, 1e-2]) ax1.plot(1e9*freq_to_wlen(ω_range), dataP, label='pump') ax1.plot(1e9*freq_to_wlen(ω_range), dataS, label='signal') ax1.set_title( r'Internal Power', fontsize=16) ax1.set_xlabel(r'Wavelength $\lambda$ $[nm]$', fontsize=16) ax1.set_ylabel(r'Internal Power $[not exactly a.u.]$', fontsize=16) legend = ax1.legend(loc='upper right', fontsize=16)#, bbox_to_anchor=(1, 0.5)) plt.show() plt.close() # + indx = np.where( dataS==max(dataS) ) print(freq_to_wlen(ω_range[indx])) indx = np.where( dataS>=max(dataS)/2 ) tmp = freq_to_wlen(ω_range[indx]) print(tmp[0]-tmp[-1]) del indx, tmp # + linear = True plt.show() plt.close() fig = plt.figure(figsize=(3*6.4, 2*4.8)) # default = 6.4, 4.8 ax1 = fig.add_subplot(111) if not linear: ax1.set_yscale('log') ax1.set_ylim([1e-20, 1e-2]) ax1.plot(1e9*freq_to_wlen(ω_range), data3, label='real') ax1.plot(1e9*freq_to_wlen(ω_range), data4, label='imaginary') ax1.set_title( r'Internal Power', fontsize=16) ax1.set_xlabel(r'Wavelength $\lambda$ $[nm]$', fontsize=16) ax1.set_ylabel(r'Internal Power $[not exactly a.u.]$', fontsize=16) legend = ax1.legend(loc='upper right', fontsize=16)#, bbox_to_anchor=(1, 0.5)) plt.show() plt.close() # -
code/Jupyter/QuasiStatic-analysis/Time-Domain-Analysis.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="LkdwhBYteqRM" colab_type="text" # This notebook contains some basics in Colab. # # # + id="SCGEzaGml6Rr" colab_type="code" cellView="both" colab={} print("Hello machine learning!") # + colab_type="code" id="M_MOJW8GzGbB" colab={} # Import TensorFlow and tf.keras import tensorflow as tf from tensorflow import keras # + colab_type="code" id="fAJe-V6pzFwl" colab={} tf.version.VERSION
E2E Android ML with tf.Keras & TFLite/L1_Colab Basics.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- import numpy as np import matplotlib.pyplot as plt import pandas as pd from plot import * # + A = np.loadtxt('resources/all_processes.txt') A = A.transpose() resultall = [] resultallratio = [] minlist = [] ratiolist = [] maxvalue = 0 length = len(A[:, 0]) index = 939 #index 603 x = np.arange(1, length + 1) single_plot(A[:, 603], 'Reading point', 'Signal range') plt.savefig("images/sample_process.svg", bbox_inches="tight") plt.show() for i in range(0, index): result = [] result = A[:, i] minlist = np.append(minlist, min(result)) minimum = min(result) result = [x - minimum for x in result] resultall.append(result) ratio = max(result) ratiolist.append(round(ratio, 2)) if ratio > maxvalue: maxvalue = ratio resultallcopy = A.transpose() multiplot(resultallcopy, 'Reading point', 'Signal range') plt.savefig("images/all_processes.svg", bbox_inches="tight") plt.show() resultallbase = np.array(resultall) multiplot(resultallbase, 'Reading point', 'Signal range') plt.savefig("images/all_processes_base.svg", bbox_inches="tight") plt.show() maxvalue2 = max(ratiolist) ratiolist = [round(x * (1/maxvalue2), 2) for x in ratiolist] ratiolistunique = np.unique(ratiolist) ratiolistcount = ratiolistunique for i in range (0, len(ratiolistunique)): ratiolistcount[i] = ratiolist.count(ratiolistunique[i]) y_pos = np.arange(len(ratiolistunique)) bar_plot(y_pos, ratiolistcount, 'Relative max values', 'Frequency') plt.show() threshold = 0.6 for i in range(0, index): if max(resultall[i]) > threshold * maxvalue: resultall[i] = [x + minlist[i] for x in resultall[i]] resultallratio.append(resultall[i]) np.savetxt('resources/filtered_processes.txt', resultallratio, fmt='%d') resultallratio = np.array(resultallratio) multiplot(resultallratio, 'Reading point', 'Signal range') plt.savefig("images/all_processes_filtered.svg", bbox_inches="tight") plt.show()
src/Python/Data preparation/Datenaufbereitung.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [conda env:fastai] # language: python # name: conda-env-fastai-py # --- # %load_ext autoreload # %autoreload 2 # %matplotlib inline import timm from EFF3D.MRI import * from fastai.vision.all import * from EFF3D.vit import MRIVisionTransformer import torch.nn as nn from sam import SAM df=pd.read_csv('../nonorm/ADNCold.csv') # path=Path('/home/staff/xin/Downloads/newMRI/ADtrain') # + db = DataBlock(blocks=(TransformBlock(type_tfms=partial(MriTensorImage.create)),CategoryBlock), get_x=ColReader('name'), get_y=ColReader('label'), splitter=RandomSplitter(valid_pct=0.2,seed=2), ) dls=db.dataloaders(source=df, bs=12, num_workers=4) # - sort=np.load('./sort.npy') model=MRIVisionTransformer(mask=sort,num_heads=4,depth=6,num_patches=100) class TstCallback(Callback): def before_fit(self): nowdlist=['pos_embed', 'cls_token', 'dist_token'] for name,p in self.named_parameters(): if name in nowdlist: self.opt.state[p]['do_wd'] = False class SAM(Callback): "Sharpness-Aware Minimization" def __init__(self, zero_grad=True, rho=0.05, eps=1e-12, **kwargs): assert rho >= 0.0, f"Invalid rho, should be non-negative: {rho}" self.state = defaultdict(dict) store_attr() def params(self): return self.learn.opt.all_params(with_grad=True) def _grad_norm(self): return torch.norm(torch.stack([p.grad.norm(p=2) for p,*_ in self.params()]), p=2) @torch.no_grad() def first_step(self): scale = self.rho / (self._grad_norm() + self.eps) for p,*_ in self.params(): self.state[p]["e_w"] = e_w = p.grad * scale p.add_(e_w) # climb to the local maximum "w + e(w)" if self.zero_grad: self.learn.opt.zero_grad() @torch.no_grad() def second_step(self): for p,*_ in self.params(): p.sub_(self.state[p]["e_w"]) def before_step(self, **kwargs): self.first_step() self.learn.pred = self.model(*self.xb); self.learn('after_pred') self.loss_func(self.learn.pred, *self.yb).backward() self.second_step() learn=Learner(dls,model=model,loss_func=LabelSmoothingCrossEntropy(),metrics=accuracy,cbs=[TstCallback,MixUp(0.4),SAM]) learn.fit_flat_cos(200,1e-4,cbs=[CSVLogger(fname='VIT100_4_6.csv',append=True),SaveModelCallback(monitor='accuracy',fname='VIT100_4_6')]) learn.fit_flat_cos(200,1e-4,cbs=[CSVLogger(fname='VIT100_4_6.csv',append=True),SaveModelCallback(monitor='accuracy',fname='VIT100_4_6')])
vittrain.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # *Dataframe* operations # Before proceeding with the Water Flow exercise, let's first pause and discuss data structures: **vectors**/**series**, **matrices**, **N-dimensional arrays**, and particularly the **dataframe**. # # ## What is a dataframe? # The **dataframe** is a key tool in data analysis. Dataframes store data a specific format, one that facilitates many different types of analyses. This format is a table similar to an Excel worksheet, but has more strict conventions: # * Each **<u>column</u>** represents a **field**. It has a header or label and the values it holds all have the same **data type**. # * Each **<u>row</u>** represents an **observation**. All values in a given row related in that they describe the same entity. # * Rows are typically referenced by an **<u>index</u>**. Index values are often, but not always, non-repeating sequential integer values. # ## Typical operations in a dataframe # Once data are organized in a dataframe, it's quite straightforward to do the following: # * <u>Select</u>/<u>filter</u>/<u>sort</u> data by row, by column, or by both. # * <u>Compute</u> new fields from existing ones # * <u>Combine</u> tables, either by appending columns or rows # * <u>Reshape</u> tables either by melting, pivoting # * <u>Summarizing</u>/<u>Grouping</u> data # * Handling <u>missing data</u> # * <u>Plotting</u> data # # We'll introduce how a few of these operations are done using the Python `Pandas` here in this notebook. Specifically, we'll examine how to subset rows and columns can be selected from dataframes as this offers more insight on how dataframes are organized and manipulated in Python. The other tasks will be examined in subsquent notebooks. # ## Diving in... # We'll begin by importing Pandas and then loading the water flow dataset retreived in the previous notebook. #import libraries import pandas as pd #Load data from the server into a dataframe named 'df' url = 'http://waterservices.usgs.gov/nwis/dv/?format=rdb&sites=02087500&startDT=1930-10-01&endDT=2017-09-30&statCd=00003&parameterCd=00060&siteStatus=all' df = pd.read_csv(url, skiprows=30, sep='\t', names=['agency_cd','site_no','datetime','MeanFlow_cfs','Confidence'], dtype={'site_no':'str'}, parse_dates=['datetime'] ) # In the above statement, we instruct pandas to read delimited text data into a dataframe, using a number of parameters to guide the reading in of the data: # * The first parameter is the location of the data.is used to specify the location of the data. If the data were saved locally as a text file, we could type in the path to the file (e.g. "c:/workspace/waterdata.csv"). However, as our data resides online, we can simply provide the web address, or URL, and Pandas is smart enough to fetch it there. # * `skiprows=` instructs Pandas to skip the first 30 rows in the text file. These are metadata rows, so we can skip them. # * `sep=` specifies that our records are separated by a tab, not a comma. # * `names=` specifies the column names we want to assign to our output dataframe. # * `dtype=` instructs Pandas to set records in the "site_no" column to be strings, not numbers # * `parse_dates=` instructs Pandas to set records in the "datetime" column to be dates, not strings # # This import statement is actually more advanced than most. Often, the source CSV file is tidier and can be imported with fewer parameters. Full documentation of the `read_csv` command is found by [Googling "pandas read_csv"](https://www.google.com/search?q=pandas+read_csv). #Display each column's data type df.dtypes # ## Selecting data # Selecting data, aka "filtering", "subsetting", "slicing", etc., can be done by column, by row, or both. Identifying the rows or columns can be done by position, index/label, or by query, as we'll see in the following examples. # ### Selecting specific *columns* of data # Isolating a specific column of data is fairly straightforward; we just enter, in brackets, the name of the column. #Create a new array from just the one column dfMeanFlow = df['MeanFlow_cfs'] #Show the first 5 rows of that array dfMeanFlow.head() # To isolate more than one column, we just pass a *list* of column names between the brackets.(*Recall that <u>lists</u> in Python are themselves surrounded by brackets `[]`.*) #Create a new dataframe view of just the Flow and Confidence columns df2 = df[['MeanFlow_cfs','Confidence']] df2.head() # ► Your turn. Extract just the `site_no` and `datetime` columns to the variable `d3` and display its first 5 records. # + #Create a new dataframe view of just the site_no and datetime columns # - # ### Selecting rows of data... # There are a few means for selecting rows of data: by <u>position</u>, by <u>index</u>, or <u>query</u>, or by <u>mask</u> ... <br>Here, we'll touch on each. # ### ♦ Selecting by position with `iloc` # First, we can pull one or a **slice** of rows by the row's sequential position in the dataframe using the `iloc` command (short for **i**nteger **loc**ation).<br>*Recall that in Python, list indices begin at zero, not one...* # * Single values #Show first row of data df.iloc[0] #Show second row df.iloc[1] #Show last row df.iloc[-1] # <font color=red>► What would the command be to show the 100th row of data?</font> #Show 100th row df.iloc[] # * Data **slices**: A slice of data is a set of contiguous rows (or columns). We can slice our data with `iloc` by providing the bounds of the slice we want.<br>*Note that the upper bound is not included in the slice*. #Show the first 4 rows. df.iloc[0:4] #Show the first 4 rows (again): Note that if we omit the lower bound, it assumes it's zero df.iloc[:4] #Show rows 100 thru 105 df.iloc[99:104] # <font color=red>► What would the command be to show the last 5 records?</font> #Show the last 5 rows df.iloc[] # * Selecting rows *and columns* using `iloc`. # Since tables are 2 dimensional, we can easily select/slice data by column or row AND column with `iloc`. #First, remind us what our columns are df.columns #Select the flow data (4th column) for the 100th record df.iloc[99,3] #Select the flow data and confidence values for the 100th to 110th records df.iloc[99:110,3:] # --- # ### ♦ Selecting by index with `loc` # While `iloc` references rows by their actual position in the data frame, `loc` references them by their **index**. Let's first examine this using the auto-generated indices created when we imported the CSV into a dataframe. Running the `index` function reveals that our initial index was assigned a sequential range of integers. #What does our index look like? df.index #Show the rows corresponding to index values 6 thru 10 df.loc[6:10] # Now, let's change our index from the autogenerated sequential values to the values in stored in the `datetime` column. #Change the index to be values in the datetime column and display them df.set_index('datetime',inplace=True) df.index #Show the row with the index matching Jan 1st, 1975 df.loc['1975-01-01'] #Show the slice of rows spanning september 10th thru 15th, 1998 df.loc['1998-09-10':'1998-09-15'] #Return select rows AND columns using loc df.loc['1998-09-10':'1998-09-15','MeanFlow_cfs':'Confidence'] # <font color=red>► Use `loc` to return `MeanFlow_cfs` data for Sept 1, 2017</font> df.loc[] # <font color=red>► Use `loc` to return `MeanFlow_cfs` data Sept, 2017 onward to the end of the dataset</font> df.loc[] # ### ♦ Selecting by querying data # Moving away from indices, we can query records matching criteria that we specify. #Select rows where the Mean flow was less than 50 cfs df.query('MeanFlow_cfs < 50') #Select rows where the Confidence indicates estimated: df.query('Confidence == "A:e"') # <font color=red>► Query the data for mean flow values equal to 55 cms</font> df.query() # ## ♦ Using *masks* to query data # This method is a bit more convoluted. First we create a **mask** which is a binary column of data, meaning values are either true or false, by supplying a criteria. And then we **apply the mask**, which returns only those records that are true. #Create a mask of flows below 53 cfs maskTinyFlow = df['MeanFlow_cfs'] < 53 #Apply the mask; this will only return rows where the mask was true df[maskTinyFlow] # ## Recap # Clearly, we are just scratching the surface of what we can do when our data is in a dataframe. However, in the next few notebooks, we'll dig a bit deeper by re-examining our water flow exercise.
02b-DataFrames.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # !pip install poetry --user ./weights/download_weights.sh # !pip install pytorchyolo --user # + import os os.environ['KMP_DUPLICATE_LIB_OK']='True' # %run -i pytorchyolo/train.py --model config/toyIID.cfg --data config/toyIID.data --epochs 10 --batch 10 # -
Experiments.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import pandas as pd import matplotlib.pyplot as plt import matplotlib.ticker as ticker import tikzplotlib import numpy as np import scipy.stats as st import os import ruamel.yaml as yaml from string import Formatter import re # plt.style.use('ggplot') plt.style.use('bmh') # plt.style.use('seaborn-paper') # plt.style.use('seaborn') SPLITTER = re.compile(r"\s+") # + def equivalent_error_rate(q1, err, q2, n=500): cdf = st.binom.cdf(err * n, n, q1) return st.binom.ppf(cdf, n, q2) / n def equivalent_success_rate(p1, success, p2, n=500): return 1 - equivalent_error_rate(1 - p1, 1 - success, 1 - p2, n=500) # + def load_many(path: str, folders: list, results_file: str = "training_log.csv", fstring: str = ""): data = {} labels = {} fieldnames = [field for _, field, _, _ in Formatter().parse(fstring) if field] for folder in folders: fname = os.path.join(path, folder, results_file) data[folder] = pd.read_csv(fname) fname = os.path.join(path, folder, "settings.yml") with open(fname) as f: settings = yaml.safe_load(f) kwargs = {} for field in fieldnames: if "?" in field: var, booltext = field.split("?") kwargs[field] = booltext if settings[var] else "" else: kwargs[field] = settings[field] label = fstring.format(**kwargs) try: final_stats_file = os.path.join(path, folder, "final_stats.yaml") with open(final_stats_file) as f: final_stats = yaml.load(f) # print(final_stats["exit_status"]) if final_stats["exit_status"] == "error": label = f"*{label}" except: pass labels[folder] = label return data, labels def plot_many(data, labels, field, goal=None, smooth_window=1, ax=None, ylabel="Success rate", xlabel="Episode", legend=True): if ax is None: ax = plt.axes() for key in data: label = labels[key] df = data[key] episodes = df["episode"] curve = df[field] smooth_curve = curve.rolling(window=smooth_window).mean() ax.plot(episodes, smooth_curve, label=label, linewidth=1.1) if goal: ax.plot(episodes, np.ones_like(episodes)*goal, color='black', linestyle='dotted') ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) if legend: ax.legend(loc="best") def add_frequent_symbols(data, window_length, threshold): for df in data.values(): n_symbols = df["symbol"].nunique() print(f"{n_symbols} unique symbols") counts = pd.get_dummies(df["symbol"]).rolling(window_length).sum() frequent_symbols = counts.gt(threshold).sum(axis=1) # frequent_symbols = counts.gt(threshold*window_length/n_symbols).sum(axis=1) frequent_symbols[:window_length] = np.NaN df["frequent_symbols"] = frequent_symbols # - # # Exp 1: REINFORCE # + name = "e1-initial" folders = """ e1-initial-210522-184838 e1-initial-210522-185258 e1-initial-210522-191018 e1-initial-210522-191441 e1-initial-210522-192819 e1-initial-210522-193505 e1-initial-210522-194205 e1-initial-210522-195258 e1-initial-210522-195941 e1-initial-210522-201425 e1-initial-210522-203034 e1-initial-210522-204924 """ data, labels = load_many( "models", SPLITTER.split(folders.strip()), "training_log.csv", "{vocabulary_size} symbols, {sender_type}" ) plot_many(data, labels, "success", smooth_window=1000) figure = plt.gcf() plt.savefig(f"{name}.png", dpi=200) # tikzplotlib.save(f"{name}.tex") # - for d, l in zip(data.values(), labels.values()): print(l) # print(d["success"][-1000:].mean()) # + name = "e1-initial" fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True) ############ folders = """ e1-initial-210522-191441 e1-initial-210522-185258 e1-initial-210522-193505 """ data, labels = load_many( "models", SPLITTER.split(folders.strip()), "training_log.csv", "{vocabulary_size} symbols" ) plot_many(data, labels, "success", ax=ax1, smooth_window=1000) ############# folders = """ e1-initial-210522-201425 e1-initial-210522-203034 e1-initial-210522-195941 """ data, labels = load_many( "models", SPLITTER.split(folders.strip()), "training_log.csv", "{vocabulary_size} symbols" ) plot_many(data, labels, "success", ax=ax2, ylabel=None, smooth_window=1000) ############# ax1.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:.0f}'.format(x/1000) + 'k')) ax2.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:.0f}'.format(x/1000) + 'k')) ax1.legend(title='Agnostic sender') ax2.legend(title='Informed sender') plt.tight_layout() fig.set_size_inches(10, 3) plt.savefig(f"{name}.png", dpi=200, bbox_inches="tight") tikzplotlib.save(f"{name}.tex") # + name = "e1-freq-symbols" fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True) ############ folders = """ e1-initial-210522-191441 e1-initial-210522-185258 e1-initial-210522-193505 """ data, labels = load_many( "models", SPLITTER.split(folders.strip()), "training_log.csv", "{vocabulary_size} symbols" ) add_frequent_symbols(data, 100, 0) plot_many(data, labels, "frequent_symbols", ax=ax1, ylabel="Used symbols", smooth_window=1000) ############# folders = """ e1-initial-210522-201425 e1-initial-210522-203034 e1-initial-210522-195941 """ data, labels = load_many( "models", SPLITTER.split(folders.strip()), "training_log.csv", "{vocabulary_size} symbols" ) add_frequent_symbols(data, 100, 0) plot_many(data, labels, "frequent_symbols", ax=ax2, ylabel=None, smooth_window=1000) ############# ax1.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:.0f}'.format(x/1000) + 'k')) ax2.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:.0f}'.format(x/1000) + 'k')) ax1.legend(title='Agnostic sender') ax2.legend(title='Informed sender') plt.tight_layout() fig.set_size_inches(10, 3) plt.savefig(f"{name}.png", dpi=200, bbox_inches="tight") tikzplotlib.save(f"{name}.tex") # + name = "e1-success-symbols" # fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True) fig = plt.figure() # grid = fig.add_gridspec(2, 2) grid = fig.add_gridspec(2, 2, hspace=0.05, wspace=0.03) (ax1, ax2), (ax3, ax4) = grid.subplots(sharex='col', sharey='row') ############ folders = """ e1-initial-210522-191441 e1-initial-210522-185258 e1-initial-210522-193505 """ data, labels = load_many( "models", SPLITTER.split(folders.strip()), "training_log.csv", "{vocabulary_size} symbols" ) plot_many(data, labels, "success", ax=ax1, xlabel=None, smooth_window=1000) add_frequent_symbols(data, 100, 0) plot_many(data, labels, "frequent_symbols", ax=ax3, xlabel="Agnostic sender", ylabel="Used symbols", smooth_window=1000) ############# folders = """ e1-initial-210522-201425 e1-initial-210522-203034 e1-initial-210522-195941 """ data, labels = load_many( "models", SPLITTER.split(folders.strip()), "training_log.csv", "{vocabulary_size} symbols" ) plot_many(data, labels, "success", ax=ax2, ylabel=None, xlabel=None, smooth_window=1000) add_frequent_symbols(data, 100, 0) plot_many(data, labels, "frequent_symbols", ax=ax4, xlabel="Informed sender", ylabel=None, smooth_window=1000) ############# ax1.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:.0f}'.format(x/1000) + 'k')) ax2.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:.0f}'.format(x/1000) + 'k')) ax3.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:.0f}'.format(x/1000) + 'k')) ax4.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:.0f}'.format(x/1000) + 'k')) # ax1.legend(title='4 images') # ax2.legend(title='6 images') plt.tight_layout() fig.set_size_inches(10, 6) plt.savefig(f"{name}.png", dpi=200, bbox_inches="tight") # tikzplotlib.save(f"{name}.tex") # - # ## Explore temperature # + folders = """ e1-explore-temp-210519-224929 e1-explore-temp-210519-225124 e1-explore-temp-210519-215110 e1-explore-temp-210519-220458 e1-explore-temp-210519-222000 e1-explore-temp-210519-223511 e1-explore-temp-210520-000257 e1-explore-temp-210520-001205 e1-explore-temp-210519-225725 e1-explore-temp-210519-231133 e1-explore-temp-210519-232929 e1-explore-temp-210519-234643 """ data, labels = load_many( "models", SPLITTER.split(folders.strip()), "training_log.csv", "{sender_type} temp {temperature}, seed {seed}" ) for d, l in zip(data.values(), labels.values()): print(l) # print(d["success"][-1000:].mean()) # - for d, l in zip(data.values(), labels.values()): print(l) # print(d["success"][-1000:].mean()) # + name = "e1-explore-temp-select" fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True) ############ folders = """ e1-explore-temp-210519-225124 e1-explore-temp-210519-215110 e1-explore-temp-210519-222000 """ data, labels = load_many( "models", SPLITTER.split(folders.strip()), "training_log.csv", "τ={temperature}" ) plot_many(data, labels, "success", ax=ax1, smooth_window=1000) ############# folders = """ e1-explore-temp-210520-001205 e1-explore-temp-210519-225725 e1-explore-temp-210519-232929 """ data, labels = load_many( "models", SPLITTER.split(folders.strip()), "training_log.csv", "τ={temperature}" ) plot_many(data, labels, "success", ax=ax2, ylabel=None, smooth_window=1000) ############# ax1.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:.0f}'.format(x/1000) + 'k')) ax2.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:.0f}'.format(x/1000) + 'k')) ax1.legend(title='Agnostic sender') ax2.legend(title='Informed sender') plt.tight_layout() fig.set_size_inches(10, 3) plt.savefig(f"{name}.png", dpi=200, bbox_inches="tight") tikzplotlib.save(f"{name}.tex") # - # # Exp 2: Q-Learning # + name = "e2-qlearning-test" folders = """ e2-qlearning-210520-002056 e2-qlearning-210520-003555 e2-qlearning-210520-004735 e2-qlearning-210520-005943 e2-qlearning-210520-011343 e2-qlearning-210520-012617 """ data, labels = load_many( "models", SPLITTER.split(folders.strip()), "training_log.csv", "{vocabulary_size} symbols, {sender_type}, {seed}" ) plot_many(data, labels, "receiver_loss", smooth_window=1000) figure = plt.gcf() # plt.savefig(f"{name}.png", dpi=200) # tikzplotlib.save(f"{name}.tex") # - for d, l in zip(data.values(), labels.values()): print(d["success"][-1000:].mean()) # + name = "e2-qlearning-losses" fig, (ax1, ax2) = plt.subplots(1, 2, sharey=False) ############ folders = """ e2-qlearning-210520-002056 e2-qlearning-210520-003555 e2-qlearning-210520-004735 """ data, labels = load_many( "models", SPLITTER.split(folders.strip()), "training_log.csv", "{vocabulary_size} symbols" ) plot_many(data, labels, "sender_loss", ax=ax1, ylabel="Loss", smooth_window=1000) ############# folders = """ e2-qlearning-210520-002056 e2-qlearning-210520-003555 e2-qlearning-210520-004735 """ data, labels = load_many( "models", SPLITTER.split(folders.strip()), "training_log.csv", "{vocabulary_size} symbols" ) plot_many(data, labels, "receiver_loss", ax=ax2, ylabel=None, smooth_window=1000) ############# ax1.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:.0f}'.format(x/1000) + 'k')) ax2.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:.0f}'.format(x/1000) + 'k')) ax1.legend(title='Agnostic sender') ax2.legend(title='Informed sender') plt.tight_layout() fig.set_size_inches(10, 3) plt.savefig(f"{name}.png", dpi=200, bbox_inches="tight") # tikzplotlib.save(f"{name}.tex") # - # # Exp 3: More images # + folders = """ e3-4images-210523-005440 e3-4images-210523-011150 e3-4images-210523-012701 e3-4images-210523-014425 e3-4images-210523-020417 e3-4images-210523-022405 """ data, labels = load_many( "models", SPLITTER.split(folders.strip()), "training_log.csv", "τ={temperature}, seed {seed}" ) for d, l in zip(data.values(), labels.values()): print(d["success"][-1000:].mean(), end="") print("\t", end="") print(l, end="") print() ############# folders = """ e3-6images-210523-024413 e3-6images-210523-030415 e3-6images-210523-031950 e3-6images-210523-033720 e3-6images-210523-035555 e3-6images-210523-041531 """ data, labels = load_many( "models", SPLITTER.split(folders.strip()), "training_log.csv", "τ={temperature}, seed {seed}" ) for d, l in zip(data.values(), labels.values()): print(d["success"][-1000:].mean(), end="") print("\t", end="") print(l, end="") print() # + name = "e3-success" # fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True) fig = plt.figure() # grid = fig.add_gridspec(2, 2) grid = fig.add_gridspec(2, 2, hspace=0.05, wspace=0.03) (ax1, ax2), (ax3, ax4) = grid.subplots(sharex='col', sharey='row') ############ folders = """ e3-4images-210523-014425 e3-4images-210523-020417 e3-4images-210523-022405 """ data, labels = load_many( "models", SPLITTER.split(folders.strip()), "training_log.csv", "τ={temperature}" ) plot_many(data, labels, "success", ax=ax1, xlabel=None, smooth_window=1000) add_frequent_symbols(data, 100, 0) plot_many(data, labels, "frequent_symbols", ax=ax3, xlabel="4 images", ylabel="Used symbols", smooth_window=1000) ############# folders = """ e3-6images-210523-024413 e3-6images-210523-030415 e3-6images-210523-031950 """ data, labels = load_many( "models", SPLITTER.split(folders.strip()), "training_log.csv", "τ={temperature}" ) plot_many(data, labels, "success", ax=ax2, ylabel=None, xlabel=None, smooth_window=1000) add_frequent_symbols(data, 100, 0) plot_many(data, labels, "frequent_symbols", ax=ax4, xlabel="6 images", ylabel=None, smooth_window=1000) ############# ax1.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:.0f}'.format(x/1000) + 'k')) ax2.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:.0f}'.format(x/1000) + 'k')) ax3.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:.0f}'.format(x/1000) + 'k')) ax4.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:.0f}'.format(x/1000) + 'k')) # ax1.legend(title='4 images') # ax2.legend(title='6 images') plt.tight_layout() fig.set_size_inches(10, 6) plt.savefig(f"{name}.png", dpi=200, bbox_inches="tight") # tikzplotlib.save(f"{name}.tex") # - add_frequent_symbols(data, 100, 0) plot_many(data, labels, "frequent_symbols", ylabel="Used symbols", smooth_window=1000) # # Role switching # + name = "e4-switch" fig, (ax1, ax2) = plt.subplots(1, 2, sharey=False) ############ folders = """ e4-switch-2img-210523-135233 e4-switch-2img-210523-140624 e4-switch-2img-210523-142302 """ data, labels = load_many( "models", SPLITTER.split(folders.strip()), "training_log.csv", "seed {seed}" ) plot_many(data, labels, "success", ax=ax1, smooth_window=1000, legend=False) ############# folders = """ e4-switch-4img-210523-153036 e4-switch-4img-210523-154352 e4-switch-4img-210523-155929 """ data, labels = load_many( "models", SPLITTER.split(folders.strip()), "training_log.csv", "seed {seed}" ) plot_many(data, labels, "success", ax=ax2, ylabel=None, smooth_window=1000, legend=False) ############# ax1.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:.0f}'.format(x/1000) + 'k')) ax2.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:.0f}'.format(x/1000) + 'k')) # ax1.legend(title='2 images') # ax2.legend(title='4 images') plt.tight_layout() fig.set_size_inches(10, 3) # plt.savefig(f"{name}.png", dpi=200, bbox_inches="tight") # tikzplotlib.save(f"{name}.tex") # + folders = """ e4-switch-2img-210523-135233 e4-switch-2img-210523-140624 e4-switch-2img-210523-142302 e4-switch-2img-210523-143928 e4-switch-2img-210523-145606 e4-switch-2img-210523-151234 """ data, labels = load_many( "models", SPLITTER.split(folders.strip()), "training_log.csv", "{shared_experience} sharexp, temp {temperature}, seed {seed}" ) for d, l in zip(data.values(), labels.values()): print(d["success"][-1000:].mean(), end="") print("\t", end="") print(l, end="") print() folders = """ e4-switch-4img-210523-153036 e4-switch-4img-210523-154352 e4-switch-4img-210523-155929 e4-switch-4img-210523-161609 e4-switch-4img-210523-163359 e4-switch-4img-210523-164913 """ data, labels = load_many( "models", SPLITTER.split(folders.strip()), "training_log.csv", "{shared_experience} sharexp, temp {temperature}, seed {seed}" ) for d, l in zip(data.values(), labels.values()): print(d["success"][-1000:].mean(), end="") print("\t", end="") print(l, end="") print() # + name = "e4-switch-shared" fig = plt.figure() grid = fig.add_gridspec(1, 2, wspace=0.1) (ax1, ax2) = grid.subplots(sharey=False) ############ folders = """ e4-switch-2img-210523-142302 e4-switch-2img-210524-124621 """ data, labels = load_many( "models", SPLITTER.split(folders.strip()), "training_log.csv", "τ={temperature}{shared_experience?, shared exp}" ) plot_many(data, labels, "success", ax=ax1, smooth_window=1000, legend=False) ############# folders = """ e4-switch-4img-210523-154352 e4-switch-4img-210524-140539 """ data, labels = load_many( "models", SPLITTER.split(folders.strip()), "training_log.csv", "τ={temperature}{shared_experience?, shared exp}" ) plot_many(data, labels, "success", ax=ax2, ylabel=None, smooth_window=1000, legend=False) ############# ax1.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:.0f}'.format(x/1000) + 'k')) ax2.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:.0f}'.format(x/1000) + 'k')) ax1.legend(title='2 images') ax2.legend(title='4 images') plt.tight_layout() fig.set_size_inches(10, 3) plt.savefig(f"{name}.png", dpi=200, bbox_inches="tight") # tikzplotlib.save(f"{name}.tex") # + name = "e4-success-3" fig = plt.figure() grid = fig.add_gridspec(1, 3, wspace=0.15) (ax1, ax2, ax3) = grid.subplots(sharey=False) ############ folders = """ e4-switch-2img-210523-142302 e4-switch-2img-210524-124621 """ data, labels = load_many( "models", SPLITTER.split(folders.strip()), "training_log.csv", "τ={temperature}{shared_experience?, shared exp}" ) plot_many(data, labels, "success", ax=ax1, xlabel='2 images', smooth_window=1000, legend=True) ############# folders = """ e4-switch-4img-210523-154352 e4-switch-4img-210524-140539 """ data, labels = load_many( "models", SPLITTER.split(folders.strip()), "training_log.csv", "τ={temperature}{shared_experience?, shared exp}" ) plot_many(data, labels, "success", ax=ax2, xlabel='4 images', ylabel=None, smooth_window=1000, legend=True) ############# folders = """ e4-switch-6img-210524-200612 e4-switch-6img-210524-204656 """ data, labels = load_many( "models", SPLITTER.split(folders.strip()), "training_log.csv", "τ={temperature}{shared_experience?, shared exp}" ) plot_many(data, labels, "success", ax=ax3, xlabel='6 images', ylabel=None, smooth_window=1000, legend=True) ############# ax1.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:.0f}'.format(x/1000) + 'k')) ax2.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:.0f}'.format(x/1000) + 'k')) ax3.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:.0f}'.format(x/1000) + 'k')) # ax1.legend(title='2 images') # ax2.legend(title='4 images') # ax3.legend(title='6 images') plt.tight_layout() fig.set_size_inches(11, 3) plt.savefig(f"{name}.png", dpi=200, bbox_inches="tight") # tikzplotlib.save(f"{name}.tex") # - "{a?abc}".format(**{"a?abc": 3}) # + name = "e4-frequent-symbols" fig, (ax1, ax2) = plt.subplots(1, 2, sharey=False) ############ folders = """ e4-switch-2images-210520-032820 e4-switch-2images-210520-034423 e4-switch-2images-210520-040046 e4-switch-2images-210520-041708 """ data, labels = load_many( "models", SPLITTER.split(folders.strip()), "training_log.csv", "seed {seed}" ) add_frequent_symbols(data, 100, 0) plot_many(data, labels, "frequent_symbols", ax=ax1, smooth_window=1000) ############# folders = """ e4-switch-4images-210520-043339 e4-switch-4images-210520-044849 e4-switch-4images-210520-050746 e4-switch-4images-210520-052225 """ data, labels = load_many( "models", SPLITTER.split(folders.strip()), "training_log.csv", "seed {seed}" ) add_frequent_symbols(data, 100, 0) plot_many(data, labels, "frequent_symbols", ax=ax2, ylabel=None, smooth_window=1000) ############# ax1.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:.0f}'.format(x/1000) + 'k')) ax2.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:.0f}'.format(x/1000) + 'k')) ax1.legend(title='2 images') ax2.legend(title='4 images') plt.tight_layout() fig.set_size_inches(10, 3) # plt.savefig(f"{name}.png", dpi=200, bbox_inches="tight") # tikzplotlib.save(f"{name}.tex") # - labels # + folders = """ e4-switch-6img-210524-194615 e4-switch-6img-210524-200612 e4-switch-6img-210524-202631 e4-switch-6img-210524-204656 e4-switch-6img-210524-211609 e4-switch-6img-210524-214312 """ data, labels = load_many( "models", SPLITTER.split(folders.strip()), "training_log.csv", "seed {seed}{shared_experience?, shared exp}" ) plot_many(data, labels, "success", smooth_window=1000) # - folders = """ /home/robin/thesis/guessing-game/top-models/e1-explore-temp-210519-222000 /home/robin/thesis/guessing-game/top-models/e3-4images-210523-022405 /home/robin/thesis/guessing-game/top-models/e3-6images-210523-031950 /home/robin/thesis/guessing-game/top-models/e4-switch-2img-210523-142302 /home/robin/thesis/guessing-game/top-models/e4-switch-2img-210524-124621 /home/robin/thesis/guessing-game/top-models/e4-switch-4img-210523-154352 /home/robin/thesis/guessing-game/top-models/e4-switch-4img-210524-140539 /home/robin/thesis/guessing-game/top-models/e4-switch-6img-210524-200612 /home/robin/thesis/guessing-game/top-models/e4-switch-6img-210524-204656 """ for f in folders.split("\n"): print(f.split("/")[-1]) # + folders = """ e1-explore-temp-210519-222000 e4-switch-2img-210523-142302 e4-switch-2img-210524-124621 e3-4images-210523-022405 e4-switch-4img-210523-154352 e4-switch-4img-210524-140539 e3-6images-210523-031950 e4-switch-6img-210524-200612 e4-switch-6img-210524-204656 """ # folders = """ # e4-switch-2img-210523-142302 # e4-switch-2img-210524-124621 # e4-switch-4img-210523-154352 # e4-switch-4img-210524-140539 # e4-switch-6img-210524-200612 # e4-switch-6img-210524-204656 # """ data, labels = load_many( "top-models", SPLITTER.split(folders.strip()), # "10000games.results.csv", "10000games-same.results.csv", # "10000games-alt.results.csv", # "training_log.csv", "{shared_experience} sharexp, temp {temperature}, seed {seed}" ) for d, l, f in zip(data.values(), labels.values(), SPLITTER.split(folders.strip())): print(d["success"][-1000:].mean(), end="") # print(",", end="") # print(f, end="") print()
analysis/Plot training curves.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # ## This Jupyter notebook is an example of how to use the backend functions from PROJECT NAME THAT I CANT REMEMBER NOW # # Our first cell imports our analyser, as well as numpy and pandas # + from backend_widgets import * import numpy as np import pandas as pd # - # Now we define some functions so that a user can create some generic data. # # The functions "rotate" and "normal_cloud" are best called via "separate_gaussians". # # "Separate_gaussians" creates two 2D gaussian ellipses, which are then randomly rotated. # It labels one cloud as +ve and one as -ve. # # Application of analyser to SKLearn toy datasets # # In its current form this notebook applies the analyser to the sklearn toy datasets. # The user can change the line # ```dataset = datasets.load_wine()``` # to any of # ```.load_breast_cancer, .load_iris, .load_wine``` # for classification examples, or # ```.load_diabetes``` # for regression. # + from sklearn import datasets # %matplotlib inline #data = construct_example_dataset(n_dimensions=2, circular=True) dataset = datasets.load_wine() data = construct_sklearn_dataset(dataset) #Finally, initiate the analyser analyse = analyser(data, "target") analyse.analyse() # - # # Mean separations & feature correlations # # The analyser class includes methods to find the separations of class means, as well as feature correlations analyse.mean_separations() analyse.feature_correlations(display=True) # # The ```.compare(x1,x2)``` method # This allows comparison of any two variables. # It draws confidence interval ellipses around the classes in the given x1 vs x2 dataspace, if the problem is classification. # It also displays histograms of the data in x1 and x2, aligned with the axis. # The main aim here is to check if data is easily separable along the given dimensions. # analyse.compare(analyse.datacols[0], analyse.datacols[1]) # # Feature importances # # Using SKLearn random forest ensembles allows us to find the comparative utility of features from both a classification and regression perspective. # This is returned to the user, and ```.compare``` is called on the two most "important" features. # Note here that random forests are stochastic in nature, and results may vary between runs on the same data. feature_importances = analyse.feature_importances() print(feature_importances) # # Linear separability # # The class also includes the ```.linear_separable()``` method to test whether data is linearly separable # It also has functionality to use different kernels and different orders within those kernels analyse.linear_separable(kernel = 'poly', order=1) analyse.linear_separable(kernel = 'poly', order=2) analyse.linear_separable(kernel = 'poly', order=3) # # Dimensionality reduction # # We also include methods to add dimensionality reduction projections to the backend dataframe. # The kwarg ```display``` allows the user to see the result using ```.compare```. # # In its current form this is implemented for PCA and TSNE and UMAP. # PCA uses class correlations, whereas TSNE and UMAP attempt to find an embedding of an underlying # manifold in the data-space. # # Dimensionality reduction is often useful to find underlying patterns in the data, reduce the number of features passed to # algorithms, or to improve class separability. analyse.add_TSNE(display = True) feature_importances = analyse.feature_importances() print(feature_importances) analyse.linear_separable(kernel = 'poly', order=1) analyse.linear_separable(kernel = 'poly', order=2) analyse.linear_separable(kernel = 'poly', order=3)
Notebook_example.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Taylor Problem 16.14 version finite difference # # Here we'll solve the wave equation for $u(x,t)$, # # $\begin{align} # \frac{\partial^2 u(x,t)}{\partial t^2} = c^2 \frac{\partial^2 u(x,t)}{\partial x^2} # \end{align}$ # # by a finite difference method, given its initial shape and velocity at $t=0$ from $x=0$ to $x=L$, with $L=1$, # The wave speed is $c=1$. # # The shape is: # # $\begin{align} # u(x,0) = \left\{ # \begin{array}{ll} # 2x & 0 \leq x \leq \frac12 \\ # 2(1-x) & \frac12 \leq x \leq 1 # \end{array} # \right. # \;, # \end{align}$ # # and the velocity is zero for all $x$ at $t=0$. So this could represent the string on a guitar plucked at $t=0$. # # * Created 03-Apr-2019. Last revised 06-Apr-2019 by <NAME> (<EMAIL>). # # **Template version: Add your own code where your see** `#***` **based on the equations below.** # # ## Background and equations # # We will discretize $0 \leq x \leq L$ into the array `x_pts` with equal spacing $\Delta x$. How do we find an expression for the second derivative in terms of points in `x_pts`? Taylor expansion, of course! Look at a step forward and back in $x$: # # $\begin{align} # u(x+\Delta x,t) &= u(x,t) + \frac{\partial u}{\partial x}\Delta x # + \frac12\frac{\partial^2 u}{\partial x^2}(\Delta x)^2 # + \frac16\frac{\partial^3 u}{\partial x^3}(\Delta x)^3 # + \mathcal{O}(\Delta x)^4 \\ # u(x-\Delta x,t) &= u(x,t) - \frac{\partial u}{\partial x}\Delta x # + \frac12\frac{\partial^2 u}{\partial x^2}(\Delta x)^2 # - \frac16\frac{\partial^3 u}{\partial x^3}(\Delta x)^3 # + \mathcal{O}(\Delta x)^4 # \end{align}$ # # with all of the derivatives evaluated at $(x,t)$. # # By adding these equations we eliminate all of the odd derivatives and can solve for the second derivative: # # $\begin{align} # \frac{\partial^2 u}{\partial x^2} = \frac{u(x+\Delta x,t) - 2 u(x,t) + u(x-\Delta x,t)}{(\Delta x)^2} # + \mathcal{O}(\Delta x)^2 # \end{align}$ # # which is good to order $(\Delta x)^2$ rather than $\Delta x$ because of the cancellation of odd terms. # We get a similar expression for the time derivative by adding equations expanding to $t\pm \Delta t$. But instead of solving for the second derivative, we solve for $u$ at a time step forward in terms of $u$ at previous times: # # $\begin{align} # u(x, t+\Delta t) \approx 2 u(x,t) - u(x, t-\Delta t) + \frac{\partial^2 u}{\partial t^2}(\Delta t)^2 # \end{align}$ # # and substitute the expression for $\partial^2 u/\partial x^2$, defining $c' \equiv \Delta x/\Delta t$. # So to take a time step of $\Delta t$ we use: # # $\begin{align} # u(x, t+\Delta t) \approx 2 u(x,t) - u(x, t-\Delta t) + \frac{c^2}{c'{}^2} # [u(x+\Delta x,t) - 2 u(x,t) + u(x-\Delta x,t)] # \qquad \textbf{(A)} # \end{align}$ # # **This is the equation to code for advancing the wave in time.** # # To use the equation, we need to save $u$ for all $x$ at two consectutive times. We'll call those `u_past` and `u_present` and call the result of applying the equation `u_future`. We have the initial $u(x,0)$ but to proceed to get $u(x,\Delta t)$ we'll still need $u(x,-\Delta t)$ while what we have is $\partial u(x,0)/\partial t$. We once again turn to a Taylor expansion: # # $\begin{align} # u(x, -\Delta t) = u(x,0) - \frac{\partial u(x,0)}{\partial t}(\Delta t) # % + \frac12 \frac{\partial^2 u}{\partial t^2}(\Delta t)^2 + \cdots \\ # % &= u(x,0) - \frac{\partial u(x,0)}{\partial t}(\Delta t) # % + \frac12 \frac{c^2}{c'{}^2} [u(x+\Delta x,0) - 2 u(x,0) + u(x-\Delta x,0)] # \qquad \textbf{(B)} # \end{align}$ # # and now we know both terms on the right side of $\textbf{(B)}$, so we can use this in $\textbf{(A)}$ to take the first step to $u(x, \Delta t)$. # # \[Note: in the class notes an expression for $u(x, -\Delta t)$ was given that included a $(\Delta t)^2$ correction. However, this doesn't work, so use $\textbf{(B)}$ instead.\] # %matplotlib inline # + import numpy as np import matplotlib.pyplot as plt from matplotlib import animation, rc from IPython.display import HTML # - class uTriangular(): """ uTriangular class sets up a wave at x_pts. Now with finite difference. Parameters ---------- x_pts : array of floats x positions of the wave delta_t : float time step c : float speed of the wave L : length of the string Methods ------- k(self, n) Returns the wave number given n. u_wave(self, t) Returns u(x, t) for x in x_pts and time t """ def __init__(self, x_pts, delta_t=0.01, c_wave=1., L=1.): #*** Add code for initializaton self.delta_x = x_pts[1] - x_pts[0] self.c_prime = self.delta_x / self.delta_t # c' definition self.u_start() # set the starting functions def u_0(self, x): """Initial shape of string.""" if (x <= L/2.): #*** fill in the rest def u_dot_0(self, x): """Initial velocity of string.""" return #*** fill this in def u_start(self): """Initiate u_past and u_present.""" self.u_present = np.zeros(len(x_pts)) self.u_dot_present = np.zeros(len(x_pts)) self.u_past = np.zeros(len(x_pts)) for i in np.arange(1, len(x_pts) - 1): x = self.x_pts[i] self.u_present[i] = #*** define the t=0 u(x,0) self.u_dot_present[i] = #*** define the t=0 u_dot(x,0) self.u_past[i] += #*** Implement equation (B) self.t_now = 0. def k(self, n): """Wave number for n """ return n * np.pi / self.L def u_wave_step(self): """Returns the wave at the next time step, t_now + delta_t. """ u_future = np.zeros(len(self.x_pts)) # initiate to zeros for i in np.arange(1, len(x_pts) - 1): u_future[i] = #*** Implement equation (A) # update past and present u self.u_past = self.u_present self.u_present = u_future return u_future def u_wave_at_t(self, t): """ Returns the wave at time t by calling u_wave_step multiple times """ self.u_start() # reset to the beginning for now (sets t_now=0) if (t < self.delta_t): return self.u_present else: for step in np.arange(self.t_now, t+self.delta_t, self.delta_t): u_future = self.u_wave_step() return u_future # First look at the initial ($t=0$) wave form. # + L = 1. c_wave = 1. omega_1 = np.pi * c_wave / L tau = 2.*np.pi / omega_1 # Set up the array of x points (whatever looks good) x_min = 0. x_max = L delta_x = 0.01 x_pts = np.arange(x_min, x_max + delta_x, delta_x) # Set up the t mesh for the animation. The maximum value of t shown in # the movie will be t_min + delta_t * frame_number t_min = 0. # You can make this negative to see what happens before t=0! t_max = 2.*tau delta_t = 0.0099 print('delta_t = ', delta_t) t_pts = np.arange(t_min, t_max + delta_t, delta_t) # instantiate a wave u_triangular_1 = uTriangular(x_pts, delta_t, c_wave, L) print('c_prime = ', u_triangular_1.c_prime) print('c wave = ', u_triangular_1.c) # Make a figure showing the initial wave. t_now = 0. u_triangular_1.u_start() fig = plt.figure(figsize=(6,4), num='Standing wave') ax = fig.add_subplot(1,1,1) ax.set_xlim(x_min, x_max) gap = 0.1 ax.set_ylim(-1. - gap, 1. + gap) ax.set_xlabel(r'$x$') ax.set_ylabel(r'$u(x, t=0)$') ax.set_title(rf'$t = {t_now:.1f}$') line, = ax.plot(x_pts, u_triangular_1.u_present, color='blue', lw=2) # add a line at a later time line_2, = ax.plot(x_pts, u_triangular_1.u_wave_at_t(0.5), color='black', lw=2) fig.tight_layout() # - # Next make some plots at an array of time points. # + t_array = tau * np.arange(0, 1.125, .125) fig_array = plt.figure(figsize=(12,12), num='Triangular wave') for i, t_now in enumerate(t_array): ax_array = fig_array.add_subplot(3, 3, i+1) ax_array.set_xlim(x_min, x_max) gap = 0.1 ax_array.set_ylim(-1. - gap, 1. + gap) ax_array.set_xlabel(r'$x$') ax_array.set_ylabel(r'$u(x, t)$') ax_array.set_title(rf'$t/\tau = {t_now/tau:.3f}$') ax_array.plot(x_pts, u_triangular_1.u_wave_at_t(t_now), color='blue', lw=2) fig_array.tight_layout() fig_array.savefig('Taylor_Problem_16p14_finite_difference.png', bbox_inches='tight') # - # Now it is time to animate! # We use the cell "magic" `%%capture` to keep the figure from being shown here. If we didn't the animated version below would be blank. # + # %%capture fig_anim = plt.figure(figsize=(6,3), num='Triangular wave') ax_anim = fig_anim.add_subplot(1,1,1) ax_anim.set_xlim(x_min, x_max) gap = 0.1 ax_anim.set_ylim(-1. - gap, 1. + gap) # By assigning the first return from plot to line_anim, we can later change # the values in the line. u_triangular_1.u_start() line_anim, = ax_anim.plot(x_pts, u_triangular_1.u_wave_at_t(t_min), color='blue', lw=2) fig_anim.tight_layout() # - def animate_wave(i): """This is the function called by FuncAnimation to create each frame, numbered by i. So each i corresponds to a point in the t_pts array, with index i. """ t = t_pts[i] y_pts = u_triangular_1.u_wave_at_t(t) line_anim.set_data(x_pts, y_pts) # overwrite line_anim with new points #return line_anim # this is needed for blit=True to work frame_interval = 80. # time between frames frame_number = 201 # number of frames to include (index of t_pts) anim = animation.FuncAnimation(fig_anim, animate_wave, init_func=None, frames=frame_number, interval=frame_interval, blit=False, repeat=False) HTML(anim.to_jshtml()) # animate using javascript
2020_week_11/Taylor_problem_16p14_finite_difference_template.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import gdal, osr import numpy as np from skimage.graph import route_through_array import pandas as pd import matplotlib.pyplot as plt from scipy import stats import os import math from osgeo import ogr import fiona # + def raster2array(rasterfn): #print('converting raster to array...') raster = gdal.Open(rasterfn) band = raster.GetRasterBand(1) array = band.ReadAsArray() return array def array2raster(array, rasProp,newRasterfn): print('converting array to raster...') cols = array.shape[1] rows = array.shape[0] driver = gdal.GetDriverByName('GTiff') outRaster = driver.Create( newRasterfn, cols, rows, bands=1, eType= gdal.GDT_Float32) outRaster.SetGeoTransform((rasProp.originX, rasProp.pixelWidth, 0, rasProp.originY, 0, rasProp.pixelHeight)) outband = outRaster.GetRasterBand(1) outband.WriteArray(array) outRasterSRS = osr.SpatialReference() outRasterSRS.ImportFromWkt(rasProp.projRef) outRaster.SetProjection(outRasterSRS.ExportToWkt()) outband.FlushCache() class RasterProp: def __init__(self, rasterFile, sliceClass=None, slicing = False): self.raster = gdal.Open(rasterFile) self.geotransform = self.raster.GetGeoTransform() self.projRef = self.raster.GetProjectionRef() self.originX = self.geotransform[0] self.originY = self.geotransform[3] self.pixelWidth = self.geotransform[1] self.pixelHeight = self.geotransform[5] if slicing: print('recomputing origin') x_ori_rel , y_ori_rel, xlen, ylen = sliceClass.relevantArea() self.originX, self.originY = pixel2coord(self.geotransform, x_ori_rel, y_ori_rel) def coord2pixelOffset(rasProp,x,y): print('coordinate to pixel offsetting...') originX = rasProp.originX originY = rasProp.originY pixelWidth = rasProp.pixelWidth pixelHeight = rasProp.pixelHeight xOffset = int((x - originX)/pixelWidth) yOffset = int((y - originY)/pixelHeight) return xOffset,yOffset def pixel2coord(geoTrans, x, y): xoff, a, b, yoff, d, e = geoTrans xp = a * x + b * y + a * 0.5 + b * 0.5 + xoff yp = d * x + e * y + d * 0.5 + e * 0.5 + yoff return(int(xp), int(yp)) # + def createTotalCostRaster(factorPathList, weightList, rasProp, rasterName, slicing=False, strPoint=None, endPoint=None): if not slicing: #print(factorNames[0]) costArray = maxMinScale(raster2array(factorPathList[0]))*weightList[0] costArray[np.isnan(costArray)]=0 for fpos in range(1,len(factorPathList)): #print(factorNames[fpos]) factorArray = maxMinScale(raster2array(factorPathList[fpos]))*weightList[fpos] factorArray[np.isnan(factorArray)]=0 #plt.imshow(factorArray) costArray = np.add(costArray, factorArray) costArray[np.isnan(costArray)]=0 plt.imshow(costArray) plt.colorbar() array2raster(costArray, rasProp, rasterName) return costArray, rasProp else: sliceObj = Slicing(rasProp, strPoint, endPoint) raster = gdal.Open(factorPathList[0]) band = raster.GetRasterBand(1) x_ori_rel , y_ori_rel, xlen, ylen = sliceObj.relevantArea() sliceRasProp = RasterProp(factorPathList[0], slicing = True, sliceClass= sliceObj) array = band.ReadAsArray(xoff=x_ori_rel, yoff=y_ori_rel, win_xsize=xlen, win_ysize=ylen ) costArray = maxMinScale(array)*weightList[0] for fpos in range(1, len(factorPathList)): raster = gdal.Open(factorPathList[fpos]) band = raster.GetRasterBand(1) factorArray = maxMinScale(band.ReadAsArray(xoff=x_ori_rel, yoff=y_ori_rel, win_xsize=xlen, win_ysize=ylen ))*weightList[fpos] costArray = np.add(costArray, factorArray) np.place(costArray, costArray==nan,0) array2raster(costArray, sliceRasProp, rasterName) plt.imshow(costArray) return costArray, sliceRasProp def maxMinScale(array): return (array/abs(array.max()-array.min())) # - def createPath(rasProp, costSurfaceArray, startCoord,stopCoord): '''returns an array of the same shape as costSurfaceArray with 1 for path and 0 for other cells''' print('creating path...') # coordinates to array index startCoordX = startCoord[0] startCoordY = startCoord[1] startIndexX,startIndexY = coord2pixelOffset(rasProp, startCoordX, startCoordY) stopCoordX = stopCoord[0] stopCoordY = stopCoord[1] stopIndexX,stopIndexY = coord2pixelOffset(rasProp, stopCoordX,stopCoordY) # create path indices, weight = route_through_array(costSurfaceArray, (startIndexY,startIndexX), (stopIndexY,stopIndexX), geometric=True, fully_connected=True) indices = np.array(indices).T path = np.zeros_like(costSurfaceArray) path[indices[0], indices[1]] = 1 print('path created...') return path # + def getStartEndCord(file): '''For reading 'start' and 'end' coordindates from shape files - used specifically for DC connection files''' shape = fiona.open(file) first = shape.next() strX, strY =first.get('properties').get('CoordX'), first.get('properties').get('CoordY') second = shape.next() endX, endY =second.get('properties').get('CoordX'), second.get('properties').get('CoordY') #return first return ((strX,strY) ,(endX,endY)) def writePath(costArray, dc, pathName): '''Calculating and writing path for DC Connections''' path = createPath(RasterProp(ecoFacRaster), costArray, getStartEndCord(dc)[0], getStartEndCord(dc)[1]) array2raster(path, RasterProp(ecoFacRaster), pathName) # - # ## Evaluation Metrics # Upon calculation of path the following information is saved: # # 1. Length of path # 2. People Affected # 3. 'Similarness' to reference path (all equally weighted) # 4. Land Quality # 4.1 Aggriculture # 4.2 Forest # 4.3 HVN # 4.4 Man-Made # 4.5 WasteLand # 6. 'Cost' based on raster # 6.1 Eco # 6.2 Env # 6.3 Pub # 6.4 Inf # 6.5 All # ecoPath = os.path.abspath('01_Data500/fac_eco_onlySlope.tif') envPath = os.path.abspath('01_Data500/fac_env.tif') pubPath = os.path.abspath('01_Data500/fac_pub.tif') infPath = os.path.abspath('01_Data500/fac_inf.tif') citPath = os.path.abspath('01_Data500/city.tif') ecoFac = raster2array(ecoPath) envFac = raster2array(envPath) pubFac = raster2array(pubPath) infFac = raster2array(infPath) citAre = raster2array(citPath) def createPath(rasProp, costSurfaceArray, startCoord,stopCoord): '''returns an array of the same shape as costSurfaceArray with 1 for path and 0 for other cells''' print('creating path...') # coordinates to array index startCoordX = startCoord[0] startCoordY = startCoord[1] startIndexX,startIndexY = coord2pixelOffset(rasProp, startCoordX, startCoordY) stopCoordX = stopCoord[0] stopCoordY = stopCoord[1] stopIndexX,stopIndexY = coord2pixelOffset(rasProp, stopCoordX,stopCoordY) # create path indices, weight = route_through_array(costSurfaceArray, (startIndexY,startIndexX), (stopIndexY,stopIndexX), geometric=True, fully_connected=True) indices = np.array(indices).T path = np.zeros_like(costSurfaceArray) path[indices[0], indices[1]] = 1 print('path created...') return path dcProjects = os.path.abspath('02_DC_Projects_DE//') dc5Path = str(dcProjects+'\\DC_5.shp') # %%time allPaths = [] for eco in range(0,11,2): for env in range(0,11,2): for inf in range(0,11,2): for pub in range(0,11,2): if (eco==env==inf==pub==0): continue; c_eco = eco/(eco+env+inf+pub) c_env = env/(eco+env+inf+pub) c_inf = inf/(eco+env+inf+pub) c_pub = pub/(eco+env+inf+pub) print([eco,env,inf,pub]) totalCost = c_eco*ecoFac + c_env*envFac + c_pub*pubFac + c_inf*infFac + citAre path = createPath(RasterProp(ecoPath), totalCost, getStartEndCord(dc5Path)[0], getStartEndCord(dc5Path)[1]) pathidx =np.nonzero(path) fileName = str(eco)+str(env)+str(inf)+str(pub) comName = os.path.abspath('02_DC_Projects_DE/02_dc5_paths/'+fileName+'.npy') np.save(comName,pathidx)
02_PathCreation.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + # %matplotlib inline import matplotlib.pyplot as plt import numpy as np import seaborn as sns # - from scipy.interpolate import interp1d x= np.linspace(0,4*np.pi,10) # + f=np.sin(x) # - plt.plot(x, f, marker='o') sin_approx= interp1d(x, f, kind='cubic') newx = np.linspace(0,4*np.pi,100) newf = sin_approx(newx) plt.plot(x, f, marker='o', linestyle='') plt.plot(newx, newf, marker='.') plt.plot(newx,np.abs(np.sin(newx)-sin_approx(newx))) x=4*np.pi*np.random.rand(15) f=np.sin(x) newx=np.linspace(np.min(x),np.max(x),100) newf=sin_approx(newx) plt.plot(x, f, marker='o', linestyle='', label='original data') plt.plot(newx, newf, marker='.', label='interpolated'); from scipy.interpolate import interp2d def wave2d(x,y): return np.sin(2*np.pi*x)*np.sin(3*np.pi*y) x=np.linspace
days/day11/Untitled.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import os import glob import numpy as np import pandas as pd files = glob.glob('./results/**/results**.csv', recursive = True) files file = files[0] df = pd.read_csv(file, index_col=0) dfm = df.mean() dfs = df.sem() dfm for file in files: df = pd.read_csv(file, index_col=0) dfm = df.mean() dfs = df.sem() print(f'Dataset: {file}') print(f'Model accuracy') print(f"${100*dfm['model_accuracy']:.2f} \pm {100*dfs['model_accuracy']:.2f}$") print(f'Explanation accuracy') print(f"${100*dfm['explanation_accuracy']:.2f} \pm {100*dfs['explanation_accuracy']:.2f}$") print(f'Complexity') print(f"${dfm['explanation_complexity']:.2f} \pm {dfs['explanation_complexity']:.2f}$") print(f'Fidelity') print(f"${100*dfm['explanation_fidelity']:.2f} \pm {100*dfs['explanation_fidelity']:.2f}$") print(f'Consistency') print(f"${100*dfm['explanation_consistency']:.2f}$") print(f'Time') print(f"${dfm['extraction_time']:.2f} \pm {dfs['extraction_time']:.2f}$") print()
experiments/elens/summary_to_latex.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ### A multinomialNaiveBayes model to predict the artist (Modest Mouse or Violent Femmes) by a snippet of lyrics: # + # import libraries: import requests import re from bs4 import BeautifulSoup import pandas as pd import time import glob import os import seaborn as sns import numpy as np from sklearn.model_selection import train_test_split, cross_val_score from sklearn.ensemble import RandomForestClassifier from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.pipeline import make_pipeline from sklearn.pipeline import Pipeline from sklearn.preprocessing import FunctionTransformer from sklearn.metrics import accuracy_score, classification_report, confusion_matrix from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import MultinomialNB # + # get linkslist from URL, save as html to disk and return as text_file: def get_linklist__to_disk(URL:str, html_filename:str): """scrape linklist from url, save html.file to disk, returns textfile of html""" response= requests.get(URL) html_file = response.text print(response.status_code) with open(f'{html_filename}.html', 'w') as file: file.write(html_file) return html_file # + # get linklist for modest mouse, save to disk and return as text_file : modest_html = get_linklist__to_disk("https://www.lyrics.com/artist/Modest-Mouse/200044", "modest") # + # get linklist for violent femmes, save to disk and return as text_file : violent_html = get_linklist__to_disk("https://www.lyrics.com/artist/Violent-Femmes/5767", "violent") # - # #### extract songlinks with regEx/BeautifulSoup, complete URL and check for duplicates: # #### Violent femmes # RegEx pattern: pattern_vf = 'href="(\/lyric.+?)"' def linklist_url_complete(pattern, textfilename): """ returns list with complete URLs of songlinks, textfilename can be output of get_linklist_to_disk""" songlist = re.findall(pattern, textfilename) complete =[] #complete links in list with missing URL part: for link in songlist: complete.append("https://www.lyrics.com" + link) return complete songs_vf = linklist_url_complete(pattern_vf, violent_html) # check for duplicate files: def check_dupes(linklist): s = set() for item in linklist: s.add(item) if (len(linklist)-(len(s)) == 0): print("no duplicates") else: print("duplicates found") check_dupes(songs_vf) # #### Modest Mouse #create beautiful soup object: modest_soup = BeautifulSoup(modest_html, 'html.parser') # parser: parser = "soup.find_all(attrs = {'class' : 'tdata-ext'})[0].find_all('tr')" # create list with complete song links (excluding album links) with beautiful soup: def linklist_complete_BS(parser:str): """ get complete URL for MM songs scraped at lyrics.com""" songs = [] for element in parser: try: songs.append(element.a.get('href')) except AttributeError: pass complete =[] for link in songs: complete.append("https://www.lyrics.com" + link) return complete songs_mm = linklist_complete_BS(parser) # check for duplicate files check_dupes(songs_mm) # #### get html files for each song # write function to request all html files in songlink-list and download as html files to disk: def get_songs_html(linklist, artist:str, artistinitials:str): """scrapes and writes html file for each songlyric to disk""" num = 1 for link in linklist: response = requests.get(link) song_html = response.text with open(f'/Users/krystanafoh/lyrics/{artist}/{num}_{artistinitials}_test.html', 'w') as file: file.write(song_html) num = num + 1 time.sleep(0.3) # + # violent femmes: #get_songs_html(songs_vf, "violentfemmes", "vf") # + # modest mouse: #get_songs_html(songs_mm, "modestmouse", "mm") # - # #### extract songlyrics of html files and safe each to textfile: def lyrics_to_text(linklist, artist:str, artistinitials:str): """extract and safe lyrics of each song to textfile""" num = 1 for i in range(len(linklist)): filename = (f'/Users/krystanafoh/lyrics/{artist}/{num}_{artistinitials}') # open html file html = open(f'{filename}.html') # create beautiful soup object soup = BeautifulSoup(html, 'html.parser') # get song text text = soup.find_all('pre', attrs = {'class' : 'lyric-body'})[0].get_text() # safe song text to text file: with open(f'{filename}.text', 'w') as file: file.write(text) num = num + 1 # + # modest mouse: #lyrics_to_text(songs_mm, "modestmouse", "mm") # + # violent femmes: #lyrics_to_text(songs_vf, "violentfemmes", "vf") # - # #### create lists of strings for each band def lyrics_to_list(path:str): """returns a list of lyricstrings""" textfile = glob.glob(os.path.join(path, '*.text'), recursive=False) lyrics = [] for file_path in textfile: with open(file_path) as f_input: lyrics.append(f_input.read()) return lyrics # create list of Modest Mouse songtexts: path = '/Users/krystanafoh/lyrics/modestmouse/' list_mm = lyrics_to_list(path) len(list_mm) # create list of Violent Femmes songtexts: path2 = '/Users/krystanafoh/lyrics/violentfemmes/' list_vf = lyrics_to_list(path2) len(list_vf) # #### create corpus and do test-train-split CORPUS = list_mm + list_vf len(CORPUS) labels = ["Modest Mouse"] * len(list_mm) + ["Violent Femmes"] * len(list_vf) X = CORPUS y = labels # train-test-split: X_test, X_train, y_test, y_train = train_test_split(X, y, stratify=y, random_state=42) # #### Feature Engineering: # + # function for cleaning text with RegEX: # - def clean_text(text): """cleans up text with RegEx, replacing "n'" with "ng", removing punctuation except "'", replaceing "\n" with whitespace, lowercaseing, removing double whitespace""" # replace "n'" with ng: text = re.sub("(\w(n')\s)","ng",text) # doesn't work #remove punctuation: text = re.sub("[^\w\s']","",text) # replace "\n" by whitespace : text = re.sub("\\n", " ", text) # lowercase text = text.lower() #removing duble whitespaces: text = re.sub("\s+"," ", text) return text def clean_list(X_split): """applies clean_text function to every item in list (of songtexts)""" clean_list = [] for song in X_split: clean_list.append(clean_text(song)) return clean_list checkout = clean_list(X_train) # #### create pipeline clean_NB_pipe = Pipeline([ ("cleaning_text", FunctionTransformer(clean_list)), ("vectorize", TfidfVectorizer(ngram_range=(1,1), smooth_idf=True)), #stop_words='english')), ('multinomialnb', MultinomialNB(alpha=1.0)) ]) # #### X train fit and evaluation of model: #fit model: clean_NB_pipe.fit(X_train, y_train) # make predictions on X_train: y_pred_train = clean_NB_pipe.predict(X_train) # #### evaluation: #classification report: print(classification_report(y_train,y_pred_train)) # training score: clean_NB_pipe.score(X_train, y_train) # don't fool me, my friend. # cross-validation: cross_val_score(clean_NB_pipe, X_train, y_train, cv=20).mean() # confusion matrix: sns.heatmap(confusion_matrix(y_train, y_pred_train), annot=True, fmt=".0f") # #### predictions on X_test and further evaluations: # predict on X_test: y_pred_test = clean_NB_pipe.predict(X_test) print(classification_report(y_test,y_pred_test)) # + # evaluation: # - # test score: clean_NB_pipe.score(X_test, y_test) # ooohkay...hm hm # cross-validation: cross_val_score(clean_NB_pipe, X_train, y_train, cv=20).mean() # confusion matrix: sns.heatmap(confusion_matrix(y_test, y_pred_test), annot=True, fmt=".0f") # #### use pipeline on guessed band lyrics: clean_NB_pipe.predict_proba(["float on"]) clean_NB_pipe.predict_proba(["getting together with you"]) clean_NB_pipe.predict_proba(["like a blister in the sun"]) clean_NB_pipe.predict_proba(["nightmares"]) clean_NB_pipe.predict_proba(["sleepwalking"]) clean_NB_pipe.predict_proba(["gimme the car"]) clean_NB_pipe.predict_proba(["askdjfaölsdkjfaölskdfj"]) # nonsense -> artist distribution. Seems to work pretty fine. clean_NB_pipe.predict_proba(["ba ba ba ba"]) clean_NB_pipe.predict_proba(["well that is that and this is this"]) # predicts correctly with or without 'stopwords=english'
Text_classification/NaiveBayes.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Import modules # + # %matplotlib inline import pandas as pd import numpy as np import cartopy.crs as ccrs from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER from matplotlib.mlab import griddata import matplotlib.pyplot as plt import matplotlib.ticker as mticker # - # # Basic map # # In this tutorial, we will be showing how to plot data on top of a map in many different ways. So then, let's make a function to make a basic map of Japan that we can use over and over again. def basic_Japan_map(): fig, ax = plt.subplots(figsize=(8,8)) proj = ccrs.PlateCarree() # the projection you want to use, many are supported, # this one is the standard for geographic coordinates ax = plt.axes(projection=proj) # sets the projection ax.coastlines(resolution='50m') # the level of resolution to render the drawings, # see documentation for more details ax.set_xlim(125,150) # set the longitude limits for the map ax.set_ylim(28,48) # set the latitude limits for the map gl = ax.gridlines(crs=ccrs.PlateCarree() , draw_labels=True # label coordinates , linewidth=0 # line properties can be changed similar to matplotlib , color='gray' , alpha=0.5 , linestyle='--') gl.xlabels_top = gl.ylabels_right = False # where labels shouldn't be gl.xlocator = mticker.FixedLocator(np.arange(130,151,10)) # sets longitude tick marks gl.ylocator = mticker.FixedLocator(np.arange(30,50,10)) # sets latitude tick marks using numpy module gl.xformatter = LONGITUDE_FORMATTER # set cartopy formatting gl.yformatter = LATITUDE_FORMATTER gl.xlabel_style = {'size': 15} # change label font sizes gl.ylabel_style = {'size': 15} return fig, ax, proj # plot our basic Japan map fig, ax, proj = basic_Japan_map() # Now that we have a function that creates a basic map we can call the function <i>basic_Japan_map( )</i> any time we would like to add data to it. # # Contour plot - Linear scale # We will first create a linear scaled contour plot on top of our basic Japan map. # # Let's create some random data for lon/lat coordinates of Japan. # + npoints = 2000 lons = np.random.uniform(125, 150, npoints) lats = np.random.uniform(28, 48, npoints) data = np.random.uniform(0.5, 1.5, npoints) # print some of the points and data to the screen print(lons[0:5]) print(lats[0:5]) print(data[0:5]) # - # As you can see, the x and y points (lons, lats) are not regularly spaced. Therefore, we need to define a grid for mapping our randomly spaced data and then we will interpolate our data to this grid. # # <u>Some things to remember about interpolation:</u> # # Interpolation is necessary when data are not at grid intersections, or are irregular or sparse. # # Interpolation becomes extrapolation 1) when areas deficient of points are interpolated, and 2) when interpolation is carried outside the data area. # + # define a regularly spaced grid xi = np.linspace(125, 150, (150-125)+1) yi = np.linspace(28, 48, (48 - 28)+1) # print some of the new grid to the screen print(xi[0:5]) print(yi[0:5]) # - # Oh that looks a lot better for plotting! # # Now, we can map our random data to this grid using interpolation. There are many types of interpolation. Your style choice of interpolation affects the result. For more information about interpolation choices and their affects, see [this page](https://docs.scipy.org/doc/scipy-0.19.1/reference/generated/scipy.interpolate.griddata.html). # # Here, we will use a linear interpolation for gridding our randomly spaced data. # grid the randomly spaced data zi = griddata(lons, lats, data , xi, yi, interp='linear') # Now, that we have our data interpolated to a regularly spaced grid we can add it to a map. # + fig, ax, proj = basic_Japan_map() # make our basic Japan map cbar = ax.contourf(xi,yi,zi # plot the contours , 15 # number of levels , cmap=plt.cm.jet # colormap , transform=proj) # projection to plot data in fig.colorbar(cbar # add a colorbar , label='data' # colorbar label , fraction=0.2 # fraction of original axes to use for colorbar , shrink=0.6 # fraction by which to shrink the colorbar , pad=0.05) # padding between cax and ax will be fixed at 0.05 inch) # - # # Contour plot - Log scale # # What if we want our data to be plotted in log scale? We will need to import <i>ticker</i> from the <i>matplotlib</i> module for this. # + from matplotlib.colors import LogNorm # import LogNorm fig, ax, proj = basic_Japan_map() # make our basic Japan map cbar = ax.contourf(xi,yi,zi # plot the contours , 15 # number of levels , cmap=plt.cm.jet # colormap , norm=LogNorm() # set scale as log for z-axis ticks , transform=proj) # projection to plot data in fig.colorbar(cbar # add a colorbar , label='data' # colorbar label , fraction=0.2 # fraction of original axes to use for colorbar , shrink=0.6 # fraction by which to shrink the colorbar , pad=0.05) # padding between cax and ax will be fixed at 0.05 inch) # - # # Block plot - Linear scale # # What if we want our data to be plotted in regularly defined mesh without smoothing between blocks? # + fig, ax, proj = basic_Japan_map() # make our basic Japan map cbar = ax.pcolormesh(xi, yi, zi # plot color mesh , cmap=plt.cm.jet # colormap , transform=proj) # projection to plot data in fig.colorbar(cbar # add a colorbar , label='data' # colorbar label , fraction=0.2 # fraction of original axes to use for colorbar , shrink=0.6 # fraction by which to shrink the colorbar , pad=0.05) # padding between cax and ax will be fixed at 0.05 inch) # - # # Block plot - Log scale # # What if we want our data to be plotted in a regularly defined mesh without smoothing between blocks but in a log scale? In this case, we would need to import <i>LogNorm</i> from the <i>matplotlib.colors</i> module. # + from matplotlib.colors import LogNorm # import LogNorm fig, ax, proj = basic_Japan_map() # make our basic Japan map cbar = ax.pcolormesh(xi, yi, zi # plot color mesh , vmin=np.min(zi) , vmax=np.max(zi) , cmap=plt.cm.jet # colormap , norm=LogNorm() # set scale as log for z-axis ticks , transform=proj) # projection to plot data in fig.colorbar(cbar # add a colorbar , label='data' # colorbar label , fraction=0.2 # fraction of original axes to use for colorbar , shrink=0.6 # fraction by which to shrink the colorbar , pad=0.05) # padding between cax and ax will be fixed at 0.05 inch) # - # # Plotting with real earthquake data # # Let's work some real earthquake data, but first we need to prepare it. Let's load an ANSS (Advanced National Seismic System) catalog. This is a catalog of magnitude >= 5 events from all around the world occurring between 1997 to 2010. # read some earthquake data from the Advanced National Seismic System df = pd.read_csv('../data/anss.csv', delim_whitespace=True) df = df[df.index>=1] # remove row with dash line df.describe() # + # cut the data around Japan df = df[df.Lon.between(125, 150) & df.Lat.between(28, 48)].copy() # count the number of earthquakes in each rounded latitude/longitude pair eq_count = df.groupby(['Lat', 'Lon']).apply(round).groupby(['Lat','Lon']).count().reset_index() # define the grid x_i = np.linspace(125, 150, (150 - 125) + 1) y_i = np.linspace(28, 48, (48 - 28) + 1) # redefine the input for contour plot data = eq_count.Mag.values lons = eq_count.Lon.values lats = eq_count.Lat.values # grid the randomly spaced data zi = griddata(lons, lats, data , xi, yi, interp='linear') # - # # Plotting real earthquake data as contours # + from matplotlib.colors import LogNorm # import LogNorm fig, ax, proj = basic_Japan_map() # make our basic Japan map # because we are doing contours, we should set levels # i.e., set discrete values for earthquake count low_power = 0 # minimum number of earthquakes = 10^0 = 1 high_power = np.ceil(np.log10(np.max(zi))) # highest power for number of earthquakes # we set levels to provide the boundaries for the contour map levels = np.logspace(low_power,high_power ,num=high_power-low_power+1 ,base=10.0,endpoint=True) cbar = ax.contourf(xi, yi, zi # plot the contours , levels=levels , cmap='jet' , norm=LogNorm() , transform=proj) fig.colorbar(cbar # plot the colorbar , label='earthquake count' # add z axis label , shrink=0.6) # shrink the color bar to fit # - # # Plotting real earthquake data as box plot # + from matplotlib.colors import LogNorm # import LogNorm fig, ax, proj = basic_Japan_map() # make our basic Japan map cbar = ax.pcolormesh(xi, yi, zi # plot color mesh , cmap='jet' # colormap , norm=LogNorm() # set scale as log for z-axis ticks , transform=proj) # projection to plot data in fig.colorbar(cbar # plot the colorbar , label='earthquake count' # add z axis label , shrink=0.6) # shrink the color bar to fit # - # # Plotting real earthquake data without interpolation # # The <i>griddata</i> function uses interpolation to smooth our data over regions where no data exists. Therefore, we should exercise caution when using interpolation or "bin" our data without interpolation. In this section, we will show how to grid our data without interpolation using Pandas. # + # create new indices from itertools import product new_index = [x for x in product(x_i, y_i)] # set the indices and columns to be the longitude and latitude pairs # keep only the latitude, longitude, and magnitude information bdata = eq_count.set_index(['Lon', 'Lat']).reindex(new_index).reset_index()[['Lon', 'Lat', 'Mag']].copy() # pivot the data for plotting zi = bdata.pivot(index='Lat', columns='Lon', values='Mag').values # - # Now let's plot the data... # + # begin making the plot from matplotlib.colors import LogNorm # import LogNorm fig, ax, proj = basic_Japan_map() # make our basic Japan map xi, yi = np.meshgrid(x_i, y_i) # create a regularly spaced meshgrid for plotting the z values on zi = np.ma.masked_invalid(zi) # mask invalid z values cbar = ax.pcolormesh(xi, yi, zi # plot color mesh , cmap='jet' # colormap , norm=LogNorm()) # set scale as log for z-axis ticks fig.colorbar(cbar # plot the colorbar , label='earthquake count' # add z axis label , shrink=0.6) # shrink the color bar to fit # - # This looks similar to the real earthquake data box plot, but there is no interpolation in areas where data does not exist!
example_notebooks/cartopy/Maps for unshaped data using cartopy.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # --- # # Shooting Pattern Analysis # # In this analysis, we analyze the shotchart of players. We show that there are different modes of shots, and each player's shooting style can be described as some combination of these modes. # # To clean up the notebook, some functions have been moved to a local module: `helper_basketball.py`. # + # %matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt import subprocess as sp import pickle import helper_basketball as h import imp imp.reload(h); # + language="bash" # cat helper_basketball.py # - # ## Import a python file as a module # # File `helper_basketball.py` is imported as a module, and can be used like any other module. For example, you can get the docstring and function source using ? and ??, respectively. # + ## h.get_nba_data? ## h.get_nba_data?? # - # ## Get team and player data # + ## get all 2016-17 teams params = {'LeagueID':'00','Season': '2016-17'} teams = h.get_nba_data('commonTeamYears', params).set_index('TEAM_ID') allteams = teams.loc[teams.MAX_YEAR=='2017'].index.values ## get all 2016-17 players params = {'LeagueID':'00', 'Season': '2016-17', 'IsOnlyCurrentSeason': '0'} players = h.get_nba_data('commonallplayers', params).set_index('PERSON_ID') allplyrs = players.loc[players.TEAM_ID.isin(allteams)].index.values # - # ## Get shooting data # # We follow the data collection procedure described in this paper: https://arxiv.org/abs/1401.0942. # # The data consists of all shots attempted by anyone during the regular season of 2016-17. The shots are filtered in the 50' x 35' offensive court then only those who made more than 50 are included. Since the process takes a long time, I commented out the code for downloading the data, but, instead, saved the data into a pickle file. # + ## params = {'PlayerID':'201939', ## 'PlayerPosition':'', ## 'Season':'2016-17', ## 'ContextMeasure':'FGA', ## 'DateFrom':'', ## 'DateTo':'', ## 'GameID':'', ## 'GameSegment':'', ## 'LastNGames':'0', ## 'LeagueID':'00', ## 'Location':'', ## 'Month':'0', ## 'OpponentTeamID':'0', ## 'Outcome':'', ## 'Period':'0', ## 'Position':'', ## 'RookieYear':'', ## 'SeasonSegment':'', ## 'SeasonType':'Regular Season', ## 'TeamID':'0', ## 'VsConference':'', ## 'VsDivision':''} ## ## shotdf = [] ## for p in allplyrs: ## ## ## get player p's data ## params['PlayerID'] = p ## shotdata = h.get_nba_data('shotchartdetail', params) ## ## ## subset columns ## sc = shotdata.loc[:,'SHOT_DISTANCE':'SHOT_MADE_FLAG'] ## sc.drop('SHOT_ATTEMPTED_FLAG', axis=1) ## ## ## filter shots to 31 feet from end zone ## sc = sc.loc[sc.LOC_Y < (31*12)] ## ## ## keep data with more than 50 shots ## ## if sc.SHOT_MADE_FLAG.sum() > 50: ## ## sc['PlayerID'] = p ## shotdf += [sc] ## ## allshots = pd.concat(shotdf) ## ## pickle.dump(allshots, open('allshots2016-17.pkl', 'wb')) # - # ## Pickle module # # A `pickle` file is a python module for saving data objects into a file. # + allshots = pickle.load(open('allshots2016-17.pkl', 'rb')) # allmade = allshots.loc[allshots.SHOT_MADE_FLAG==1] allmade = allshots allmade.head() # - # ## Data preprocessing # # We want to limit X and Y locations to 35 feet (length-wise) by 50 feet (width-wise). Data contains more of the court: pd.DataFrame([allmade.LOC_X.describe(), allmade.LOC_Y.describe()]) # ## Binned shot counts # # We divide the court up into bins, and, for each player, count number of shots that fall into each bin. Then, we vectorize the bins into a row vector. # + ## players info player_ids = allmade.PlayerID.unique() num_players = player_ids.size ## bin edge definitions in inches xedges = (np.linspace(start=-25, stop=25, num=151, dtype=np.float)) * 12 yedges = (np.linspace(start= -4, stop=31, num=106, dtype=np.float)) * 12 ## number of bins is one less than number of edges nx = xedges.size - 1 ny = yedges.size - 1 ## 2d histogram containers for binned counts and smoothed binned counts all_counts = {} all_smooth = {} ## data matrix: players (row) by vectorized 2-d court locations (column) for i, one in enumerate(allmade.groupby('PlayerID')): ## what does this line do? pid, pdf = one ## h.bin_shots: what is this function doing? tmp1, xedges, yedges = h.bin_shots(pdf, bin_edges=(xedges, yedges), density=True, sigma=2) tmp2, xedges, yedges = h.bin_shots(pdf, bin_edges=(xedges, yedges), density=False) ## vectorize and store into dictionary all_smooth[pid] = tmp1.reshape(-1) all_counts[pid] = tmp2.reshape(-1) # - # ## Kernel smoothing (filtering) # # Kernel smoothing is a frequently used function in image processing. It can also be used to smooth-out the histogram. Then, the smoothed histogram is normalized to sum to 1 to create an empirical distribution function. It is important we do this since each player has attempted different number of shots, and this procedure normalizes everyone's shooting pattern. # # What is the name of the kernel smoothing function? # + # # h.bin_shots?? # - # ## Visualizing star players # # We will visualize the shot chart counts and smoothed fields for some players. Recall the player data structure. players.head() # ## select players from paper stars = 'Le<NAME>|<NAME>|<NAME>|<NAME>|<NAME>|<NAME>|<NAME>|<NAME>|<NAME>' starids = players[players.DISPLAY_FIRST_LAST.str.contains(stars)].loc[player_ids].dropna() # + ## create figure and axes fig, ax = plt.subplots(starids.shape[0], 2, figsize=(20,60)) for axi, plyri in enumerate(starids.index.values): h.plot_shotchart(all_counts[plyri], xedges, yedges, ax=ax[axi,0]) h.plot_shotchart(all_smooth[plyri], xedges, yedges, ax=ax[axi,1]) ax[axi,0].set_title(players.DISPLAY_FIRST_LAST[plyri]+', '+str(all_counts[plyri].sum().astype('int'))) ax[axi,1].set_title(players.DISPLAY_FIRST_LAST[plyri]+', '+str(all_counts[plyri].sum().astype('int'))) # - # ## Non-negative matrix factorization (NMF) # # Given some matrix $X$ is $p\times n$ matrix, NMF computes the following factorization: # $$ \min_{W,H} \| X - WH \|_F\\ # \text{ subject to } W\geq 0,\ H\geq 0, $$ # where $W$ is ${p\times r}$ matrix and $H$ is ${r\times n}$ matrix. # # NMF is a unique factorization in that all values are non-negative; hence, it is used for factorization of $X$ into bases consist of non-negative values. In many practical settings such assumptions enable some realistic interpretation. # # Some common applications include: # - Image processing: pixel intensities are non-negative # - Bioinformatics: gene expressions are non-negative # - Text mining: document term matrix # # [This paper](https://arxiv.org/abs/1401.5226) discusses some of these in more detail. # # In our case, columns of matrix $X$ represent vectorized smoothed density of one player, and we compute the non-negative $r$-bases vectors in matrix $W$. Columns in matrix $H$ are the vector of coefficients. Each coefficient in a column says how important each of the bases (columns of $W$) are. # + ## Non-negative Matrix Factorization import sklearn.decomposition as skld X = np.stack(all_smooth.values()).T ## what are the different options mean for NMF()? model = skld.NMF(n_components=10, init='nndsvda', max_iter=500, random_state=0) W = model.fit_transform(X) H = model.components_ # - # ### Data matrix: $X$ # # Data matrix $X^T$ has dimensions of (number of players)-by-(number of bins), so $X$ is of dimension $n=\text{\{number of players\}}$ and $p=\text{\{number of bins\}}$. # + p, n = X.shape print('Number of bins (p) :', p) print('Number of players (n):', n) # - # ### Bases matrix: $W$ # # Columns $W_i$ contain the bases. Since the function call asks for $r=10$ as number of bases, we get: # + p_w, r = W.shape print('Number of bins (p) :', p_w) print('Number of bases (r):', r) # - # It has the shape of (number of bins)-by-(10 components). # # ### Coefficient matrix: H # # Each column of $H$ gives a coefficient for each of the bases vectors in $W$, and there are $n$ columns for each player. # + r_h, n_h = H.shape print('Number of bases (r) :', r_h) print('Number of players (n):', n_h) # - # ### Visualizing the Bases $W$ # # Each column vector of $W$ gives a spatial basis. Below we plot the bases in 2-d space. # + ## h.plot_shotchart?? # + fig, ax = plt.subplots(5, 2, figsize=(20,40)) for i, axi in enumerate(ax.flatten()): h.plot_shotchart(W[:,i], xedges, yedges, ax=axi) axi.set_title('NMF component ' + str(i)) # - # ## Interpreting the players shooting styles # # Let's inspect the players shooting styles by looking at the coefficients. ## Hd holds coefficients Hd = pd.DataFrame(H, columns=all_smooth.keys()) star_coeff = Hd.loc[:,starids.index.values] star_coeff.columns = starids.DISPLAY_FIRST_LAST star_coeff.T # Note that these players coefficients are not scaled to sum to 1. starids star_coeff.T.sum(1) # So we scale each player to sum to 1. star_coeff /= star_coeff.sum(0) star_coeff.T star_coeff.T.sum(1) pickle.load(open('allshots2016-17.pkl', 'rb')) # + pickle.dump(X, open('allpatterns2016-17.pkl', 'wb')) # - pickle.load(open('allpatterns2016-17.pkl', 'rb'))
07-Shooting-Pattern-Analysis.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import pandas as pd import numpy as np import matplotlib.pyplot as plt # %matplotlib inline df=pd.read_csv("C:\\Users\\Sudip\\Desktop\\machine learning\\Absenteeism_at_work.csv",sep=';') df.head() df.shape df.columns[df.isna().any()] df.info() data=df.drop('Disciplinary failure',axis=1) target=df['Disciplinary failure'] from sklearn.model_selection import train_test_split x_train,x_test,y_train,y_test=train_test_split(data,target,train_size=.8,random_state=4) from sklearn.linear_model import LogisticRegression model=LogisticRegression(solver='lbfgs',max_iter=500) model.fit(x_train,y_train) model.score(x_test,y_test) from sklearn.metrics import confusion_matrix predicted=model.predict(x_test) cm=confusion_matrix(y_test,predicted) cm import seaborn as sn plt.figure(figsize=(10,7)) sn.heatmap(cm,annot=True)
my_python_1.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- from IPython.core.display import display, HTML display(HTML("<style>.container { width:80% !important; }</style>")) # %load_ext watermark # %watermark -a "author: eljirg" -u -n -t -z # # Time Series - Sklearn # # A note regarding `time series` implementation using sklearn # ## Imports # + # %matplotlib inline import os, sys, time, tqdm import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn import datasets, linear_model from sklearn.model_selection import train_test_split from sklearn.datasets import load_boston # + df = pd.read_csv('./dataset/zuerich_monthly_sunspot_numbers.csv') df = df.iloc[:-1,:] df['Date'] = pd.to_datetime(df['Month']) df = df.drop('Month',axis=1) df['Year'] = df['Date'].dt.year df['Month'] = df['Date'].dt.month df = df.set_index('Date') df.head(3) # - df.describe() df.loc[:,'Zuerich monthly sunspot numbers 1749-1983'].plot() df_mm = df.loc[:,'Zuerich monthly sunspot numbers 1749-1983'].resample('A').mean() # resample annually df_mm.plot(style='g--') df_mm = df.loc[:,'Zuerich monthly sunspot numbers 1749-1983'].resample("A").apply(['mean', np.min, np.max]) df_mm['1900':'2020'].plot(subplots=True) df_mm['1900':'2020'].plot() # + from statsmodels.graphics.tsaplots import plot_acf import matplotlib.dates as mdates import statsmodels.api as sm import seaborn as sns sns.set_style('whitegrid') sns.set_context('talk') plot_acf(df.loc[:,'Zuerich monthly sunspot numbers 1749-1983'], lags=31) plt.show() # - # ### Time Series Decomposition # # This is not fully functional at this time, see this SO question # # The frequency of decomposition must be an interval, which 'may' repeat. So we have data with 15min frequency and we are looking for a weekly repetition of behavior. # # $decompfreq = \cfrac{24h \cdot 60min}{15min} \cdot 7days$ type(df.loc[0,'Zuerich monthly sunspot numbers 1749-1983']) type(decompfreq) type(df.loc[:,'Zuerich monthly sunspot numbers 1749-1983']) decompfreq = np.float64(24*60/15*7) res = sm.tsa.seasonal_decompose(df.loc[:,'Zuerich monthly sunspot numbers 1749-1983'].interpolate(), freq=int(decompfreq), model='additive') with mpl.rc_context(): mpl.rc("figure", figsize=(30,10)) resplot = res.plot() resplot.savefig('Seasonal_Decompose.png', dpi=150) # ?res.plot
Simple Timeseries.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Lists and strings # # Lists are data arrays. They can contain elements of different types (integers, floats). # # An example of a list is l = [1,4.5, 6, 9.0, 10, -1] l # The most basic operation on a list is extracting its elements at a given position. # For that we use the position in the list keeping in mind that the first element starts at `0`. l[0] l[5] # The indexing also works backwards using negative numbers l[-1] l[-3] # If you try to use an index beyond the list size you will get an error l[6] # Lists are mutable. That means you can change the value of an item as follows l[0] = 100 l # ## Slicing # # Arguably, the most useful list operation is *slicing*. # You can use it to quickly select a subset from the list. # Slicing consists in using two different indices separated by `:` to select the elements # with the syntax `l[start:end]` # # # Here are some examples. Please be sure that you understand how tthe `start:end` indexing works!. That's the whole point of slicing, if some of the examples are unclear, please ask! print(l) # this is the full list l[0:4] #start=0, end=4 l[2:4] #start=2, end=4 l[-4:-1] #start=-4, end=-1, negative values are allowed. # Slicing also works if you use only one index. l[3:] l[:4] # The mathematical operations `+` and `*` can also be used with lists. # The first operation is used for concatenation and the second for repetition. m = [45, -56] print('l=', l) print('m=', m) n = l + m print('n=',n) # this is the concatenation m + l #sum of lists does not commute! 2 * l # here I am reapeating the list `l` two times. # The function `sorted` can be used on lists to reorder the objects l_sorted = sorted(l) print(l_sorted) # and the function `len` gives you the number of items in the list len(l) # In python the strings are defined as a list of characters given_name = "Silvia" family_name = "<NAME>" print(given_name + " " + family_name) # This is the concatenations of the strings # These strings have many useful methods given_name.upper() #convert to upper case given_name.replace('i', 'y') #replace 'i' with 'y' given_name.count('i') # count how many times 'i' is the string family_name.split() # split the original string in the places with spaces, the result is a new list. # # Exercise 2.01 # # * Define a list with the integers from 1 to 10 and use slicing print the second half of the list. # # Exercise 2.02 # # * Build a list with 100 repetitions of the sequence `1`, `-1` (i.e. `[1,-1,1,-1,1,-1,...]`) # # Exercise 2.03 # # * Build a list that contains a `1` surrounded by 15 zeroes on the left and the right. # # Exercise 2.04 # # * Compute the median of the following list # # `a = [21, 48, 79, 60, 77, # 15, 43, 90, 5, 49, # 15, 52, 20, 70, 55, # 4, 86, 49, 87, 59]`
ejercicios/02/02_lists.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %matplotlib inline import numpy as np from os import walk from os.path import join from sklearn.model_selection import train_test_split from skimage import io F = open("../UFPR-ALPR-dataset/training/track0008/track0008[18].txt") cords = F.readlines() print(cords) position = cords[7][:-1] car_position = cords[1][:-1] print("CAR Position\n") print(car_position.split(" ")) car_x = int(car_position.split(" ")[1]) car_y = int(car_position.split(" ")[2]) car_w = int(car_position.split(" ")[3]) car_h = int(car_position.split(" ")[4]) print("PLATE Position\n") print(position.split(" ")) y = int(position.split(" ")[2]) - car_y x = int(position.split(" ")[1]) - car_x h = int(position.split(" ")[4]) w = int(position.split(" ")[3]) ya = list((y, x, h, w)) print(position.split(" ")[2]) print(ya) im = io.imread("../UFPR-ALPR-dataset/training/track0008/track0008[18].png") im = im[car_y:car_y+car_h, car_x:car_x+car_w] io.imshow(im[y:y+h, x:x+w]); # ## Training x = [] y = [] for root, dirs, files in walk("../UFPR-ALPR-dataset/training/"): for name in files: path = str(join(root, name)) if path.endswith(".png"): pathtxt = path.replace(".png", ".txt") F = open(pathtxt) cords = F.readlines() car_position = cords[1][:-1] car_position = car_position.split(" ") car_x = int(car_position[1]) car_y = int(car_position[2]) car_w = int(car_position[3]) car_h = int(car_position[4]) position = cords[7][:-1] a = int(position.split(" ")[2]) - car_y b = int(position.split(" ")[1]) - car_x h = int(position.split(" ")[4]) w = int(position.split(" ")[3]) x.append(path) y.append((a, b, h, w, car_x, car_y, car_w, car_h)) print(len(x), len(y)) x_train = np.asarray(x) y_train = np.asarray(y) print(x_train[1], y_train[1]) np.save("../Cache/LPD/final/x_train.npy", x_train) np.save("../Cache/LPD/final/y_train.npy", y_train) # ## Validation x = [] y = [] for root, dirs, files in walk("../UFPR-ALPR-dataset/validation/"): for name in files: path = str(join(root, name)) if path.endswith(".png"): pathtxt = path.replace(".png", ".txt") F = open(pathtxt) cords = F.readlines() car_position = cords[1][:-1] car_position = car_position.split(" ") car_x = int(car_position[1]) car_y = int(car_position[2]) car_w = int(car_position[3]) car_h = int(car_position[4]) position = cords[7][:-1] a = int(position.split(" ")[2]) - car_y b = int(position.split(" ")[1]) - car_x h = int(position.split(" ")[4]) w = int(position.split(" ")[3]) x.append(path) y.append((a, b, h, w, car_x, car_y, car_w, car_h)) x_validation = np.asarray(x) y_validation = np.asarray(y) np.save("../Cache/LPD/final/x_validation.npy", x_validation) np.save("../Cache/LPD/final/y_validation.npy", y_validation) # ## Test x = [] y = [] for root, dirs, files in walk("../UFPR-ALPR-dataset/testing/"): for name in files: path = str(join(root, name)) if path.endswith(".png"): pathtxt = path.replace(".png", ".txt") F = open(pathtxt) cords = F.readlines() car_position = cords[1][:-1] car_position = car_position.split(" ") car_x = int(car_position[1]) car_y = int(car_position[2]) car_w = int(car_position[3]) car_h = int(car_position[4]) position = cords[7][:-1] a = int(position.split(" ")[2]) - car_y b = int(position.split(" ")[1]) - car_x h = int(position.split(" ")[4]) w = int(position.split(" ")[3]) x.append(path) y.append((a, b, h, w, car_x, car_y, car_w, car_h)) x_test = np.asarray(x) y_test = np.asarray(y) np.save("../Cache/LPD/final/x_test.npy", x_test) np.save("../Cache/LPD/final/y_test.npy", y_test) print(x_train.shape, x_validation.shape, x_test.shape) print(y_train.shape, y_validation.shape, y_test.shape)
Notebooks/License Plate Detection - Generating cache original.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + tags=["remove_input"] from datascience import * import numpy as np path_data = '../../data/' import matplotlib matplotlib.use('Agg') # %matplotlib inline import matplotlib.pyplot as plots plots.style.use('fivethirtyeight') import warnings warnings.simplefilter(action="ignore", category=FutureWarning) # + tags=["remove_input"] # As of Jan 2017, this census file is online here: data = 'http://www2.census.gov/programs-surveys/popest/datasets/2010-2015/national/asrh/nc-est2015-agesex-res.csv' # A local copy can be accessed here in case census.gov moves the file: # data = path_data + 'nc-est2015-agesex-res.csv' full_census_table = Table.read_table(data) full_census_table partial_census_table = full_census_table.select('SEX', 'AGE', 'POPESTIMATE2010', 'POPESTIMATE2014') partial_census_table us_pop = partial_census_table.relabeled('POPESTIMATE2010', '2010').relabeled('POPESTIMATE2014', '2014') # - # # Example: Trends in Gender # # We are now equipped with enough coding skills to examine features and trends in subgroups of the U.S. population. In this example, we will look at the distribution of males and females across age groups. We will continue using the `us_pop` table from the previous section. us_pop # As we know from having examined this dataset earlier, a [description of the table](http://www2.census.gov/programs-surveys/popest/datasets/2010-2015/national/asrh/nc-est2015-agesex-res.pdf) appears online. Here is a reminder of what the table contains. # # Each row represents an age group. The `SEX` column contains numeric codes: `0` stands for the total, `1` for male, and `2` for female. The `AGE` column contains ages in completed years, but the special value `999` represents the entire population regardless of age. The rest of the columns contain estimates of the US population. # ### Understanding `AGE` = 100 ### # As a preliminary, let's interpret data in the final age category in the table, where `AGE` is 100. The code below extracts the rows for the combined group of men and women (`SEX` code 0) for the highest ages. us_pop.where('SEX', are.equal_to(0)).where('AGE', are.between(97, 101)) # Not surprisingly, the numbers of people are smaller at higher ages – for example, there are fewer 99-year-olds than 98-year-olds. # # It does come as a surprise, though, that the numbers for `AGE` 100 are quite a bit larger than those for age 99. A closer examination of the documentation shows that it's because the Census Bureau used 100 as the code for everyone aged 100 or more. # # The row with `AGE` 100 doesn't just represent 100-year-olds – it also includes those who are older than 100. That is why the numbers in that row are larger than in the row for the 99-year-olds. # ### Overall Proportions of Males and Females ### # We will now begin looking at gender ratios in 2014. First, let's look at all the age groups together. Remember that this means looking at the rows where the "age" is coded 999. The table `all_ages` contains this information. There are three rows: one for the total of both genders, one for males (`SEX` code 1), and one for females (`SEX` code 2). us_pop_2014 = us_pop.drop('2010') all_ages = us_pop_2014.where('AGE', are.equal_to(999)) all_ages # Row 0 of `all_ages` contains the total U.S. population in each of the two years. The United States had just under 319 million in 2014. # # Row 1 contains the counts for males and Row 2 for females. Compare these two rows to see that in 2014, there were more females than males in the United States. # # The population counts in Row 1 and Row 2 add up to the total population in Row 0. # # For comparability with other quantities, we will need to convert these counts to percents out of the total population. Let's access the total for 2014 and name it. Then, we'll show a population table with a proportion column. Consistent with our earlier observation that there were more females than males, about 50.8% of the population in 2014 was female and about 49.2% male in each of the two years. pop_2014 = all_ages.column('2014').item(0) all_ages.with_column( 'Proportion', all_ages.column('2014')/pop_2014 ).set_format('Proportion', PercentFormatter) # ### Proportions of Boys and Girls among Infants # When we look at infants, however, the opposite is true. Let's define infants to be babies who have not yet completed one year, represented in the row corresponding to `AGE` 0. Here are their numbers in the population. You can see that male infants outnumbered female infants. infants = us_pop_2014.where('AGE', are.equal_to(0)) infants # As before, we can convert these counts to percents out of the total numbers of infants. The resulting table shows that in 2014, just over 51% of infants in the U.S. were male. infants_2014 = infants.column('2014').item(0) infants.with_column( 'Proportion', infants.column('2014')/infants_2014 ).set_format('Proportion', PercentFormatter) # In fact, it has long been observed that the proportion of boys among newborns is slightly more than 1/2. The reason for this is not thoroughly understood, and [scientists are still working on it](http://www.npr.org/sections/health-shots/2015/03/30/396384911/why-are-more-baby-boys-born-than-girls). # ### Female:Male Gender Ratio at Each Age ### # We have seen that while there are more baby boys than baby girls, there are more females than males overall. So it's clear that the split between genders must vary across age groups. # # To study this variation, we will separate out the data for the females and the males, and eliminate the row where all the ages are aggregated and `AGE` is coded as 999. # # The tables `females` and `males` contain the data for each the two genders. females_all_rows = us_pop_2014.where('SEX', are.equal_to(2)) females = females_all_rows.where('AGE', are.not_equal_to(999)) females males_all_rows = us_pop_2014.where('SEX', are.equal_to(1)) males = males_all_rows.where('AGE', are.not_equal_to(999)) males # The plan now is to compare the number of women and the number of men at each age, for each of the two years. Array and Table methods give us straightforward ways to do this. Both of these tables have one row for each age. males.column('AGE') females.column('AGE') # For any given age, we can get the Female:Male gender ratio by dividing the number of females by the number of males. To do this in one step, we can use `column` to extract the array of female counts and the corresponding array of male counts, and then simply divide one array by the other. Elementwise division will create an array of gender ratios for all the years. ratios = Table().with_columns( 'AGE', females.column('AGE'), '2014 F:M RATIO', females.column('2014')/males.column('2014') ) ratios # You can see from the display that the ratios are all around 0.96 for children aged nine or younger. When the Female:Male ratio is less than 1, there are fewer females than males. Thus what we are seeing is that there were fewer girls than boys in each of the age groups 0, 1, 2, and so on through 9. Moreover, in each of these age groups, there were about 96 girls for every 100 boys. # So how can the overall proportion of females in the population be higher than the males? # # Something extraordinary happens when we examine the other end of the age range. Here are the Female:Male ratios for people aged more than 75. ratios.where('AGE', are.above(75)).show() # Not only are all of these ratios greater than 1, signifying more women than men in all of these age groups, many of them are considerably greater than 1. # # - At ages 89 and 90 the ratios are close to 2, meaning that there were about twice as many women as men at those ages in 2014. # - At ages 98 and 99, there were about 3.5 to 4 times as many women as men. # # If you are wondering how many people there were at these advanced ages, you can use Python to find out: males.where('AGE', are.between(98, 100)) females.where('AGE', are.between(98, 100)) # The graph below shows the gender ratios plotted against age. The blue curve shows the 2014 ratio by age. # # The ratios are almost 1 (signifying close to equal numbers of males and females) for ages 0 through 60, but they start shooting up dramatically (more females than males) starting at about age 65. # # That females outnumber males in the U.S. is partly due to the marked gender imbalance in favor of women among senior citizens. ratios.plot('AGE')
interactivecontent/create-and-manipulate-tables-using-the-datascience-library/example-gender-ratio-in-the-us-population.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import sqlite3 def create_db(): conn = sqlite3.connect("sqlite.db") cur = conn.cursor() cur.execute("CREATE TABLE IF NOT EXISTS store (item TEXT, quantity INTEGER, price REAL)") conn.commit() conn.close() def insert_val(item,quantity,price): '''adds (str,int,float)(item,quantity,price) to DB''' conn = sqlite3.connect("sqlite.db") cur = conn.cursor() cur.execute("INSERT INTO store VALUES(?,?,?)",(item,quantity,price)) conn.commit() conn.close() def update(quantity,price,item): '''updates quantity, price, item in DB''' conn = sqlite3.connect("sqlite.db") cur = conn.cursor() cur.execute("UPDATE store SET quantity = ?, price = ? WHERE item = ? ",(quantity,price,item)) conn.commit() conn.close() def delete(item): conn = sqlite3.connect("sqlite.db") cur = conn.cursor() cur.execute("DELETE FROM store WHERE item=?",(item,)) conn.commit() conn.close() def view(): conn = sqlite3.connect("sqlite.db") cur = conn.cursor() cur.execute("SELECT * FROM store") rows = cur.fetchall() conn.close() return rows insert_val('item_0',0,0) update(12,2,'item_0') insert_val('item_1',1,2) insert_val('item_2',3,4) insert_val('item_3',0,0) delete("item_3") print(view()) # -
SQLite db.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/westjin12321/westjin12321.github.io/blob/master/22/PPO_colab_cartpole.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="e7JowRQEGGKQ" # ################################################################################ # > # **Clone GitHub repository** # ################################################################################ # + id="IyGzuEMQF6sJ" outputId="376b170d-0bb1-4242-daab-d4a58598844c" colab={"base_uri": "https://localhost:8080/"} ################# Clone repository from github to colab session ################ """ run this section if you want to clone all the preTrained networks, logs, graph figures, gifs from the GitHub repository to this colab session """ print("============================================================================================") # !git clone https://github.com/nikhilbarhate99/PPO-PyTorch print("============================================================================================") # + [markdown] id="Z4VJcUT2GlJz" # ################################################################################ # > # **Install Dependencies** # ################################################################################ # + id="rbpSQTflGlAr" outputId="63343a01-7652-4c05-868d-fde0f4276d6b" colab={"base_uri": "https://localhost:8080/"} ############ install compatible version of OpenAI roboschool and gym ########### # !pip install roboschool==1.0.48 gym==0.15.4 # !pip install box2d-py # !pip install pybullet # + [markdown] id="pzZairIiGQ11" # ################################################################################ # > # **Introduction** # > The notebook is divided into 5 major parts : # # * **Part I** : define actor-critic network and PPO algorithm # * **Part II** : train PPO algorithm and save network weights and log files # * **Part III** : load (preTrained) network weights and test PPO algorithm # * **Part IV** : load log files and plot graphs # * **Part V** : install xvbf, load (preTrained) network weights and save images for gif and then generate gif # # ################################################################################ # + [markdown] id="s37cJXAYGrTY" # ################################################################################ # > # **Part - I** # # * define actor critic networks # * define PPO algorithm # # ################################################################################ # + id="UT6VUBg-F8Zm" colab={"base_uri": "https://localhost:8080/"} outputId="afd2d93a-463d-4f3d-f4d1-85a45f0e918c" ############################### Import libraries ############################### import os import glob import time from datetime import datetime import torch import torch.nn as nn from torch.distributions import MultivariateNormal from torch.distributions import Categorical import numpy as np import gym import roboschool import pybullet_envs ################################## set device ################################## print("============================================================================================") # set device to cpu or cuda device = torch.device('cpu') if(torch.cuda.is_available()): device = torch.device('cuda:0') torch.cuda.empty_cache() print("Device set to : " + str(torch.cuda.get_device_name(device))) else: print("Device set to : cpu") print("============================================================================================") ################################## PPO Policy ################################## class RolloutBuffer: def __init__(self): self.actions = [] self.states = [] self.logprobs = [] self.rewards = [] self.is_terminals = [] def clear(self): del self.actions[:] del self.states[:] del self.logprobs[:] del self.rewards[:] del self.is_terminals[:] class ActorCritic(nn.Module): def __init__(self, state_dim, action_dim, has_continuous_action_space, action_std_init): super(ActorCritic, self).__init__() self.has_continuous_action_space = has_continuous_action_space if has_continuous_action_space: self.action_dim = action_dim self.action_var = torch.full((action_dim,), action_std_init * action_std_init).to(device) # actor if has_continuous_action_space : self.actor = nn.Sequential( nn.Linear(state_dim, 64), nn.Tanh(), nn.Linear(64, 64), nn.Tanh(), nn.Linear(64, action_dim), nn.Tanh() ) else: self.actor = nn.Sequential( nn.Linear(state_dim, 64), nn.Tanh(), nn.Linear(64, 64), nn.Tanh(), nn.Linear(64, action_dim), nn.Softmax(dim=-1) ) # critic self.critic = nn.Sequential( nn.Linear(state_dim, 64), nn.Tanh(), nn.Linear(64, 64), nn.Tanh(), nn.Linear(64, 1) ) def set_action_std(self, new_action_std): if self.has_continuous_action_space: self.action_var = torch.full((self.action_dim,), new_action_std * new_action_std).to(device) else: print("--------------------------------------------------------------------------------------------") print("WARNING : Calling ActorCritic::set_action_std() on discrete action space policy") print("--------------------------------------------------------------------------------------------") def forward(self): raise NotImplementedError def act(self, state): if self.has_continuous_action_space: action_mean = self.actor(state) cov_mat = torch.diag(self.action_var).unsqueeze(dim=0) dist = MultivariateNormal(action_mean, cov_mat) else: action_probs = self.actor(state) dist = Categorical(action_probs) action = dist.sample() action_logprob = dist.log_prob(action) return action.detach(), action_logprob.detach() def evaluate(self, state, action): if self.has_continuous_action_space: action_mean = self.actor(state) action_var = self.action_var.expand_as(action_mean) cov_mat = torch.diag_embed(action_var).to(device) dist = MultivariateNormal(action_mean, cov_mat) # for single action continuous environments if self.action_dim == 1: action = action.reshape(-1, self.action_dim) else: action_probs = self.actor(state) dist = Categorical(action_probs) action_logprobs = dist.log_prob(action) dist_entropy = dist.entropy() state_values = self.critic(state) return action_logprobs, state_values, dist_entropy class PPO: def __init__(self, state_dim, action_dim, lr_actor, lr_critic, gamma, K_epochs, eps_clip, has_continuous_action_space, action_std_init=0.6): self.has_continuous_action_space = has_continuous_action_space if has_continuous_action_space: self.action_std = action_std_init self.gamma = gamma self.eps_clip = eps_clip self.K_epochs = K_epochs self.buffer = RolloutBuffer() self.policy = ActorCritic(state_dim, action_dim, has_continuous_action_space, action_std_init).to(device) self.optimizer = torch.optim.Adam([ {'params': self.policy.actor.parameters(), 'lr': lr_actor}, {'params': self.policy.critic.parameters(), 'lr': lr_critic} ]) self.policy_old = ActorCritic(state_dim, action_dim, has_continuous_action_space, action_std_init).to(device) self.policy_old.load_state_dict(self.policy.state_dict()) self.MseLoss = nn.MSELoss() def set_action_std(self, new_action_std): if self.has_continuous_action_space: self.action_std = new_action_std self.policy.set_action_std(new_action_std) self.policy_old.set_action_std(new_action_std) else: print("--------------------------------------------------------------------------------------------") print("WARNING : Calling PPO::set_action_std() on discrete action space policy") print("--------------------------------------------------------------------------------------------") def decay_action_std(self, action_std_decay_rate, min_action_std): print("--------------------------------------------------------------------------------------------") if self.has_continuous_action_space: self.action_std = self.action_std - action_std_decay_rate self.action_std = round(self.action_std, 4) if (self.action_std <= min_action_std): self.action_std = min_action_std print("setting actor output action_std to min_action_std : ", self.action_std) else: print("setting actor output action_std to : ", self.action_std) self.set_action_std(self.action_std) else: print("WARNING : Calling PPO::decay_action_std() on discrete action space policy") print("--------------------------------------------------------------------------------------------") def select_action(self, state): if self.has_continuous_action_space: with torch.no_grad(): state = torch.FloatTensor(state).to(device) action, action_logprob = self.policy_old.act(state) self.buffer.states.append(state) self.buffer.actions.append(action) self.buffer.logprobs.append(action_logprob) return action.detach().cpu().numpy().flatten() else: with torch.no_grad(): state = torch.FloatTensor(state).to(device) action, action_logprob = self.policy_old.act(state) self.buffer.states.append(state) self.buffer.actions.append(action) self.buffer.logprobs.append(action_logprob) return action.item() def update(self): # Monte Carlo estimate of returns rewards = [] discounted_reward = 0 for reward, is_terminal in zip(reversed(self.buffer.rewards), reversed(self.buffer.is_terminals)): if is_terminal: discounted_reward = 0 discounted_reward = reward + (self.gamma * discounted_reward) rewards.insert(0, discounted_reward) # Normalizing the rewards rewards = torch.tensor(rewards, dtype=torch.float32).to(device) rewards = (rewards - rewards.mean()) / (rewards.std() + 1e-7) # convert list to tensor old_states = torch.squeeze(torch.stack(self.buffer.states, dim=0)).detach().to(device) old_actions = torch.squeeze(torch.stack(self.buffer.actions, dim=0)).detach().to(device) old_logprobs = torch.squeeze(torch.stack(self.buffer.logprobs, dim=0)).detach().to(device) # Optimize policy for K epochs for _ in range(self.K_epochs): # Evaluating old actions and values logprobs, state_values, dist_entropy = self.policy.evaluate(old_states, old_actions) # match state_values tensor dimensions with rewards tensor state_values = torch.squeeze(state_values) # Finding the ratio (pi_theta / pi_theta__old) ratios = torch.exp(logprobs - old_logprobs.detach()) # Finding Surrogate Loss advantages = rewards - state_values.detach() surr1 = ratios * advantages surr2 = torch.clamp(ratios, 1-self.eps_clip, 1+self.eps_clip) * advantages # final loss of clipped objective PPO loss = -torch.min(surr1, surr2) + 0.5*self.MseLoss(state_values, rewards) - 0.01*dist_entropy # take gradient step self.optimizer.zero_grad() loss.mean().backward() self.optimizer.step() # Copy new weights into old policy self.policy_old.load_state_dict(self.policy.state_dict()) # clear buffer self.buffer.clear() def save(self, checkpoint_path): torch.save(self.policy_old.state_dict(), checkpoint_path) def load(self, checkpoint_path): self.policy_old.load_state_dict(torch.load(checkpoint_path, map_location=lambda storage, loc: storage)) self.policy.load_state_dict(torch.load(checkpoint_path, map_location=lambda storage, loc: storage)) # + id="-xCb_EyxF8cF" ################################# End of Part I ################################ # + [markdown] id="yr-ZjT_CGyEi" # ################################################################################ # > # **Part - II** # # * train PPO algorithm on environments # * save preTrained networks weights and log files # # ################################################################################ # + id="YY1-DzVCF8eh" print("============================================================================================") ################################### Training ################################### ####### initialize environment hyperparameters ###### env_name = "CartPole-v1" has_continuous_action_space = False max_ep_len = 400 # max timesteps in one episode max_training_timesteps = int(1e5) # break training loop if timeteps > max_training_timesteps print_freq = max_ep_len * 4 # print avg reward in the interval (in num timesteps) log_freq = max_ep_len * 2 # log avg reward in the interval (in num timesteps) save_model_freq = int(2e4) # save model frequency (in num timesteps) action_std = None ##################################################### ## Note : print/log frequencies should be > than max_ep_len ################ PPO hyperparameters ################ update_timestep = max_ep_len * 4 # update policy every n timesteps K_epochs = 40 # update policy for K epochs eps_clip = 0.2 # clip parameter for PPO gamma = 0.99 # discount factor lr_actor = 0.0003 # learning rate for actor network lr_critic = 0.001 # learning rate for critic network random_seed = 0 # set random seed if required (0 = no random seed) ##################################################### print("training environment name : " + env_name) env = gym.make(env_name) # state space dimension state_dim = env.observation_space.shape[0] # action space dimension if has_continuous_action_space: action_dim = env.action_space.shape[0] else: action_dim = env.action_space.n ###################### logging ###################### #### log files for multiple runs are NOT overwritten log_dir = "PPO_logs" if not os.path.exists(log_dir): os.makedirs(log_dir) log_dir = log_dir + '/' + env_name + '/' if not os.path.exists(log_dir): os.makedirs(log_dir) #### get number of log files in log directory run_num = 0 current_num_files = next(os.walk(log_dir))[2] run_num = len(current_num_files) #### create new log file for each run log_f_name = log_dir + '/PPO_' + env_name + "_log_" + str(run_num) + ".csv" print("current logging run number for " + env_name + " : ", run_num) print("logging at : " + log_f_name) ##################################################### ################### checkpointing ################### run_num_pretrained = 0 #### change this to prevent overwriting weights in same env_name folder directory = "PPO_preTrained" if not os.path.exists(directory): os.makedirs(directory) directory = directory + '/' + env_name + '/' if not os.path.exists(directory): os.makedirs(directory) checkpoint_path = directory + "PPO_{}_{}_{}.pth".format(env_name, random_seed, run_num_pretrained) print("save checkpoint path : " + checkpoint_path) ##################################################### ############# print all hyperparameters ############# print("--------------------------------------------------------------------------------------------") print("max training timesteps : ", max_training_timesteps) print("max timesteps per episode : ", max_ep_len) print("model saving frequency : " + str(save_model_freq) + " timesteps") print("log frequency : " + str(log_freq) + " timesteps") print("printing average reward over episodes in last : " + str(print_freq) + " timesteps") print("--------------------------------------------------------------------------------------------") print("state space dimension : ", state_dim) print("action space dimension : ", action_dim) print("--------------------------------------------------------------------------------------------") if has_continuous_action_space: print("Initializing a continuous action space policy") print("--------------------------------------------------------------------------------------------") print("starting std of action distribution : ", action_std) print("decay rate of std of action distribution : ", action_std_decay_rate) print("minimum std of action distribution : ", min_action_std) print("decay frequency of std of action distribution : " + str(action_std_decay_freq) + " timesteps") else: print("Initializing a discrete action space policy") print("--------------------------------------------------------------------------------------------") print("PPO update frequency : " + str(update_timestep) + " timesteps") print("PPO K epochs : ", K_epochs) print("PPO epsilon clip : ", eps_clip) print("discount factor (gamma) : ", gamma) print("--------------------------------------------------------------------------------------------") print("optimizer learning rate actor : ", lr_actor) print("optimizer learning rate critic : ", lr_critic) if random_seed: print("--------------------------------------------------------------------------------------------") print("setting random seed to ", random_seed) torch.manual_seed(random_seed) env.seed(random_seed) np.random.seed(random_seed) ##################################################### print("============================================================================================") ################# training procedure ################ # initialize a PPO agent ppo_agent = PPO(state_dim, action_dim, lr_actor, lr_critic, gamma, K_epochs, eps_clip, has_continuous_action_space, action_std) # track total training time start_time = datetime.now().replace(microsecond=0) print("Started training at (GMT) : ", start_time) print("============================================================================================") # logging file log_f = open(log_f_name,"w+") log_f.write('episode,timestep,reward\n') # printing and logging variables print_running_reward = 0 print_running_episodes = 0 log_running_reward = 0 log_running_episodes = 0 time_step = 0 i_episode = 0 # training loop while time_step <= max_training_timesteps: state = env.reset() current_ep_reward = 0 for t in range(1, max_ep_len+1): # select action with policy action = ppo_agent.select_action(state) state, reward, done, _ = env.step(action) # saving reward and is_terminals ppo_agent.buffer.rewards.append(reward) ppo_agent.buffer.is_terminals.append(done) time_step +=1 current_ep_reward += reward # update PPO agent if time_step % update_timestep == 0: ppo_agent.update() # if continuous action space; then decay action std of ouput action distribution if has_continuous_action_space and time_step % action_std_decay_freq == 0: ppo_agent.decay_action_std(action_std_decay_rate, min_action_std) # log in logging file if time_step % log_freq == 0: # log average reward till last episode log_avg_reward = log_running_reward / log_running_episodes log_avg_reward = round(log_avg_reward, 4) log_f.write('{},{},{}\n'.format(i_episode, time_step, log_avg_reward)) log_f.flush() log_running_reward = 0 log_running_episodes = 0 # printing average reward if time_step % print_freq == 0: # print average reward till last episode print_avg_reward = print_running_reward / print_running_episodes print_avg_reward = round(print_avg_reward, 2) print("Episode : {} \t\t Timestep : {} \t\t Average Reward : {}".format(i_episode, time_step, print_avg_reward)) print_running_reward = 0 print_running_episodes = 0 # save model weights if time_step % save_model_freq == 0: print("--------------------------------------------------------------------------------------------") print("saving model at : " + checkpoint_path) ppo_agent.save(checkpoint_path) print("model saved") print("Elapsed Time : ", datetime.now().replace(microsecond=0) - start_time) print("--------------------------------------------------------------------------------------------") # break; if the episode is over if done: break print_running_reward += current_ep_reward print_running_episodes += 1 log_running_reward += current_ep_reward log_running_episodes += 1 i_episode += 1 log_f.close() env.close() # print total training time print("============================================================================================") end_time = datetime.now().replace(microsecond=0) print("Started training at (GMT) : ", start_time) print("Finished training at (GMT) : ", end_time) print("Total training time : ", end_time - start_time) print("============================================================================================") # + id="UEy2qKdZF8ha" ################################ End of Part II ################################ # + [markdown] id="DHhK13_1G6zX" # ################################################################################ # > # **Part - III** # # * load and test preTrained networks on environments # # ################################################################################ # + id="SZWyhkq9Gxm5" colab={"base_uri": "https://localhost:8080/"} outputId="eb21c926-f866-4fb7-cbd0-4c14ba7b45b6" print("============================================================================================") #################################### Testing ################################### ################## hyperparameters ################## env_name = "CartPole-v1" has_continuous_action_space = False max_ep_len = 400 action_std = None # env_name = "LunarLander-v2" # has_continuous_action_space = False # max_ep_len = 300 # action_std = None # env_name = "BipedalWalker-v2" # has_continuous_action_space = True # max_ep_len = 1500 # max timesteps in one episode # action_std = 0.1 # set same std for action distribution which was used while saving # env_name = "RoboschoolWalker2d-v1" # has_continuous_action_space = True # max_ep_len = 1000 # max timesteps in one episode # action_std = 0.1 # set same std for action distribution which was used while saving total_test_episodes = 10 # total num of testing episodes K_epochs = 80 # update policy for K epochs eps_clip = 0.2 # clip parameter for PPO gamma = 0.99 # discount factor lr_actor = 0.0003 # learning rate for actor lr_critic = 0.001 # learning rate for critic ##################################################### env = gym.make(env_name) # state space dimension state_dim = env.observation_space.shape[0] # action space dimension if has_continuous_action_space: action_dim = env.action_space.shape[0] else: action_dim = env.action_space.n # initialize a PPO agent ppo_agent = PPO(state_dim, action_dim, lr_actor, lr_critic, gamma, K_epochs, eps_clip, has_continuous_action_space, action_std) # preTrained weights directory random_seed = 0 #### set this to load a particular checkpoint trained on random seed run_num_pretrained = 0 #### set this to load a particular checkpoint num directory = "PPO_preTrained" + '/' + env_name + '/' checkpoint_path = directory + "PPO_{}_{}_{}.pth".format(env_name, random_seed, run_num_pretrained) print("loading network from : " + checkpoint_path) ppo_agent.load(checkpoint_path) print("--------------------------------------------------------------------------------------------") test_running_reward = 0 for ep in range(1, total_test_episodes+1): ep_reward = 0 state = env.reset() for t in range(1, max_ep_len+1): action = ppo_agent.select_action(state) state, reward, done, _ = env.step(action) ep_reward += reward if done: break # clear buffer ppo_agent.buffer.clear() test_running_reward += ep_reward print('Episode: {} \t\t Reward: {}'.format(ep, round(ep_reward, 2))) ep_reward = 0 env.close() print("============================================================================================") avg_test_reward = test_running_reward / total_test_episodes avg_test_reward = round(avg_test_reward, 2) print("average test reward : " + str(avg_test_reward)) print("============================================================================================") # + id="n6IYC_JCGxlB" ################################ End of Part III ############################### # + [markdown] id="ZewQELovHFt4" # ################################################################################ # > # **Part - IV** # # * load log files using pandas # * plot graph using matplotlib # # ################################################################################ # + id="bY-E5HGcGxiu" colab={"base_uri": "https://localhost:8080/", "height": 629} outputId="2dd1e86f-e14a-440e-e61e-ab2ca8b0498c" import os import pandas as pd import matplotlib.pyplot as plt print("============================================================================================") env_name = 'CartPole-v1' # env_name = 'LunarLander-v2' # env_name = 'BipedalWalker-v2' # env_name = 'RoboschoolWalker2d-v1' fig_num = 0 #### change this to prevent overwriting figures in same env_name folder plot_avg = True # plot average of all runs; else plot all runs separately fig_width = 10 fig_height = 6 # smooth out rewards to get a smooth and a less smooth (var) plot lines window_len_smooth = 50 min_window_len_smooth = 1 linewidth_smooth = 1.5 alpha_smooth = 1 window_len_var = 5 min_window_len_var = 1 linewidth_var = 2 alpha_var = 0.1 colors = ['red', 'blue', 'green', 'orange', 'purple', 'olive', 'brown', 'magenta', 'cyan', 'crimson','gray', 'black'] # make directory for saving figures figures_dir = "PPO_figs" if not os.path.exists(figures_dir): os.makedirs(figures_dir) # make environment directory for saving figures figures_dir = figures_dir + '/' + env_name + '/' if not os.path.exists(figures_dir): os.makedirs(figures_dir) fig_save_path = figures_dir + '/PPO_' + env_name + '_fig_' + str(fig_num) + '.png' # get number of log files in directory log_dir = "PPO_logs" + '/' + env_name + '/' current_num_files = next(os.walk(log_dir))[2] num_runs = len(current_num_files) all_runs = [] for run_num in range(num_runs): log_f_name = log_dir + '/PPO_' + env_name + "_log_" + str(run_num) + ".csv" print("loading data from : " + log_f_name) data = pd.read_csv(log_f_name) data = pd.DataFrame(data) print("data shape : ", data.shape) all_runs.append(data) print("--------------------------------------------------------------------------------------------") ax = plt.gca() if plot_avg: # average all runs df_concat = pd.concat(all_runs) df_concat_groupby = df_concat.groupby(df_concat.index) data_avg = df_concat_groupby.mean() # smooth out rewards to get a smooth and a less smooth (var) plot lines data_avg['reward_smooth'] = data_avg['reward'].rolling(window=window_len_smooth, win_type='triang', min_periods=min_window_len_smooth).mean() data_avg['reward_var'] = data_avg['reward'].rolling(window=window_len_var, win_type='triang', min_periods=min_window_len_var).mean() data_avg.plot(kind='line', x='timestep' , y='reward_smooth',ax=ax,color=colors[0], linewidth=linewidth_smooth, alpha=alpha_smooth) data_avg.plot(kind='line', x='timestep' , y='reward_var',ax=ax,color=colors[0], linewidth=linewidth_var, alpha=alpha_var) # keep only reward_smooth in the legend and rename it handles, labels = ax.get_legend_handles_labels() ax.legend([handles[0]], ["reward_avg_" + str(len(all_runs)) + "_runs"], loc=2) else: for i, run in enumerate(all_runs): # smooth out rewards to get a smooth and a less smooth (var) plot lines run['reward_smooth_' + str(i)] = run['reward'].rolling(window=window_len_smooth, win_type='triang', min_periods=min_window_len_smooth).mean() run['reward_var_' + str(i)] = run['reward'].rolling(window=window_len_var, win_type='triang', min_periods=min_window_len_var).mean() # plot the lines run.plot(kind='line', x='timestep' , y='reward_smooth_' + str(i),ax=ax,color=colors[i % len(colors)], linewidth=linewidth_smooth, alpha=alpha_smooth) run.plot(kind='line', x='timestep' , y='reward_var_' + str(i),ax=ax,color=colors[i % len(colors)], linewidth=linewidth_var, alpha=alpha_var) # keep alternate elements (reward_smooth_i) in the legend handles, labels = ax.get_legend_handles_labels() new_handles = [] new_labels = [] for i in range(len(handles)): if(i%2 == 0): new_handles.append(handles[i]) new_labels.append(labels[i]) ax.legend(new_handles, new_labels, loc=2) # ax.set_yticks(np.arange(0, 1800, 200)) # ax.set_xticks(np.arange(0, int(4e6), int(5e5))) ax.grid(color='gray', linestyle='-', linewidth=1, alpha=0.2) ax.set_xlabel("Timesteps", fontsize=12) ax.set_ylabel("Rewards", fontsize=12) plt.title(env_name, fontsize=14) fig = plt.gcf() fig.set_size_inches(fig_width, fig_height) print("============================================================================================") plt.savefig(fig_save_path) print("figure saved at : ", fig_save_path) print("============================================================================================") plt.show() # + id="YaWPRW9EGxgH" ################################ End of Part IV ################################ # + [markdown] id="G8uG43MtHNGC" # ################################################################################ # > # **Part - V** # # * install virtual display libraries for rendering on colab / remote server ^ # * load preTrained networks and save images for gif # * generate and save gif from previously saved images # # * ^ If running locally; do not install xvbf and pyvirtualdisplay. Just comment out the virtual display code and render it normally. # * ^ You will still require to use ipythondisplay, if you want to render it in the Jupyter Notebook. # # ################################################################################ # + id="VL3tpKf3HLAq" #### to render on colab / server / headless machine install virtual display libraries # !apt-get install -y xvfb python-opengl > /dev/null 2>&1 # !pip install gym pyvirtualdisplay > /dev/null 2>&1 # + id="j5Rx_IFKHK-D" ############################# save images for gif ############################## import os import glob import gym import roboschool import numpy as np import matplotlib.pyplot as plt from PIL import Image from IPython import display as ipythondisplay from pyvirtualdisplay import Display """ One frame corresponding to each timestep is saved in a folder : PPO_gif_images/env_name/000001.jpg PPO_gif_images/env_name/000002.jpg PPO_gif_images/env_name/000003.jpg ... ... ... if this section is run multiple times or for multiple episodes for the same env_name; then the saved images will be overwritten. """ #### beginning of virtual display code section display = Display(visible=0, size=(400, 300)) display.start() #### end of virtual display code section print("============================================================================================") ################## hyperparameters ################## env_name = "CartPole-v1" has_continuous_action_space = False max_ep_len = 400 action_std = None # env_name = "LunarLander-v2" # has_continuous_action_space = False # max_ep_len = 300 # action_std = None # env_name = "BipedalWalker-v2" # has_continuous_action_space = True # max_ep_len = 1500 # max timesteps in one episode # action_std = 0.1 # set same std for action distribution which was used while saving # env_name = "RoboschoolWalker2d-v1" # has_continuous_action_space = True # max_ep_len = 1000 # max timesteps in one episode # action_std = 0.1 # set same std for action distribution which was used while saving total_test_episodes = 1 # save gif for only one episode render_ipython = False # plot the images using matplotlib and ipythondisplay before saving (slow) K_epochs = 80 # update policy for K epochs eps_clip = 0.2 # clip parameter for PPO gamma = 0.99 # discount factor lr_actor = 0.0003 # learning rate for actor lr_critic = 0.001 # learning rate for critic ##################################################### env = gym.make(env_name) # state space dimension state_dim = env.observation_space.shape[0] # action space dimension if has_continuous_action_space: action_dim = env.action_space.shape[0] else: action_dim = env.action_space.n # make directory for saving gif images gif_images_dir = "PPO_gif_images" + '/' if not os.path.exists(gif_images_dir): os.makedirs(gif_images_dir) # make environment directory for saving gif images gif_images_dir = gif_images_dir + '/' + env_name + '/' if not os.path.exists(gif_images_dir): os.makedirs(gif_images_dir) # make directory for gif gif_dir = "PPO_gifs" + '/' if not os.path.exists(gif_dir): os.makedirs(gif_dir) # make environment directory for gif gif_dir = gif_dir + '/' + env_name + '/' if not os.path.exists(gif_dir): os.makedirs(gif_dir) ppo_agent = PPO(state_dim, action_dim, lr_actor, lr_critic, gamma, K_epochs, eps_clip, has_continuous_action_space, action_std) # preTrained weights directory random_seed = 0 #### set this to load a particular checkpoint trained on random seed run_num_pretrained = 0 #### set this to load a particular checkpoint num directory = "PPO_preTrained" + '/' + env_name + '/' checkpoint_path = directory + "PPO_{}_{}_{}.pth".format(env_name, random_seed, run_num_pretrained) print("loading network from : " + checkpoint_path) ppo_agent.load(checkpoint_path) print("--------------------------------------------------------------------------------------------") test_running_reward = 0 for ep in range(1, total_test_episodes+1): ep_reward = 0 state = env.reset() for t in range(1, max_ep_len+1): action = ppo_agent.select_action(state) state, reward, done, _ = env.step(action) ep_reward += reward img = env.render(mode = 'rgb_array') #### beginning of ipythondisplay code section 1 if render_ipython: plt.imshow(img) ipythondisplay.clear_output(wait=True) ipythondisplay.display(plt.gcf()) #### end of ipythondisplay code section 1 img = Image.fromarray(img) img.save(gif_images_dir + '/' + str(t).zfill(6) + '.jpg') if done: break # clear buffer ppo_agent.buffer.clear() test_running_reward += ep_reward print('Episode: {} \t\t Reward: {}'.format(ep, round(ep_reward, 2))) ep_reward = 0 env.close() #### beginning of ipythondisplay code section 2 if render_ipython: ipythondisplay.clear_output(wait=True) #### end of ipythondisplay code section 2 print("============================================================================================") print("total number of frames / timesteps / images saved : ", t) avg_test_reward = test_running_reward / total_test_episodes avg_test_reward = round(avg_test_reward, 2) print("average test reward : " + str(avg_test_reward)) print("============================================================================================") # + id="BoVshl_ZHK7s" ######################## generate gif from saved images ######################## print("============================================================================================") env_name = 'CartPole-v1' # env_name = 'LunarLander-v2' # env_name = 'BipedalWalker-v2' # env_name = 'RoboschoolWalker2d-v1' gif_num = 0 #### change this to prevent overwriting gifs in same env_name folder # adjust following parameters to get desired duration, size (bytes) and smoothness of gif total_timesteps = 300 step = 10 frame_duration = 150 # input images gif_images_dir = "PPO_gif_images/" + env_name + '/*.jpg' # ouput gif path gif_dir = "PPO_gifs" if not os.path.exists(gif_dir): os.makedirs(gif_dir) gif_dir = gif_dir + '/' + env_name if not os.path.exists(gif_dir): os.makedirs(gif_dir) gif_path = gif_dir + '/PPO_' + env_name + '_gif_' + str(gif_num) + '.gif' img_paths = sorted(glob.glob(gif_images_dir)) img_paths = img_paths[:total_timesteps] img_paths = img_paths[::step] print("total frames in gif : ", len(img_paths)) print("total duration of gif : " + str(round(len(img_paths) * frame_duration / 1000, 2)) + " seconds") # save gif img, *imgs = [Image.open(f) for f in img_paths] img.save(fp=gif_path, format='GIF', append_images=imgs, save_all=True, optimize=True, duration=frame_duration, loop=0) print("saved gif at : ", gif_path) print("============================================================================================") # + id="20d1bR8xHK5j" ############################# check gif byte size ############################## import os import glob print("============================================================================================") env_name = 'CartPole-v1' # env_name = 'LunarLander-v2' # env_name = 'BipedalWalker-v2' # env_name = 'RoboschoolWalker2d-v1' gif_dir = "PPO_gifs/" + env_name + '/*.gif' gif_paths = sorted(glob.glob(gif_dir)) for gif_path in gif_paths: file_size = os.path.getsize(gif_path) print(gif_path + '\t\t' + str(round(file_size / (1024 * 1024), 2)) + " MB") print("============================================================================================") # + id="rM5UIAkcGxeA" ################################# End of Part V ################################ # + [markdown] id="7YUzQOu1HYHR" # ################################################################################ # # ---------------------------------------------------------------------------- That's all folks ! ---------------------------------------------------------------------------- # # # ################################################################################
22/PPO_colab_cartpole.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: 'Python 3.7.10 64-bit (''base'': conda)' # name: python3 # --- # + # import modules import numpy as np import tensorflow as tf import custom.dataloader as dataloader import custom.utils as utils # + save_location = "downloads" model_dir = "Saved_models" bucket_name = "trained_models_bucket" train_dataset = 'cifar10' ood_dataset = 'svhn' model_name = 'masked_ensemble_vgg' version = 0 num_models = 5 # + # download zipped models from cloud storage bucket import os os.system(f"gsutil cp -r gs://{bucket_name}/{model_dir} {save_location}/") # unzip zip_fname = f"zipped_{train_dataset}_{model_name}_v{version}.zip" os.system(f"unzip -o {save_location}/{model_dir}/{zip_fname} -d {save_location}/") # + # load models from unzipped files save_dir = f"{save_location}/{model_dir}/{train_dataset}_{model_name}_v{version}" model_list = list() counter = 1 for i in range(num_models): model = tf.keras.models.load_model(f"{save_dir}/Model_{counter}") model_list.append(model) counter = counter + 1 # + import importlib importlib.reload(dataloader) importlib.reload(utils) # load In-distribution data (_, _), (x_test_in, y_test_in) = dataloader.get_data(train_dataset, num_train=1, num_test = 5000) # load Out-distribution data (_, _), (x_test_in, y_test_in) = dataloader.get_data(ood_dataset, num_test=5000) # + # For binning # Merge both datasets x_test = np.concatenate((x_test_in, x_test_out)) y_test = np.concatenate((y_test_in, y_test_out)) # calculate calibration scores threshold_list = list(np.linspace(0.1,.9, 9)) if model_name == 'mc_dropout' or model_name == 'mc_dropout_da': dropout = True else: drouput = False binned_accuracies_in = utils.get_binned_scores(model_list, x_test_in, y_test_in, threshold_list, verbose=0, isdropout=dropout) print("Binning complete (in-distribution data)") binned_accuracies = utils.get_binned_scores(model_list, x_test, y_test, threshold_list, verbose=0, isdropout=dropout) print("Binning complete (corrupt data)") # save calibration results np.savetxt(f'results/binned_acc_in_{train_dataset}_{model_name}_v{version}_n{num_models}.txt', binned_accuracies_in) np.savetxt(f'results/binned_acc_{train_dataset}_{model_name}_v{version}_n{num_models}.txt', binned_accuracies) print("Results saved") # + import importlib importlib.reload(dataloader) importlib.reload(utils) # load ID (_, _), (x_test_in, y_test_in) = dataloader.get_data(train_dataset, num_train=1, num_test = 10000) # load OOD x_test_out, y_test_out = dataloader.get_data(ood_dataset, num_test=18000) # Merge both datasets x_test = np.concatenate((x_test_in, x_test_out)) y_test = np.concatenate((y_test_in, y_test_out)) # calculate calibration scores threshold_list = list(np.linspace(0.1,.9, 9)) if model_name == 'mc_dropout' or model_name == 'mc_dropout_da': dropout = True else: drouput = False auc_score = utils.get_auc_scores(model_list, x_test_in, x_test_out, y_test_in, y_test_out, verbose=0, isdropout=dropout) print(f"AUROC Score: {auc_score}") np.savetxt(f'results/auroc_{train_dataset}_{model_name}_v{version}_n{num_models}.txt', np.expand_dims(auc_score, axis=0)) # + import importlib importlib.reload(dataloader) importlib.reload(utils) # load MNIST (_, _), (x_test_in, y_test_in) = dataloader.get_data(train_dataset, num_train=1, num_test = 10000) # load notMNIST x_test_out, y_test_out = dataloader.get_data(ood_dataset, num_test=18000) # Merge both datasets x_test = np.concatenate((x_test_in, x_test_out)) y_test = np.concatenate((y_test_in, y_test_out)) # - importlib.reload(utils) importlib.reload(dataloader) (_, _), (x_test_in, y_test_in) = dataloader.get_data(train_dataset, num_train=1, num_test = 5000) top1_score, top3_score, nll_score, brier_score = utils.get_scores(model_list, x_test_in, y_test_in, dropout=False) print(f"Dataset: {train_dataset}, Model: {model_name}") print(f"Top 1 Acc: {top1_score}") print(f"Top 3 Acc: {top3_score}") print(f"NLL Score: {nll_score}") print(f"Brier Score: {brier_score}") importlib.reload(utils) importlib.reload(dataloader) (_, _), (x_test_in, y_test_in) = dataloader.get_data(ood_dataset, num_train=1, num_test = 5000) top1_score, top3_score, nll_score, brier_score = utils.get_scores(model_list, x_test_in, y_test_in, dropout=False) print(f"Dataset: {train_dataset}, Model: {model_name}") print(f"Top 1 Acc: {top1_score}") print(f"Top 3 Acc: {top3_score}") print(f"NLL Score: {nll_score}") print(f"Brier Score: {brier_score}") importlib.reload(utils) importlib.reload(dataloader) (_, _), (x_test_in, y_test_in) = dataloader.get_data(train_dataset, num_train=1, num_test = 5000) top1_score, top3_score, nll_score, brier_score = utils.get_scores(model_list, x_test_in, y_test_in, dropout=False) print(f"Dataset: {train_dataset}, Model: {model_name}") print(f"Top 1 Acc: {top1_score}") print(f"Top 3 Acc: {top3_score}") print(f"NLL Score: {nll_score}") print(f"Brier Score: {brier_score}") importlib.reload(utils) importlib.reload(dataloader) (_, _), (x_test_in, y_test_in) = dataloader.get_data(train_dataset, num_train=1, num_test = 5000) top1_score, top3_score, nll_score, brier_score = utils.get_scores(model_list, x_test_in, y_test_in, dropout=False) print(f"Dataset: {train_dataset}, Model: {model_name}") print(f"Top 1 Acc: {top1_score}") print(f"Top 3 Acc: {top3_score}") print(f"NLL Score: {nll_score}") print(f"Brier Score: {brier_score}") importlib.reload(utils) importlib.reload(dataloader) (_, _), (x_test_in, y_test_in) = dataloader.get_data(ood_dataset, num_train=1, num_test = 5000) top1_score, top3_score, nll_score, brier_score = utils.get_scores(model_list, x_test_in, y_test_in, dropout=False) print(f"Performance on OOD") print(f"OOD Dataset: {ood_dataset}, Model: {model_name}") print(f"Top 1 Acc: {top1_score}") print(f"Top 3 Acc: {top3_score}") print(f"NLL Score: {nll_score}") print(f"Brier Score: {brier_score}") importlib.reload(utils) importlib.reload(dataloader) (_, _), (x_test_in, y_test_in) = dataloader.get_data(ood_dataset, num_train=1, num_test = 5000) top1_score, top3_score, nll_score, brier_score = utils.get_scores(model_list, x_test_in, y_test_in, dropout=False) print(f"Performance on OOD") print(f"OOD Dataset: {ood_dataset}, Model: {model_name}") print(f"Top 1 Acc: {top1_score}") print(f"Top 3 Acc: {top3_score}") print(f"NLL Score: {nll_score}") print(f"Brier Score: {brier_score}") importlib.reload(utils) importlib.reload(dataloader) (_, _), (x_test_in, y_test_in) = dataloader.get_data(ood_dataset, num_train=1, num_test = 5000) top1_score, top3_score, nll_score, brier_score = utils.get_scores(model_list, x_test_in, y_test_in, dropout=False) print(f"Performance on OOD") print(f"OOD Dataset: {ood_dataset}, Model: {model_name}") print(f"Top 1 Acc: {top1_score}") print(f"Top 3 Acc: {top3_score}") print(f"NLL Score: {nll_score}") print(f"Brier Score: {brier_score}") importlib.reload(utils) importlib.reload(dataloader) (_, _), (x_test_in, y_test_in) = dataloader.get_data(ood_dataset, num_train=1, num_test = 5000) top1_score, top3_score, nll_score, brier_score = utils.get_scores(model_list, x_test_in, y_test_in, dropout=False) print(f"Performance on OOD") print(f"OOD Dataset: {ood_dataset}, Model: {model_name}") print(f"Top 1 Acc: {top1_score}") print(f"Top 3 Acc: {top3_score}") print(f"NLL Score: {nll_score}") print(f"Brier Score: {brier_score}")
experiments.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- import json from micromort.data_stores.mongodb import getConnection from multiprocessing.dummy import Pool as ThreadPool import traceback, sys import os mongo_db_name = "micromort" mongo_collection_name = "newstweets" mongoClient = getConnection(mongo_db_name, mongo_collection_name) # + def gen_dict_extract(key, var): if hasattr(var, 'items'): for k, v in var.items(): if k == key: yield v if isinstance(v, dict): for result in gen_dict_extract(key, v): yield result elif isinstance(v, list): for d in v: for result in gen_dict_extract(key, d): yield result def getUrl(tweet): return gen_dict_extract("expanded_url", tweet) # + count = 0 fil_path = "" f = open("./my_data.txt", "a") def myFun(tweet): try: #idx = multiprocessing.current_process() #print(idx, os.getpid()) _str = "" global count count = count+1 if count%1000 == 0: print(count/1000) urls = getUrl(tweet) tweet_id = tweet["id"] filtered_urls = [] for url in urls: if "twitter.com" not in url: filtered_urls.append(url) if not len(filtered_urls): return 1 for url in filtered_urls: url = url[:1000] #url_id = insertUrl(url, con) _str += str(tweet_id) + "\t" + url + "\n" f.write(_str) return 1 except Exception as e: print(e) traceback.print_exc() return 1 pool = ThreadPool(6) results = pool.imap(myFun, mongoClient.find()) # - # cat my_data.txt | awk '{print $2}' | sort | uniq > unique_urls
micromort/tweets_processing/tweets_urls_extractor.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import tensorflow as tf import matplotlib.pyplot as plt import numpy as np from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('./mnist/data/', one_hot = True) # + n_input = 28 * 28 n_noise = 128 # 은닉층 노드 수 n_hidden = 256 total_epoch = 100 batch_size = 100 learning_rate = 0.0002 # 학습률 # - X = tf.placeholder(tf.float32, [None, n_input]) # 생성망에 들어갈 입력데이터(정규 분포를 따르는 128개의 데이터) Z = tf.placeholder(tf.float32, [None, n_noise]) # ## 생성자 신경망 # - W (가중치) # - b (편향) G_W1 = tf.Variable(tf.random_normal([n_noise, n_hidden], stddev=0.01)) G_b1 = tf.Variable(tf.zeros([n_hidden])) G_W2 = tf.Variable(tf.random_normal([n_hidden, n_input], stddev=0.01)) G_b2 = tf.Variable(tf.zeros([n_input])) # ## 판별기 신경망 # + D_W1 = tf.Variable(tf.random_normal([n_input, n_hidden], stddev=0.01)) D_b1 = tf.Variable(tf.zeros([n_hidden])) D_W2 = tf.Variable(tf.random_normal([n_hidden, 1], stddev = 0.01)) D_b2 = tf.Variable(tf.zeros([1])) # 최종 0부터 1 사이의 값 하나 # - # ## 생성자(G) 신경망 구성 # - 무작위 노이즈를 받아 가중치와 편향을 반영한 은닉층을 구성한다. # - Activation 함수를 이용해 최종 결과값 0~1 사이 반환 # # #### 노이즈 데이터 발생을 위한 노이즈 생성 함수 # - def get_noise(데이터 개수, 노이즈 개수) # 노이즈 생성 함수 def get_noise(batch_size, n_noise) : return np.random.normal(size=(batch_size, n_noise)) # 생성자 신경망 직접 구성 def generator(noise_z) : hidden = tf.nn.relu(tf.matmul(noise_z, G_W1) + G_b1) output = tf.nn.sigmoid(tf.matmul(hidden, G_W2) + G_b2) return output # ## 판별자 신경망 구성 # - 구분자 신경망 구성, 가중치와 편향을 반영한 데이터 출력 # - Activation 함수를 이용해 최종 결과 반환 def discriminator(inputs) : hidden = tf.nn.relu(tf.matmul(inputs, D_W1) + D_b1) output = tf.nn.sigmoid(tf.matmul(hidden, D_W2) + D_b2) return output # + # 노이즈를 이용, 랜덤 이미지 생성 # Z는 실행시 noise가 입력됨 G = generator(Z) # 노이즈를 이용하여 생성한 이미지가 진짜 이미지인지 판별 D_fake = discriminator(G) # 진짜 이미지를 이용해 판별한 값 D_real = discriminator(X) # - # ## 비용함수, 최적화 함수 # + loss_D = tf.reduce_mean(tf.log(D_real) + tf.log(1 - D_fake)) loss_G = tf.reduce_mean(tf.log(D_fake)) # - # loss_D 를 구할 때는 판별기 신경망에 사용되는 변수만 사용하고, # loss_G 를 구할 때는 생성기 신경망에 사용되는 변수만 사용하여 최적화 D_var_list = [D_W1, D_b1, D_W2, D_b2] G_var_list = [G_W1, G_b1, G_W2, G_b2] # + ### 오차의 최소화가 아닌 ### loss_D와 loss_G의 최대화가 목표 # - # 최적화 대상인 loss_D와 loss_G에 음수 부호 train_D = tf.train.AdamOptimizer(learning_rate).minimize(-loss_D, var_list = D_var_list) train_G = tf.train.AdamOptimizer(learning_rate).minimize(-loss_G, var_list = G_var_list) # !mkdir samples # ## 모델 학습 # + sess = tf.Session() sess.run(tf.global_variables_initializer()) total_batch = int(mnist.train.num_examples/batch_size) loss_val_D, loss_val_G = 0, 0 # + for epoch in range(total_epoch) : for i in range(total_batch) : batch_xs, batch_ys = mnist.train.next_batch(batch_size) # 판별망의 데이터 noise = get_noise(batch_size, n_noise) # 생성망의 입력 데이터 # 판별기와 생성기 신경망 각각 학습 _, loss_val_D = sess.run([train_D, loss_D], feed_dict = {X: batch_xs, Z : noise}) _, loss_val_G = sess.run([train_G, loss_G], feed_dict = {Z: noise}) print("Epoch : {}, 판별망 성능 : {:.4f}, 생성망 성능 : {:.4f}".format (epoch, loss_val_D, loss_val_G)) if epoch == 0 or (epoch+1) % 10 == 0 : sample_size = 10 noise = get_noise(sample_size, n_noise) samples = sess.run(G, feed_dict = {Z: noise}) fig, ax = plt.subplots(1, sample_size, figsize = (sample_size,1)) for i in range(sample_size) : ax[i].set_axis_off() ax[i].imshow(np.reshape(samples[i], (28,28))) plt.savefig('samples/{}.png'.format(str(epoch).zfill(3)), bbox_inches='tight') plt.close(fig) print('FIN') # -
B/ML/code/GAN.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import torch import torch.nn as nn import torch.optim as optim import matplotlib.pyplot as plt # %matplotlib inline torch.manual_seed(1) N_SAMPLES = 20 N_HIDDENS = 300 # + x = torch.unsqueeze(torch.linspace(-1, 1, 2*N_SAMPLES), dim = 1) y = x + 0.3 * torch.normal(torch.zeros(2*N_SAMPLES, 1), torch.ones(2*N_SAMPLES, 1)) test_x = torch.unsqueeze(torch.linspace(-1, 1, N_SAMPLES), dim = 1) test_y = test_x + 0.3 * torch.normal(torch.zeros(N_SAMPLES, 1), torch.ones(N_SAMPLES, 1)) plt.scatter(x, y, c='magenta', s=50, alpha=0.5, label='train') plt.scatter(test_x, test_y, c='cyan', s=50, alpha=0.5, label='test') plt.legend(loc='upper left') plt.ylim((-2.5, 2.5)) plt.show() # + net_overfitting = nn.Sequential( nn.Linear(1, N_HIDDENS), nn.ReLU(), nn.Linear(N_HIDDENS, N_HIDDENS), nn.ReLU(), nn.Linear(N_HIDDENS, 1) ) net_dropout = nn.Sequential( nn.Linear(1, N_HIDDENS), nn.Dropout(0.5), nn.ReLU(), nn.Linear(N_HIDDENS, N_HIDDENS), nn.Dropout(0.5), nn.ReLU(), nn.Linear(N_HIDDENS, 1) ) print(net_overfitting) print(net_dropout) # + device = 'cuda:0' if torch.cuda.is_available() else 'cpu' # device = 'cpu' net_overfitting.to(device) net_dropout.to(device) criterion = nn.MSELoss() optimizer_overfitting = optim.Adam(net_overfitting.parameters(), lr=0.01) optimizer_dropout = optim.Adam(net_dropout.parameters(), lr=0.01) for t in range(1001): net_overfitting.zero_grad() outputs_overfitting = net_overfitting(x.to(device)) loss_overfitting = criterion(outputs_overfitting, y.to(device)) loss_overfitting.backward() optimizer_overfitting.step() net_dropout.zero_grad() outputs_dropout = net_dropout(x.to(device)) loss_dropout = criterion(outputs_dropout, y.to(device)) loss_dropout.backward() optimizer_dropout.step() if t % 100 == 0: net_overfitting.eval() net_dropout.eval() plt.cla() test_overfitting = net_overfitting(test_x.to(device)).cpu().detach() test_dropout = net_dropout(test_x.to(device)).cpu().detach() plt.scatter(x, y, c='magenta', s=50, alpha=0.3, label='train') plt.scatter(test_x, test_y, c='cyan', s=50, alpha=0.3, label='test') plt.plot(test_x, test_overfitting, 'r-', lw=3, label='overfitting') plt.plot(test_x, test_dropout, 'b--', lw=3, label='dropout(50%)') plt.text(0, -1.2, 'overfitting train loss=%.4f' % loss_overfitting.cpu().item(), fontdict={'size': 20, 'color': 'red'}) plt.text(0, -1.5, 'dropout train loss=%.4f' % loss_dropout.cpu().item(), fontdict={'size': 20, 'color': 'blue'}) plt.text(0, -1.8, 'overfitting test loss=%.4f' % criterion(test_overfitting, test_y).item(), fontdict={'size': 20, 'color': 'red'}) plt.text(0, -2.1, 'dropout test loss=%.4f' % criterion(test_dropout, test_y).item(), fontdict={'size': 20, 'color': 'blue'}) plt.legend(loc='upper left'); plt.ylim((-2.5, 2.5));plt.pause(0.1) net_overfitting.train() net_dropout.train() plt.show() # -
tutorial-contents-notebooks/503new.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + # # %matplotlib inline # probability integral transform import numpy as np import math from scipy.stats import norm import matplotlib.pyplot as plt from scipy.stats import expon x = np.random.randn(100000) z = np.random.exponential(1,100000) k = np.random.uniform(-3,3,100000) y = norm.cdf(x) a = norm.pdf(x) w = expon.cdf(z) fig, axs = plt.subplots(3, 2,figsize=(20, 10)) axs[0,0].hist(x, 100,align='left', color='r', edgecolor='black', linewidth=1) axs[0,1].hist(y, 100,align='left', color='b', edgecolor='black', linewidth=1) axs[1,0].hist(z, 100,align='left', color='y', edgecolor='black', linewidth=1) axs[1,1].hist(w, 100,align='left', color='b', edgecolor='black', linewidth=1) axs[2,0].plot(x,y) axs[2,1].plot(x,a) plt.show() # + # # %matplotlib inline #MSE & MAE import numpy as np import math x = np.random.rand(1000) msd1 = sum((x - np.average(x))**2)/1000 msd2 = sum((x - np.median(x))**2)/1000 mad1 = sum(abs(x - np.median(x)))/1000 mad2 = sum(abs(x - np.average(x)))/1000 print(msd1,msd2,mad1,mad2) # + import pandas as pd import seaborn as sns; import matplotlib.pyplot as plt df = pd.read_csv('RegionalInterestByConditionOverTime.csv','\t') average = df.mean(axis =0) average.rename(lambda x : "".join( letter for letter in x if letter.isalpha()), inplace = True) average.drop('geoCode',inplace = True) avg_frame = average.to_frame() avg_frame.index.name = 'disease' avg_frame.columns = ['count'] avg_frame = avg_frame.reset_index().melt('disease', var_name='count') avg_frame['count'] = 2004 + avg_frame.groupby('disease').cumcount() avg_frame = avg_frame.pivot('disease','count').droplevel(0,1) avg_frame = avg_frame.T corr = avg_frame.corr() m = corr > 0.8 k = corr.where(m ,0) fig, ax = plt.subplots(figsize=(6,6)) ax.set_ylim(-2, 2) ax = sns.heatmap(k,cmap="Blues") ax # + import pandas as pd import numpy as np import seaborn as sns; import matplotlib.pyplot as plt df = pd.read_csv('RegionalInterestByConditionOverTime.csv','\t') df.drop('geoCode',axis = 1 ,inplace = True) df.set_index('dma', inplace = True) df.columns = pd.MultiIndex.from_tuples([(col[5:], int(col[0:4])) for col in df.columns], names=['Disease', 'Year']) df1 = df['cancer'].T test = df1.head(0).T set1 = set(df.columns.get_level_values(0)) list1 = list(set1) list1.sort() i = 0 for value in list1: df1 = df[value].T slopes = df1.apply(lambda x: np.polyfit(df1.index, x, 1)[0]) test.insert(i,value ,slopes) i+=1 for column in test.columns: print(column, test[column].idxmax(),test[column].max(axis =0)) print ('---------------------------------------------------------------') for index in test.index: print( index,test.loc[index].idxmax(), test.loc[index].max(axis =0)) # + import numpy as np import matplotlib.pyplot as plt fig, axs = plt.subplots(3, 2,figsize=(20,10)) a1 = np.random.binomial(1,0.4,10000) a2 = np.random.binomial(5,0.4,10000) a3 = np.random.hypergeometric(4,6,5,10000) a4 = np.random.negative_binomial(5,0.4,10000) a5 = np.random.negative_binomial(1,0.4,10000) a6 = np.random.poisson(5,10000) axs[0,0].hist(a1,25, color='y', edgecolor='black') axs[0,1].hist(a2, 25,color='r', edgecolor='black') axs[1,0].hist(a3, 25,color='b', edgecolor='black') axs[1,1].hist(a4, 25,color='y', edgecolor='black') axs[2,0].hist(a5, 25,color='r', edgecolor='black') axs[2,1].hist(a6, 25,color='b', edgecolor='black') plt.show() # + import numpy as np import matplotlib.pyplot as plt fig, axs = plt.subplots(2, 2,figsize=(20,10)) a1 = np.random.randn(10000) a2 = np.random.lognormal(0,1,10000) a3 = np.log(a2) a4 = np.exp(a1) axs[0,0].hist(a1,25, color='y', edgecolor='black') axs[0,1].hist(a2, 25,color='r', edgecolor='black') axs[1,0].hist(a3, 25,color='r', edgecolor='black') axs[1,1].hist(a4, 25,color='b', edgecolor='black') plt.show() # + import numpy as np import matplotlib.pyplot as plt a7 = np.random.poisson(1,100000) a8 = np.random.exponential(1,100000) a9 = np.random.gamma(2,1,100000) a10 = np.random.gamma(4,1,100000) a11 = np.random.beta(10 ,1,100000) a12 = np.random.beta(1 ,10,100000) a13 = np.random.beta(1 ,1,100000) a14 = np.random.beta(10 ,10,100000) fig, axs = plt.subplots(4, 2,figsize=(20,10)) axs[0,0].hist(a7,50, color='y', edgecolor='black') axs[0,1].hist(a8,50, color='b', edgecolor='black') axs[1,0].hist(a9,50, color='b', edgecolor='black') axs[1,1].hist(a10,50, color='b', edgecolor='black') axs[2,0].hist(a11,50, color='b', edgecolor='black') axs[2,1].hist(a12,50, color='b', edgecolor='black') axs[3,0].hist(a13,50, color='b', edgecolor='black') axs[3,1].hist(a14,50, color='b', edgecolor='black') plt.show() # + # Multinomial plot import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D k = np.random.multinomial(10 ,[1/3,1/3,1/3],100000) m = k[0:100000 ,0:2] rows = np.unique(m, axis=0,return_counts = True) unique_rows = rows[0] row, col = unique_rows.shape xpos = unique_rows[0:row ,0:1].flatten() ypos = unique_rows[0:row ,1:2].flatten() zpos = [0] * row zsize = np.array(rows[1]).reshape(row,1).flatten() xsize = np.ones(row) ysize = np.ones(row) fig = plt.figure(figsize=(30, 15)) ax1 = fig.add_subplot(121, projection='3d') ax1.set_xticks([0, 10, 1]) ax1.set_yticks([0, 10, 1]) ax1.bar3d(xpos, ypos, zpos, xsize, ysize, zsize, color='blue', linewidth=1, edgecolor='y',zsort='average',shade = True) plt.show() # + import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.mplot3d import Axes3D import math np.random.seed(np.random.randint(20)) Z1 = np.random.randn(100000) np.random.seed(np.random.randint(50)) Z2 = np.random.randn(100000) AvgX = 65 AvgY = 150 SigX = 5 SigY = 10 rho = 0 coeff = (2*math.pi*(1- rho*rho)**(1/2)*SigX*SigY)**(-1) X1 = SigX*Z1 + AvgX X2 = SigY*(rho*Z1 + (1- rho*rho)**(1/2)*Z2) + AvgY expo = (((X1 - AvgX)**2/(SigX)**2) + ((X2 - AvgY)**2/(SigY)**2) - (2*rho*(X1 - AvgX)*(X2 - AvgY)/(SigX*SigY)))*((-1)/(2*((1- rho*rho)**(1/2)))) val = np.exp(expo) density = coeff*val fig = plt.figure(figsize=(30, 15)) ax = fig.gca(projection='3d') surf = ax.plot_trisurf(X1, X2, density, cmap=cm.coolwarm, antialiased=False) plt.show() # + # Delta method example ( a14) import numpy as np import matplotlib.pyplot as plt a1 = np.random.poisson(1,100000) a2 = np.random.poisson(1,100000) a3 = np.random.poisson(1,100000) a4 = np.random.poisson(1,100000) a5 = np.random.poisson(1,100000) a6 = np.random.poisson(1,100000) a7 = np.random.poisson(1,100000) a8 = np.random.poisson(1,100000) a9 = np.random.poisson(1,100000) a10 = np.random.poisson(1,100000) a11 = (a1 +a2 + a3)/3 a12 = (a1 + a2 + a3 + a4 + a5)/5 a13 = (a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10)/10 a14 = (10**(1/2)/2) * (a13*a13 - 1) fig, axs = plt.subplots(3,2,figsize=(20,10)) axs[0,0].hist(a1,50, color='y', edgecolor='black') axs[0,1].hist(a11,50, color='b', edgecolor='black') axs[1,0].hist(a12,50, color='b', edgecolor='black') axs[1,1].hist(a13,50, color='b', edgecolor='black') axs[2,1].hist(a14,50, color='b', edgecolor='black') plt.show() # + # Correction for continuity # # %matplotlib inline import numpy as np import scipy from scipy.stats import binom,norm import matplotlib.pyplot as plt fig = plt.figure(figsize=(20, 10)) ax = plt.gca() ax.set_xlim(30,70) ax.set_ylim(0, 1) ax.set_xticks(np.linspace(30,70,num = 81)) ax.set_yticks(np.linspace(0,1,25)) plt.xticks(rotation=270) p = 0.5 n = 100 x = 0 result = [] result1 = [] for a in range(0,121): result.append((a,scipy.stats.binom.cdf(x, n, p))) result1.append((a,scipy.stats.norm.cdf(x, loc = 50, scale = 5))) x+= 1 xy2=zip(*result) xy3=zip(*result1) plt.plot(*xy2,color='red', marker='*',linewidth=2, markersize=8) plt.plot(*xy3,color='green', marker='o', linestyle='dashed',linewidth=2, markersize=8) plt.grid(b=True, which='major', color='#666666', linestyle='-') plt.show() # + # Bayesian inference of a binomial distribution - n = 100 , p = 0.56 , observing samples of 20 for 6 times. # We know that n = 100 , and estimating for p. # Each time we plot the prior & posterior import scipy import numpy as np from scipy import stats import matplotlib.pyplot as plt def calc_prior(thetas, a, b): return scipy.stats.beta(a, b).pdf(thetas) def calc_posterior(thetas, a_old, b_old, n, k): a_new = a_old+k b_new = b_old+n-k posterior = scipy.stats.beta(a_new, b_new).pdf(thetas) return posterior, a_new, b_new fig, axs = plt.subplots(7,2,figsize=(40,30)) thetas = np.linspace(0, 1, 500) a, b = 0, 0 tup = [(0,0),(0,1),(1,0),(1,1),(2,0),(2,1),(3,0),(3,1),(4,0),(4,1),(5,0),(5,1),(6,0),(6,1)] for x,y in tup: print(a,b) k = sum(np.random.binomial(size=20, n=1, p= 0.6)) prior = calc_prior(thetas, a, b) axs[x,y].set_ylim(0, 15) axs[x,y].plot(thetas, prior, label="Prior", c="red") posterior, a, b = calc_posterior(thetas, a, b, 20, k) axs[x,y].plot(thetas, posterior, label="Posterior", c="blue") # + # EM algorithm for missing data _ but doesn't converge import numpy as np def start_estimate(): avg1,avg2 = np.nanmean(start_data , axis = 0) std1 ,std2 = np.nanstd(start_data,axis =0) corr = np.corrcoef(start_data[0:3,0:1],start_data[0:3,1:2],rowvar = False)[0,1] return (avg1,avg2,std1,std2,corr) def iter_estimate(k,var_x,var_y): avg1,avg2 = np.nanmean(k , axis = 0) sum1,sum2 = np.nanvar(k,axis =0) prod1, prod2 = np.nanvar(k,axis =0)*6 rho = np.sum((iter_data[:,0] - avg1)*(iter_data[:,1] - avg2))/((prod1 +var_x)**(1/2)*(prod2 + var_y)**(1/2)) return (avg1 , avg2, (sum1 + var_x/6)**(1/2), (sum2 + var_y/6)**(1/2),rho) def cond_mean_var_wt(ht,estimate): avg1,avg2,std1,std2,rho = estimate cond_mean_wt = avg2 + rho*std2/std1*(ht-avg1) cond_var_wt = (1 - rho*rho)*std2*std2 return (cond_mean_wt, cond_var_wt) def cond_mean_var_ht(wt,estimate): avg1,avg2,std1,std2,rho = estimate cond_mean_ht = avg1 + rho*std1/std2*(wt-avg2) cond_var_ht = (1 - rho*rho)*std1*std1 return (cond_mean_ht , cond_var_ht) #def log_likelihood(array): #avg1,avg2,std1,std2,rho = estimate() start_data = np.empty([6, 2]) start_data[:] = np.NaN start_data[0:3,] = [[72,197],[70,204],[73,208]] start_data[3,0] = 68 start_data[4,0] = 65 start_data[5,1] = 170 iter_data = [] estimate0 = start_estimate() var_delta_x = 0 var_delta_y = 0 for row in start_data: x, y = row if np.isnan(x): x = cond_mean_var_ht(y,estimate0)[0] var_delta_x = var_delta_x + cond_mean_var_ht(y,estimate0)[1] elif np.isnan(y): y = cond_mean_var_wt(x,estimate0)[0] var_delta_y = var_delta_y + cond_mean_var_wt(x,estimate0)[1] row = x,y iter_data.append(row) iter_data = np.array(iter_data) estimate1 = iter_estimate(iter_data,var_delta_x,var_delta_y) var_delta_x2 = 0 var_delta_y2 = 0 estimate_new = estimate1 estimate_old = (0,0,0,0,0) counter = 0 while(counter <35): iter_new = [] for row in zip(start_data,iter_data): x,y = row x1,y1 = x x2,y2 = y if np.isnan(x1): x2 = cond_mean_var_ht(y2,estimate_new)[0] var_delta_x2 = var_delta_x2 + cond_mean_var_ht(y2,estimate_new)[1] elif np.isnan(y1): y2 = cond_mean_var_wt(x2,estimate_new)[0] var_delta_y2 = var_delta_y2 + cond_mean_var_wt(x2,estimate_new)[1] y = x2,y2 iter_new.append(y) iter_data = np.array(iter_new) estimate_old = estimate_new estimate_new = iter_estimate(iter_data,var_delta_x2,var_delta_y2) print(estimate_old) print(estimate_new) counter+=1 # + # # %matplotlib inline import matplotlib.pyplot as plt import numpy as np fig, (ax1,ax2) = plt.subplots(1,2,figsize=(20,10)) sample_var = [] for i in range ( 0,10000): x = np.random.normal(loc=10, scale=3.0, size=5) # normal distribution with mean 10 & var = 9 ( std dev = 3) avg = np.mean(x) sample_var.append((np.sum((x -avg)**2))/4) # Sample variance sample_var = np.array(sample_var) chi_sq = 5/9 *sample_var # ( chi square statistic = n* sample var/population var) ax1.hist(sample_var,50, color='b', edgecolor='black') ax2.hist(chi_sq,50, color='r', edgecolor='black') ax2.set_xlim(ax1.get_xlim()) ax1.set_ylim(ax2.get_ylim()) plt.show() # -
Statistics-1.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # #!pip3 install -q numpy pandas catboost hyperopt scikit-learn frozendict matplotlib from __future__ import absolute_import, division, print_function, unicode_literals # !jupyter nbextension enable --py widgetsnbextension # + #Initial code used from https://www.analyticsvidhya.com/blog/2017/08/catboost-automated-categorical-data/ # and parameter search from https://effectiveml.com/using-grid-search-to-optimise-catboost-parameters.html import catboost as cb import numpy as np import numpy.random as nr import pandas as pd import catboost.utils as cbu import hyperopt import sys import sklearn.model_selection as ms import sklearn.metrics as sklm from frozendict import frozendict # %matplotlib inline # print module versions for reproducibility print('CatBoost version {}'.format(cb.__version__)) print('NumPy version {}'.format(np.__version__)) print('Pandas version {}'.format(pd.__version__)) # + # Load already prepared training dataset, display shape, & explore first 10 rows of Pandas data frame train_set = pd.read_csv('progressData/LoanTrain_Clean_2019-08-12-A2e2a.csv') print(train_set.shape) train_set.head() # + #Load test data previously prepared in data preparation step. test_set = pd.read_csv('progressData/LoanTest_Clean_2019-08-12-A2w2a.csv') print(test_set.shape) test_set.head() # + # Testing for Class Imbalance by Examining Classes where label= accepted # Unequal numbers of cases for the categories of labels, which can seriously bias the training of classifier alogrithms # higher error rate for the minority class. This should be tested for before training any model. train_set_counts = train_set[['loan_type','accepted']].groupby('accepted').count() print(train_set_counts) # + # Check training data types train_set.dtypes # + # Check test data types test_set.dtypes # + #Creating a training set for modeling and validation set to check model performance train_set = train_set.drop('accepted', axis=1) # remove labels # + # ReCheck training data types train_set.dtypes # + # Now, you’ll see that we will only identify categorical variables. We will not perform any preprocessing steps for # categorical variables: categorical_features_indices = np.where(train_set.dtypes != np.float)[0] categorical_features_indices # + # Convert datasets to numpy arrays # Load training labels train_set = np.array(train_set) test_set = np.array(test_set) l = pd.read_csv('data/train_labels.csv') labels = np.array(l['accepted']) print(labels.shape) labels[:5] # + # Check labels print(labels) # + # Creating a training set for modeling and validation set to check model performance nr.seed(1115) # Randomly sample cases to create independent training & test data indx = range(train_set.shape[0]) indx = ms.train_test_split(indx, test_size = 150000) x_train = train_set[indx[0],:] y_train = np.ravel(labels[indx[0]]) x_validation = train_set[indx[1],:] y_validation = np.ravel(labels[indx[1]]) # + # Check validation set print(y_validation) # + # Create prediction set x_predict = test_set # + # Check prediction set print(y_validation) # - class HLClassifierObjective(object): def __init__(self, dataset, const_params, fold_count): self._dataset = dataset self._const_params = const_params.copy() self._fold_count = fold_count self._evaluated_count = 0 def _to_catboost_params(self, hyper_params): return { 'learning_rate': hyper_params['learning_rate'], 'depth': hyper_params['depth'], 'l2_leaf_reg': hyper_params['l2_leaf_reg']} # hyperopt optimizes an objective using `__call__` method (e.g. by doing # `foo(hyper_params)`), so we provide one def __call__(self, hyper_params): # join hyper-parameters provided by hyperopt with hyper-parameters # provided by the user params = self._to_catboost_params(hyper_params) params.update(self._const_params) print('evaluating params={}'.format(params), file=sys.stdout) sys.stdout.flush() # we use cross-validation for objective evaluation, to avoid overfitting scores = cb.cv( pool=self._dataset, params=params, fold_count=self._fold_count, partition_random_seed=20181224, verbose=False) # scores returns a dictionary with mean and std (per-fold) of metric # value for each cv iteration, we choose minimal value of objective # mean (though it will be better to choose minimal value among all folds) # because noise is additive min_mean_auc = np.min(scores['test-AUC-mean']) print('evaluated score={}'.format(min_mean_auc), file=sys.stdout) self._evaluated_count += 1 print('evaluated {} times'.format(self._evaluated_count), file=sys.stdout) # negate because hyperopt minimizes the objective return {'loss': -min_mean_auc, 'status': hyperopt.STATUS_OK} # + def find_best_hyper_params(dataset, const_params, max_evals=100): # we are going to optimize these three parameters, though there are a lot more of them (see CatBoost docs) parameter_space = { 'learning_rate': hyperopt.hp.uniform('learning_rate', 0.2, 1.0), 'depth': hyperopt.hp.randint('depth', 7), 'l2_leaf_reg': hyperopt.hp.uniform('l2_leaf_reg', 1, 10)} objective = HLClassifierObjective(dataset=dataset, const_params=const_params, fold_count=6) trials = hyperopt.Trials() best = hyperopt.fmin( fn=objective, space=parameter_space, algo=hyperopt.rand.suggest, max_evals=max_evals, rstate=np.random.RandomState(seed=20181224)) return best def train_best_model(X, y, const_params, max_evals=100, use_default=False): # convert pandas.DataFrame to catboost.Pool to avoid converting it on each # iteration of hyper-parameters optimization dataset = cb.Pool(X, y, cat_features=categorical_features_indices) if use_default: # pretrained optimal parameters best = { 'learning_rate': 0.4234185321620083, 'depth': 5, 'l2_leaf_reg': 9.464266235679002} else: best = find_best_hyper_params(dataset, const_params, max_evals=max_evals) # merge subset of hyper-parameters provided by hyperopt with hyper-parameters # provided by the user hyper_params = best.copy() hyper_params.update(const_params) # drop `use_best_model` because we are going to use entire dataset for # training of the final model hyper_params.pop('use_best_model', None) model = cb.CatBoostClassifier(**hyper_params) model.fit(dataset, verbose=False) return model, hyper_params # + # make it True if your want to use GPU for training import time start=time.time() have_gpu = False # skip hyper-parameter optimization and just use provided optimal parameters use_optimal_pretrained_params = False # number of iterations of hyper-parameter search hyperopt_iterations = 50 const_params = frozendict({ 'task_type': 'GPU' if have_gpu else 'CPU', 'loss_function': 'Logloss', 'eval_metric': 'AUC', 'custom_metric': ['AUC'], 'iterations': 100, 'random_seed': 20181224}) model, params = train_best_model( x_train, y_train, const_params, max_evals=hyperopt_iterations, use_default=use_optimal_pretrained_params) print('best params are {}'.format(params), file=sys.stdout) end = time.time() print(end-start) # - def calculate_score_on_dataset_and_show_graph(X, y, model): import sklearn.metrics import matplotlib.pylab as pl pl.style.use('ggplot') dataset = cb.Pool(X, y, cat_features=categorical_features_indices) fpr, tpr, _ = cbu.get_roc_curve(model, dataset) auc = sklearn.metrics.auc(fpr, tpr) pl.figure(figsize=(8, 8,)) pl.plot(fpr, tpr) pl.xlim([-0.1, 1.1]) pl.ylim([-0.1, 1.1]) pl.xlabel('FPR') pl.ylabel('TPR') pl.title('ROC curve (AUC={:.3f})'.format(auc)) pl.show() return auc # + #Above- AUC = 0.807 #Below- Compute & display sample of class probabilities for test feature data set. # Class w/ highest probability is taken as score (prediction) probabilities = model.predict_proba(data=x_validation) print(probabilities[:15, :]) # + #Above- 1st column= probability of score 0, 2nd column= prob of score 1. #Below- Transform class probabilities into class scores. # Set threshold to prob b/w 2 likelihoods at 0.5. This is applied to prob of score 0 below. def score_model(probs, threshold): return np.array([1 if x> threshold else 0 for x in probs[:, 1]]) scores = score_model(probabilities, 0.5) print(np.array(scores[:15])) print(y_validation[:15]) # + # ReCheck accuracy by the equal provided by DrivenData N = len(y_validation) print(N) def isEqual(a): return a[0] == a[1] ClRt = (1/N)*sum(1 for i in filter(isEqual, zip(scores, y_validation))) print(ClRt) # + import sklearn.metrics as sklm #Below- Compute a confusion matrix as a metric to evaluate the results for the logisitic regression model #True Positive (TP)- cases w/ positive labels which have been correctly classified as positive #True Negative (TN)- cases w/ negative labels which have been correctly classified as negative #False Positive (FP)- cases w/ negative labels which have been incorrectly classified as positive #False Negative (FN)- cases w/ positive labels which have been incorrectly classified as negative # where positive is 1 and neagtive is 0 #Accuracy/Bias- fraction of cases correctly classified #Precision- fraction of correctly calssified label cases out of all cases classified w/ that label value # is sentistive to the # of cases correctly classified for a given score value #Recall- fraction of cases of a label value correctly classified out of all cases for that have that label value # is sensitive to the # of cases correctly classified for a given true label value #F1- weighted average of precision and recall (overall model performance) #ROC- (receiver operating characteristic) displays relationship b/w TP rate on y and FP rate on x #AUC- (area/integral under the curve) overall performance of classifer model # higher the AUC, the lower the increase in FP rate req to achieve a req TP rate # Ideally AUC= 1.0, TP rate is achieved w/ 0 FP rate. # can compare classifiers, one w/ higher AUC is generally better # ROC diagonal for Bernoulli w/ AUC 0.5, anything greater than this is better than random guessing in balanced cases #Below- Compute & examine the performance metrics for the classifier using precision_recall_fscore_support # & accuracy_score functions from metric package in scikit-learn. Confusion matrix is computed through # confusion_matrix from same package. def print_metrics(labels, scores): metrics = sklm.precision_recall_fscore_support(labels, scores) conf = sklm.confusion_matrix(labels, scores) print(' Confusion Matrix ') print(' Score Positive Score Negative ') print('Actual Positive %6d' % conf[0, 0] + ' %5d' % conf[0, 1]) print('Actual Negative %6d' % conf[1, 0] + ' %5d' % conf[1, 1]) print('') print('Accuracy %0.2f' % sklm.accuracy_score(labels, scores)) print('') print(' Positive Negative') print('Num Case %6d' % metrics[3][0] + ' %6d' % metrics[3][1]) print('Precision %6.2f' % metrics[0][0] + ' %6.2f' % metrics [0][1]) print('Recall %6.2f' % metrics[1][0] + ' %6.2f' % metrics[1][1]) print('F1 %6.2f' % metrics[2][0] + ' %6.2f' % metrics[2][0]) print_metrics(y_validation, scores) # + # Check probabilities for predictions print(model.predict_proba(data=x_predict)) # + # Check scores for predictions print(model.predict(data=x_predict)) # - Y_PREDICT = model.predict(data=x_predict) print(Y_PREDICT) Y_PREDICT_df = pd.DataFrame(Y_PREDICT) # + # Save data to csv for submission Y_PREDICT_df.to_csv('results/results_2019-08-15.csv', index = False, header = True) # + # Get Feature Importances model.get_feature_importance(prettified=True) # + # Score & display performance metrics for test dataset model import sklearn.metrics as sklm def score_model(probs, threshold): return np.array([1 if x > threshold else 0 for x in probs[:,1]]) def print_metrics(labels, probs, threshold): scores = score_model(probs, threshold) metrics = sklm.precision_recall_fscore_support(labels, scores) conf = sklm.confusion_matrix(labels, scores) print(' Confusion Matrix') print(' Score Positive Score Negative') print('Actual Positive %6d' % conf[0,0] + ' %5d' % conf[0,1]) print('Actual Negative %6d' % conf[1,0] + ' %5d' % conf[1,1]) print('') print('Accuracy %0.2f' % sklm.accuracy_score(labels, scores)) print('AUC %0.2f' % sklm.roc_auc_score(labels, probs[:,1])) print('Macro Precision %0.2f' % float((float(metrics[0][0]) + float(metrics[0][1]))/2.0)) print('Macro Recall %0.2f' % float((float(metrics[1][0]) + float(metrics[1][1]))/2.0)) print(' ') print(' Positive Negative') print('Num Case %6d' % metrics[3][0] + ' %6d' % metrics[3][1]) print('Precision %6.2f' % metrics[0][0] + ' %6.2f' % metrics[0][1]) print('Recall %6.2f' % metrics[1][0] + ' %6.2f' % metrics[1][1]) print('F1 %6.2f' % metrics[2][0] + ' %6.2f' % metrics[2][1]) probabilities = model.predict_proba(x_validation) print_metrics(y_validation, probabilities, 0.5)
CatBoostTuningClassificationModel.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ___ # # <a href='https://www.udemy.com/user/joseportilla/'><img src='../Pierian_Data_Logo.png'/></a> # ___ # <center><em>Content Copyright by <NAME></em></center> # # filter # # The function filter(function, list) offers a convenient way to filter out all the elements of an iterable, for which the function returns True. # # The function filter(function,list) needs a function as its first argument. The function needs to return a Boolean value (either True or False). This function will be applied to every element of the iterable. Only if the function returns True will the element of the iterable be included in the result. # # Like map(), filter() returns an *iterator* - that is, filter yields one result at a time as needed. Iterators and generators will be covered in an upcoming lecture. For now, since our examples are so small, we will cast filter() as a list to see our results immediately. # # Let's see some examples: #First let's make a function def even_check(num): if num%2 ==0: return True # Now let's filter a list of numbers. Note: putting the function into filter without any parentheses might feel strange, but keep in mind that functions are objects as well. # + lst =range(20) list(filter(even_check,lst)) # - # filter() is more commonly used with lambda functions, because we usually use filter for a quick job where we don't want to write an entire function. Let's repeat the example above using a lambda expression: list(filter(lambda x: x%2==0,lst)) # Great! You should now have a solid understanding of filter() and how to apply it to your code!
Complete-Python-3-Bootcamp-master/09-Built-in Functions/03-Filter.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import numpy as np import scipy as sp import pandas as pd import datetime from compute import * # + #constants ProjectName = "Tower St 4plex and 2 adus" # assumptions NumberUnits=4 price = 1000000 rent = 1400*4 ltv = 75 loanRatePer = 3.5 expenseRate = 30 rentPF = 1800*4 # Proforma expenseRatePF=30 capPF =4.5 repairCost = 10000*4+15000 computeProjectSimple(ProjectName, NumberUnits, price, rent,expenseRate, ltv, loanRatePer, rentPF,expenseRatePF,capPF,repairCost) # -
5834-Lauretta-St.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # MindSpore API概述 # # [![](https://gitee.com/mindspore/docs/raw/master/resource/_static/logo_source.png)](https://gitee.com/mindspore/docs/blob/master/docs/mindspore/programming_guide/source_zh_cn/api_structure.ipynb)&emsp;[![](https://gitee.com/mindspore/docs/raw/master/resource/_static/logo_notebook.png)](https://obs.dualstack.cn-north-4.myhuaweicloud.com/mindspore-website/notebook/master/programming_guide/zh_cn/mindspore_api_structure.ipynb)&emsp;[![](https://gitee.com/mindspore/docs/raw/master/resource/_static/logo_modelarts.png)](https://authoring-modelarts-cnnorth4.huaweicloud.com/console/lab?share-url-b64=aHR0cHM6Ly9vYnMuZHVhbHN0YWNrLmNuLW5vcnRoLTQubXlodWF3ZWljbG91ZC5jb20vbWluZHNwb3JlLXdlYnNpdGUvbm90ZWJvb2svbW9kZWxhcnRzL3Byb2dyYW1taW5nX2d1aWRlL21pbmRzcG9yZV9hcGlfc3RydWN0dXJlLmlweW5i&imageid=65f636a0-56cf-49df-b941-7d2a07ba8c8c) # ## 总体架构 # MindSpore是一个全场景深度学习框架,旨在实现易开发、高效执行、全场景覆盖三大目标,其中易开发表现为API友好、调试难度低,高效执行包括计算效率、数据预处理效率和分布式训练效率,全场景则指框架同时支持云、边缘以及端侧场景。 # # ME(MindExpression)提供了用户级应用软件编程接口(Application Programming Interface,API),用于科学计算以及构建和训练神经网络,并将用户的Python代码转换为数据流图。更多总体架构的相关内容请参见[总体架构](https://www.mindspore.cn/docs/programming_guide/zh-CN/master/architecture.html)。 # ## 设计理念 # MindSpore源于全产业的最佳实践,向数据科学家和算法工程师提供了统一的模型训练、推理和导出等接口,支持端、边、云等不同场景下的灵活部署,推动深度学习和科学计算等领域繁荣发展。 # # MindSpore目前提供了Python编程范式,用户使用Python原生控制逻辑即可构建复杂的神经网络模型,AI编程变得简单,具体示例请参见[实现一个图片分类应用](https://www.mindspore.cn/docs/programming_guide/zh-CN/master/quick_start/quick_start.html)。 # # 目前主流的深度学习框架的执行模式有两种,分别为静态图模式和动态图模式。静态图模式拥有较高的训练性能,但难以调试。动态图模式相较于静态图模式虽然易于调试,但难以高效执行。MindSpore提供了动态图和静态图统一的编码方式,大大增加了静态图和动态图的可兼容性,用户无需开发多套代码,仅变更一行代码便可切换动态图/静态图模式,例如设置`context.set_context(mode=context.PYNATIVE_MODE)`切换成动态图模式,设置`context.set_context(mode=context.GRAPH_MODE)`即可切换成静态图模式,用户可拥有更轻松的开发调试及性能体验。 # # 神经网络模型通常基于梯度下降算法进行训练,但手动求导过程复杂,结果容易出错。MindSpore的基于源码转换(Source Code Transformation,SCT)的自动微分(Automatic Differentiation)机制采用函数式可微分编程架构,在接口层提供Python编程接口,包括控制流的表达。用户可聚焦于模型算法的数学原生表达,无需手动进行求导,自动微分的样例代码如下所示。 # > 本样例适用于GPU和Ascend环境。 # + import mindspore as ms from mindspore import ops grad_all = ops.composite.GradOperation() def func(x): return x * x * x def df_func(x): return grad_all(func)(x) @ms.ms_function def df2_func(x): return grad_all(df_func)(x) if __name__ == "__main__": print(df2_func(ms.Tensor(2, ms.float32))) # - # 其中,第一步定义了一个函数(计算图),第二步利用MindSpore提供的反向接口进行自动微分,定义了一个一阶导数函数(计算图),第三步定义了一个二阶导数函数(计算图),最后给定输入就能获取第一步定义的函数在指定处的二阶导数,二阶导数求导结果为`12`。 # # 此外,SCT能够将Python代码转换为MindSpore函数中间表达(Intermediate Representation,IR),该函数中间表达构造出能够在不同设备解析和执行的计算图,并且在执行该计算图前,应用了多种软硬件协同优化技术,端、边、云等不同场景下的性能和效率得到针对性的提升。 # # 如何提高数据处理能力以匹配人工智能芯片的算力,是保证人工智能芯片发挥极致性能的关键。MindSpore为用户提供了多种数据处理算子,通过自动数据加速技术实现了高性能的流水线,包括数据加载、数据论证、数据转换等,支持CV/NLP/GNN等全场景的数据处理能力。MindRecord是MindSpore的自研数据格式,具有读写高效、易于分布式处理等优点,用户可将非标准的数据集和常用的数据集转换为MindRecord格式,从而获得更好的性能体验,转换详情请参见[MindSpore数据格式转换](https://www.mindspore.cn/docs/programming_guide/zh-CN/master/dataset_conversion.html)。MindSpore支持加载常用的数据集和多种数据存储格式下的数据集,例如通过`dataset=dataset.Cifar10Dataset("Cifar10Data/")`即可完成CIFAR-10数据集的加载,其中`Cifar10Data/`为数据集本地所在目录,用户也可通过`GeneratorDataset`自定义数据集的加载方式。数据增强是一种基于(有限)数据生成新数据的方法,能够减少网络模型过拟合的现象,从而提高模型的泛化能力。MindSpore除了支持用户自定义数据增强外,还提供了自动数据增强方式,使得数据增强更加灵活,详情请见[自动数据增强](https://www.mindspore.cn/docs/programming_guide/zh-CN/master/auto_augmentation.html)。 # # 深度学习神经网络模型通常含有较多的隐藏层进行特征提取,但特征提取随机化、调试过程不可视限制了深度学习技术的可信和调优。MindSpore支持可视化调试调优(MindInsight),提供训练看板、溯源、性能分析和调试器等功能,帮助用户发现模型训练过程中出现的偏差,轻松进行模型调试和性能调优。例如用户可在初始化网络前,通过`profiler=Profiler()`初始化`Profiler`对象,自动收集训练过程中的算子耗时等信息并记录到文件中,在训练结束后调用`profiler.analyse()`停止收集并生成性能分析结果,以可视化形式供用户查看分析,从而更高效地调试网络性能,更多调试调优相关内容请见[训练过程可视化](https://www.mindspore.cn/mindinsight/docs/zh-CN/master/index.html)。 # # 随着神经网络模型和数据集的规模不断增加,分布式并行训练成为了神经网络训练的常见做法,但分布式并行训练的策略选择和编写十分复杂,这严重制约着深度学习模型的训练效率,阻碍深度学习的发展。MindSpore统一了单机和分布式训练的编码方式,开发者无需编写复杂的分布式策略,在单机代码中添加少量代码即可实现分布式训练,例如设置`context.set_auto_parallel_context(parallel_mode=ParallelMode.AUTO_PARALLEL)`便可自动建立代价模型,为用户选择一种较优的并行模式,提高神经网络训练效率,大大降低了AI开发门槛,使用户能够快速实现模型思路,更多内容请见[分布式并行训练](https://www.mindspore.cn/docs/programming_guide/zh-CN/master/distributed_training.html)。 # ## 层次结构 # # MindSpore向用户提供了3个不同层次的API,支撑用户进行网络构建、整图执行、子图执行以及单算子执行,从低到高分别为Low-Level Python API、Medium-Level Python API以及High-Level Python API。 # ![image](https://gitee.com/mindspore/docs/raw/master/docs/mindspore/programming_guide/source_zh_cn/images/api_structure.png) # - Low-Level Python API # # 第一层为低阶API,主要包括张量定义、基础算子、自动微分等模块,用户可使用低阶API轻松实现张量定义和求导计算,例如用户可通过`Tensor`接口自定义张量,使用`ops.composite`模块下的`GradOperation`算子计算函数在指定处的导数。 # # # - Medium-Level Python API # # 第二层为中阶API,其封装了低阶API,提供网络层、优化器、损失函数等模块,用户可通过中阶API灵活构建神经网络和控制执行流程,快速实现模型算法逻辑,例如用户可调用`Cell`接口构建神经网络模型和计算逻辑,通过使用`loss`模块和`Optimizer`接口为神经网络模型添加损失函数和优化方式,利用`dataset`模块对数据进行处理以供模型的训练和推导使用。 # # # - High-Level Python API # # 第三层为高阶API,其在中阶API的基础上又提供了训练推理的管理、混合精度训练、调试调优等高级接口,方便用户控制整网的执行流程和实现神经网络的训练推理及调优,例如用户使用Model接口,指定要训练的神经网络模型和相关的训练设置,对神经网络模型进行训练,通过`Profiler`接口调试神经网络性能。
docs/mindspore/programming_guide/source_zh_cn/api_structure.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: 'Python 3.8.2 64-bit (''base'': conda)' # metadata: # interpreter: # hash: 5afca213e3fd4a905a1ee04cf013c4a2a70ed6bf52820ba3c074a5841fff5c71 # name: python3 # --- # 写txt文件 with open('data.txt','a') as f: #设置文件对象 x = 1 y = 1 f.write(str(1)+','+str(y)+';') #将字符串写入文件中 import numpy as np # 0,0在最左上角 ## 设一个像素点长度为1,我们画(X-250)^2 + (Y-250)^2 = 100^2 for x in range(201): posx = x + 150 posy = int(np.floor(np.sqrt(100**2 - (posx - 250)**2) + 250)) # print(posx,posy) with open('circle_sqrt.txt','a') as f: f.write(str(posx)+','+str(posy)+';') for x in range(349,150,-1):#range(5,0,-1) posx = x posy = int(np.floor(250 - np.sqrt(100**2 - (posx - 250)**2))) # print(posx,posy) with open('circle_sqrt.txt','a') as f: f.write(str(posx)+','+str(posy)+';')
CGtask3/circle_sqrt.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + from __future__ import print_function import time import init_paths import skimage.io as skio import matplotlib.pyplot as plt import demo import os os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" # see issue #152 os.environ["CUDA_VISIBLE_DEVICES"]="0,1,2" import tensorflow from tensorflow.python.client import device_lib print(device_lib.list_local_devices()) # - # ## Initialize Demo Solver # Arg: quality and num_per_dim -> tradeoffs between quality and time spent running # quality affects dense=False, and num_per_dim affects dense=True ckpt_path = './ckpt/exif_final/exif_final.ckpt' exif_demo = demo.Demo(ckpt_path=ckpt_path, use_gpu=0, quality=3.0, num_per_dim=30) # ## Run examples # This takes some time be patient :) # + # MeanShift + dense affinities (as described in our paper) ms_st = time.time() im1, res1 = exif_demo('./images/demo.png', dense=True) # Upsampled via bilinear upsampling print('MeanShift run time: %.3f' % (time.time() - ms_st)) # DBSCAN + sparse anchors db_st = time.time() im2, res2 = exif_demo('./images/demo.png', dense=False) # No upsampling print('DBSCAN run time: %.3f' % (time.time() - db_st)) # + % matplotlib inline plt.subplots(figsize=(16, 8)) plt.subplot(1, 3, 1) plt.title('Input Image') plt.imshow(im1) plt.axis('off') plt.subplot(1, 3, 2) plt.title('Cluster w/ MeanShift') plt.axis('off') plt.imshow(1.0 - res1, cmap='jet', vmin=0.0, vmax=1.0) plt.subplot(1, 3, 3) plt.title('Cluster w/ DBSCAN') plt.axis('off') plt.imshow(res2, cmap='jet', vmin=0.0, vmax=1.0) plt.show() # + # ckpt_path = './ckpt/exif_final/exif_final.ckpt' # exif_demo = Demo(ckpt_path=ckpt_path, use_gpu=1, quality=3.0, num_per_dim=30) images_path = './images/' results_path = './results/' # Need to run multipe images for file_path in os.listdir(images_path): image_path = os.path.join(images_path, file_path) # results_path = os.path.join(cfg.results_path, file) imid = image_path.split('/')[-1].split('.')[0] save_path = os.path.join(results_path, imid + '_result.png') print('Running image %s' % image_path) ms_st = time.time() im_path = image_path im, res = exif_demo(im_path, dense=True) print('MeanShift run time: %.3f' % (time.time() - ms_st)) plt.subplots(figsize=(16, 8)) plt.subplot(1, 3, 1) plt.title('Input Image') plt.imshow(im) plt.axis('off') plt.subplot(1, 3, 2) plt.title('Cluster w/ MeanShift') plt.axis('off') if np.mean(res > 0.5) > 0.5: res = 1.0 - res plt.imshow(res, cmap='jet', vmin=0.0, vmax=1.0) plt.savefig(save_path) print('Result saved %s' % save_path) # - # ## Normalized Cuts # While running the dense version, the algorithm produces a dense affinity which can be used in popular spectral clustering methods. The following code runs both the clustering with MeanShift and segmentation with N-Cuts. # + res = exif_demo.run(im1, use_ncuts=True, blue_high=True) % matplotlib inline plt.subplots(figsize=(16, 8)) plt.subplot(1, 3, 1) plt.title('Input Image') plt.imshow(im1) plt.axis('off') plt.subplot(1, 3, 2) plt.title('Cluster w/ MeanShift') plt.axis('off') plt.imshow(res[0], cmap='jet', vmin=0.0, vmax=1.0) plt.subplot(1, 3, 3) plt.title('Segment with NCuts') plt.axis('off') plt.imshow(res[1], vmin=0.0, vmax=1.0) plt.show()
demo.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [conda env:root] * # language: python # name: conda-root-py # --- from pyckmeans import NucleotideAlignment, CKmeans from pyckmeans.io.nucleotide_alignment import BASE_ENCODING_INVERSE, BASE_ENCODING import numpy as np import time # + tags=[] # import pprofile # profiler = pprofile.Profile() # with profiler: # # aln = NucleotideAlignment.from_file('../../docs/datasets/rhodanthemum_ct85_msl68.snps.phy') # aln = NucleotideAlignment.from_file('C:/Users/Tankr/Downloads/leu_reference_msl12.phy') # # Process profile content: generate a cachegrind file and send it to user. # # You can also write the result to the console: # profiler.print_stats() # + tags=[] # import pprofile # profiler = pprofile.Profile() # with profiler: # # aln = NucleotideAlignment.from_file('../../docs/datasets/rhodanthemum_ct85_msl68.snps.phy', fast_encoding=True) # aln2 = NucleotideAlignment.from_file('C:/Users/Tankr/Downloads/leu_reference_msl12.phy', fast_encoding=True) # # Process profile content: generate a cachegrind file and send it to user. # # You can also write the result to the console: # profiler.print_stats() # + # %%timeit -n 5 -r 1 aln = NucleotideAlignment.from_file('../../docs/datasets/rhodanthemum_ct85_msl68.snps.phy') # + # %%timeit -n 5 -r 1 aln2 = NucleotideAlignment.from_file('../../docs/datasets/rhodanthemum_ct85_msl68.snps.phy', fast_encoding=True) # - t0 = time.time() # aln = NucleotideAlignment.from_file('../../docs/datasets/rhodanthemum_ct85_msl68.snps.phy') aln = NucleotideAlignment.from_file('C:/Users/Tankr/Downloads/leu_reference_msl12.phy', fast_encoding=False) t1 = time.time() aln.sequences[0, :10] t2 = time.time() # aln2 = NucleotideAlignment.from_file('../../docs/datasets/rhodanthemum_ct85_msl68.snps.phy', fast_encoding=True) aln2 = NucleotideAlignment.from_file('C:/Users/Tankr/Downloads/leu_reference_msl12.phy', fast_encoding=True) t3 = time.time() aln2.sequences[0, : 10] # + print(t1 - t0) print(t3 - t2) (aln.sequences == aln2.sequences).all()
pyckmeans/tests/manual_tests.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- ANother approach using Keras Pretrained models # + # %matplotlib inline import numpy as np import pandas as pd import datetime as dt import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import ImageGrid from os import listdir, makedirs from os.path import join, exists, expanduser from tqdm import tqdm from sklearn.metrics import log_loss, accuracy_score from keras.preprocessing import image from keras.applications.vgg16 import VGG16 from keras.applications.resnet50 import ResNet50 from keras.applications import xception from keras.applications import inception_v3 from keras.applications.vgg16 import preprocess_input, decode_predictions from sklearn.linear_model import LogisticRegression # + start = dt.datetime.now() # - # !ls # !ls cache_dir = expanduser(join('~', '.keras')) if not exists(cache_dir): makedirs(cache_dir) models_dir = join(cache_dir, 'models') if not exists(models_dir): makedirs(models_dir) # !cp keraspretrain/*notop* ~/.keras/models/ # !cp keraspretrain/imagenet_class_index.json ~/.keras/models/ # !cp keraspretrain/resnet50* ~/.keras/models/ # !ls ~/.keras/models INPUT_SIZE = 224 NUM_CLASSES = 20 SEED = 1987 data_dir = '../../Data/Dogbreedclassifier/' labels = pd.read_csv(join(data_dir, 'labels.csv')) sample_submission = pd.read_csv(join(data_dir, 'sample_submission.csv')) print(len(listdir(join(data_dir, 'train'))), len(labels)) print(len(listdir(join(data_dir, 'test'))), len(sample_submission)) # + selected_breed_list = list(labels.groupby('breed').count().sort_values(by='id', ascending=False).head(NUM_CLASSES).index) labels = labels[labels['breed'].isin(selected_breed_list)] labels['target'] = 1 labels_pivot = labels.pivot('id', 'breed', 'target').reset_index().fillna(0) np.random.seed(seed=SEED) rnd = np.random.random(len(labels)) train_idx = rnd < 0.8 valid_idx = rnd >= 0.8 y_train = labels_pivot[selected_breed_list].values ytr = y_train[train_idx] yv = y_train[valid_idx] # - def read_img(img_id, train_or_test, size): """Read and resize image. # Arguments img_id: string train_or_test: string 'train' or 'test'. size: resize the original image. # Returns Image as numpy array. """ img = image.load_img(join(data_dir, train_or_test, '%s.jpg' % img_id), target_size=size) img = image.img_to_array(img) return img model = ResNet50(weights='imagenet') j = int(np.sqrt(NUM_CLASSES)) i = int(np.ceil(1. * NUM_CLASSES / j)) fig = plt.figure(1, figsize=(16, 16)) grid = ImageGrid(fig, 111, nrows_ncols=(i, j), axes_pad=0.05) for i, (img_id, breed) in enumerate(labels.loc[labels['rank'] == 1, ['id', 'breed']].values): ax = grid[i] img = read_img(img_id, 'train', (224, 224)) ax.imshow(img / 255.) x = preprocess_input(np.expand_dims(img.copy(), axis=0)) preds = model.predict(x) _, imagenet_class_name, prob = decode_predictions(preds, top=1)[0][0] ax.text(10, 180, 'ResNet50: %s (%.2f)' % (imagenet_class_name , prob), color='w', backgroundcolor='k', alpha=0.8) ax.text(10, 200, 'LABEL: %s' % breed, color='k', backgroundcolor='w', alpha=0.8) ax.axis('off') plt.show() INPUT_SIZE = 224 POOLING = 'avg' x_train = np.zeros((len(labels), INPUT_SIZE, INPUT_SIZE, 3), dtype='float32') for i, img_id in tqdm(enumerate(labels['id'])): img = read_img(img_id, 'train', (INPUT_SIZE, INPUT_SIZE)) x = preprocess_input(np.expand_dims(img.copy(), axis=0)) x_train[i] = x print('Train Images shape: {} size: {:,}'.format(x_train.shape, x_train.size)) # + Xtr = x_train[train_idx] Xv = x_train[valid_idx] print((Xtr.shape, Xv.shape, ytr.shape, yv.shape)) vgg_bottleneck = VGG16(weights='imagenet', include_top=False, pooling=POOLING) train_vgg_bf = vgg_bottleneck.predict(Xtr, batch_size=32, verbose=1) valid_vgg_bf = vgg_bottleneck.predict(Xv, batch_size=32, verbose=1) print('VGG train bottleneck features shape: {} size: {:,}'.format(train_vgg_bf.shape, train_vgg_bf.size)) print('VGG valid bottleneck features shape: {} size: {:,}'.format(valid_vgg_bf.shape, valid_vgg_bf.size)) # + logreg = LogisticRegression(multi_class='multinomial', solver='lbfgs', random_state=SEED) logreg.fit(train_vgg_bf, (ytr * range(NUM_CLASSES)).sum(axis=1)) valid_probs = logreg.predict_proba(valid_vgg_bf) valid_preds = logreg.predict(valid_vgg_bf) # + print('Validation VGG LogLoss {}'.format(log_loss(yv, valid_probs))) print('Validation VGG Accuracy {}'.format(accuracy_score((yv * range(NUM_CLASSES)).sum(axis=1), valid_preds))) # -
Dogbreedclassification.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- lst = list(range(1000)) # + def armstronggen(lst): for item in lst: order = len(str(item)) sum = 0 temp = item while temp >0: digit = temp%10 sum += digit ** order temp //=10 if sum == item: yield item # - list((armstronggen(lst)))
armstrong-genetaror.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [conda env:imaging] # language: python # name: conda-env-imaging-py # --- # # Connected-element Analysis # --- # - Author: <NAME> # - GitHub: [github.com/diegoinacio](https://github.com/diegoinacio) # - Notebook: [connectedComponent_analysis.ipynb](https://github.com/diegoinacio/computer-vision-notebooks/blob/master/Computer-Vision-Fundamentals/connectedComponent_analysis.ipynb) # --- # Find and label bi-dimensional subsets of connected elements. # + # %matplotlib inline import matplotlib.pyplot as plt import numpy as np from connectedComponent_analysis_plot import * from _utils import histogram # - # Given an input grid, find the connected-components. # + grid = [ [ 0, 1, 0, 0, 0, 0, 0, 0], [ 0, 1, 1, 0, 0, 1, 0, 0], [ 0, 1, 0, 0, 0, 1, 0, 0], [ 0, 0, 0, 0, 1, 0, 0, 1], [ 0, 0, 0, 0, 1, 0, 0, 0], [ 0, 0, 0, 0, 1, 0, 0, 0], [ 0, 0, 0, 0, 1, 0, 0, 0], [ 0, 1, 1, 0, 0, 0, 0, 0] ] grid = np.array(grid) histogram(grid, interval=[0, 1]) # - # ## Checking neighborhood # --- # First step is to define which element of the neighborhood is valid, for the current position. def _valid_neighborhood(grid, labels, s, t, M, N): # Check if current member of neighborhood is valid if (s or t) < 0: return None if (s >= M) or (t >= N): return None if labels[s][t]: return None if grid[s][t] <= 0: labels[s][t] = -1 return None return (s, t) # ## 4-conectivity # --- # This analysis consider only the elements connected horizontally or vertically. It means that, for an element $(x, y)$, its neighborhood is only $(x \pm 1, y)$ or $(x, y \pm 1)$. # # $$ \large # \begin{bmatrix} # 0 & & 1 & & 0 \\ # & \nwarrow & \uparrow & \nearrow \\ # 1 & \leftarrow & ? & \rightarrow & 1 \\ # & \swarrow & \downarrow & \searrow \\ # 0 & & 1 & & 0 # \end{bmatrix} # $$ def connect4(grid): ''' Define number of subsets given the 4-connected neighborhood ''' subsets = 0 M, N = len(grid), len(grid[0]) # 4-connected neighborhood offset connected_4 = [(1, 0), (0, 1), (-1, 0), (0, -1)] # Matrix of labels labels = [[0 for _ in range(M)] for _ in range(N)] for m in range(M): for n in range(N): if labels[m][n]: # Ignore visited positions continue if not grid[m][n]: # Ignore invalid positions (p == 0) # and mark its labels as -1 labels[m][n] = -1 continue subsets += 1 connected = [(m, n)] # Init scan from the current position for (s, t) in connected: neighborhood = set([None, *connected]) # Search for valid neighbors neighborhood |= {*[_valid_neighborhood( grid, labels, s + u, t + v, M, N ) for (u, v) in connected_4]} neighborhood.remove(None) # Include valid neighbors to the current scan connected += list([v for v in neighborhood if v not in connected]) # Add subset label to the position [s, t] labels[s][t] = subsets return labels, subsets # + grid_labeled, subsets = connect4(grid) visualize_grid(grid, grid_labeled, subsets) # - # ## 8-conectivity # --- # For each element $(x, y)$, this analysis consider as connected all neighbors that touch one of its corners. # # $$ \large # \begin{bmatrix} # 1 & & 1 & & 1 \\ # & \nwarrow & \uparrow & \nearrow \\ # 1 & \leftarrow & ? & \rightarrow & 1 \\ # & \swarrow & \downarrow & \searrow \\ # 1 & & 1 & & 1 # \end{bmatrix} # $$ def connect8(grid): ''' Define number of subsets given the 8-connected neighborhood ''' subsets = 0 M, N = len(grid), len(grid[0]) # 8-connected neighborhood offset connected_8 = [ (1 , -1), (1 , 0), ( 1, 1), (0 , -1), ( 0, 1), (-1, -1), (-1, 0), (-1, 1) ] # Matrix of labels labels = [[0 for _ in range(M)] for _ in range(N)] for m in range(M): for n in range(N): if labels[m][n]: # Ignore visited positions continue if not grid[m][n]: # Ignore invalid positions (p == 0) # and mark its labels as -1 labels[m][n] = -1 continue subsets += 1 connected = [(m, n)] # Init scan from the current position for (s, t) in connected: neighborhood = set([None, *connected]) # Search for valid neighbors neighborhood |= {*[_valid_neighborhood( grid, labels, s + u, t + v, M, N ) for (u, v) in connected_8]} neighborhood.remove(None) # Include valid neighbors to the current scan connected += list([v for v in neighborhood if v not in connected]) # Add subset label to the position [s, t] labels[s][t] = subsets return labels, subsets # + grid_labeled, subsets = connect8(grid) visualize_grid(grid, grid_labeled, subsets)
Computer-Vision-Fundamentals/connectedComponent_analysis.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: sa2021 # language: python # name: sa2021 # --- import pandas as pd import geopandas as gp import numpy as np import os import math import zipfile # DONT RUN for filename in os.listdir('../raw/slope-aspect/'): if filename.endswith('.zip'): zip_f = zipfile.ZipFile("../raw/slope-aspect/"+filename, "r") f = filename.strip("NASADEM_SC_").strip(".zip") # zip_f.extract("../raw/slope-aspect/hgt/"+f+".hgt") zip_f.extract(f+".aspect") zip_f.close() print(filename) file_path = '../raw/slope-aspect/aspect-raw/' for filename in os.listdir(file_path): filename_noext = filename.strip('.aspect') os.rename(file_path+filename, file_path+filename_noext+'.hgt') final = pd.DataFrame() for filename in os.listdir(file_path): if filename.endswith('.hgt'): lons = [] lats = [] lon_tile = int(filename[4:7]) lat_tile = int(filename[1:3]) siz = os.path.getsize(file_path + filename) dim = int(math.sqrt(siz/2)) assert dim*dim*2 == siz, 'Invalid file size' data = np.fromfile(file_path + filename, np.dtype('>i2'), dim*dim).reshape((dim, dim)) for i in range(0, 3601): lon = lon_tile + 1/7200 + i*(1/3601) lat = lat_tile + 1/7200 + i*(1/3601) lons.append(lon) lats.append(lat) tile_df = pd.DataFrame(data) tile_df.index = lats tile_df = tile_df.T tile_df.index = lons tile_df = tile_df.T tile_df = tile_df.iloc[::50, ::50] tile_final = tile_df.stack().reset_index() tile_final = tile_final.rename(columns = {'level_0': 'lat', 'level_1': 'lon', 0: 'aspect'}) final = final.append(tile_final) print(filename) # tile_final.to_csv(f"../raw/slope-aspect/slope-vector/{filename}.csv", index = False) final = final[final['aspect'] >= 0] final final.to_csv('../raw/slope-aspect/aspect-vector/aspect_50.csv', index = False)
data/processing/aspect.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # ABSTRACT # # The data comes from Austin Animal Center from October 1st, 2013 to March, 2016. Outcomes represent the status of animals as they leave the Animal Center. All animals receive a unique Animal ID during intake. In this competition, you are going to predict the outcome of the animal as they leave the Animal Center. These outcomes include: Adoption, Died, Euthanasia, Return to owner, and Transfer. The train and test data are randomly split. # # We intially started off by applying H2O, wherein the best model was Stacked Ensemble as mentioned by the software and it provided a log-loss of 0.14. However, when we used an existing kaggle kernel, we found that the log-loss was 0.88 on applying Gradient Boosting Machines. From this we can conclude that there was an 84% improvement in the log-loss of the model having used H2O. We also stood 3rd on the public leaderboard for the log-loss value given by h2O # ### IMPORTING LIBRARIES import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import time, warnings, h2o, logging, os, sys, psutil, random import numpy as np from h2o.automl import H2OAutoML from sklearn.ensemble import GradientBoostingClassifier from sklearn import preprocessing from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score, log_loss # # Using H2O: pct_memory=0.95 virtual_memory=psutil.virtual_memory() min_mem_size=int(round(int(pct_memory*virtual_memory.available)/1073741824,0)) print(min_mem_size) # + # Connect to a cluster port_no=random.randint(5555,55555) # h2o.init(strict_version_check=False,min_mem_size_GB=min_mem_size,port=port_no) # start h2o try: h2o.init(strict_version_check=False,min_mem_size_GB=min_mem_size,port=port_no) # start h2o except: logging.critical('h2o.init') h2o.download_all_logs(dirname=logs_path, filename=logfile) h2o.cluster().shutdown() sys.exit(2) # - # ### READING DATA AND PRE-PROCESSING #Setting the path current_dir = os.path.dirname(os.path.abspath(os.getcwd() + "/Kaggle Competition.ipynb")) os.chdir('../data') data_dir = os.getcwd() data_path = data_dir + '/train.csv' #Ingest data train_data = h2o.import_file(path = data_path, destination_frame = "train_data") #Peeking inside the data train_data.show() # used to gain statistical information of the columns present in the dataset train_data.describe() # + target = 'OutcomeType' def get_independent_variables(train_data, targ): C = [name for name in train_data.columns if name != targ] # determine column types ints, reals, enums = [], [], [] for key, val in train_data.types.items(): if key in C: if val == 'enum': enums.append(key) elif val == 'int': ints.append(key) else: reals.append(key) x = ints + enums + reals return x X = get_independent_variables(train_data, target) print(X) y = target # - train_data[y] = train_data[y].asfactor() train_data.describe() # setup autoML # min_mem_size=6 run_time=333 aml = H2OAutoML(max_runtime_secs=run_time) os.getcwd() os.chdir('../logs') logs_path = os.getcwd() logfile = 'logs.txt' # + model_start_time = time.time() try: aml.train(x=X,y=y,training_frame=train_data) # Change training_frame=train except Exception as e: logging.critical('aml.train') h2o.download_all_logs(dirname=logs_path, filename=logfile) h2o.cluster().shutdown() sys.exit(4) # - meta_data={} meta_data['model_execution_time'] = {"classification":(time.time() - model_start_time)} meta_data # d = meta_data['model_execution_time'] # d['classification'] = (time.time() - model_start_time) # meta_data['model_execution_time'] = d print(aml.leaderboard) best_model = h2o.get_model(aml.leaderboard[0,'model_id']) best_model.algo print(best_model.logloss(train = True)) # ## Save the leaderboard model # # There are two ways to save the leader model -- binary format and MOJO format. If you're taking your leader model to production, then usually it is stored in MOJO(Model ObJect, Optimized) format since it's optimized for production use. aml.leader.download_mojo(path = "./") # ## RESULTS # Our evaluation metric is logloss for this dataset. The best on the kaggle leaderboard is logloss = 0.0000 whereas we get the logloss = 0.1485 for the first model while running it on H2O. We stand 3rd on the Kaggle public leaderboard and hence we are in the top 1% in this competition. Following is the leaderboard link for this competition: # # [Kaggle Leaderboard](https://www.kaggle.com/c/shelter-animal-outcomes/leaderboard) # # # Using existing Kaggle Kernel animals = pd.read_csv(data_path) animals.head() # statistical description animals.describe() # detailed information about animals animals.info() # From above we see that the data does not contain any null values and it seems to be complete. # + # converting columns to categorical cat_columns = ['OutcomeType', 'OutcomeSubtype', 'AnimalType', 'SexuponOutcome', 'AgeuponOutcome', 'Breed', 'Color'] for col in cat_columns: animals[col] = animals[col].astype('category') animals.info() # - # dateTime,AnimalId and Name does not play any significant role in classifying outcomeType, hence dropping the column animals = animals.drop('DateTime', axis=1) animals = animals.drop('AnimalID', axis=1) animals = animals.drop('Name', axis=1) cat_columns = ['OutcomeType', 'OutcomeSubtype', 'AnimalType', 'SexuponOutcome', 'AgeuponOutcome', 'Breed', 'Color'] for col in cat_columns: print(animals[col].unique()) # ### Exploring our target variable: sns.countplot(animals.OutcomeType, palette='Set3') # ### Exploring our features: sns.countplot(animals.AnimalType, palette='Set3') sns.countplot(animals.SexuponOutcome, palette='Set3') # ### Feature Engineering: # check different values for SexuponOutcome animals['SexuponOutcome'].value_counts() # check for null values animals['SexuponOutcome'].isna().sum() # lets fill the nan value with unknown type animals['SexuponOutcome'] = animals['SexuponOutcome'].fillna('Unknown') # functions to create new features, sex and neutered def get_sex(x): x = str(x) if x.find('Male') >= 0: return 'male' if x.find('Female') >= 0: return 'female' return 'unknown' def get_neutered(x): x = str(x) if x.find('Spayed') >= 0: return 'neutered' if x.find('Neutered') >= 0: return 'neutered' if x.find('Intact') >= 0: return 'intact' return 'unknown' animals['Sex'] = animals.SexuponOutcome.apply(get_sex) animals['Neutered'] = animals.SexuponOutcome.apply(get_neutered) f, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 4)) sns.countplot(animals.Sex, palette='Set3', ax=ax1) sns.countplot(animals.Neutered, palette='Set3', ax=ax2) # lets now drop SexuponOutcome column animals = animals.drop('SexuponOutcome', axis = 1) def get_mix(x): x = str(x) if x.find('Mix') >= 0: return 'mix' return 'not' animals['Mix'] = animals.Breed.apply(get_mix) sns.countplot(animals.Mix, palette='Set3') # lets now drop Breed column animals = animals.drop('Breed', axis = 1) f, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 4)) sns.countplot(data=animals, x='OutcomeType',hue='Sex', ax=ax1) sns.countplot(data=animals, x='Sex',hue='OutcomeType', ax=ax2) f, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 4)) sns.countplot(data=animals, x='OutcomeType',hue='AnimalType', ax=ax1) sns.countplot(data=animals, x='AnimalType',hue='OutcomeType', ax=ax2) f, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 4)) sns.countplot(data=animals, x='OutcomeType',hue='Neutered', ax=ax1) sns.countplot(data=animals, x='Neutered',hue='OutcomeType', ax=ax2) f, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 4)) sns.countplot(data=animals, x='OutcomeType',hue='Mix', ax=ax1) sns.countplot(data=animals, x='Mix',hue='OutcomeType', ax=ax2) animals['AgeuponOutcome'].value_counts() # check for null values animals['AgeuponOutcome'].isna().sum() # let us now drop these null values animals = animals.dropna(subset=['AgeuponOutcome']) def calc_age_in_years(x): x = str(x) age = int(x.split()[0]) if x.find('year') > -1: return float(format(age,'.2f')) if x.find('month')> -1: return float(format((age / 12),'.2f')) if x.find('week')> -1: return float(format((age / 52),'.2f')) if x.find('day')> -1: return float(format((age / 365),'.2f')) else: return 0 animals['AgeInYears'] = animals.AgeuponOutcome.apply(calc_age_in_years) sns.distplot(animals.AgeInYears, bins = 20, kde=False) animals['AgeInYears'].describe() def calc_age_category(x): if x <= 10: return 'young' else: return 'adult' animals['AgeCategory'] = animals.AgeInYears.apply(calc_age_category) f, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 4)) sns.countplot(data=animals, x='OutcomeType',hue='AgeCategory', ax=ax1) sns.countplot(data=animals, x='AgeCategory',hue='OutcomeType', ax=ax2) # lets now drop AgeuponOutcome column animals = animals.drop('AgeuponOutcome', axis = 1) animals.info() # converting engineered features to categorical types cat_columns = ['Sex', 'Neutered', 'Mix', 'AgeCategory'] for col in cat_columns: animals[col] = animals[col].astype('category') animals.info() # explore OutcomeSubtype feature values animals['OutcomeSubtype'].value_counts() # check for null values animals['OutcomeSubtype'].isna().sum() # explore shape of data animals.shape # From above, we see that half of the values in OutcomeSubtype is null. Hence, let us drop that column. animals = animals.drop('OutcomeSubtype', axis = 1) # Also, there is a redundant AgeCategory column for data modelling as we already have AgeInYears. #Hence, let us now drop AgeCategory column as well. animals = animals.drop('AgeCategory', axis = 1) # ### Data Modeling: animals.info() def convert_to_numeric(df): for col in ['AnimalType', 'Color', 'OutcomeType', 'Sex', 'Neutered', 'Mix', 'AgeInYears']: if col in df.columns: _col = "_%s" % (col) values = df[col].unique() _values = dict(zip(values, range(len(values)))) df[_col] = df[col].map(_values).astype(int) df = df.drop(col, axis = 1) return df # converting columns to numeric animals = convert_to_numeric(animals) animals.columns animals = animals[['_AnimalType', '_Color', '_Sex', '_Neutered', '_Mix', '_AgeInYears', '_OutcomeType']] Y = animals['_OutcomeType'] X = animals[['_AnimalType', '_Color', '_Sex', '_Neutered', '_Mix', '_AgeInYears']] X_train_sub, X_validation_sub, y_train_sub, y_validation_sub = train_test_split(X, Y, random_state=20) classifiers = [GradientBoostingClassifier()] for classifier in classifiers: animal_log = classifier animal_log.fit(X_train_sub, y_train_sub) show_validation = True if (show_validation == True): dog_y_probs = animal_log.predict_proba(X_validation_sub) dog_y_pred = animal_log.predict(X_validation_sub) print(type(classifier)) print("accuracy_score:", accuracy_score(y_validation_sub, dog_y_pred)) print("log_loss:", log_loss(y_validation_sub, dog_y_probs)) elif (show_validation == False): dog_y_probs = animal_log.predict_proba(X_train_sub) dog_y_pred = animal_log.predict(X_train_sub) print(type(classifier)) print("accuracy_score:", accuracy_score(y_train_sub, dog_y_pred)) print("log_loss:", log_loss(y_train_sub, dog_y_probs)) #fit dog data animal_log.fit(X, Y) print(animal_log.classes_) #plot feature importance plt.figure(0) plt.title("Feature Importance") print(animal_log.feature_importances_) print(X.columns) importance = animal_log.feature_importances_ sns.barplot(y=X.columns, x=importance) # ### Summary: # # We initially did the EDA on the entire data. Since the data had lots of categorical columns we went about converting them into numeric ones. Having done that and dropping insignificant columns while removing NaN values, we finally modelled our data using Gradient Boosting Machines algorithm. # # Here, we find that the logloss is 0.88 which is not better than the one which we achieved from H2O. Hence we conclude that H2O gives better results using Stacked Ensemble than Gradient Boosting Machine algorithm. # # RESULTS # # **1. Using H20:** </br> # We find the logloss using H2o for best model to be - 0.14. This leads us to the top 1% (3rd) on the public leaderboard on kaggle # # # # **2. Using existing kernel:** </br> # After expanding the EDA, we added data modeling section to find the logloss using Gradient Boosting Method to be - 0.88 # # # CONCLUSION # # Hence, the conclusion is that H2o outperforms to get the best logloss score with ensemble technique to solve the classification problem where we need to classify the outcome type of the dog. We achieve 84% improvement in the log-loss value having used H2O # # CONTRIBUTIONS # # We derived 20% from the existing kernel and performend the remaining 80% on our own. # Individual contributions: # 1. <NAME> - 40% # 2. <NAME> - 40% # # CITATIONS # # 1. [Existing kernel](https://www.kaggle.com/aquatic/entity-embedding-neural-net) # 2. [H2O](https://h2o-release.s3.amazonaws.com/h2o/rel-ueno/2/docs-website/h2o-docs/pojo-quick-start.html) # 3. [H2O AutoML](https://github.com/h2oai/h2o-tutorials/blob/master/h2o-world-2017/automl/Python/automl_binary_classification_product_backorders.ipynb) # 4. [<NAME>](https://github.com/nikbearbrown) # 5. [Gradient Boosting Machines](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.GradientBoostingClassifier.html) # # LICENSE # # Copyright 2019 <NAME>, <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
code/Kaggle Competition.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Random Forest # In random forests, each tree in the ensemble is built from a **sample drawn with replacement** (i.e., a bootstrap sample) from the training set. In addition, when splitting a node during the construction of the tree, the split that is chosen is no longer the best split among all features. Instead, the split that is picked is the best split among a **random subset of the features**. # # As a result of this randomness, the bias of the forest usually slightly increases (with respect to the bias of a single non-random tree) but, due to averaging, its variance also decreases, usually more than compensating for the increase in bias, hence yielding an overall better model. # # ## Data Preparation import pandas as pd import numpy as np import matplotlib.pyplot as plt # %matplotlib inline plt.style.use('fivethirtyeight') df = pd.read_csv("data/historical_loan.csv") # refine the data df.years = df.years.fillna(np.mean(df.years)) #Load the preprocessing module from sklearn import preprocessing categorical_variables = df.dtypes[df.dtypes=="object"].index.tolist() for i in categorical_variables: lbl = preprocessing.LabelEncoder() lbl.fit(list(df[i])) df[i] = lbl.transform(df[i]) df.head() X = df.iloc[:,1:8] y = df.iloc[:,0] # ## Implementing Random Forest from sklearn.ensemble import RandomForestClassifier clf = RandomForestClassifier() clf.fit(X, y) clf.me # #### Key input parameters (in addition to decision trees) # - **bootstrap**: Whether bootstrap samples are used when building trees # - **max_features**: The number of features to consider when looking for the best split (auto = sqrt) # - **n_estimators**: The number of trees in the forest # - **oob_score**: Whether to use out-of-bag samples to estimate the generalization accuracy # #### Key output parameters # # - **Feature Importance**: The higher, the more important the feature # - **Out-of-Bag Score**: Validation score of the training dataset obtained using an out-of-bag estimate. # # ## Feature Importance # # There are several ways to get feature "importances" with no strict consensus on what it means. # # #### Mean Decrease Impurity # # The relative rank (i.e. depth) of a feature used as a decision node in a tree can be used to assess the relative importance of that feature with respect to the predictability of the target variable. Features used at the top of the tree contribute to the final prediction decision of a larger fraction of the input samples. The **expected fraction of the samples they contribute to** can thus be used as an estimate of the relative importance of the features. # # In scikit-learn, it is implemented by using "gini importance" or "mean decrease impurity" and is defined as the total decrease in node impurity (weighted by the probability of reaching that node (which is approximated by the proportion of samples reaching that node)) averaged over all trees of the ensemble. # # # #### Mean Decrease Accuracy # # In the literature or in some other packages, you can also find feature importances implemented as the "mean decrease accuracy". Basically, the idea is to measure the decrease in accuracy on OOB data when you randomly permute the values for that feature. If the decrease is low, then the feature is not important, and vice-versa. # # # # # By averaging those expected activity rates over random trees one can reduce the variance of such an estimate and use it for feature selection. importances = clf.feature_importances_ # Importance of the features in the forest importances #Calculate the standard deviation of variable importance std = np.std([tree.feature_importances_ for tree in clf.estimators_], axis=0) std indices = np.argsort(importances)[::-1] indices length = X.shape[1] labels = [] for i in range(length): labels.append(X.columns[indices[i]]) # Plot the feature importances of the forest plt.figure(figsize=(16, 6)) plt.title("Feature importances") plt.bar(range(length), importances[indices], yerr=std[indices], align="center") plt.xticks(range(length), labels) plt.xlim([-1, length]) plt.show() # ### Exercise 1 # Calculate the Feature Importance plot for max_depth = 6 # ## Out-of-Bag Error # The out-of-bag (OOB) error is the average error for each training observation calculated using predictions from the trees that do not contain it in their respective bootstrap sample. This allows the RandomForest to be fit and validated whilst being trained. import warnings warnings.filterwarnings('ignore') clf2 = RandomForestClassifier(warm_start=True, class_weight="balanced", oob_score=True, max_features=None) clf2.fit(X, y) clf2.oob_score_ min_estimators = 10 max_estimators = 50 error_rate = [] for i in range(min_estimators, max_estimators + 1): clf2.set_params(n_estimators=i) clf2.fit(X, y) oob_error = 1 - clf2.oob_score_ error_rate.append(oob_error) error_rate_indice = [x for x in range(min_estimators, max_estimators + 1)] plt.figure() plt.figure(figsize=(16, 6)) plt.plot(error_rate_indice, error_rate) plt.xlim(min_estimators, max_estimators) plt.xlabel("n_estimators") plt.ylabel("OOB error rate") plt.show() # ### Exercise 2 # Calculate the OOB error rate plot with max_feature = sqrt # ### Exercise 3 # Calculate the OOB error rate plot with max_depth = 6 # ## Exercise 4 # Plot the change of AUC score for change in max-depth and no of estimators
Module-03e-Model-RandomForest.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import turtle x = 0 while x<300: y = x**2/300 #x**2 is the same as x*x turtle.goto(x, y) x = x + 100 # + num_pts=6 for i in range (num_pts): turtle.left(360/num_pts) turtle.forward(100) # - turtle.mainloop()
unit 6.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: 'Python 3.7.5 64-bit (''env_py37'': conda)' # language: python # name: python37564bitenvpy37conda17150a11545f4ac4a3ea6d7b215219bc # --- # # Using the Modified Gravity emulator # Users only need to use the _emu_ function for predicting the enhancement in the matter power spectra, *P<sub>MG</sub>(k)/P<sub>LCDM</sub>(k)* for *f(R)* Hu-Sawicki model from mgemu import emu # ## The emulator takes 6 inputs shown below. ### LCDM parameters h=0.67 # See README and the accompanying paper regarding the value of h. Omh2=(h**2)*0.281 ns=0.971 s8=0.82 ### Hu-Sawicki model parameters fr0=1e-5 n=1 ### Redshift z=0.3 # ## Output from the _mgemu.emu_ function will be the binned power spectra enhancement *P<sub>MG</sub>(k)/P<sub>LCDM</sub>(k)* and wavenumber *k* in 213 bins. pkratio, k = emu(Omh2=Omh2, ns=ns, s8=s8, fR0=fr0, n=n, z=z) # ## Inputs can be any value within the range of the parameters. # - 0.12 ≤ Ω<sub>m</sub>h<sup>2</sup> ≤ 0.15 # - 0.85 ≤ n<sub>s</sub> ≤ 1.1 # - 0.7≤ σ<sub>8</sub> ≤0.9 # - 10<sup>−8</sup> ≤ f<sub>R<sub>0</sub></sub> ≤10<sup>−4</sup> # - 0 ≤ n ≤4 # - 0 ≤ z ≤ 50 # # ## Although the wavenumber range of the emulator is up to 0 ≤ k ≤ 3.5 h/Mpc, we do not advocate the use of the emulator for small scales beyond k ~ 1.0 h/Mpc. # + import matplotlib.pylab as plt import numpy as np plt.figure(1, figsize=(9, 6) ) fR0_arr= np.logspace(-6, -4, 10) for i in range(10): fR0 = fR0_arr[i] pkratio, k = emu(Omh2=Omh2, ns=ns, s8=s8, fR0=fR0, n=n, z=z) plt.plot(k, pkratio) plt.xscale('log') plt.ylabel(r'$P_MG(k)/P_{LCDM}(k)$', fontsize=23) plt.xlabel(r'$k$', fontsize=23) # plt.xlim(0, 1.01) plt.show() # -
notebooks/emulator_plot.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import pandas as pd import numpy as np from sklearn.model_selection import train_test_split import seaborn as sns sns.set_style("whitegrid") import matplotlib.pyplot as plt # %matplotlib inline import matplotlib as mpl from copy import deepcopy # ### Import data data = pd.read_csv('clustering-datasets.csv') data data.describe() # ### Check for the missing values missing_values = data.isnull().sum() missing_values def boxPlot(data1, data2): mpl.rcParams['figure.dpi'] = 100 plt.figure(figsize=(60, 60)) f, axes = plt.subplots(1, 2) sns.boxplot(y=data1, ax=axes[0]) sns.boxplot(y=data2, ax=axes[1]) plt.subplots_adjust(wspace=1) boxPlot(data["overall"], data["potential"]) # #### Formula to find out upper limit and lower limit from Outliers def setbound(datacolumn): sorted(datacolumn) Q1,Q3 = np.percentile(datacolumn , [25,75]) IQR = Q3 - Q1 print(Q1, Q3) lower_range = Q1 - (1.5 * IQR) upper_range = Q3 + (1.5 * IQR) return lower_range,upper_range # #### Get the outliers data def getOutlierData(data, mainData): lowerbound,upperbound = setbound(data) return mainData[(data < lowerbound) | (data > upperbound)] # #### Drop the outliers data def outliering(data1, data2, mainData): while True: lowerbound,upperbound = setbound(data1) res1 = getOutlierData(data1, mainData) # print(getOutlierData(data1, mainData)) lowerbound,upperbound = setbound(data2) # print(getOutlierData(data2, mainData)) res2 = getOutlierData(data2, mainData) res = pd.concat([res1,res2]).drop_duplicates() res = res.index print('Total Outliers = ',len(res)) print('=== The Outliers ===') print(res) mainData.drop(res, inplace=True) if(len(res)==0): break print("BLOXPOT AFTER OUTLIERING") boxPlot(mainData['overall'], mainData['potential']) return mainData newData = outliering(data["overall"], data["potential"], data) plt.scatter(newData['overall'], newData['potential']) plt.xlabel('overall') plt.ylabel('potential') k = 5 # #### Function to generate centroids def generateCentroids(k, data1, data2): # Randomize value from 0 until max of data depend on size of k xCentroids = np.random.randint(np.min(data1), np.max(data1), size=k) yCentroids = np.random.randint(np.min(data1), np.max(data2), size=k) # Merge X and Y Centroids centroids = np.array(list(zip(xCentroids, yCentroids))) return centroids, xCentroids, yCentroids # ##### Generate centroids centroids, x, y = generateCentroids(k,newData['overall'],newData['potential']) centroids.sort() centroids # ##### Plot first centroids plt.scatter(newData['overall'], newData['potential'], c='#050505', s=7) plt.scatter(x, y, marker='*', s=200, c='g') # #### Euclidean Distance Formula def euclideanDistance(data, centroids, ax=1): return np.linalg.norm(data - centroids, axis=ax) # #### Convert data to array npData = np.array(newData) npData # #### Formula to update centroids based on the data def updateCentroids(idx, clusters, data): points = np.array([data[j] for j in range(len(data)) if clusters[j] == idx]) return points # ## K-Means Function def kMeans(k, data, centroids): # Set all cluster to 0 clusters = np.zeros(len(data)) clusters # assign old centroid as 0 oldCentroid = np.zeros(centroids.shape) print("INITIALIZE CENTROIDS ", oldCentroid) # Error func. - Distance between new centroids and old centroids error = euclideanDistance(centroids, oldCentroid,None) print("INITIALIZE ERROR ", error) idx=0 while error != 0: # Assigning each value to its closest cluster for i in range(len(data)): distances = euclideanDistance(data[i], centroids) cluster = np.argmin(distances) clusters[i] = cluster # Storing the old centroid values oldCentroid = deepcopy(centroids) # Finding the new centroids by taking the average value for i in range(k): points = updateCentroids(i,clusters, data) #[data[j] for j in range(len(data)) if clusters[j] == i] centroids[i] = np.mean(points, axis=0) error = euclideanDistance(centroids, oldCentroid, None) return centroids, clusters lastCentroids, clusters = kMeans(k, npData, centroids) lastCentroids clusters # ### The clustering result # + colors = ['r', 'g', 'b', 'y', 'c', 'm'] fig, ax = plt.subplots() for i in range(k): points = updateCentroids(i, clusters, npData) ax.scatter(points[:, 0], points[:, 1], c=colors[i]) plt.scatter(lastCentroids[:, 0], lastCentroids[:, 1], marker='*', s=100, c='#050505') # - # <p>Copyright &copy; 2020 <a href=https://www.linkedin.com/in/pratamays/><NAME></a> </p>
.ipynb_checkpoints/Clustering-checkpoint.ipynb
// --- // jupyter: // jupytext: // text_representation: // extension: .cpp // format_name: light // format_version: '1.5' // jupytext_version: 1.14.4 // kernelspec: // display_name: Xeus-C++11 // language: C++11 // name: xeus-cling-cpp11 // --- // # C++ learnxinyminutes (env (base)) // https://learnxinyminutes.com/docs/c++/ // + ////////////////// // Comparison to C ////////////////// // C++ is _almost_ a superset of C and shares its basic syntax for // variable declarations, primitive types, and functions. // Just like in C, your program's entry point is a function called // main with an integer return type. // This value serves as the program's exit status. // See http://en.wikipedia.org/wiki/Exit_status for more information. int main(int argc, char** argv) { // Command line arguments are passed in by argc and argv in the same way // they are in C. // argc indicates the number of arguments, // and argv is an array of C-style strings (char*) // representing the arguments. // The first argument is the name by which the program was called. // argc and argv can be omitted if you do not care about arguments, // giving the function signature of int main() // An exit status of 0 indicates success. return 0; } // However, C++ varies in some of the following ways: // In C++, character literals are chars sizeof('c') == sizeof(char) == 1 // In C, character literals are ints sizeof('c') == sizeof(int) // C++ has strict prototyping void func(); // function which accepts no arguments // In C void func(); // function which may accept any number of arguments // Use nullptr instead of NULL in C++ int* ip = nullptr; // C standard headers are available in C++, // but are prefixed with "c" and have no .h suffix. #include <cstdio> int main() { printf("Hello, world!\n"); return 0; } /////////////////////// // Function overloading /////////////////////// // C++ supports function overloading // provided each function takes different parameters. void print(char const* myString) { printf("String %s\n", myString); } void print(int myInt) { printf("My int is %d", myInt); } int main() { print("Hello"); // Resolves to void print(const char*) print(15); // Resolves to void print(int) } ///////////////////////////// // Default function arguments ///////////////////////////// // You can provide default arguments for a function // if they are not provided by the caller. void doSomethingWithInts(int a = 1, int b = 4) { // Do something with the ints here } int main() { doSomethingWithInts(); // a = 1, b = 4 doSomethingWithInts(20); // a = 20, b = 4 doSomethingWithInts(20, 5); // a = 20, b = 5 } // Default arguments must be at the end of the arguments list. void invalidDeclaration(int a = 1, int b) // Error! { } ///////////// // Namespaces ///////////// // Namespaces provide separate scopes for variable, function, // and other declarations. // Namespaces can be nested. namespace First { namespace Nested { void foo() { printf("This is First::Nested::foo\n"); } } // end namespace Nested } // end namespace First namespace Second { void foo() { printf("This is Second::foo\n"); } } void foo() { printf("This is global foo\n"); } int main() { // Includes all symbols from namespace Second into the current scope. Note // that simply foo() no longer works, since it is now ambiguous whether // we're calling the foo in namespace Second or the top level. using namespace Second; Second::foo(); // prints "This is Second::foo" First::Nested::foo(); // prints "This is First::Nested::foo" ::foo(); // prints "This is global foo" } /////////////// // Input/Output /////////////// // C++ input and output uses streams // cin, cout, and cerr represent stdin, stdout, and stderr. // << is the insertion operator and >> is the extraction operator. #include <iostream> // Include for I/O streams using namespace std; // Streams are in the std namespace (standard library) int main() { int myInt; // Prints to stdout (or terminal/screen) cout << "Enter your favorite number:\n"; // Takes in input cin >> myInt; // cout can also be formatted cout << "Your favorite number is " << myInt << "\n"; // prints "Your favorite number is <myInt>" cerr << "Used for error messages"; } ////////// // Strings ////////// // Strings in C++ are objects and have many member functions #include <string> using namespace std; // Strings are also in the namespace std (standard library) string myString = "Hello"; string myOtherString = " World"; // // + is used for concatenation. cout << myString + myOtherString; // "Hello World" cout << myString + " You"; // "Hello You" // C++ strings are mutable. myString.append(" Dog"); cout << myString; // "Hello Dog" ///////////// // References ///////////// // In addition to pointers like the ones in C, // C++ has _references_. // These are pointer types that cannot be reassigned once set // and cannot be null. // They also have the same syntax as the variable itself: // No * is needed for dereferencing and // & (address of) is not used for assignment. using namespace std; string foo = "I am foo"; string bar = "I am bar"; string& fooRef = foo; // This creates a reference to foo. fooRef += ". Hi!"; // Modifies foo through the reference cout << fooRef; // Prints "I am foo. Hi!" // Doesn't reassign "fooRef". This is the same as "foo = bar", and // foo == "I am bar" // after this line. cout << &fooRef << endl; //Prints the address of foo fooRef = bar; cout << &fooRef << endl; //Still prints the address of foo cout << fooRef; // Prints "I am bar" //The address of fooRef remains the same, i.e. it is still referring to foo. const string& barRef = bar; // Create a const reference to bar. // Like C, const values (and pointers and references) cannot be modified. barRef += ". Hi!"; // Error, const references cannot be modified. // Sidetrack: Before we talk more about references, we must introduce a concept // called a temporary object. Suppose we have the following code: string tempObjectFun() { ... } string retVal = tempObjectFun(); // What happens in the second line is actually: // - a string object is returned from tempObjectFun // - a new string is constructed with the returned object as argument to the // constructor // - the returned object is destroyed // The returned object is called a temporary object. Temporary objects are // created whenever a function returns an object, and they are destroyed at the // end of the evaluation of the enclosing expression (Well, this is what the // standard says, but compilers are allowed to change this behavior. Look up // "return value optimization" if you're into this kind of details). So in this // code: foo(bar(tempObjectFun())) // assuming foo and bar exist, the object returned from tempObjectFun is // passed to bar, and it is destroyed before foo is called. // Now back to references. The exception to the "at the end of the enclosing // expression" rule is if a temporary object is bound to a const reference, in // which case its life gets extended to the current scope: void constReferenceTempObjectFun() { // constRef gets the temporary object, and it is valid until the end of this // function. const string& constRef = tempObjectFun(); ... } // Another kind of reference introduced in C++11 is specifically for temporary // objects. You cannot have a variable of its type, but it takes precedence in // overload resolution: void someFun(string& s) { ... } // Regular reference void someFun(string&& s) { ... } // Reference to temporary object string foo; someFun(foo); // Calls the version with regular reference someFun(tempObjectFun()); // Calls the version with temporary reference // For example, you will see these two versions of constructors for // std::basic_string: basic_string(const basic_string& other); basic_string(basic_string&& other); // Idea being if we are constructing a new string from a temporary object (which // is going to be destroyed soon anyway), we can have a more efficient // constructor that "salvages" parts of that temporary string. You will see this // concept referred to as "move semantics". ///////////////////// // Enums ///////////////////// // Enums are a way to assign a value to a constant most commonly used for // easier visualization and reading of code enum ECarTypes { Sedan, Hatchback, SUV, Wagon }; ECarTypes GetPreferredCarType() { return ECarTypes::Hatchback; } // As of C++11 there is an easy way to assign a type to the enum which can be // useful in serialization of data and converting enums back-and-forth between // the desired type and their respective constants enum ECarTypes : uint8_t { Sedan, // 0 Hatchback, // 1 SUV = 254, // 254 Hybrid // 255 }; void WriteByteToFile(uint8_t InputValue) { // Serialize the InputValue to a file } void WritePreferredCarTypeToFile(ECarTypes InputCarType) { // The enum is implicitly converted to a uint8_t due to its declared enum type WriteByteToFile(InputCarType); } // On the other hand you may not want enums to be accidentally cast to an integer // type or to other enums so it is instead possible to create an enum class which // won't be implicitly converted enum class ECarTypes : uint8_t { Sedan, // 0 Hatchback, // 1 SUV = 254, // 254 Hybrid // 255 }; void WriteByteToFile(uint8_t InputValue) { // Serialize the InputValue to a file } void WritePreferredCarTypeToFile(ECarTypes InputCarType) { // Won't compile even though ECarTypes is a uint8_t due to the enum // being declared as an "enum class"! WriteByteToFile(InputCarType); } ////////////////////////////////////////// // Classes and object-oriented programming ////////////////////////////////////////// // First example of classes #include <iostream> // Declare a class. // Classes are usually declared in header (.h or .hpp) files. class Dog { // Member variables and functions are private by default. std::string name; int weight; // All members following this are public // until "private:" or "protected:" is found. public: // Default constructor Dog(); // Member function declarations (implementations to follow) // Note that we use std::string here instead of placing // using namespace std; // above. // Never put a "using namespace" statement in a header. void setName(const std::string& dogsName); void setWeight(int dogsWeight); // Functions that do not modify the state of the object // should be marked as const. // This allows you to call them if given a const reference to the object. // Also note the functions must be explicitly declared as _virtual_ // in order to be overridden in derived classes. // Functions are not virtual by default for performance reasons. virtual void print() const; // Functions can also be defined inside the class body. // Functions defined as such are automatically inlined. void bark() const { std::cout << name << " barks!\n"; } // Along with constructors, C++ provides destructors. // These are called when an object is deleted or falls out of scope. // This enables powerful paradigms such as RAII // (see below) // The destructor should be virtual if a class is to be derived from; // if it is not virtual, then the derived class' destructor will // not be called if the object is destroyed through a base-class reference // or pointer. virtual ~Dog(); }; // A semicolon must follow the class definition. // Class member functions are usually implemented in .cpp files. Dog::Dog() { std::cout << "A dog has been constructed\n"; } // Objects (such as strings) should be passed by reference // if you are modifying them or const reference if you are not. void Dog::setName(const std::string& dogsName) { name = dogsName; } void Dog::setWeight(int dogsWeight) { weight = dogsWeight; } // Notice that "virtual" is only needed in the declaration, not the definition. void Dog::print() const { std::cout << "Dog is " << name << " and weighs " << weight << "kg\n"; } Dog::~Dog() { std::cout << "Goodbye " << name << "\n"; } int main() { Dog myDog; // prints "A dog has been constructed" myDog.setName("Barkley"); myDog.setWeight(10); myDog.print(); // prints "Dog is Barkley and weighs 10 kg" return 0; } // prints "Goodbye Barkley" // Inheritance: // This class inherits everything public and protected from the Dog class // as well as private but may not directly access private members/methods // without a public or protected method for doing so class OwnedDog : public Dog { public: void setOwner(const std::string& dogsOwner); // Override the behavior of the print function for all OwnedDogs. See // http://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping // for a more general introduction if you are unfamiliar with // subtype polymorphism. // The override keyword is optional but makes sure you are actually // overriding the method in a base class. void print() const override; private: std::string owner; }; // Meanwhile, in the corresponding .cpp file: void OwnedDog::setOwner(const std::string& dogsOwner) { owner = dogsOwner; } void OwnedDog::print() const { Dog::print(); // Call the print function in the base Dog class std::cout << "Dog is owned by " << owner << "\n"; // Prints "Dog is <name> and weights <weight>" // "Dog is owned by <owner>" } ////////////////////////////////////////// // Initialization and Operator Overloading ////////////////////////////////////////// // In C++ you can overload the behavior of operators such as +, -, *, /, etc. // This is done by defining a function which is called // whenever the operator is used. #include <iostream> using namespace std; class Point { public: // Member variables can be given default values in this manner. double x = 0; double y = 0; // Define a default constructor which does nothing // but initialize the Point to the default value (0, 0) Point() { }; // The following syntax is known as an initialization list // and is the proper way to initialize class member values Point (double a, double b) : x(a), y(b) { /* Do nothing except initialize the values */ } // Overload the + operator. Point operator+(const Point& rhs) const; // Overload the += operator Point& operator+=(const Point& rhs); // It would also make sense to add the - and -= operators, // but we will skip those for brevity. }; Point Point::operator+(const Point& rhs) const { // Create a new point that is the sum of this one and rhs. return Point(x + rhs.x, y + rhs.y); } Point& Point::operator+=(const Point& rhs) { x += rhs.x; y += rhs.y; return *this; } int main () { Point up (0,1); Point right (1,0); // This calls the Point + operator // Point up calls the + (function) with right as its parameter Point result = up + right; // Prints "Result is upright (1,1)" cout << "Result is upright (" << result.x << ',' << result.y << ")\n"; return 0; } ///////////////////// // Templates ///////////////////// // Templates in C++ are mostly used for generic programming, though they are // much more powerful than generic constructs in other languages. They also // support explicit and partial specialization and functional-style type // classes; in fact, they are a Turing-complete functional language embedded // in C++! // We start with the kind of generic programming you might be familiar with. To // define a class or function that takes a type parameter: template<class T> class Box { public: // In this class, T can be used as any other type. void insert(const T&) { ... } }; // During compilation, the compiler actually generates copies of each template // with parameters substituted, so the full definition of the class must be // present at each invocation. This is why you will see template classes defined // entirely in header files. // To instantiate a template class on the stack: Box<int> intBox; // and you can use it as you would expect: intBox.insert(123); // You can, of course, nest templates: Box<Box<int> > boxOfBox; boxOfBox.insert(intBox); // Until C++11, you had to place a space between the two '>'s, otherwise '>>' // would be parsed as the right shift operator. // You will sometimes see // template<typename T> // instead. The 'class' keyword and 'typename' keywords are _mostly_ // interchangeable in this case. For the full explanation, see // http://en.wikipedia.org/wiki/Typename // (yes, that keyword has its own Wikipedia page). // Similarly, a template function: template<class T> void barkThreeTimes(const T& input) { input.bark(); input.bark(); input.bark(); } // Notice that nothing is specified about the type parameters here. The compiler // will generate and then type-check every invocation of the template, so the // above function works with any type 'T' that has a const 'bark' method! Dog fluffy; fluffy.setName("Fluffy") barkThreeTimes(fluffy); // Prints "Fluffy barks" three times. // Template parameters don't have to be classes: template<int Y> void printMessage() { cout << "Learn C++ in " << Y << " minutes!" << endl; } // And you can explicitly specialize templates for more efficient code. Of // course, most real-world uses of specialization are not as trivial as this. // Note that you still need to declare the function (or class) as a template // even if you explicitly specified all parameters. template<> void printMessage<10>() { cout << "Learn C++ faster in only 10 minutes!" << endl; } printMessage<20>(); // Prints "Learn C++ in 20 minutes!" printMessage<10>(); // Prints "Learn C++ faster in only 10 minutes!" ///////////////////// // Exception Handling ///////////////////// // The standard library provides a few exception types // (see http://en.cppreference.com/w/cpp/error/exception) // but any type can be thrown an as exception #include <exception> #include <stdexcept> // All exceptions thrown inside the _try_ block can be caught by subsequent // _catch_ handlers. try { // Do not allocate exceptions on the heap using _new_. throw std::runtime_error("A problem occurred"); } // Catch exceptions by const reference if they are objects catch (const std::exception& ex) { std::cout << ex.what(); } // Catches any exception not caught by previous _catch_ blocks catch (...) { std::cout << "Unknown exception caught"; throw; // Re-throws the exception } /////// // RAII /////// // RAII stands for "Resource Acquisition Is Initialization". // It is often considered the most powerful paradigm in C++ // and is the simple concept that a constructor for an object // acquires that object's resources and the destructor releases them. // To understand how this is useful, // consider a function that uses a C file handle: void doSomethingWithAFile(const char* filename) { // To begin with, assume nothing can fail. FILE* fh = fopen(filename, "r"); // Open the file in read mode. doSomethingWithTheFile(fh); doSomethingElseWithIt(fh); fclose(fh); // Close the file handle. } // Unfortunately, things are quickly complicated by error handling. // Suppose fopen can fail, and that doSomethingWithTheFile and // doSomethingElseWithIt return error codes if they fail. // (Exceptions are the preferred way of handling failure, // but some programmers, especially those with a C background, // disagree on the utility of exceptions). // We now have to check each call for failure and close the file handle // if a problem occurred. bool doSomethingWithAFile(const char* filename) { FILE* fh = fopen(filename, "r"); // Open the file in read mode if (fh == nullptr) // The returned pointer is null on failure. return false; // Report that failure to the caller. // Assume each function returns false if it failed if (!doSomethingWithTheFile(fh)) { fclose(fh); // Close the file handle so it doesn't leak. return false; // Propagate the error. } if (!doSomethingElseWithIt(fh)) { fclose(fh); // Close the file handle so it doesn't leak. return false; // Propagate the error. } fclose(fh); // Close the file handle so it doesn't leak. return true; // Indicate success } // C programmers often clean this up a little bit using goto: bool doSomethingWithAFile(const char* filename) { FILE* fh = fopen(filename, "r"); if (fh == nullptr) return false; if (!doSomethingWithTheFile(fh)) goto failure; if (!doSomethingElseWithIt(fh)) goto failure; fclose(fh); // Close the file return true; // Indicate success failure: fclose(fh); return false; // Propagate the error } // If the functions indicate errors using exceptions, // things are a little cleaner, but still sub-optimal. void doSomethingWithAFile(const char* filename) { FILE* fh = fopen(filename, "r"); // Open the file in read mode if (fh == nullptr) throw std::runtime_error("Could not open the file."); try { doSomethingWithTheFile(fh); doSomethingElseWithIt(fh); } catch (...) { fclose(fh); // Be sure to close the file if an error occurs. throw; // Then re-throw the exception. } fclose(fh); // Close the file // Everything succeeded } // Compare this to the use of C++'s file stream class (fstream) // fstream uses its destructor to close the file. // Recall from above that destructors are automatically called // whenever an object falls out of scope. void doSomethingWithAFile(const std::string& filename) { // ifstream is short for input file stream std::ifstream fh(filename); // Open the file // Do things with the file doSomethingWithTheFile(fh); doSomethingElseWithIt(fh); } // The file is automatically closed here by the destructor // This has _massive_ advantages: // 1. No matter what happens, // the resource (in this case the file handle) will be cleaned up. // Once you write the destructor correctly, // It is _impossible_ to forget to close the handle and leak the resource. // 2. Note that the code is much cleaner. // The destructor handles closing the file behind the scenes // without you having to worry about it. // 3. The code is exception safe. // An exception can be thrown anywhere in the function and cleanup // will still occur. // All idiomatic C++ code uses RAII extensively for all resources. // Additional examples include // - Memory using unique_ptr and shared_ptr // - Containers - the standard library linked list, // vector (i.e. self-resizing array), hash maps, and so on // all automatically destroy their contents when they fall out of scope. // - Mutexes using lock_guard and unique_lock // containers with object keys of non-primitive values (custom classes) require // compare function in the object itself or as a function pointer. Primitives // have default comparators, but you can override it. class Foo { public: int j; Foo(int a) : j(a) {} }; struct compareFunction { bool operator()(const Foo& a, const Foo& b) const { return a.j < b.j; } }; //this isn't allowed (although it can vary depending on compiler) //std::map<Foo, int> fooMap; std::map<Foo, int, compareFunction> fooMap; fooMap[Foo(1)] = 1; fooMap.find(Foo(1)); //true /////////////////////////////////////// // Lambda Expressions (C++11 and above) /////////////////////////////////////// // lambdas are a convenient way of defining an anonymous function // object right at the location where it is invoked or passed as // an argument to a function. // For example, consider sorting a vector of pairs using the second // value of the pair vector<pair<int, int> > tester; tester.push_back(make_pair(3, 6)); tester.push_back(make_pair(1, 9)); tester.push_back(make_pair(5, 0)); // Pass a lambda expression as third argument to the sort function // sort is from the <algorithm> header sort(tester.begin(), tester.end(), [](const pair<int, int>& lhs, const pair<int, int>& rhs) { return lhs.second < rhs.second; }); // Notice the syntax of the lambda expression, // [] in the lambda is used to "capture" variables // The "Capture List" defines what from the outside of the lambda should be available inside the function body and how. // It can be either: // 1. a value : [x] // 2. a reference : [&x] // 3. any variable currently in scope by reference [&] // 4. same as 3, but by value [=] // Example: vector<int> dog_ids; // number_of_dogs = 3; for(int i = 0; i < 3; i++) { dog_ids.push_back(i); } int weight[3] = {30, 50, 10}; // Say you want to sort dog_ids according to the dogs' weights // So dog_ids should in the end become: [2, 0, 1] // Here's where lambda expressions come in handy sort(dog_ids.begin(), dog_ids.end(), [&weight](const int &lhs, const int &rhs) { return weight[lhs] < weight[rhs]; }); // Note we captured "weight" by reference in the above example. // More on Lambdas in C++ : http://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11 /////////////////////////////// // Range For (C++11 and above) /////////////////////////////// // You can use a range for loop to iterate over a container int arr[] = {1, 10, 3}; for(int elem: arr){ cout << elem << endl; } // You can use "auto" and not worry about the type of the elements of the container // For example: for(auto elem: arr) { // Do something with each element of arr } ///////////////////// // Fun stuff ///////////////////// // Aspects of C++ that may be surprising to newcomers (and even some veterans). // This section is, unfortunately, wildly incomplete; C++ is one of the easiest // languages with which to shoot yourself in the foot. // You can override private methods! class Foo { virtual void bar(); }; class FooSub : public Foo { virtual void bar(); // Overrides Foo::bar! }; // 0 == false == NULL (most of the time)! bool* pt = new bool; *pt = 0; // Sets the value points by 'pt' to false. pt = 0; // Sets 'pt' to the null pointer. Both lines compile without warnings. // nullptr is supposed to fix some of that issue: int* pt2 = new int; *pt2 = nullptr; // Doesn't compile pt2 = nullptr; // Sets pt2 to null. // There is an exception made for bools. // This is to allow you to test for null pointers with if(!ptr), // but as a consequence you can assign nullptr to a bool directly! *pt = nullptr; // This still compiles, even though '*pt' is a bool! // '=' != '=' != '='! // Calls Foo::Foo(const Foo&) or some variant (see move semantics) copy // constructor. Foo f2; Foo f1 = f2; // Calls Foo::Foo(const Foo&) or variant, but only copies the 'Foo' part of // 'fooSub'. Any extra members of 'fooSub' are discarded. This sometimes // horrifying behavior is called "object slicing." FooSub fooSub; Foo f1 = fooSub; // Calls Foo::operator=(Foo&) or variant. Foo f1; f1 = f2; /////////////////////////////////////// // Tuples (C++11 and above) /////////////////////////////////////// #include<tuple> // Conceptually, Tuples are similar to old data structures (C-like structs) but instead of having named data members, // its elements are accessed by their order in the tuple. // We start with constructing a tuple. // Packing values into tuple auto first = make_tuple(10, 'A'); const int maxN = 1e9; const int maxL = 15; auto second = make_tuple(maxN, maxL); // Printing elements of 'first' tuple cout << get<0>(first) << " " << get<1>(first) << "\n"; //prints : 10 A // Printing elements of 'second' tuple cout << get<0>(second) << " " << get<1>(second) << "\n"; // prints: 1000000000 15 // Unpacking tuple into variables int first_int; char first_char; tie(first_int, first_char) = first; cout << first_int << " " << first_char << "\n"; // prints : 10 A // We can also create tuple like this. tuple<int, char, double> third(11, 'A', 3.14141); // tuple_size returns number of elements in a tuple (as a constexpr) cout << tuple_size<decltype(third)>::value << "\n"; // prints: 3 // tuple_cat concatenates the elements of all the tuples in the same order. auto concatenated_tuple = tuple_cat(first, second, third); // concatenated_tuple becomes = (10, 'A', 1e9, 15, 11, 'A', 3.14141) cout << get<0>(concatenated_tuple) << "\n"; // prints: 10 cout << get<3>(concatenated_tuple) << "\n"; // prints: 15 cout << get<5>(concatenated_tuple) << "\n"; // prints: 'A' ///////////////////// // Containers ///////////////////// // Containers or the Standard Template Library are some predefined templates. // They manage the storage space for its elements and provide // member functions to access and manipulate them. // Few containers are as follows: // Vector (Dynamic array) // Allow us to Define the Array or list of objects at run time #include <vector> string val; vector<string> my_vector; // initialize the vector cin >> val; my_vector.push_back(val); // will push the value of 'val' into vector ("array") my_vector my_vector.push_back(val); // will push the value into the vector again (now having two elements) // To iterate through a vector we have 2 choices: // Either classic looping (iterating through the vector from index 0 to its last index): for (int i = 0; i < my_vector.size(); i++) { cout << my_vector[i] << endl; // for accessing a vector's element we can use the operator [] } // or using an iterator: vector<string>::iterator it; // initialize the iterator for vector for (it = my_vector.begin(); it != my_vector.end(); ++it) { cout << *it << endl; } // Set // Sets are containers that store unique elements following a specific order. // Set is a very useful container to store unique values in sorted order // without any other functions or code. #include<set> set<int> ST; // Will initialize the set of int data type ST.insert(30); // Will insert the value 30 in set ST ST.insert(10); // Will insert the value 10 in set ST ST.insert(20); // Will insert the value 20 in set ST ST.insert(30); // Will insert the value 30 in set ST // Now elements of sets are as follows // 10 20 30 // To erase an element ST.erase(20); // Will erase element with value 20 // Set ST: 10 30 // To iterate through Set we use iterators set<int>::iterator it; for(it=ST.begin();it<ST.end();it++) { cout << *it << endl; } // Output: // 10 // 30 // To clear the complete container we use Container_name.clear() ST.clear(); cout << ST.size(); // will print the size of set ST // Output: 0 // NOTE: for duplicate elements we can use multiset // Map // Maps store elements formed by a combination of a key value // and a mapped value, following a specific order. #include<map> map<char, int> mymap; // Will initialize the map with key as char and value as int mymap.insert(pair<char,int>('A',1)); // Will insert value 1 for key A mymap.insert(pair<char,int>('Z',26)); // Will insert value 26 for key Z // To iterate map<char,int>::iterator it; for (it=mymap.begin(); it!=mymap.end(); ++it) std::cout << it->first << "->" << it->second << '\n'; // Output: // A->1 // Z->26 // To find the value corresponding to a key it = mymap.find('Z'); cout << it->second; // Output: 26 /////////////////////////////////// // Logical and Bitwise operators ////////////////////////////////// // Most of the operators in C++ are same as in other languages // Logical operators // C++ uses Short-circuit evaluation for boolean expressions, i.e, the second argument is executed or // evaluated only if the first argument does not suffice to determine the value of the expression true && false // Performs **logical and** to yield false true || false // Performs **logical or** to yield true ! true // Performs **logical not** to yield false // Instead of using symbols equivalent keywords can be used true and false // Performs **logical and** to yield false true or false // Performs **logical or** to yield true not true // Performs **logical not** to yield false // Bitwise operators // **<<** Left Shift Operator // << shifts bits to the left 4 << 1 // Shifts bits of 4 to left by 1 to give 8 // x << n can be thought as x * 2^n // **>>** Right Shift Operator // >> shifts bits to the right 4 >> 1 // Shifts bits of 4 to right by 1 to give 2 // x >> n can be thought as x / 2^n ~4 // Performs a bitwise not 4 | 3 // Performs bitwise or 4 & 3 // Performs bitwise and 4 ^ 3 // Performs bitwise xor // Equivalent keywords are compl 4 // Performs a bitwise not 4 bitor 3 // Performs bitwise or 4 bitand 3 // Performs bitwise and 4 xor 3 // Performs bitwise xor
C-plus.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # ENGR 1330 Computational Thinking with Data Science # Last GitHub Commit Date: 31 January 2021 # # ## Lesson 9 Visual Display of Data # # This lesson will introduce the `matplotlib` external module package, and examine how to construct # line charts, scatter plots, bar charts, box plot, and histograms using methods in `matplotlib` and `pandas` # # The theory of histograms will appear in later lessons, here we only show how to construct one using `matplotlib` # # - Graphic Standards for Plots # - Parts of a Plot # - Building Plots using `matplotlib` external package # # --- # # ## Objectives # - Define the ordinate, abscissa, independent and dependent variables # - Identify the parts of a proper plot # - Define how to plot experimental data and theoretical data # # # #### About `matplotlib` # Quoting from: https://matplotlib.org/tutorials/introductory/pyplot.html#sphx-glr-tutorials-introductory-pyplot-py # # `matplotlib.pyplot` is a collection of functions that make matplotlib work like MATLAB. Each pyplot function makes some change to a figure: e.g., creates a figure, creates a plotting area in a figure, plots some lines in a plotting area, decorates the plot with labels, etc. # # In `matplotlib.pyplot` various states are preserved across function calls, so that it keeps track of things like the current figure and plotting area, and the plotting functions are directed to the current axes (please note that "axes" here and in most places in the documentation refers to the axes part of a figure and not the strict mathematical term for more than one axis). # # **Computational thinking (CT)** concepts involved are: # # - `Decomposition` : Break a problem down into smaller pieces; separating plotting from other parts of analysis simplifies maintenace of scripts # - `Abstraction` : Pulling out specific differences to make one solution work for multiple problems; wrappers around generic plot calls enhances reuse # - `Algorithms` : A list of steps that you can follow to finish a task; Often the last step and most important to make professional graphics to justify the expense (of paying you to do engineering) to the client. # # # ## Graphics Conventions for Plots # # ### Terminology: Ordinate, Abscissa, Dependent and Independent Variables # # A few terms are used in describing plots: # - Abscissa – the horizontal axis on a plot (the left-right axis) # - Ordinate – the vertical axis on a plot (the up-down axis) # # A few terms in describing data models # - Independent Variable (Explainatory, Predictor, Feature, ...) – a variable that can be controlled/manipulated in an experiment or theoretical analysis # - Dependent Variable (Response, Prediction, ...) – the variable that measured/observed as a function of the independent variable # # Plotting convention in most cases assigns explainatory variables to the horizontal axis (e.g. Independent variable is plotted on the Abscissa) and the response variable(s) to the vertical axis (e.g. Dependent Variable is plotted on the Ordinate) # # ![](slide1.png) # #### Conventions for Proper Plots # - Include a title OR a caption with a brief description of the plot # - Label both axes clearly # - Include the variable name, the variable, and the unit in each label # ![](slide2.png) # - If possible, select increments for both the x and y axes that provide for easy interpolation # ![](slide3.png) # - Include gridlines # - Show experimental measurements as symbols # - Show model (theoretical) relationships as lines # ![](slide4.png) # - Use portrait orientation when making your plot # - Make the plot large enough to be easily read # - If more than one experimental dataset is plotted # - Use different shapes for each dataset # - Use different colors for each dataset # - Include a legend defining the datasets # ![](markers.png) # ![](dataplot.png) # ![](modelplot.png) # ## Background # # Data are not always numerical. # Data can music (audio files), or places on a map (georeferenced attributes files), images (various imge files, e.g. .png, jpeg) # # They can also be categorical into which you can place individuals: # - The individuals are cartons of ice-cream, and the category is the flavor in the carton # - The individuals are professional basketball players, and the category is the player's team. # # ### Bar Graphs # # Bar charts (graphs) are good display tools to graphically represent categorical information. # The bars are evenly spaced and of constant width. # The height/length of each bar is proportional to the `relative frequency` of the corresponding category. # # `Relative frequency` is the ratio of how many things in the category to how many things in the whole collection. # # The example below uses `matplotlib` to create a box plot for the ice cream analogy, the example is adapted from an example at https://www.geeksforgeeks.org/bar-plot-in-matplotlib/ # + ice_cream = {'Chocolate':16, 'Strawberry':5, 'Vanilla':9} # build a data model import matplotlib.pyplot # the python plotting library flavors = list(ice_cream.keys()) # make a list object based on flavors cartons = list(ice_cream.values()) # make a list object based on carton count -- assumes 1:1 association! myfigure = matplotlib.pyplot.figure(figsize = (10,5)) # generate a object from the figure class, set aspect ratio # Built the plot matplotlib.pyplot.bar(flavors, cartons, color ='maroon', width = 0.4) matplotlib.pyplot.xlabel("Flavors") matplotlib.pyplot.ylabel("No. of Cartons in Stock") matplotlib.pyplot.title("Current Ice Cream in Storage") matplotlib.pyplot.show() # - # Lets tidy up the script so it is more understandable, a small change in the import statement makes a simpler to read (for humans) script - also changed the bar colors just 'cause! # + ice_cream = {'Chocolate':16, 'Strawberry':5, 'Vanilla':9} # build a data model import matplotlib.pyplot as plt # the python plotting library flavors = list(ice_cream.keys()) # make a list object based on flavors cartons = list(ice_cream.values()) # make a list object based on carton count -- assumes 1:1 association! myfigure = plt.figure(figsize = (10,5)) # generate a object from the figure class, set aspect ratio # Built the plot plt.bar(flavors, cartons, color ='orange', width = 0.4) plt.xlabel("Flavors") plt.ylabel("No. of Cartons in Stock") plt.title("Current Ice Cream in Storage") plt.show() # - # Now lets deconstruct the script a bit: # # ice_cream = {'Chocolate':16, 'Strawberry':5, 'Vanilla':9} # build a data model # import matplotlib.pyplot as plt # the python plotting library # # flavors = list(ice_cream.keys()) # make a list object based on flavors # cartons = list(ice_cream.values()) # make a list object based on carton count -- assumes 1:1 association! # # This part of the code creates a dictionary object, keys are the flavors, values are the carton counts (not the best way, but good for our learning needs). Next we import the python plotting library from `matplotlib` and name it **plt** to keep the script a bit easier to read. # # # # Next we use the list method to create two lists from the dictionary, **flavors** and **cartons**. Keep this in mind plotting is usually done on lists, so we need to prepare the structures properly. # # The next statement # # myfigure = plt.figure(figsize = (10,5)) # generate a object from the figure class, set aspect ratio # # Uses the figure class in **pyplot** from **matplotlib** to make a figure object named myfigure, the plot is built into this object. Every call to a method in `plt` adds content to `myfigure` until we send the instruction to render the plot (`plt.show()`) # # The next portion of the script builds the plot: # # plt.bar(flavors, cartons, color ='orange', width = 0.4) # Build a bar chart, plot series flavor on x-axis, plot series carton on y-axis. Make the bars orange, set bar width (units unspecified) # plt.xlabel("Flavors") # Label the x-axis as Flavors # plt.ylabel("No. of Cartons in Stock") # Label the x-axis as Flavors # plt.title("Current Ice Cream in Storage") # Title for the whole plot # # This last statement renders the plot to the graphics device (probably localhost in the web browser) # # plt.show() # # Now lets add another set of categories to the plot and see what happens # + ice_cream = {'Chocolate':16, 'Strawberry':5, 'Vanilla':9} # build a data model eaters = {'Cats':6, 'Dogs':5, 'Ferrets':19} # build a data model import matplotlib.pyplot as plt # the python plotting library flavors = list(ice_cream.keys()) # make a list object based on flavors cartons = list(ice_cream.values()) # make a list object based on carton count -- assumes 1:1 association! animals = list(eaters.keys()) beasts = list(eaters.values()) myfigure = plt.figure(figsize = (10,5)) # generate a object from the figure class, set aspect ratio # Built the plot plt.bar(flavors, cartons, color ='orange', width = 0.4) plt.bar(animals, beasts, color ='green', width = 0.4) plt.xlabel("Flavors") plt.ylabel("Counts: Cartons and Beasts") plt.title("Current Ice Cream in Storage") plt.show() # - # Now suppose we want horizontal bars we can search pyplot for such a thing. If one types horizontal bar chart into the pyplot search engine there is a link that leads to: # # ![](SearchPyplot.png) # # Which has the right look! If we examine the script there is a method called `barh` so lets try that. # + ice_cream = {'Chocolate':16, 'Strawberry':5, 'Vanilla':9} # build a data model eaters = {'Cats':6, 'Dogs':5, 'Ferrets':19} # build a data model import matplotlib.pyplot as plt # the python plotting library flavors = list(ice_cream.keys()) # make a list object based on flavors cartons = list(ice_cream.values()) # make a list object based on carton count -- assumes 1:1 association! animals = list(eaters.keys()) beasts = list(eaters.values()) myfigure = plt.figure(figsize = (10,5)) # generate a object from the figure class, set aspect ratio # Built the plot plt.barh(flavors, cartons, color ='orange') plt.barh(animals, beasts, color ='green') plt.xlabel("Flavors") plt.ylabel("Counts: Cartons and Beasts") plt.title("Current Ice Cream in Storage") plt.show() # - # Now using pandas, we can build bar charts a bit easier. # + import pandas as pd my_data = { "Flavor": ['Chocolate', 'Strawberry', 'Vanilla'], "Number of Cartons": [16, 5, 9] } df = pd.DataFrame(my_data) df.head() # - df.plot.bar(x='Flavor', y='Number of Cartons', color='magenta' ) df.plot.bar(x='Flavor', y='Number of Cartons', color="red") # rotate the category labels # + import numpy as np import matplotlib.pyplot as plt # creating the dataset data = {'C':20, 'C++':15, 'Java':30, 'Python':35} courses = list(data.keys()) values = list(data.values()) fig = plt.figure(figsize = (10, 5)) # creating the bar plot plt.bar(courses, values, color ='maroon', width = 0.4) plt.xlabel("Courses offered") plt.ylabel("No. of students enrolled") plt.title("Students enrolled in different courses") plt.show() # - # ### Line Charts # A line chart or line plot or line graph or curve chart is a type of chart which displays information as a series of data points called 'markers' connected by straight line segments. # # It is a basic type of chart common in many fields. It is similar to a scatter plot (below) except that the measurement points are **ordered** (typically by their x-axis value) and joined with straight line segments. # # A line chart is often used to visualize a trend in data over intervals of time – a time series – thus the line is often drawn chronologically. # # The x-axis spacing is sometimes tricky, hence line charts can unintentionally decieve - so be careful that it is the appropriate chart for your application. # # Example # # Consider the experimental data below # # |Elapsed Time (s)|Speed (m/s)| # |---:|---:| # |0 |0| # |1.0 |3| # |2.0 |7| # |3.0 |12| # |4.0 |20| # |5.0 |30| # |6.0 | 45.6| # # Show the relationship between time and speed. Is the relationship indicating acceleration? How much? # Create two lists; time and speed. time = [0,1.0,2.0,3.0,4.0,5.0,6.0] speed = [0,3,7,12,20,30,45.6] # Create a line chart of speed on y axis and time on x axis mydata = plt.figure(figsize = (10,5)) # build a square drawing canvass from figure class plt.plot(time, speed, c='red', marker='v',linewidth=1) # basic line plot plt.show() time = [0,1.0,4.0,5.0,6.0,2.0,3.0] speed = [0,3,20,30,45.6,7,12] # Create a line chart of speed on y axis and time on x axis mydata = plt.figure(figsize = (10,5)) # build a square drawing canvass from figure class plt.plot(time, speed, c='green', marker='o',linewidth=1) # basic line plot plt.show() # Estimate acceleration (naive) dvdt = (max(speed) - min(speed))/(max(time)-min(time)) plottitle = 'Average acceleration %.3f' % (dvdt) + ' m/sec/sec' seriesnames = ['Data','Model'] modely = [min(speed),max(speed)] modelx = [min(time),max(time)] mydata = plt.figure(figsize = (10,5)) # build a square drawing canvass from figure class plt.plot(time, speed, c='red', marker='v',linewidth=1) # basic line plot plt.plot(modelx, modely, c='blue',linewidth=1) # basic line plot plt.xlabel('Time (sec)') plt.ylabel('Speed (m/sec)') plt.legend(seriesnames) plt.title(plottitle) plt.show() # ### Scatter Plots # A scatter plot (also called a scatterplot, scatter graph, scatter chart, scattergram, or scatter diagram) is a type of plot or mathematical diagram using Cartesian coordinates to display values for typically two variables for a set of data. If the points are coded (color/shape/size), one additional variable can be displayed. The data are displayed as a collection of points, each having the value of one variable determining the position on the horizontal axis and the value of the other variable determining the position on the vertical axis. # # A scatter plot can be used either when one continuous variable that is under the control of the experimenter and the other depends on it or when both continuous variables are independent. If a parameter exists that is systematically incremented and/or decremented by the other, it is called the control parameter or independent variable and is customarily plotted along the horizontal axis. The measured or dependent variable is customarily plotted along the vertical axis. If no dependent variable exists, either type of variable can be plotted on either axis and a scatter plot will illustrate only the degree of correlation (not causation) between two variables. # # A scatter plot can suggest various kinds of correlations between variables with a certain confidence interval. For example, weight and height, weight would be on y axis and height would be on the x axis. # Correlations may be positive (rising), negative (falling), or null (uncorrelated). # If the pattern of dots slopes from lower left to upper right, it indicates a positive correlation between the variables being studied. # If the pattern of dots slopes from upper left to lower right, it indicates a negative correlation. # # A line of best fit (alternatively called 'trendline') can be drawn in order to study the relationship between the variables. An equation for the correlation between the variables can be determined by established best-fit procedures. For a linear correlation, the best-fit procedure is known as linear regression and is guaranteed to generate a correct solution in a finite time. No universal best-fit procedure is guaranteed to generate a solution for arbitrary relationships. # A scatter plot is also very useful when we wish to see how two comparable data sets agree and to show nonlinear relationships between variables. # # Furthermore, if the data are represented by a mixture model of simple relationships, these relationships will be visually evident as superimposed patterns. # # Scatter charts can be built in the form of bubble, marker, or/and line charts. # # Much of the above is verbatim/adapted from: https://en.wikipedia.org/wiki/Scatter_plot # Example 1. A data file containing heights of fathers, mothers, and sons is to be examined df = pd.read_csv('galton_subset.csv') df['child']= df['son'] ; df.drop('son', axis=1, inplace = True) # rename son to child - got to imagine there are some daughters df.head() # build some lists daddy = df['father'] ; mommy = df['mother'] ; baby = df['child'] myfamily = plt.figure(figsize = (10, 10)) # build a square drawing canvass from figure class plt.scatter(baby, daddy, c='red') # basic scatter plot plt.show() # Looks lousy, needs some labels myfamily = plt.figure(figsize = (10, 10)) # build a square drawing canvass from figure class plt.scatter(baby, daddy, c='red' , label='Father') # one plot series plt.scatter(baby, mommy, c='blue', label='Mother') # two plot series plt.xlabel("Child's height") plt.ylabel("Parents' height") plt.legend() plt.show() # render the two plots # Repeat in pandas - The dataframe already is built df.plot.scatter(x="child", y="father") # + ax = df.plot.scatter(x="child", y="father", c="red", label='Father') df.plot.scatter(x="child", y="mother", c="blue", label='Mother', ax=ax) ax.set_xlabel("Child's height") ax.set_ylabel("Parents' Height") # - df.plot.scatter(x="child", y="father") # ## Histograms # # Quiting from https://en.wikipedia.org/wiki/Histogram # # "A histogram is an approximate representation of the distribution of numerical data. It was first introduced by <NAME>.[1] To construct a histogram, the first step is to "bin" (or "bucket") the range of values—that is, divide the entire range of values into a series of intervals—and then count how many values fall into each interval. The bins are usually specified as consecutive, non-overlapping intervals of a variable. The bins (intervals) must be adjacent, and are often (but not required to be) of equal size. # # If the bins are of equal size, a rectangle is erected over the bin with height proportional to the frequency—the number of cases in each bin. A histogram may also be normalized to display "relative" frequencies. It then shows the proportion of cases that fall into each of several categories, with the sum of the heights equaling 1. # # However, bins need not be of equal width; in that case, the erected rectangle is defined to have its area proportional to the frequency of cases in the bin. The vertical axis is then not the frequency but frequency density—the number of cases per unit of the variable on the horizontal axis. Examples of variable bin width are displayed on Census bureau data below. # # As the adjacent bins leave no gaps, the rectangles of a histogram touch each other to indicate that the original variable is continuous. # # Histograms give a rough sense of the density of the underlying distribution of the data, and often for density estimation: estimating the probability density function of the underlying variable. The total area of a histogram used for probability density is always normalized to 1. If the length of the intervals on the x-axis are all 1, then a histogram is identical to a relative frequency plot. # # A histogram can be thought of as a simplistic kernel density estimation, which uses a kernel to smooth frequencies over the bins. This yields a smoother probability density function, which will in general more accurately reflect distribution of the underlying variable. The density estimate could be plotted as an alternative to the histogram, and is usually drawn as a curve rather than a set of boxes. Histograms are nevertheless preferred in applications, when their statistical properties need to be modeled. The correlated variation of a kernel density estimate is very difficult to describe mathematically, while it is simple for a histogram where each bin varies independently. # # An alternative to kernel density estimation is the average shifted histogram, which is fast to compute and gives a smooth curve estimate of the density without using kernels. # # The histogram is one of the seven basic tools of quality control. # # Histograms are sometimes confused with bar charts. A histogram is used for continuous data, where the bins represent ranges of data, while a bar chart is a plot of categorical variables. Some authors recommend that bar charts have gaps between the rectangles to clarify the distinction." # + import pandas as pd df = pd.read_csv('top_movies.csv') df.head() # - df[["Gross"]].hist() df[["Gross"]].hist(bins=100) df.describe() # ## References # # https://matplotlib.org/gallery/lines_bars_and_markers/horizontal_barchart_distribution.html?highlight=horizontal%20bar%20chart # # https://www.geeksforgeeks.org/bar-plot-in-matplotlib/ # #
1-Lessons/Lesson12/.ipynb_checkpoints/Lesson9-AsANotebook-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- from nltk.corpus import stopwords from collections import Counter import pandas as pd import numpy as np import nltk.data from __future__ import division # Python 2 users only import nltk, re, pprint from nltk import word_tokenize # ## Open the files cmu_trans = open('transcription_cmu.txt','rU').read() wat_trans = open('transcription_watson_2.txt','rU').read() stop = set(stopwords.words('english')) # # Tokenize and lower # + def tokenize_and_lower(textfile): tokens = word_tokenize(textfile) lower = [w.lower() for w in tokens] filtered_words = [word for word in lower if word not in stop] series = pd.Series(filtered_words) return series '''def keep_stop_words(textfile): tokens = word_tokenize(textfile) lower = [w.lower() for w in tokens] nonfiltered_words = [word for word in lower if word in stop] series = pd.Series(nonfiltered_words) return series #cmu_stop = keep_stop_words(cmu_trans) #wat_stop = keep_stop_words(wat_trans)''' # - # # Compare Results with value_counts cmu = tokenize_and_lower(cmu_trans) wat = tokenize_and_lower(wat_trans) cmu = pd.Series.to_frame(cmu) wat = pd.Series.to_frame(wat) cmu.columns = [['words']] wat.columns = [['words']] cmu = cmu.groupby('words').size().reset_index() wat = wat.groupby('words').size().reset_index() df = pd.merge(cmu, wat, on='words') df.columns = [['words','cmu','wat']] df['cmu_diff_wat'] = df.cmu - df.wat # %matplotlib inline df.cmu_diff_wat.value_counts().plot(kind='bar') df.cmu_diff_wat.value_counts()
podcast/compare_methods.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: PythonData # language: python # name: python3 # --- # Import the random module. import random random.randint(-90, 90) x = 1 latitudes = [] while x < 11: random_lat = random.randint(-90, 89) + random.random() latitudes.append(random_lat) x += 1 latitudes # - Assign the variable x to 1. # - Initialize an empty list, latitudes. # - We create a while loop where we generate a random latitude and add it to the list. # - After the random latitude is added to the list we add one to the variable "x". # - The while loop condition is checked again and will continue to run as long as x is less than 11. # Function | Output | Limitation # |---|---|---| # randint(-90, 89) | Returns an integer between the interval, -90 and up to 89. | Will not generate a floating-point decimal number. # random() | Returns a floating-point decimal number between 0 and 1. | Will not generate a whole integer. # randrange(-90, 90, step=1) | Returns a whole integer between the interval, -90 and 90 where the step is the difference between each number in the sequence. | Will not generate a floating-point decimal number. # uniform(-90, 90) | Returns a floating-point decimal number between the interval, -90 and 90. | Will not generate a whole integer. # # Adding NumPy # Import the NumPy module. import numpy as np # .**uniform** np.random.uniform(-90.000, 90.000) # **Alternate** # alt usage np.random.uniform(low=-90, high=90) # **'size' parameter** np.random.uniform(-90.000, 90.000, size=50) # **Test how long code runs, as we increase to 1500 - timeit** # Import timeit. import timeit # %timeit np.random.uniform(-90.000, 90.000, size=1500) # **Build a function w/ timeit** # + def latitudes(size): latitudes = [] x = 0 while x < (size): random_lat = random.randint(-90, 90) + random.random() latitudes.append(random_lat) x += 1 return latitudes # Call the function with 1500. # %timeit latitudes(1500) # - # **SKILL DRILL** # Refactor the code for the while loop with the `%timeit` magic command and write a for loop that will generate the 1,500 latitudes. # + def latty(size): latitudes = [] for x in range(0,size): random_lat = random.randint(-90, 90) + random.random() latitudes.append(random_lat) return latitudes # %timeit latty(1500) # - # Import linear regression from the SciPy stats module. from scipy.stats import linregress # Create an equal number of latitudes and temperatures. lats = [42.5, 43.9, 8.1, 36.8, 79.9, 69.1, 25.7, 15.3, 12.7, 64.5] temps = [80.5, 75.3, 90.9, 90.0, 40.4, 62.3, 85.4, 79.6, 72.5, 72.0] # Perform linear regression. (slope, intercept, r_value, p_value, std_err) = linregress(lats, temps) # Get the equation of the line. Optional line_eq = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2)) print(line_eq) print(f"The p-value is: {p_value:.3f}") # In the code to perform linear regression, the linregress function takes only two arguments, the x- and y-axes data (lats and temps) in the form of arrays. And it returns the following: # # - Slope of the regression line as `slope` # - y-intercept as `intercept` # - Correlation coefficient as `r_value` # - p-value as `p_value` # - Standard error as `std_err` # ### Important: # The `slope`, `intercept`, `r_value`, `p_value`, and `std_err` are always returned when we run the `linregress` function. If you don't want to calculate one of these values but do not add it inside the parentheses, you'll get a `ValueError: too many values to unpack`. # # To prevent this error, add a comma and underscore for each value you don't want to calculate. # # For instance, if you don't want to print out the p-value and the standard error, write your function as `(slope, intercept, r_value, _, _) = linregress(x, y)`. # ### Note # # In statistics, the **p-value** is used to determine significance of results. In most cases, data scientists like to use a significance level of 0.05, which means: # # - A linear regression with a p-value > 0.05 is not statistically significant. # - A linear regression with a p-value < 0.05 is statistically significant. # # P-values can also be used to justify rejecting a null hypothesis. We will discuss p-values and hypothesis testing in more detail later in the course. # Calculate the regression line "y values" from the slope and intercept. regress_values = [(lat * slope + intercept) for lat in lats] # + # Import Matplotlib. import matplotlib.pyplot as plt # Create a scatter plot of the x and y values. plt.scatter(lats,temps) # Plot the regression line with the x-values and the y coordinates based on the intercept and slope. plt.plot(lats,regress_values,"r") # Annotate the text for the line equation and add its coordinates. plt.annotate(line_eq, (10,40), fontsize=15, color="red") # optional plt.xlabel('Latitude') plt.ylabel('Temp') plt.show() # - # Let's review what this code does: # # - We plot the latitudes and temperatures on a scatter plot. # - We create a line plot of our regression line with the ideal temperatures. # - We annotate the line plot by adding the equation of our regression line, where the x-axis is 10 and the y-axis is 40, and specify the font and color. # - We create x- and y-axes labels. # # **scipy.stats.linregress — SciPy v1.7.1 Manual** [(view)](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.linregress.html#scipy.stats.linregress)
Cleanup/random_numbers.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # <hr> # # [cknowledge.org](http://cknowledge.org): Community-driven benchmarking and optimization of computing systems - from classical to quantum # <hr> # [Quantum Computing](https://github.com/ctuning/ck-quantum/wiki) # * [CK-QISKit](https://github.com/ctuning/ck-qiskit) (IBM) # * [CK-Rigetti](https://github.com/ctuning/ck-rigetti) ([Rigetti Computing](https://rigetti.com/)) # * [CK-ProjectQ](https://github.com/ctuning/ck-projectq) ([ProjectQ](https://projectq.ch/)) # [Artificial Intelligence and Machine Learning](http://cknowledge.org/ai) # * [Reproducible Quality-Efficient Systems Tournaments](http://cknowledge.org/request) ([ReQuEST initiative](http://cknowledge.org/request.html#organizers)) # * [AI artifacts](http://cknowledge.org/ai-artifacts) (cTuning foundation) # * [Android app](https://play.google.com/store/apps/details?id=openscience.crowdsource.video.experiments) (dividiti) # * [Desktop app](https://github.com/dividiti/ck-crowdsource-dnn-optimization) (dividiti) # * [CK-Caffe](https://github.com/dividiti/ck-caffe) (Berkeley) # * [CK-Caffe2](https://github.com/ctuning/ck-caffe2) (Facebook) # * [CK-CNTK](https://github.com/ctuning/ck-cntk) (Microsoft) # * [CK-KaNN](https://github.com/ctuning/ck-kann) (Kalray) # * [CK-MVNC](https://github.com/ctuning/ck-mvnc) (Movidius / Intel) # * [CK-MXNet](https://github.com/ctuning/ck-mxnet) (Apache) # * [CK-NNTest](https://github.com/ctuning/ck-nntest) (cTuning foundation) # * [CK-TensorFlow](https://github.com/ctuning/ck-tensorflow) (Google) # * [CK-TensorRT](https://github.com/ctuning/ck-tensorrt) (NVIDIA) # * etc. # <hr> # # Variational Quantum Eigensolver (VQE) on Rigetti machines # [Quantum Collective Knowledge Hackaton](https://www.eventbrite.co.uk/e/quantum-computing-hackathon-tickets-46441126660#), [Centre for Mathematical Science - University of Cambridge](http://www.cms.cam.ac.uk/), 15 June 2018 # ## Table of Contents # 1. [Organisers](#organisers) # 1. [References](#references) # 1. [Time-to-solution metric](#metric) # 1. [Setting up](#settingup) # 1. [Running experiments](#running) # 1. [Experimental data](#data) # 1. [Data wrangling code](#code) (for developers) # 1. [Analysis](#analysis) # <a id="organisers"></a> # ## Organisers # - [Rigetti Computing](https://rigetti.com): access to [Quantum Virtual Machine](http://pyquil.readthedocs.io/en/latest/qvm.html) (QVM) and [Quantum Processing Unit](http://pyquil.readthedocs.io/en/latest/qpu.html) (QPU). # - [River Lane Research](https://riverlane.io/): <NAME>, <NAME>, <NAME>, <NAME> # - [dividiti](http://dividiti.com/): <NAME>, <NAME>, <NAME>, <NAME> # <a id="references"></a> # ## References # - [Rigetti's docs](http://grove-docs.readthedocs.io/en/latest/vqe.html) # - ["A variational eigenvalue solver on a quantum processor"](https://arxiv.org/abs/1304.3061) (2013) # - ["The theory of variational hybrid quantum-classical algorithms"](https://arxiv.org/abs/1509.04279) (2015) # - ["Quantum optimization using variational algorithms # on near-term quantum devices"](https://arxiv.org/abs/1710.01022) [2017] # <a id="metric"></a> # ## Time-to-solution metric # To compare solutions of participants we use a **time-to-solution** $T$ metric defined as follows. # ### Definition # Let's assume that to find the ground state of a given molecule (e.g. [Helium](https://en.wikipedia.org/wiki/Helium)) a participant makes $N$ runs of their implementation (e.g. $N=3$). A run is considered _successful_ if the ground state found in this run is equal to the ground state known for the molecule to given precision $\delta$ (e.g. $\delta=0.1$). Assume that a single run takes $t$ samples (calls to the quantum computer) on average. # # Let $s$ be the probability of success of the participant's VQE implementation (i.e. the number of successful runs divided by the total number of runs $N$). # # Let $R$ be the number of runs required to find the ground state with given probability $p$ (e.g. $p=0.6$): # \begin{equation} # R = {\frac{\log(1-p)}{\log(1-s)}}. # \end{equation} # # The **time-to-solution** $T$, defined as the total number of samples used throughout the whole optimisation procedure of VQE, is then calculated as: # \begin{equation} # T = R \times t. # \end{equation} # ### Derivation # If the probability of success is $s$, then the probability of _failing to find_ the ground state after $R$ runs is $(1-s)^R$. Therefore, the probability of finding the ground state at least once after $R$ runs is $p =1 - (1-s)^R$. Therefore, the number of runs $R$ required to find the ground state at least once with probability $p$ can be found by solving $p=1-(1-s)^R$. # ### Uncertainties # We can also calculate the standard error associated with the calculated time-to-solution $T$. # # From the [binomial distribution](Binomial_distribution), the uncertainty $\sigma_s$ in the success probability $s$ is: # \begin{equation} # \sigma_s=\sqrt{\frac{s(1-s)}{N}} # \end{equation} # where $N$ is the number of runs used to determine $s$. # # The uncertainty in the time taken per run $t$ is: # \begin{equation} # \sigma_t=\frac{\mathrm{std}}{\sqrt{N}} # \end{equation} # where $\mathrm{std}$ is the standard deviation of the times taken by all $N$ runs. # # The uncertainty in total time taken is: # \begin{equation} # \sigma_T=\sqrt{0.25 \cdot (T(t+\sigma_t, s) - T(t-\sigma_t,s))^2 + (T(t, s + \sigma_s) - T(t,s))^2} # \end{equation} # <a id="settingup"></a> # ## Setting up # Please follow instructions [here](https://github.com/ctuning/ck-quantum/blob/master/README.md). # <a id="running"></a> # ## Running experiments # ``` # $ ck benchmark program:rigetti-vqe \ # --env.RIGETTI_QUANTUM_DEVICE=<platform> \ # --env.VQE_MINIMIZER_METHOD=<minimizer_method> \ # --env.VQE_SAMPLE_SIZE=<sample_number> \ # --env.VQE_MAX_ITERATIONS=<max_iterations> \ # --record --record_repo=local --record_uoa=<email>-<plaform> \ # --tags=qck,hackathon-2018_06_15,<email>,<platform>,<minimizer_method> \ # --repetitions=<repetitions> # ``` # where: # - `platform`: `8Q-Agave` or `QVM`; # - `minimizer_method`: `my_melder_nead` or `my_cobyla` or `my_minimizer` (as defined in [optimizers.py](https://github.com/ctuning/ck-quantum/blob/master/package/tool-hackathon/hackathon-src/hackathon/optimizers.py) installed under e.g. `$CK_TOOLS/hackathon-1.0-linux-64/lib/hackathon`); # - `sample_size`: e.g. `100` (or another resolution); # - `max_iterations`: e.g. `80` (or another cut-off point); # - `email`: a valid email address (later to be replaced with a team id e.g. `team-01`); # - `repetitions`: how many times to run the experiment with the given parameters: e.g. `3`. # <a id="data"></a> # ## Get sample experimental data # The sample experimental data can be downloaded and registered with CK as follows: # ``` # $ wget https://www.dropbox.com/s/a1odux4asze9zpd/ck-quantum-hackathon-20180615.zip # $ ck add repo --zip=ck-quantum-hackathon-20180615.zip # ``` repo_uoa = 'ck-quantum-hackathon-20180615' # !ck list $repo_uoa:experiment:* --print_full | sort # <a id="code"></a> # ## Data wrangling code # **NB:** Please ignore this section if you are not interested in re-running or modifying this notebook. # ### Includes # #### Standard import os import sys import json import re # #### Scientific # If some of the scientific packages are missing, please install them using: # ``` # # pip install jupyter pandas numpy matplotlib # ``` import IPython as ip import pandas as pd import numpy as np import matplotlib as mp print ('IPython version: %s' % ip.__version__) print ('Pandas version: %s' % pd.__version__) print ('NumPy version: %s' % np.__version__) print ('Matplotlib version: %s' % mp.__version__) from IPython.display import Image, display def display_in_full(df): pd.options.display.max_columns = len(df.columns) pd.options.display.max_rows = len(df.index) display(df) import matplotlib.pyplot as plt from matplotlib import cm # %matplotlib inline default_colormap = cm.autumn default_fontsize = 16 default_barwidth = 0.8 default_figwidth = 16 default_figheight = 8 default_figdpi = 200 default_figsize = [default_figwidth, default_figheight] if mp.__version__[0]=='2': mp.style.use('classic') mp.rcParams['figure.max_open_warning'] = 200 mp.rcParams['figure.dpi'] = default_figdpi mp.rcParams['font.size'] = default_fontsize mp.rcParams['legend.fontsize'] = 'medium' # #### Collective Knowledge # If CK is not installed, please install it using: # ``` # # pip install ck # ``` import ck.kernel as ck print ('CK version: %s' % ck.__version__) # + # NB: Make sure the quantum hackathon tool is installed. (It should be if you have run any experiments.) # $ ck install package --tags=ck-quantum,tool,hackathon,v1 r=ck.access({'action':'show', 'module_uoa':'env', 'tags':'tool,hackathon'}) if r['return']>0: print ("Error: %s" % r['error']) exit(1) # Get the path to the first returned environment entry. tool_hackathon_dir=r['lst'][0]['meta']['env']['CK_ENV_LIB_HACKATHON_LIB'] sys.path.append(tool_hackathon_dir) from hackathon.utils import * # - # ### Access experimental data def get_experimental_results(repo_uoa, tags='qck', module_uoa='experiment'): r = ck.access({'action':'search', 'repo_uoa':repo_uoa, 'module_uoa':module_uoa, 'tags':tags}) if r['return']>0: print('Error: %s' % r['error']) exit(1) experiments = r['lst'] dfs = [] for experiment in experiments: data_uoa = experiment['data_uoa'] r = ck.access({'action':'list_points', 'repo_uoa':repo_uoa, 'module_uoa':module_uoa, 'data_uoa':data_uoa}) if r['return']>0: print('Error: %s' % r['error']) exit(1) tags = r['dict']['tags'] skip = False # Get team name (final data) or email (submission data). team_tags = [ tag for tag in tags if tag.startswith('team-') ] email_tags = [ tag for tag in tags if tag.find('@')!=-1 ] if len(team_tags) > 0: team = team_tags[0][0:7] elif len(email_tags) > 0: team = email_tags[0] else: print('[Warning] Cannot determine team name for experiment in: \'%s\'' % r['path']) team = 'team-default' if skip: print('[Warning] Skipping experiment with bad tags:') print(tags) continue # For each point. for point in r['points']: point_file_path = os.path.join(r['path'], 'ckp-%s.0001.json' % point) with open(point_file_path) as point_file: point_data_raw = json.load(point_file) characteristics_list = point_data_raw['characteristics_list'] num_repetitions = len(characteristics_list) data = [ { # features 'platform': characteristics['run'].get('vqe_input', {}).get('q_device_name', 'unknown').lower(), # choices 'minimizer_method': characteristics['run'].get('vqe_input', {}).get('minimizer_method', 'n/a'), 'minimizer_options': characteristics['run'].get('vqe_input', {}).get('minimizer_options', {'maxfev':-1}), 'minimizer_src': characteristics['run'].get('vqe_input', {}).get('minimizer_src', ''), 'sample_number': characteristics['run'].get('vqe_input', {}).get('sample_number','n/a'), # statistical repetition 'repetition_id': repetition_id, # runtime characteristics 'run': characteristics['run'], 'report': characteristics['run'].get('report', {}), 'vqe_output': characteristics['run'].get('vqe_output', {}), } for (repetition_id, characteristics) in zip(range(num_repetitions), characteristics_list) if len(characteristics['run']) > 0 ] for datum in data: datum['team'] = team datum['point'] = point datum['success'] = datum.get('vqe_output',{}).get('success',False) datum['nfev'] = np.int64(datum.get('vqe_output',{}).get('nfev',-1)) datum['nit'] = np.int64(datum.get('vqe_output',{}).get('nit',-1)) datum['fun'] = np.float64(datum.get('vqe_output',{}).get('fun',0)) datum['fun_validated'] = np.float64(datum.get('vqe_output',{}).get('fun_validated',0)) datum['fun_exact'] = np.float64(datum.get('vqe_output',{}).get('fun_exact',0)) datum['total_seconds'] = np.float64(datum.get('report',{}).get('total_seconds',0)) datum['total_q_seconds'] = np.float64(datum.get('report',{}).get('total_q_seconds',0)) datum['total_q_shots'] = np.int64(datum.get('report',{}).get('total_q_shots',0)) tmp_max_iterations = list(datum.get('minimizer_options',{'maxfev':-1}).values()) datum['max_iterations'] = tmp_max_iterations[0] if len(tmp_max_iterations)>0 else -1 index = [ 'platform', 'team', 'minimizer_method', 'sample_number', 'max_iterations', 'point', 'repetition_id' ] # Construct a DataFrame. df = pd.DataFrame(data) df = df.set_index(index) # Append to the list of similarly constructed DataFrames. dfs.append(df) if dfs: # Concatenate all thus constructed DataFrames (i.e. stack on top of each other). result = pd.concat(dfs) result.sort_index(ascending=True, inplace=True) else: # Construct a dummy DataFrame the success status of which can be safely checked. result = pd.DataFrame(columns=['success']) return result # Merge experimental results from the same team with the same parameters # (minimizer_method, sample_number, max_iterations) and minimizer source. def merge_experimental_results(df): dfs = [] df_prev = None for index, row in df.iterrows(): # Construct a DataFrame. df_curr = pd.DataFrame(row).T # Check if this row is similar to the previous row. if df_prev is not None: # if not the very first row if df_prev.index.levels[:-2]==df_curr.index.levels[:-2]: # if the indices match for all but the last two levels if df_prev.index.levels[-2]!=df_curr.index.levels[-2]: # if the experiments are different if df_prev['minimizer_src'].values==df_curr['minimizer_src'].values: # if the minimizer source is the same print('[Info] Merging experiment:') print(df_curr.index.levels) print('[Info] into:') print(df_prev.index.levels) print('[Info] as:') # df_curr.index = df_prev.index.copy() # TODO: increment repetition_id df_curr.index = pd.MultiIndex.from_tuples([(x[0],x[1],x[2],x[3],x[4],x[5],x[6]+1) for x in df_prev.index]) print(df_curr.index.levels) print else: print('[Warning] Cannot merge experiments as the minimizer source is different:') # print('------------------------------------------------------------------------') print(df_prev.index.levels) # print(df_prev['minimizer_src'].values[0]) # print # print('------------------------------------------------------------------------') print(df_curr.index.levels) # print(df_curr['minimizer_src'].values[0]) print # else: # print('[Info] Keeping experiments separate:') # print(df_prev.index.levels) # print(df_curr.index.levels) # print # Append to the list of similarly constructed DataFrames. dfs.append(df_curr) # Prepare for next iteration. df_prev = df_curr # Concatenate all thus constructed DataFrames (i.e. stack on top of each other). result = pd.concat(dfs) result.index.names = df.index.names result.sort_index(ascending=True, inplace=True) return result def get_metrics(df, delta=0.1, prob=0.5, which_fun_key='fun_exact', which_time_key='total_q_shots'): dfs = [] names_no_repetitions = df.index.names[:-1] for index, group in df.groupby(level=names_no_repetitions): # Compute metrics. classical_energy, minimizer_method, minimizer_src, n_succ, T_ave, T_err, t_ave, t_err, s, s_err = \ benchmark_list_of_runs(group['run'], verbose=False, delta=delta, prob=prob, which_fun_key=which_fun_key, which_time_key=which_time_key) # Construct a DataFrame from the metrics. data = { # Time to solution. 'T_ave' : T_ave, 'T_err' : T_err, # Time metric (seconds or shots). 't_ave' : t_ave, 't_err' : t_err, # Tries metric. 's' : s, 's_err' : s_err } data.update({ k : v for (k, v) in zip(names_no_repetitions, index) }) data['num_repetitions'] = len(group) # NB: index must be something. df_ = pd.DataFrame(data=data, index=[0]) df_ = df_.set_index(names_no_repetitions) # Append to the list of similarly constructed DataFrames. dfs.append(df_) if dfs: # Concatenate all thus constructed DataFrames (i.e. stack on top of each other). result = pd.concat(dfs).dropna() result.sort_index(ascending=True, inplace=True) return result # ### Plot experimental data def plot(df, platform_set=None, minimizer_method_set=None, sample_number_set=None, max_iterations_set=None, markersize_divisor=20, xmin=0.0, xmax=85.01, xstep=5.00, ymin=-3.0, ymax=-0.49, ystep=0.25, figsize=(18,9), dpi=200, legend_loc='lower right'): platform_set = platform_set or df.index.get_level_values(level='platform').unique() minimizer_method_set = minimizer_method_set or df.index.get_level_values(level='minimizer_method').unique() sample_number_set = sample_number_set or df.index.get_level_values(level='sample_number').unique() max_iterations_set = max_iterations_set or df.index.get_level_values(level='max_iterations').unique() # Options. minimizer_method_to_color = { 'my_cobyla' : 'orange', 'my_nelder_mead' : 'green', 'my_minimizer' : 'blue' } platform_to_marker = { '8q-agave' : '8', # octagon 'qvm' : 's', # square 'local_qasm_simulator' : 'p' # pentagon } last_marker_size = 10 last_marker_color = 'black' last_marker_success_true = '^' last_marker_success_false = 'v' fig = plt.figure(figsize=figsize, dpi=dpi) ax = fig.gca() for index, row in df.iterrows(): (platform, team, minimizer_method, sample_number, max_iterations, point, repetition_id) = index if platform not in platform_set: continue if sample_number not in sample_number_set: continue if minimizer_method not in minimizer_method_set: continue # NB: This uses 'fun', not 'fun_exact' or 'fun_validated'. energies = [ iteration['energy'] for iteration in row['report']['iterations'] ] marker=platform_to_marker[platform] markersize=sample_number/markersize_divisor color=minimizer_method_to_color.get(minimizer_method, 'red') markerfacecolor=color linestyle='-' ax.plot(range(len(energies)), energies, marker=marker, color=color, linestyle=linestyle, markerfacecolor=markerfacecolor, markersize=markersize) # Mark last function evaluation. last_energy = energies[-1] last_fev = row['nfev']-1 if minimizer_method=='my_cobyla' or 'my_nelder_mead' else row['nfev'] last_marker = last_marker_success_true if row['success'] else last_marker_success_false ax.plot(last_fev, last_energy, color=last_marker_color, marker=last_marker, markersize=last_marker_size) # Horizontal line for the known ground state. plt.axhline(y=-2.80778395754, color='red', linestyle='--') # Vertical lines for max_iterations. for max_iterations in max_iterations_set: plt.axvline(x=max_iterations, color='black') # Grid. plt.grid() # Title. title = 'Variational Quantum Eigensolver (VQE)' ax.set_title(title) # X axis. xlabel='Function evaluation' ax.set_xlabel(xlabel) ax.set_xlim(xmin, xmax) ax.set_xticks(np.arange(xmin, xmax, xstep)) # Y axis. ylabel='Energy' ax.set_ylabel(ylabel) ax.set_ylim(ymin, ymax) ax.set_yticks(np.arange(ymin, ymax, ystep)) # Legend. https://matplotlib.org/users/legend_guide.html handles = [ mp.lines.Line2D([], [], label='platform="%s",minimizer_method="%s"' % (p,m), color=minimizer_method_to_color.get(m, 'red'), marker=platform_to_marker[p], markersize=last_marker_size) for p in sorted(platform_set) for m in sorted(minimizer_method_set) ] handles.append(mp.lines.Line2D([],[], label='ground state', color='red', linestyle='--')) plt.legend(handles=handles, title='platform,minimizer_method', loc=legend_loc) # Save figure. # plt.savefig('vqe.energy.png') def plot_metric(df, metric='total_q_seconds'): df.columns.name='metric' # "df.index.names[:-1]" means reduce along 'repetition_id' (statistical variation). df_mean = df[[metric]].groupby(level=df.index.names[:-1]).mean().unstack('platform') df_std = df[[metric]].groupby(level=df.index.names[:-1]).std().unstack('platform') ax = df_mean.plot(kind='bar', yerr=df_std, grid=True, legend=True, rot=45, fontsize=default_fontsize, figsize=default_figsize, colormap=default_colormap) # <a id="analysis"></a> # ## Analysis # ### All experimental data df = get_experimental_results(repo_uoa=repo_uoa) display_in_full(df) # ### Merge experimental results from different runs with the same parameters df = merge_experimental_results(df) display_in_full(df) # ### Compute the time-to-solution metric etc. df_metrics = get_metrics(df, delta=0.1, prob=0.5, which_fun_key='fun_exact', which_time_key='total_q_shots') df_metrics # ### The (unexpected) winner # Somewhat unexpectedly, the winner obtained the exact answer (!) with `sample_number=1` (!!) on real hardware (!!!). Please see below an explanation why this was the case. idxmin1 = df_metrics['T_ave'].idxmin() idxmin1 df_metrics.loc[[idxmin1]] df.loc[idxmin1] # Platform, Team, minimizer Function, number of Samples, number of function eValuations, Experiment, Repetition (p,t,f,s,v,e) = idxmin1 # Plot the winner. plot(df.loc[[(p,t,f,s,v,e,k) for k in range(len(df.loc[idxmin1]))]], xmax=7, xstep=1, ymin=-3.00, ymax=0.00+0.01, legend_loc='upper center') # Exclude the winner. df_metrics = df_metrics.drop(idxmin1) # #### Explanation # The [Hamiltonian](https://en.wikipedia.org/wiki/Hamiltonian_(quantum_mechanics)) of [Helium](https://en.wikipedia.org/wiki/Helium) in the [STO-3G](https://en.wikipedia.org/wiki/STO-nG_basis_sets) basis is given by: # # \begin{equation} # H = -1.6678202144537553 + 0.7019459893849936 \cdot Z_0 + 0.7019459893849936 \cdot Z_1 + 0.263928235683768058 \cdot Z_0 \cdot Z_1 # \end{equation} # # Since the Hamiltonian consists of a sum of commuting operators ($Z_0$, $Z_1$, $Z_0\cdot Z1$), there exists a simultaneous eigenbasis (including the ground state) on which the value of each of the operators is $+1$ or $-1$. # # When `sample_number=1`, measuring an operator once in any state also results in $+1$ or $-1$. This implies that one get "lucky" with _any_ mininizer method even on noisy hardware. (Indeed, we have been able to reproduce this result with `my_nelder_mead`.) # # For more complex molecules, the Hamiltonian is unlikely to consist of a sum of commuting operators, hence picking up a good optimizer and its parameters will be crucial for success. # ### The (conditional) runner-up # The runner-up also used `sample_number=1` but only a single run (hence, it's a "conditional" runner-up, as we can determine the error only from multiple runs). idxmin2 = df_metrics['T_ave'].idxmin() idxmin2 df_metrics.loc[[idxmin2]] df.loc[idxmin2] # Platform, Team, minimizer Function, number of Samples, number of function eValuations, Experiment, Repetition (p,t,f,s,v,e) = idxmin2 # Plot the winner. plot(df.loc[[(p,t,f,s,v,e,k) for k in range(len(df.loc[idxmin2]))]], xmax=7, xstep=1, ymin=-3.00, ymax=0.00+0.01, legend_loc='upper center') # Print the minimizer source. print(df.loc[(p,t,f,s,v,e,0)]['minimizer_src']) # Exclude the conditional runner-up. df_metrics = df_metrics.drop(idxmin2) # ### The QVM runner-up platform_qvm = 'qvm' df_metrics_qvm = df_metrics.loc[platform_qvm] idxmin_qvm = df_metrics_qvm['T_ave'].idxmin() idxmin_qvm df_metrics.loc[platform_qvm].loc[[idxmin_qvm]] df.loc[platform_qvm].loc[idxmin_qvm] # Platform, Team, minimizer Function, number of Samples, number of function eValuations, Experiment, Repetition p = platform_qvm (t,f,s,v,e) = idxmin_qvm # Plot the runner up. plot(df.loc[[(p,t,f,s,v,e,k) for k in range(len(df.loc[(p,t,f,s,v,e)]))]], xmax=9, xstep=1, ymin=-3.00, ymax=0.00+0.01, legend_loc='upper right') # Print the minimizer source. print(df.loc[(p,t,f,s,v,e,0)]['minimizer_src']) # Exclude the QVM runner-up. df_metrics = df_metrics.drop((p,t,f,s,v,e)) # ### The QPU runner-up platform_qpu = '8q-agave' df_metrics_qpu = df_metrics.loc[platform_qpu] idxmin_qpu = df_metrics_qpu['T_ave'].idxmin() idxmin_qpu df_metrics_qpu.loc[[idxmin_qpu]] df.loc[platform_qpu].loc[idxmin_qpu] # Platform, Team, Experiment, minimizer Function, number of Samples, number of function eValuations, Repetition p = platform_qpu (t,f,s,v,e) = idxmin_qpu # Plot the QPU runner-up. plot(df.loc[[(p,t,f,s,v,e,k) for k in range(len(df.loc[(p,t,f,s,v,e)]))]], xmax=7, xstep=1, ymin=-3.00, ymax=-0.00+0.01, legend_loc='upper right') # Print the minimizer source. print(df.loc[(p,t,f,s,v,e,0)]['minimizer_src']) # Exclude the QPU runner-up. df_metrics = df_metrics.drop((p,t,f,s,v,e)) # ### The best entry with 100% convergence (prob=0.999) df_metrics_prob100 = get_metrics(df, delta=0.1, prob=0.999, which_fun_key='fun_exact', which_time_key='total_q_shots') df_metrics_prob100 = df_metrics_prob100[(df_metrics_prob100['s']==1) & (df_metrics_prob100['num_repetitions']>1)] idxmin_prob100 = df_metrics_prob100['T_ave'].idxmin() idxmin_prob100 df_metrics_prob100.loc[[idxmin_prob100]] df.loc[idxmin_prob100] # Platform, Team, Experiment, minimizer Function, number of Samples, number of function eValuations, Repetition (p,t,f,s,v,e) = idxmin_prob100 # Plot. plot(df.loc[[(p,t,f,s,v,e,k) for k in range(len(df.loc[(p,t,f,s,v,e)]))]], xmax=30, xstep=1, ymin=-3.00, ymax=-0.00+0.01, legend_loc='upper right') # ### The worst entry with 100% convergence (prob=0.999) idxmax_prob100 = df_metrics_prob100['T_ave'].idxmax() idxmax_prob100 df_metrics_prob100.loc[[idxmax_prob100]] df.loc[idxmax_prob100] # Platform, Team, Experiment, minimizer Function, number of Samples, number of function eValuations, Repetition (p,t,f,s,v,e) = idxmax_prob100 # Plot. plot(df.loc[[(p,t,f,s,v,e,k) for k in range(len(df.loc[(p,t,f,s,v,e)]))]], xmax=31, xstep=1, ymin=-3.00, ymax=-0.00+0.01, legend_loc='upper right') # The ratio of the worst of the best with 100% convergence. df_metrics_prob100.loc[idxmax_prob100]['T_ave'] / df_metrics_prob100.loc[idxmin_prob100]['T_ave'] # Exclude the best entry with 100% convergence. df_metrics_prob100 = df_metrics_prob100.drop(idxmin_prob100) # ### The most accurate entry (also the runner-up with 100% convergence!) df_metrics_delta0 = get_metrics(df, delta=0.01, prob=0.999, which_fun_key='fun_exact', which_time_key='total_q_shots') df_metrics_delta0 = df_metrics_delta0[(df_metrics_delta0['num_repetitions']>1)] idxmin_delta0 = df_metrics_delta0['T_ave'].idxmin() idxmin_delta0 # Also, the runner-up entry with 100% convergence! idxmin_prob100 = df_metrics_prob100['T_ave'].idxmin() idxmin_prob100 df_metrics_delta0.loc[[idxmin_delta0]] df.loc[idxmin_delta0] # Platform, Team, Experiment, minimizer Function, number of Samples, number of function eValuations, Repetition (p,t,f,s,v,e) = idxmin_delta0 # Plot. plot(df.loc[[(p,t,f,s,v,e,k) for k in range(len(df.loc[(p,t,f,s,v,e)]))]], xmax=9, xstep=1, ymin=-3.00, ymax=-0.00+0.01, legend_loc='upper right') # Print the minimizer source. print(df.loc[(p,t,f,s,v,e,0)]['minimizer_src']) # ### Plot convergence # + # # Plot all. # plot(df, legend_loc='center') # - # Plot QPU only. plot(df, platform_set=[platform_qpu], markersize_divisor=10, xmin=0, xmax=34+0.01, xstep=1, ymin=-2.80, ymax=-1.80-0.01, ystep=0.05, legend_loc='lower left') # Plot COBYLA only. plot(df, minimizer_method_set=['my_cobyla'], sample_number_set=[50], markersize_divisor=5, xmin=5, xmax=32+0.01, xstep=1, ymin=-2.89, ymax=-1.79+0.01, ystep=0.05, legend_loc='upper right') # ### Plot execution metrics # + # plot_metric(df) # + # plot_metric(df, metric='total_q_shots')
jnotebook/hackathon.20181006/analysis.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # jupyter/base-notebook on Binder # # Run the cells below to inspect what's in the [jupyter/base-notebook](https://jupyter-docker-stacks.readthedocs.io/en/latest/using/selecting.html#jupyter-base-notebook) image from the Jupyter Docker Stacks project. # # Click here to open a [JupyterLab](../lab) tab. Click here to open a [Classic Notebook](../notebooks) tab. import os print(f'This container is using tag {os.environ["TAG"]} of the jupyter/base-notebook image') # The notebook server is running as the following user. # !id # Here's the contents of that user's home directory, the default notebook directory for the server. # !ls -al # Conda is available in the user's path. # !which conda # The user has read/write access to the root conda environment. # !ls -l /opt/conda # The following packages are conda-installed in the base image to support [Jupyter Notebook](https://github.com/jupyter/notebook), [JupyterLab](https://github.com/jupyterlab/jupyterlab), and their use in [JupyterHub](https://github.com/jupyterhub/jupyterhub) environments (e.g., [MyBinder](http://mybinder.org/)). # !conda list # Other images in the [jupyter/docker-stacks project](https://github.com/jupyter/docker-stacks) include additional libraries. See the [Jupyter Docker Stacks documentation](https://jupyter-docker-stacks.readthedocs.io/en/latest/) for full details.
0x-launch-kit.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # **Connect With Me in Linkedin :-** https://www.linkedin.com/in/dheerajkumar1997/ # ## Regression # # In this lecture, I will bring together various techniques for feature engineering that we have covered in this course to tackle a regression problem. This would give you an idea of the end-to-end pipeline to build machine learning algorithms for regression. # # =================================================================================================== # # ## Real Life example: # # ### Predicting Sale Price of Houses # # The problem at hand aims to predict the final sale price of homes based on different explanatory variables describing aspects of residential homes. Predicting house prices is useful to identify fruitful investments, or to determine whether the price advertised for a house is over or underestimated, before making a buying judgment. # ## House Prices dataset # + # to handle datasets import pandas as pd import numpy as np # for plotting import matplotlib.pyplot as plt % matplotlib inline # to divide train and test set from sklearn.model_selection import train_test_split # feature scaling from sklearn.preprocessing import StandardScaler # for tree binarisation from sklearn.tree import DecisionTreeRegressor from sklearn.model_selection import cross_val_score # to build the models from sklearn.linear_model import LinearRegression, Lasso from sklearn.ensemble import RandomForestRegressor from sklearn.svm import SVR import xgboost as xgb # to evaluate the models from sklearn.metrics import mean_squared_error pd.pandas.set_option('display.max_columns', None) import warnings warnings.filterwarnings('ignore') # - # load dataset data = pd.read_csv('houseprice.csv') print(data.shape) data.head() # + # Load the dataset for submission (the one on which our model will be evaluated by Kaggle) # it contains exactly the same variables, but not the target submission = pd.read_csv('house_price_submission.csv') submission.head() # - # The House Price dataset is bigger than the Titanic dataset. It contains more variables for each one of the houses. Thus, manual inspection of each one of them is a bit time demanding. Therefore, here instead of deciding variable by variable what is the best way to proceed, I will try to automate the feature engineering pipeline, making some a priori decisions on when I will apply one technique or the other, and then expanding them to the entire dataset. # ### Types of variables (section 2) # # Let's go ahead and find out what types of variables there are in this dataset # let's inspect the type of variables in pandas data.dtypes # There are a mixture of categorical and numerical variables. Numerical are those of type int and float. Categorical those of type object. print('Number of House Id labels: ', len(data.Id.unique())) print('Number of Houses in the Dataset: ', len(data)) # Id is a unique identifier for each of the houses. Thus this is not a variable that we can use. # find categorical variables categorical = [var for var in data.columns if data[var].dtype=='O'] print('There are {} categorical variables'.format(len(categorical))) # find numerical variables numerical = [var for var in data.columns if data[var].dtype!='O'] print('There are {} numerical variables'.format(len(numerical))) # #### Find discrete variables # # To identify discrete variables, I will select from all the numerical ones, those that contain a finite and small number of distinct values. See below. # + # let's visualise the values of the discrete variables discrete = [] for var in numerical: if len(data[var].unique())<20: print(var, ' values: ', data[var].unique()) discrete.append(var) print('There are {} discrete variables'.format(len(discrete))) # - # ### Types of problems within the variables (section 3) # # #### Missing values # let's visualise the percentage of missing values for var in data.columns: if data[var].isnull().sum()>0: print(var, data[var].isnull().mean()) # let's inspect the type of those variables with a lot of missing information for var in data.columns: if data[var].isnull().mean()>0.80: print(var, data[var].unique()) # There are a few variables with missing data. The ones with a lot of missing data are categorical variables. We will need to fill those out. See below. # # #### Outliers continuous = [var for var in numerical if var not in discrete and var not in ['Id', 'SalePrice']] continuous # + # let's make boxplots to visualise outliers in the continuous variables # and histograms to get an idea of the distribution for var in continuous: plt.figure(figsize=(15,6)) plt.subplot(1, 2, 1) fig = data.boxplot(column=var) fig.set_title('') fig.set_ylabel(var) plt.subplot(1, 2, 2) fig = data[var].hist(bins=20) fig.set_ylabel('Number of houses') fig.set_xlabel(var) plt.show() # - # The majority of the continuous variables seem to contain outliers. In addition, the majority of the variables are not normally distributed. If we are planning to build linear regression, we might need to tackle these to improve the model performance. To tackle the 2 aspects together, I will do discretisation. And in particular, I will use trees to find the right buckets onto which I will divide the variables. # #### Outlies in discrete variables # # Let's calculate the percentage of houses for each of the values that can take the discrete variables in the titanic dataset. I will call outliers, those values that are present in less than 1% of the houses. This is exactly the same as finding rare labels in categorical variables. Discrete variables, in essence can be pre-processed / engineered as if they were categorical. Keep this in mind. # outlies in discrete variables for var in discrete: print(data[var].value_counts() / np.float(len(data))) print() # Most of the discrete variables show values that are shared by a tiny proportion of houses in the dataset. For linear regression, this may not be a problem, but it most likely will be for tree methods. # # # #### Number of labels: cardinality for var in categorical: print(var, ' contains ', len(data[var].unique()), ' labels') # Most of the variables, contain only a few labels. Then, we do not have to deal with high cardinality. That is good news! # ### Separate train and test set # + # Let's separate into train and test set X_train, X_test, y_train, y_test = train_test_split(data, data.SalePrice, test_size=0.2, random_state=0) X_train.shape, X_test.shape # - # ### Engineering missing values in numerical variables (section 5) # #### Continuous variables # print variables with missing data for col in continuous: if X_train[col].isnull().mean()>0: print(col, X_train[col].isnull().mean()) # - LotFrontage and GarageYrBlt: create additional variable with NA + median imputation # - CMasVnrArea: median imputation # + # add variable indicating missingness + median imputation for df in [X_train, X_test, submission]: for var in ['LotFrontage', 'GarageYrBlt']: df[var+'_NA'] = np.where(df[var].isnull(), 1, 0) df[var].fillna(X_train[var].median(), inplace=True) for df in [X_train, X_test, submission]: df.MasVnrArea.fillna(X_train.MasVnrArea.median(), inplace=True) # - # #### Discrete variables # print variables with missing data for col in discrete: if X_train[col].isnull().mean()>0: print(col, X_train[col].isnull().mean()) # There are no missing data in the discrete variables. Good, then we don't have to engineer them. # # ### Engineering Missing Data in categorical variables (section 6) # print variables with missing data for col in categorical: if X_train[col].isnull().mean()>0: print(col, X_train[col].isnull().mean()) # I will add a 'Missing' Label to all of them. If the missing data are rare, I will handle those together with rare labels in a subsequent engineering step. # + # add label indicating 'Missing' to categorical variables for df in [X_train, X_test, submission]: for var in categorical: df[var].fillna('Missing', inplace=True) # - # check absence of null values for var in X_train.columns: if X_train[var].isnull().sum()>0: print(var, X_train[var].isnull().sum()) # check absence of null values for var in X_train.columns: if X_test[var].isnull().sum()>0: print(var, X_test[var].isnull().sum()) # check absence of null values submission_vars = [] for var in X_train.columns: if var!='SalePrice' and submission[var].isnull().sum()>0: print(var, submission[var].isnull().sum()) submission_vars.append(var) # Fare in the submission dataset contains one null value, I will replace it by the median for var in submission_vars: submission[var].fillna(X_train[var].median(), inplace=True) # ### Outliers in Numerical variables (15) # # In order to tackle outliers and skewed distributions at the same time, I suggested I would do discretisation. And in order to find the optimal buckets automatically, I would use decision trees to find the buckets for me. def tree_binariser(var): score_ls = [] # here I will store the mse for tree_depth in [1,2,3,4]: # call the model tree_model = DecisionTreeRegressor(max_depth=tree_depth) # train the model using 3 fold cross validation scores = cross_val_score(tree_model, X_train[var].to_frame(), y_train, cv=3, scoring='neg_mean_squared_error') score_ls.append(np.mean(scores)) # find depth with smallest mse depth = [1,2,3,4][np.argmax(score_ls)] #print(score_ls, np.argmax(score_ls), depth) # transform the variable using the tree tree_model = DecisionTreeRegressor(max_depth=depth) tree_model.fit(X_train[var].to_frame(), X_train.SalePrice) X_train[var] = tree_model.predict(X_train[var].to_frame()) X_test[var] = tree_model.predict(X_test[var].to_frame()) submission[var] = tree_model.predict(submission[var].to_frame()) for var in continuous: tree_binariser(var) X_train[continuous].head() for var in continuous: print(var, len(X_train[var].unique())) # ### Engineering rare labels in categorical and discrete variables (section 9) def rare_imputation(variable): # find frequent labels / discrete numbers temp = X_train.groupby([variable])[variable].count()/np.float(len(X_train)) frequent_cat = [x for x in temp.loc[temp>0.03].index.values] X_train[variable] = np.where(X_train[variable].isin(frequent_cat), X_train[variable], 'Rare') X_test[variable] = np.where(X_test[variable].isin(frequent_cat), X_test[variable], 'Rare') submission[variable] = np.where(submission[variable].isin(frequent_cat), submission[variable], 'Rare') for var in ['BsmtFullBath', 'BsmtHalfBath', 'GarageCars']: submission[var] = submission[var].astype('int') # + # find infrequent labels in categorical variables for var in categorical: rare_imputation(var) for var in discrete: rare_imputation(var) # - for var in X_train.columns: if var!='SalePrice' and submission[var].isnull().sum()>0: print(var, submission[var].isnull().sum()) submission_vars.append(var) # let's check that it worked for var in categorical: print(var, X_train[var].value_counts()/np.float(len(X_train))) print() for var in X_train.columns: if var!='SalePrice' and submission[var].isnull().sum()>0: print(var, submission[var].isnull().sum()) # ### Encode categorical and discrete variables (section 10) # + def encode_categorical_variables(var, target): # make label to price dictionary ordered_labels = X_train.groupby([var])[target].mean().to_dict() # encode variables X_train[var] = X_train[var].map(ordered_labels) X_test[var] = X_test[var].map(ordered_labels) submission[var] = submission[var].map(ordered_labels) # encode labels in categorical vars for var in categorical: encode_categorical_variables(var, 'SalePrice') # encode labels in discrete vars for var in discrete: encode_categorical_variables(var, 'SalePrice') # - for var in X_train.columns: if var!='SalePrice' and submission[var].isnull().sum()>0: print(var, submission[var].isnull().sum()) #let's inspect the dataset X_train.head() # We can see that the labels have now been replaced by the mean house price. # # ### Feature scaling (section 13) X_train.describe() training_vars = [var for var in X_train.columns if var not in ['Id', 'SalePrice']] # fit scaler scaler = StandardScaler() # create an instance scaler.fit(X_train[training_vars]) # fit the scaler to the train set for later use # The scaler is now ready, we can use it in a machine learning algorithm when required. See below. # # ### Machine Learning algorithm building # # #### xgboost # + xgb_model = xgb.XGBRegressor() eval_set = [(X_test[training_vars], y_test)] xgb_model.fit(X_train[training_vars], y_train, eval_set=eval_set, verbose=False) pred = xgb_model.predict(X_train[training_vars]) print('xgb train mse: {}'.format(mean_squared_error(y_train, pred))) pred = xgb_model.predict(X_test[training_vars]) print('xgb test mse: {}'.format(mean_squared_error(y_test, pred))) # - # #### Random Forests # + rf_model = RandomForestRegressor() rf_model.fit(X_train[training_vars], y_train) pred = rf_model.predict(X_train[training_vars]) print('rf train mse: {}'.format(mean_squared_error(y_train, pred))) pred = rf_model.predict(X_test[training_vars]) print('rf test mse: {}'.format(mean_squared_error(y_test, pred))) # - # #### Support vector machine # + SVR_model = SVR() SVR_model.fit(scaler.transform(X_train[training_vars]), y_train) pred = SVR_model.predict(scaler.transform(X_train[training_vars])) print('SVR train mse: {}'.format(mean_squared_error(y_train, pred))) pred = SVR_model.predict(scaler.transform(X_test[training_vars])) print('SVR test mse: {}'.format(mean_squared_error(y_test, pred))) # - # #### Regularised linear regression # + lin_model = Lasso(random_state=2909) lin_model.fit(scaler.transform(X_train[training_vars]), y_train) pred = lin_model.predict(scaler.transform(X_train[training_vars])) print('linear train mse: {}'.format(mean_squared_error(y_train, pred))) pred = lin_model.predict(scaler.transform(X_test[training_vars])) print('linear test mse: {}'.format(mean_squared_error(y_test, pred))) # - # ### Submission to Kaggle # + pred_ls = [] for model in [xgb_model, rf_model]: pred_ls.append(pd.Series(model.predict(submission[training_vars]))) pred = SVR_model.predict(scaler.transform(submission[training_vars])) pred_ls.append(pd.Series(pred)) pred = lin_model.predict(scaler.transform(submission[training_vars])) pred_ls.append(pd.Series(pred)) final_pred = pd.concat(pred_ls, axis=1).mean(axis=1) # - temp = pd.concat([submission.Id, final_pred], axis=1) temp.columns = ['Id', 'SalePrice'] temp.head() temp.to_csv('submit_housesale.csv', index=False) # ### Feature importance importance = pd.Series(rf_model.feature_importances_) importance.index = training_vars importance.sort_values(inplace=True, ascending=False) importance.plot.bar(figsize=(18,6)) importance = pd.Series(xgb_model.feature_importances_) importance.index = training_vars importance.sort_values(inplace=True, ascending=False) importance.plot.bar(figsize=(18,6)) importance = pd.Series(np.abs(lin_model.coef_.ravel())) importance.index = training_vars importance.sort_values(inplace=True, ascending=False) importance.plot.bar(figsize=(18,6)) # **Connect With Me in Linkedin :-** https://www.linkedin.com/in/dheerajkumar1997/
Feature Engineering Techniques/Regression.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Metrics # # ## Inception Score (IS) # ​ # [original paper](https://arxiv.org/abs/1606.03498) # ​ # # **Aim**: see how variate samples are # # ### Idea # Let's see how much classes our generative model is able to generate # # ![image](https://miro.medium.com/max/2976/1*X29oOi1Tzch2j6MuG9XS1Q.png) # ![image](https://miro.medium.com/max/2812/1*t8lE_W4UKQ8jKgzxCAbHTA.png) # # ### How it works # We compare each samples classes with averaged (marginal) one. If each sample's distribution differs from common (marginal) one, then it differs from others. # # ![image](https://miro.medium.com/max/3472/1*hPEJY3MkOZyKFA6yEqzuyg.png) # # Here KL divergence is used to calculate the distance # # # ## Frechet Inception Distance (FID) # # **Idea**: compare distributions of real and generated samples # # **Algorithm**: # 1. Get samples embeddings from intermediate layers of neural network pre-trained on some external dataset # 2. Approximate embeddings of real and generated samples by gaussians $\mathcal{N}(\mu_1, \Sigma_1)$ and $\mathcal{N}(\mu_2, \Sigma_2)$ respectively # 3. Calclulate Frecher Distance = $\|\mu_1 – \mu_2\|^2 + Tr(\Sigma_1 + \Sigma_2 - 2 * \text{sqrt}(\Sigma_1*\Sigma_2))$. The smaller the better # ## Metrics summary # # ![](https://miro.medium.com/max/875/0*GHvXKp6DQPAHGdqH) # # # # ### Comparison # # | Metric | IS | FID | # |----------------------------------:|:------------------------------------------------------------------:|----------------------------------------------------------------| # | **Aim** | show *how variate* generated images are | show *how close* generated images to real ones are | # | Which distributions are compared? | Discrete predicted class distributions (marginal vs. sample's one) | Two continuous gaussian distributions (real vs. generated one) | # | Which data is used? | Generated only | Generated and real | # | Which distance is used? | KL | Frechet distance | # ### Task # Implement FID and IS distances # # The code is based on https://github.com/lzhbrian/metrics # + import torch import torch.nn as nn from torch.autograd import Variable from torch.nn import functional as F import torch.utils.data from torchvision.models.inception import inception_v3 from scipy.stats import entropy import scipy.misc from scipy import linalg import numpy as np from tqdm import tqdm from glob import glob import pathlib import os import sys import random def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6): """Numpy implementation of the Frechet Distance. The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1) and X_2 ~ N(mu_2, C_2) is d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)). Stable version by <NAME>. Params: -- mu1 : Numpy array containing the activations of a layer of the inception net (like returned by the function 'get_predictions') for generated samples. -- mu2 : The sample mean over activations, precalculated on an representative data set. -- sigma1: The covariance matrix over activations for generated samples. -- sigma2: The covariance matrix over activations, precalculated on an representative data set. Returns: -- : The Frechet Distance. """ if isinstance(mu1, int): mu1 = mu1*np.ones_like(mu2) if isinstance(sigma1, int): sigma1 = sigma1*np.ones_like(sigma2) mu1 = np.atleast_1d(mu1) mu2 = np.atleast_1d(mu2) sigma1 = np.atleast_2d(sigma1) sigma2 = np.atleast_2d(sigma2) assert mu1.shape == mu2.shape, \ 'Training and test mean vectors have different lengths %s, %s' % (mu1.shape, mu2.shape) assert sigma1.shape == sigma2.shape, \ 'Training and test covariances have different dimensions %s, %s' % (sigma1.shape, sigma2.shape) # Implement FID distance here ### BEGIN SOLUTION diff = mu1 - mu2 # Product might be almost singular covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False) if not np.isfinite(covmean).all(): msg = ('fid calculation produces singular product; ' 'adding %s to diagonal of cov estimates') % eps print(msg) offset = np.eye(sigma1.shape[0]) * eps covmean = linalg.sqrtm((sigma1 + offset).dot(sigma2 + offset)) # Numerical error might give slight imaginary component if np.iscomplexobj(covmean): if not np.allclose(np.diagonal(covmean).imag, 0, atol=1e-3): m = np.max(np.abs(covmean.imag)) raise ValueError('Imaginary component {}'.format(m)) covmean = covmean.real tr_covmean = np.trace(covmean) fid = diff.dot(diff) + np.trace(sigma1) + np.trace(sigma2) - 2 * tr_covmean ### END SOLUTION return fid class ScoreModel: def __init__(self, mode, cuda=True, stats_file='', mu1=0, sigma1=0): """ Computes the inception score of the generated images cuda -- whether or not to run on GPU mode -- image passed in inceptionV3 is normalized by mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5] and in range of [-1, 1] 1: image passed in is normalized by mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] 2: image passed in is normalized by mean=[0.500, 0.500, 0.500], std=[0.500, 0.500, 0.500] """ self.mu1, self.sigma1 = mu1, sigma1 # Set up dtype if cuda: self.dtype = torch.cuda.FloatTensor else: if torch.cuda.is_available(): print("WARNING: You have a CUDA device, so you should probably set cuda=True") self.dtype = torch.FloatTensor # setup image normalization mode self.mode = mode if self.mode == 1: transform_input = True elif self.mode == 2: transform_input = False else: raise Exception("ERR: unknown input img type, pls specify norm method!") self.inception_model = inception_v3(pretrained=True, transform_input=transform_input).type(self.dtype) self.inception_model.eval() # self.up = nn.Upsample(size=(299, 299), mode='bilinear', align_corners=False).type(self.dtype) # remove inception_model.fc to get pool3 output 2048 dim vector self.fc = self.inception_model.fc self.inception_model.fc = nn.Sequential() def __forward(self, x): """ x should be N x 3 x 299 x 299 and should be in range [-1, 1] """ x = F.interpolate(x, size=(299, 299), mode='bilinear', align_corners=False) x = self.inception_model(x) pool3_ft = x.data.cpu().numpy() # inner activation (of the last layer) x = self.fc(x) # output predictions preds = F.softmax(x, 1).data.cpu().numpy() return pool3_ft, preds @staticmethod def __calc_is(preds, n_split): """ regularly, return (is_mean, is_std) if n_split==1 and return_each_score==True: return (scores, 0) # scores is a list with len(scores) = n_img = preds.shape[0] """ n_img = preds.shape[0] # Implement Inception Score here # Split predictions by chunks of size "n_split" and add IS scores of the chunks to "split_scores" list split_scores = [] ### BEGIN SOLUTION # Now compute the mean kl-div for k in range(n_split): part = preds[k * (n_img // n_split): (k + 1) * (n_img // n_split), :] py = np.mean(part, axis=0) scores = [] for i in range(part.shape[0]): pyx = part[i, :] scores.append(entropy(pyx, py)) split_scores.append(np.exp(np.mean(scores))) ### END SOLUTION return np.mean(split_scores), np.std(split_scores) @staticmethod def __calc_stats(pool3_ft): # pool3_ft is 2048 dimensional inner activation of the InceptionV3 network mu = np.mean(pool3_ft, axis=0) sigma = np.cov(pool3_ft, rowvar=False) return mu, sigma def get_score_image_tensor(self, imgs_nchw, mu1=0, sigma1=0, n_split=10, batch_size=32): """ param: imgs_nchw -- Pytorch Tensor, size=(N,C,H,W), in range of [-1, 1] batch_size -- batch size for feeding into Inception v3 n_splits -- number of splits return: is_mean, is_std, fid mu, sigma of dataset regularly, return (is_mean, is_std) """ n_img = imgs_nchw.shape[0] assert batch_size > 0 assert n_img > batch_size pool3_ft = np.zeros((n_img, 2048)) preds = np.zeros((n_img, 1000)) # Fill inner activations "pool3_ft" and output predictions "preds" by the network # Hint: use self.__forward() ### BEGIN SOLUTION for i in tqdm(range(np.int32(np.ceil(1.0 * n_img / batch_size)))): batch_size_i = min((i+1) * batch_size, n_img) - i * batch_size batchv = Variable(imgs_nchw[i * batch_size:i * batch_size + batch_size_i, ...].type(self.dtype)) pool3_ft[i * batch_size:i * batch_size + batch_size_i], preds[i * batch_size:i * batch_size + batch_size_i] = self.__forward(batchv) ### END SOLUTION mu2, sigma2 = None, None # Calculate statistics for inner activations "pool3_ft" ### BEGIN SOLUTION mu2, sigma2 = self.__calc_stats(pool3_ft) ### END SOLUTION mu1, sigma1 = self.mu1, self.sigma1 is_mean, is_std = None, None # Calculate IS score ### BEGIN SOLUTION is_mean, is_std = self.__calc_is(preds, n_split) ### END SOLUTION fid = -1 # Calculate FID score ### BEGIN SOLUTION fid = calculate_frechet_distance(mu1, sigma1, mu2, sigma2) ### END SOLUTION return is_mean, is_std, fid, mu2, sigma2 def get_score_dataset(self, dataset, mu1=0, sigma1=0, n_split=10, batch_size=32): """ get score from a dataset param: dataset -- pytorch dataset, img in range of [-1, 1] batch_size -- batch size for feeding into Inception v3 n_splits -- number of splits return: is_mean, is_std, fid mu, sigma of dataset """ n_img = len(dataset) dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size) pool3_ft = np.zeros((n_img, 2048)) preds = np.zeros((n_img, 1000)) # Fill inner activations "pool3_ft" and output predictions "preds" by the network # Hint: use self.__forward() ### BEGIN SOLUTION for i, batch in tqdm(enumerate(dataloader, 0)): batch = batch.type(self.dtype) batchv = Variable(batch) batch_size_i = batch.size()[0] pool3_ft[i * batch_size:i * batch_size + batch_size_i], preds[i * batch_size:i * batch_size + batch_size_i] = self.__forward(batchv) ### END SOLUTION mu2, sigma2 = None, None # Calculate statistics for inner activations "pool3_ft" ### BEGIN SOLUTION mu2, sigma2 = self.__calc_stats(pool3_ft) ### END SOLUTION mu1, sigma1 = self.mu1, self.sigma1 is_mean, is_std = None, None # Calculate IS score ### BEGIN SOLUTION is_mean, is_std = self.__calc_is(preds, n_split) ### END SOLUTION fid = -1 # Calculate FID score ### BEGIN SOLUTION fid = calculate_frechet_distance(mu1, sigma1, mu2, sigma2) ### END SOLUTION return is_mean, is_std, fid, mu2, sigma2 # read folder, return torch Tensor in NCHW, normalized def read_folder(foldername): files = [] for ext in ('*.png', '*.jpg', '*.jpeg', '.bmp'): files.extend(glob(os.path.join(foldername, ext))) img_list = [] print('Reading Images from %s ...' % foldername) for file in tqdm(files): img = scipy.misc.imread(file, mode='RGB') img = scipy.misc.imresize(img, (299, 299), interp='bilinear') img = np.cast[np.float32]((-128 + img) / 128.) # 0~255 -> -1~1 img = np.expand_dims(img, axis=0).transpose(0, 3, 1, 2) # NHWC -> NCHW img_list.append(img) random.shuffle(img_list) img_list_tensor = torch.Tensor(np.concatenate(img_list, axis=0)) return img_list_tensor class IgnoreLabelDataset(torch.utils.data.Dataset): def __init__(self, orig, size=1000): self.orig = orig self.size = size def __getitem__(self, index): return self.orig[index][0] def __len__(self): if self.size: return self.size else: return len(self.orig) import torchvision.datasets as dset import torchvision.transforms as transforms cifar = dset.CIFAR10(root='../data/cifar10', download=True, transform=transforms.Compose([ transforms.Resize(32), transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) ]) ) IgnoreLabelDataset(cifar) print ("Calculating IS score on CIFAR 10...") is_fid_model = ScoreModel(mode=2, cuda=True) is_mean, is_std, fid, _, _ = is_fid_model.get_score_dataset(IgnoreLabelDataset(cifar), n_split=10) ### BEGIN HIDDEN TEST import numpy.testing as np_testing np_testing.assert_almost_equal(is_mean, 7.8371, decimal=4) np_testing.assert_almost_equal(is_std, 0.4692, decimal=4) ### END HIDDEN TEST print(u"Inception score: %.4f\u00B1%.4f"%(is_mean, is_std)) print("FID: %.4f"%fid) # - # # LPIPS (Learned Perceptual Image Similarity) # $$d_{LPIPS}(x,y)=\Sigma_l\frac{1}{H_lW_l}\Sigma_{i,j}||w_l\cdot(\hat{x}^l_{ij}-\hat{y}^l_{ij})||^2_2$$ # where $\hat{x}^l_{ij}$ and $\hat{y}^l_{ij}$ denote the normalized feature vectors at layer $l$ and pixel $(i, j)$, $w_l$ contains weights for each of the features in layer $l$, and $\cdot$ multiplies the feature vectors at each pixel by the specifically learned weights import torchvision dataset = torchvision.datasets.FashionMNIST('../data/fashion_mnist', download=True) # !pip install git+https://github.com/S-aiueo32/lpips-pytorch.git # + # %matplotlib inline import matplotlib.pyplot as plt original_img_idx = 0 original_img, original_label = dataset[original_img_idx] plt.imshow(original_img, cmap='gray') # - # ### Task # Find closest image to the above one # + from lpips_pytorch import LPIPS, lpips from tqdm.notebook import tqdm # define as a criterion module (recommended) criterion = LPIPS( net_type='alex', # choose a network type from ['alex', 'squeeze', 'vgg'] version='0.1' # Currently, v0.1 is supported ) def img2tensor(img): return torch.from_numpy(np.array(img.resize((512,512)))) np.random.seed(10) img_indices = np.random.choice(np.arange(len(dataset)), 1000) # random images to be compared img_indices = [idx for idx in img_indices if idx != original_img_idx] distances, labels = [], [] # calculate LPIPS distances ### BEGIN SOLUTION for idx in tqdm(img_indices): img, label = dataset[idx] labels.append(label) distances.append(criterion(img2tensor(original_img), img2tensor(img)).detach().cpu().squeeze().item()) ### END SOLUTION # - plt.figure(figsize=(17,10)) n_classes = 10 for label in range(n_classes): plt.subplot(4,3,label+1) plt.title(f'LPIPS. %s label (%d)' % ({True: 'Same', False: 'Another'}[label==original_label], label)) plt.xlim((0.,0.7)) plt.hist(np.array(distances)[np.array(labels)==label], bins=20, alpha=0.5); plt.tight_layout(); # + plt.figure(figsize=(17,10)) closest_img_cnt = 9 closest_img_indices, closest_distances, closest_labels = [ np.array(img_indices)[np.argsort(distances)[:closest_img_cnt]], np.array(distances)[np.argsort(distances)[:closest_img_cnt]], np.array(labels)[np.argsort(distances)[:closest_img_cnt]]] for ax_idx, (img_idx, distance, label) in enumerate(zip(closest_img_indices, closest_distances, closest_labels)): img = np.array(dataset[img_idx][0]) plt.subplot(3,3,ax_idx+1) plt.title(f'Label: %d Distance: %.3f'%(label, distance)) plt.imshow(img, cmap='gray') plt.tight_layout(); # - ### BEGIN HIDDEN TEST assert(min(distances) < 0.2) assert((np.array(closest_labels) == original_label).mean() > 0.9) ### END HIDDEN TEST
seminars/seminar-2-metrics/metrics.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: venv # language: python # name: venv # --- # # Reducto extraction from top 4000 pypi packages ordered by downloads # This notebook presents a simple study of the measures obtained by running the [reducto](https://pypi.org/project/reducto/) package on the 4000 most downloaded pypi packages. # # *Section 1* presents the data extraction methodology, *section 2* explores the descriptive statistics of the packages (that could be parsed), *section 3* plots the histograms of the variables, *section 4* presents the linear regression model of the number of downloads explained by the *reducto* variables, and *section 5* presents a the clusters obtained from the 2 first principal components. # ## 1. Data # # The data extracted corresponds to the packages obtained from: https://hugovk.github.io/top-pypi-packages/, # specifically to the last version of 4000 most downloaded packages from PyPI (obtained from the github repo: [top_pypi_packages](https://github.com/hugovk/top-pypi-packages/blob/master/top-pypi-packages-365-days.json)) # # From the total number of pacakges, 3647 packages are present: # - 353 of the total failed due to the following reasons: # - 153 are discarded as the algorithm to obtain the package installed from the corresponding package failed. The name of the package stored internally could not be found. These packages could be included by solving this issue. # An example of this type is: [google-cloud-core](https://github.com/googleapis/python-cloud-core) # Many google or azure packages failed in this category. # # - 123 are discarded due to installation issues. an example of this type would be: [pyobjc-framework-modelio](https://pypi.org/project/pyobjc-framework-ModelIO/), a library expected to be installed for macos (the code is run on an ubuntu machine). # # - 77 discareded due to reducto issues. An example of this type: [kafka](https://pypi.org/project/kafka/), which contains source code from older python versions not suported by the ast parser used in *reducto* (python 3.8). # # \* *The measures obtained regarding the lines obtained only apply to python code. Only .py files are accounted, other data folders or possible extensions like .c/.h files aren't taken into account. # These measures are obtained pointing to the same module that would be directly importable from python. This means that for packages which include the tests in the distribution [scikit-learn](https://github.com/scikit-learn/scikit-learn), the number of lines will be higher, while other packages which let the tests outside the distribution like [requests](https://github.com/psf/requests) show a lower number of lines.* # #### Import visualization and features # !python -m ipykernel install --user --name=venv # + import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt sns.set_style("darkgrid") import src.visualization.visualize as viz import src.features.build_features as bf # - # ## 2. Descriptive statistics of the variables reducto_table = bf.get_reducto_reports_table() reducto_table.describe(percentiles=[0.05, 0.25, 0.5, 0.75, 0.95]) # The total number of packages under study from the original 4000 are 3647. Given the high dispersion across the different packages, the mean values of the variables may be highly skewed, so the median value may be more representative of the results. # # Regarding the median number of `lines`, reads 1.603k lines, while the mean value is 14.024k. # The `average_function_length` of the packages is 12.85, with a median of 9 lines (less outliers are found in this variable, expected as we are taking the average of mean values). A mean of 534 `number_of_functions` is found on these packages (81 in median), and the mean/median `source_files` (.py files in the package) are 49.21 and 8 respectively. # The variables `source_lines`, `blank_lines`, `docstring_lines` and `comment_lines` are more interesting when seen as a percentage of the total of lines of each package, shown in the histograms of *section 3*. # ###### Packages with the biggest values by field df = pd.concat([reducto_table.idxmax(), reducto_table.max()], axis=1) df.columns = ["package name", "value"] df # ## 3. Histograms of the variables # # The variables studied include the `source_lines`, `blank_lines`, `docstring_lines` and `comment_lines` scaled by the total lines: # # A log-transformation is applied to the total number of `lines` to normalize the values and simplify the visualization due to the difference in scale across packages. # # The distribution of the `average_function_length` is plotted for every package (left), and to the subset of packages with less than 50 lines in average (only 51 packages are extracted), to remove the noise from a those packages with a big average gunction length: log_lines = reducto_table['lines'].apply(np.log) sns.histplot(log_lines, kde=True) plt.title(r"Histogram of $log(lines)$"); viz.plot_average_function_length() # The following figures show the distribution of the relative `source_lines`, `blank_lines`, `docstring_lines` and `comment_lines`: viz.plot_histogram_relative_numbers() print(bf.get_reducto_reports_relative()[['source_lines', 'blank_lines', 'docstring_lines', 'comment_lines']].describe()) # From the previous figures we can see that a the average package in PyPI (from the sample studied here) has a distribution of 67% `source_lines` , 14% `blank_lines`, 11% `docstring_lines` and 6% `comment_lines`. # ## 4. Linear regression: downloads per package explained by reducto features # To see if there is any relationship between the variables obtained from `reducto` and the total number of downloads by of each package, the following model is estimated: # $$log(downloads\_per\_package) = \beta_0 + \beta_1 source\_lines + \beta_2 docstring\_lines + \beta_3 comment\_lines + \beta_4 log(average\_function\_length) + \beta_5 log(number\_of\_functions) + \beta_6 log(source\_files) + \epsilon $$ # The `downloads_per_package` are transformed to logarithm, as well as the `average_function_lentgh`, the `number_of_functions` and the `source_files`. Things to keep in mind: # # - The variables `source_lines`, `docstring_lines`, `comment_lines`, and `blank_lines` are a linear combination, so one has to be removed to estimate the model. In this case `blank_lines` is dropped. # # - The total number of `lines` is removed to avoid estimation errors due to multicollinearity, as this variable is highly correlated with `number_of_functions` and `source_files`. # # - A correction to the standard errors is applied against heteroscedasticity. # ### 4.1. Correlations across variables # # The following heatmap shows the correlation accross the different variables: # # - The `number_of_functions`, `source_files` are highly correlated with the `lines` of a package (0.91 and 0.83 respectively). # # - `source_lines`, `blank_lines`, `docstring_lines` and `comment_lines` are negatively correlated with each other as expected, with the higher magnitude between `source_lines` and `docstring_lines`, which suggests that these variables are interchangeable, when more `source_lines` are present, less `docstring_lines` are expected in average. import importlib importlib.reload(viz) data = bf.get_reducto_reports_relative() viz.plot_correlation(data) plt.title("Correlation heatmap"); # ### 4.2. Model # # Inspecting the linear regression results, the only two variables (apart from the constant) statistically different from zero are the `number_of_functions` and `source_files`. # # - The interpretation for `number_of_functions` would be: a 1% increase in the number of functions would **increase** around 8.5% the number of downloads in average. # # - A 1% increase in `source_files` would **decrease** around 8.7% the number of downloads in average. # # The difference in packages (3537 vs 3647) comes from removing the packages considered outliers (defined as those with over 6 standard deviations in the fields `lines`, `number_of_functions`, `source_files` and `average_function_length`, or a value of 0 in those variables). # # Regarding the variance of the `number of downloads` explained by these variables, the Adjusted R-squared statistic suggests that these variables have a low explanatory power. import src.models.models as md import importlib importlib.reload(md) model = md.reducto_explain_downloads(log_y=True, log_x=True, drop_columns=['lines']) # ## 5. Clustering # # Finally, an attempt to visualize possible clusters formed by these variables is made by applying the [KMeans](https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html) algorithm to the 2 main Principal Components [PCA](https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html) (only 2 PCs are used to simplify the visualization). # # The number of clusters is selected using a [silhouette analysis](https://scikit-learn.org/stable/auto_examples/cluster/plot_kmeans_silhouette_analysis.html). # # ### 5.1. PC weights # # These weights are extracted of the variables transformed by logarithms and standardized, to avoid having the variables like the number of lines getting an excessive weight due to the higher scale. # viz.plot_pc_weights() # The first component seems to allocate most of the weight in the variables number of `lines`, `average_function_length`, `number_of_functions` and `source_lines`, wigh negative sign, while the variables (scaled by the number of `lines`) are represented in the second component. This second component mixes positive and negative weights, according with the negative correlation between these variables. # ### 5.2. KMeans clusters # # The algorithm seems to discriminate between the packages with a number of lines above the average (PC1<0)** vs smaller packages (in terms of python lines of code, remember every other language used for possible extensions isn't tracked here), more information (in terms of variables) should be used to see if there is some structure across different types packages. # # **Note** # (PC1<0)** : An example can be seen with *matplotlib*, the variables and weights for this package are: # - features: ( 2.4307685 , -0.26933659, -0.45693385, 0.49524478, -0.04750621, 0.4783165 , 2.42425339, 2.04149785) # - weights of PC1: (-0.57168787, -0.01308915, 0.2442107 , -0.08547451, -0.02184428, -0.21088967, -0.54474551, -0.51415718) # # Which returns a PC1 value of -4.0101206039001625. viz.plot_clusters(bf.get_pc(bf.get_reducto_reports_relative(log=True), standardize=True), n_clusters=2) # #### Further research # # - The results may be improved if more variables were used in the linear regression, like the ones used in [SourceRank](https://libraries.io/pypi/firmware-variables/sourcerank). # - A higher correlation may be found across variables like the number of stars per package, or the number of contributors. # - Different clustering algorithms may find different types of clusters. # - Associating these metrics to the package (maybe by associating the tags present in the repositories) may show different types of groups.
reducto.ipynb