code
stringlengths
2.5k
150k
kind
stringclasses
1 value
# Exploratory Data Analysis ``` # Import libraries %matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.preprocessing import StandardScaler, MinMaxScaler from sklearn import neighbors from matplotlib.colors import ListedColormap ``` ## Descripti...
github_jupyter
``` import numpy as np %matplotlib inline import matplotlib.pyplot as plt import pandas as pd ``` ## Exercise 1 - load the dataset: `../data/international-airline-passengers.csv` - inspect it using the `.info()` and `.head()` commands - use the function `pd.to_datetime()` to change the column type of 'Month' to a da...
github_jupyter
``` from datetime import datetime import mysql.connector from sys import exit HOST = "localhost" USER = "root" PASSWORD = "root" DATABASE = "hotel" database = mysql.connector.connect( host="localhost", user="noel", password="root", auth_plugin='mysql_native_password' ...
github_jupyter
``` import sympy as sym from sympy.polys.multivariate_resultants import MacaulayResultant sym.init_printing() ``` Macaulay Resultant ------------------ The Macauly resultant is a multivariate resultant. It is used for calculating the resultant of $n$ polynomials in $n$ variables. The Macaulay resultant is calculated...
github_jupyter
# Visulizing spatial information - California Housing This demo shows a simple workflow when working with geospatial data: * Obtaining a dataset which includes geospatial references. * Obtaining a desired geometries (boundaries etc.) * Visualisation In this example we will make a simple **proportional symbols m...
github_jupyter
# Build sentence/paragraph level QA application from python with Vespa > Retrieve paragraph and sentence level information with sparse and dense ranking features We will walk through the steps necessary to create a question answering (QA) application that can retrieve sentence or paragraph level answers based on a co...
github_jupyter
# Basic Protein-Ligand Affinity Models #Tutorial: Use machine learning to model protein-ligand affinity. Written by Evan Feinberg and Bharath Ramsundar Copyright 2016, Stanford University This DeepChem tutorial demonstrates how to use mach.ine learning for modeling protein-ligand binding affinity Overview: In this...
github_jupyter
# Quadtrees iterating on pairs of neighbouring items A quadtree is a tree data structure in which each node has exactly four children. It is a particularly efficient way to store elements when you need to quickly find them according to their x-y coordinates. A common problem with elements in quadtrees is to detect pa...
github_jupyter
``` import sys import os # path_to_script = os.path.dirname(os.path.abspath(__file__)) path_to_imcut = os.path.abspath("..") sys.path.insert(0, path_to_imcut) path_to_imcut import imcut imcut.__file__ import numpy as np import scipy import scipy.ndimage # import sed3 import matplotlib.pyplot as plt ``` ## Input da...
github_jupyter
``` import numpy as np import matplotlib.pyplot as plt import IPython import scipy.io.wavfile as wav import scipy.signal as ss def plotSound(signal, frameRate): plt.plot(signal) plt.show() soundStrings = ['aeiou.wav', 'an_in_on.wav'] selectedSoundString = soundStrings[1] frameRate, frames = wav.read(selectedSo...
github_jupyter
``` from edahelper import * import sklearn.naive_bayes as NB import sklearn.linear_model from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.pipeline import Pipeline from sklearn.linear...
github_jupyter
## Sleep analysis, using Passive Infrared (PIR) data, in 10sec bins from a single central PIR, at 200-220mm above the cage floor. Previously EEG-telemetered animals allow direct comparison of sleep scored by direct and non-invasive methods. ### 1st setup analysis environment: ``` import numpy as np # calculations i...
github_jupyter
# Notebook to Look at SMELT results ``` import netCDF4 as nc import matplotlib.pyplot as plt import matplotlib.colors from matplotlib.colors import LogNorm import datetime import os import numpy as np from salishsea_tools import visualisations as vis from salishsea_tools import (teos_tools, tidetools, viz_tools) %ma...
github_jupyter
### What is Matplotlib? Matplotlib is a plotting library for the Python, Pyplot is a matplotlib module which provides a MATLAB-like interface. Matplotlib is designed to be as usable as MATLAB, with the ability to use Python, and the advantage of being free and open-source. #### What does Matplotlib Pyplot do? Matplot...
github_jupyter
##### Copyright 2019 The TensorFlow Authors. ``` #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
github_jupyter
``` !wget https://download.microsoft.com/download/3/E/1/3E1C3F21-ECDB-4869-8368-6DEBA77B919F/kagglecatsanddogs_3367a.zip !unzip -q kagglecatsanddogs_3367a.zip import os import numpy as np import shutil import glob import warnings warnings.filterwarnings('ignore') cat_files = os.listdir('PetImages/Cat') dog_files = os....
github_jupyter
``` import pandas as pd medicare = pd.read_csv("/netapp2/home/se197/data/CMS/Data/medicare.csv") train_set = medicare[medicare.Hospital != 'BWH'] # MGH; n = 204014 validation_set = medicare[medicare.Hospital == 'BWH'] # BWH and Neither; n = 115726 import numpy as np fifty_perc_EHR_cont = np.percentile(medicare['Cal_M...
github_jupyter
Import des données ``` from __future__ import division, print_function, unicode_literals # imports import numpy as np import os import pandas as pd # stabilité du notebook d'une exécution à l'autre np.random.seed(42) # ignorer les warnings inutiles (voir SciPy issue #5998) import warnings warnings.filterwarnings(ac...
github_jupyter
This script is based on instructions given in [this lesson](https://github.com/HeardLibrary/digital-scholarship/blob/master/code/scrape/pylesson/lesson2-api.ipynb). ## Import libraries and load API key from file The API key should be the only item in a text file called `flickr_api_key.txt` located in the user's home...
github_jupyter
``` import matplotlib.pyplot as plt import torch import gpytorch import time import numpy as np %matplotlib inline import pickle import finite_ntk %pdb class ExactGPModel(gpytorch.models.ExactGP): # exact RBF Gaussian process class def __init__(self, train_x, train_y, likelihood, model, use_linearstrategy=Fals...
github_jupyter
### Lab 3: Expectation Maximization and Variational Autoencoder ### Machine Learning 2 (2017/2018) * The lab exercises should be made in groups of two or three people. * The deadline is Friday, 01.06. * Assignment should be submitted through BlackBoard! Make sure to include your and your teammates' names with the sub...
github_jupyter
## Set up ### package install ``` !sudo apt-get install build-essential swig !curl https://raw.githubusercontent.com/automl/auto-sklearn/master/requirements.txt | xargs -n 1 -L 1 pip install !pip install auto-sklearn !pip install pipelineprofiler # visualize the pipelines created by auto-sklearn !pip install shap !pi...
github_jupyter
#[1] Mount Drive ``` from google.colab import drive drive.mount('/content/drive') ``` # [2] Install Requirements and Load Libs ## Install RequirementsRequirements ``` !pip install datasets &> /dev/null !pip install rouge_score &> /dev/null !pip install -q transformers==4.8.2 &> /dev/null !pip install sentencepiece ...
github_jupyter
Precipitation Metrics (consecutive dry days, rolling 5-day precip accumulation, return period) ``` ! pip install xclim %matplotlib inline import xarray as xr import numpy as np import matplotlib.pyplot as plt import os import pandas as pd from datetime import datetime, timedelta, date import dask import dask.array a...
github_jupyter
# PageRank Performance Benchmarking This notebook benchmarks performance of running PageRank within cuGraph against NetworkX. NetworkX contains several implementations of PageRank. This benchmark will compare cuGraph versus the defaukt Nx implementation as well as the SciPy version Notebook Credits Original Aut...
github_jupyter
# lab 4 ## import libs and connect db ``` !pip install psycopg2 import pandas import configparser import psycopg2 config = configparser.ConfigParser() config.read('config.ini') host = config['my aws']['host'] db = config['my aws']['db'] user = config['my aws']['user'] password = config['my aws']['password'] conn = p...
github_jupyter
# IElixir - Elixir kernel for Jupyter Project <img src="logo.png" title="Hosted by imgur.com" style="margin: 0 0;"/> --- ## Google Summer of Code 2015 > Developed by [Piotr Przetacznik](https://twitter.com/pprzetacznik) > Mentored by [José Valim](https://twitter.com/josevalim) --- ## References * [Elixir language...
github_jupyter
``` import pandas as pd import numpy as np import matplotlib.pyplot as plt A = np.random.randn(4,3) B = np.sum(A, axis = 1, keepdims = True) B.shape ``` # Data Loading ``` data = pd.read_csv("ner_dataset.csv", encoding="latin1") data = data.drop(['POS'], axis =1) data.head() plt.style.use("ggplot") data = pd.read_csv...
github_jupyter
##### Copyright 2019 The TF-Agents Authors. ``` #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
github_jupyter
# TUTORIAL FOR TRAVELING SALESMAN PROBLEM __Introduction__: The famous travelling salesman problem (also called the travelling salesperson problem or in short TSP) is a well-known NP-hard problem in combinatorial optimization, asking for the shortest possible route that visits each city exactly once, given a list of c...
github_jupyter
# Logistic Regression Notebook version: 2.0 (Nov 21, 2017) 2.1 (Oct 19, 2018) Author: Jesús Cid Sueiro (jcid@tsc.uc3m.es) Jerónimo Arenas García (jarenas@tsc.uc3m.es) Changes: v.1.0 - First version v.1.1 - Typo correction. Prepared for slide presentation ...
github_jupyter
# Installation Make sure to have all the required software installed after proceeding. For installation help, please consult the [school guide](http://lxmls.it.pt/2018/LxMLS_guide_2018.pdf). # Python Basics ``` print('Hello World!') ``` We could also have this code in a separate file and still run it on a notebook ...
github_jupyter
TSG086 - Run `top` in all containers ==================================== Steps ----- ### Instantiate Kubernetes client ``` # Instantiate the Python Kubernetes client into 'api' variable import os from IPython.display import Markdown try: from kubernetes import client, config from kubernetes.stream import ...
github_jupyter
``` import pandas as pd data_folder = '..\\\\..\\\\..\\\\..\\\\Google Drive\\\\datasets\\\\mf_data_kaggle\\\\' def flip_cols2rows(src_df, col_list, item_category, key_col): df1 = pd.DataFrame() for i in col_list: df2 = src_df[[key_col, i]].rename(columns = {key_col: key_col, i: 'value'}).assign(item_des...
github_jupyter
**[Data Visualization: From Non-Coder to Coder Micro-Course Home Page](https://www.kaggle.com/learn/data-visualization-from-non-coder-to-coder)** --- In this tutorial you'll learn all about **histograms** and **density plots**. # Set up the notebook As always, we begin by setting up the coding environment. (_This ...
github_jupyter
## Output data preparation for dataset Twitch #### Plots and figures in separate notebook ``` # IMPORTS import matplotlib.pyplot as plt import numpy as np import csv import networkx as nx from random import sample import time import math import random import scipy import pandas as pd # Define necessary functions def...
github_jupyter
### Irrigation model input file prep This code prepares the final input file to the irrigation (agrodem) model. It extracts all necessary attributes to crop locations. It also applies some name fixes as needed for the model to run smoothly.The output dataframe is exported as csv and ready to be used in the irrigation ...
github_jupyter
# Self-Driving Car Engineer Nanodegree ## Project: **Finding Lane Lines on the Road** *** In this project, you will use the tools you learned about in the lesson to identify lane lines on the road. You can develop your pipeline on a series of individual images, and later apply the result to a video stream (really j...
github_jupyter
<a href="https://colab.research.google.com/github/KristynaPijackova/Radio-Modulation-Recognition-Networks/blob/main/Radio_Modulation_Recognition_Networks.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Radio Modulation Recognition Networks --- *...
github_jupyter
``` ## Hash Table ``` ### 1_TWO SUM ``` # interesting way is dictionary comprehension dict = dict((key, value) for (key, value) in iterable) dict = dict(key:value for key in iterable) # two way hash: # remeber the number sum combinations def twoSum( nums, target): """ :type nums: List[int] :t...
github_jupyter
``` %reload_ext autoreload %autoreload 2 from fastai.gen_doc.gen_notebooks import * from pathlib import Path ``` ### To update this notebook Run `tools/sgen_notebooks.py Or run below: You need to make sure to refresh right after ``` import glob for f in Path().glob('*.ipynb'): generate_missing_metadata(f) ```...
github_jupyter
# Building your Recurrent Neural Network - Step by Step Welcome to Course 5's first assignment! In this assignment, you will implement key components of a Recurrent Neural Network in numpy. Recurrent Neural Networks (RNN) are very effective for Natural Language Processing and other sequence tasks because they have "m...
github_jupyter
# Comparison FFTConv & SpatialConv In this notebook, we compare the speed and the error of utilizing fft and spatial convolutions. In particular, we will: * Perform a forward and backward pass on a small network utilizing different types of convolution. * Analyze their speed and their error response w.r.t. spatial c...
github_jupyter
##### Copyright 2019 The TensorFlow Authors. ``` #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
github_jupyter
## [Experiments] Uncertainty Sampling with a 1D Gaussian Process as model First, we define a prior probablility for a model. The GaussianRegressor approximates this model using an optimization method (probably similar to EM) for a given data input. The resulting model has a mean and a certainty. We use these to determ...
github_jupyter
# Probability Distribution: In [probability theory](https://en.wikipedia.org/wiki/Probability_theory) and [statistics](https://en.wikipedia.org/wiki/statistics), a probability distribution is a [mathematical function](https://en.wikipedia.org/wiki/Function_(mathematics)) that, stated in simple terms, can be thought o...
github_jupyter
<h1>02 Pandas</h1> $\newcommand{\Set}[1]{\{#1\}}$ $\newcommand{\Tuple}[1]{\langle#1\rangle}$ $\newcommand{\v}[1]{\pmb{#1}}$ $\newcommand{\cv}[1]{\begin{bmatrix}#1\end{bmatrix}}$ $\newcommand{\rv}[1]{[#1]}$ $\DeclareMathOperator{\argmax}{arg\,max}$ $\DeclareMathOperator{\argmin}{arg\,min}$ $\DeclareMathOperator{\...
github_jupyter
##### 1 ![1](http://7xqhfk.com1.z0.glb.clouddn.com/dl-waterloo/lec03/0001.jpg) ##### 2 ![2](http://7xqhfk.com1.z0.glb.clouddn.com/dl-waterloo/lec03/0002.jpg) ##### 3 ![3](http://7xqhfk.com1.z0.glb.clouddn.com/dl-waterloo/lec03/0003.jpg) ##### 4 ![4](http://7xqhfk.com1.z0.glb.clouddn.com/dl-waterloo/lec03/0004.jp...
github_jupyter
# Traffic Light Classifier --- In this project, you’ll use your knowledge of computer vision techniques to build a classifier for images of traffic lights! You'll be given a dataset of traffic light images in which one of three lights is illuminated: red, yellow, or green. In this notebook, you'll pre-process these i...
github_jupyter
# Tutorial 01: Running Sumo Simulations This tutorial walks through the process of running non-RL traffic simulations in Flow. Simulations of this form act as non-autonomous baselines and depict the behavior of human dynamics on a network. Similar simulations may also be used to evaluate the performance of hand-design...
github_jupyter
### Data Frame Plots documentation: http://pandas.pydata.org/pandas-docs/stable/visualization.html ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt plt.style.use('ggplot') ``` The plot method on Series and DataFrame is just a simple wrapper around plt.plot() If the index consists of dates, ...
github_jupyter
<a href="http://landlab.github.io"><img style="float: left" src="../media/landlab_header.png"></a> # The deAlmeida Overland Flow Component <hr> <small>For more Landlab tutorials, click here: <a href="https://landlab.readthedocs.io/en/latest/user_guide/tutorials.html">https://landlab.readthedocs.io/en/latest/user_guid...
github_jupyter
# Modes of the Ball-Channel Pendulum Linear Model ``` import numpy as np import numpy.linalg as la import matplotlib.pyplot as plt from resonance.linear_systems import BallChannelPendulumSystem %matplotlib widget ``` A (almost) premade system is available in `resonance`. The only thing missing is the function that ca...
github_jupyter
# Accessing WordNet through the NLTK interface >- [Accessing WordNet](#Accessing-WordNet) > > >- [WN-based Semantic Similarity](#WN-based-Semantic-Similarity) --- ## Accessing WordNet WordNet 3.0 can be accessed from NLTK by calling the appropriate NLTK corpus reader ``` from nltk.corpus import wordnet as wn ``` ...
github_jupyter
Steane code fault tolerance encoding scheme b ======================================= 1. Set up two logical zero for Steane code based on the parity matrix in the book by Nielsen MA, Chuang IL. Quantum Computation and Quantum Information, 10th Anniversary Edition. Cambridge University Press; 2016. p. 474 2. Set up ...
github_jupyter
``` import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set_style('whitegrid') plt.style.use("fivethirtyeight") %matplotlib inline # For reading stock data from yahoo from pandas_datareader.data import DataReader # For time stamps from datetime import datetime tech_list =...
github_jupyter
``` from pytorch_h5dataset.benchmark import Benchmarker, BenchmarkDataset from pytorch_h5dataset import H5DataLoader from torch.utils.data import DataLoader from torch import nn, float32, as_tensor from torch.nn import MSELoss from time import time from numpy import prod import seaborn as sns from matplotlib import py...
github_jupyter
``` # This Python 3 environment comes with many helpful analytics libraries installed # It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python # For example, here's several helpful packages to load import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O...
github_jupyter
#Design a Deep Neural Network using Keras and pyTorch ``` import keras print(keras.__version__) import torch print(torch.__version__) ``` ##Tensors and Attributes ``` data = torch.tensor([[1,2,3],[4,5,6]]) print(data.shape) print(data.dtype) #dimesnion along each axis print(data.ndim) #number of axes print(data.dev...
github_jupyter
``` import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline from datetime import time import geopandas as gpd from shapely.geometry import Point, LineString, shape ``` ## Load Data ``` df = pd.read_csv(r'..\data\processed\trips_custom_variables.csv', dtype = {'VORIHORAINI':str, 'VDE...
github_jupyter
# Variational Quantum Eigensolver - Ground State Energy for $LiH$ Molecule using the RY ansatz ``` import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * fro...
github_jupyter
``` # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
github_jupyter
(ch:trainingModels)= # 모델 훈련 **감사의 글** 자료를 공개한 저자 오렐리앙 제롱과 강의자료를 지원한 한빛아카데미에게 진심어린 감사를 전합니다. **소스코드** 본문 내용의 일부를 파이썬으로 구현한 내용은 [(구글코랩) 모델 훈련](https://colab.research.google.com/github/codingalzi/handson-ml3/blob/master/notebooks/code_training_models.ipynb)에서 확인할 수 있다. **주요 내용** * 선형 회귀 모델 구현 * 선형대수 활용 * ...
github_jupyter
# OPTIMADE and *pymatgen* # What is *pymatgen*? [*pymatgen*](https://pymatgen.org) is a materials science analysis code written in the Python programming language. It helps power the [Materials Project](https://materialsproject.org)'s high-throughput DFT workflows. It supports integration with a wide variety of simul...
github_jupyter
# U.S. Border Patrol Nationwide Apprehensions by Citizenship and Sector **Data Source:** [CBP Apprehensions](https://www.cbp.gov/sites/default/files/assets/documents/2021-Aug/USBORD~3.PDF) <br> **Download the Output:** [here](../data/extracted_data/) ## Overview The source PDF is a large and complex PDF with varying...
github_jupyter
# FAQs for Regression, MAP and MLE * So far we have focused on regression. We began with the polynomial regression example where we have training data $\mathbf{X}$ and associated training labels $\mathbf{t}$ and we use these to estimate weights, $\mathbf{w}$ to fit a polynomial curve through the data: \begin{equatio...
github_jupyter
# 7. Overfitting Prevention ## Why do we need to solve overfitting? - To increase the generalization ability of our deep learning algorithms - Able to make predictions well for out-of-sample data ## Overfitting and Underfitting: Examples ![](./images/overfitting.png) - **_This is an example from scikit-learn's webs...
github_jupyter
# Soccerstats Predictions v1.2 The changelog from v1.1: * Train on `train` data, and validate using `test` data. ## A. Data Cleaning & Preparation ### 1. Read csv file ``` # load and cache data stat_df = sqlContext.read\ .format("com.databricks.spark.csv")\ .options(header = True)\ .load("data/teamFixtu...
github_jupyter
# Credits Updated to detectwaste by: * Sylwia Majchrowska ``` %matplotlib inline import sys from pycocotools.coco import COCO import json import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns; sns.set() import os import skimage import skimage.io as io import copy def show_values...
github_jupyter
``` import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline train = pd.read_csv('titanic_train.csv') test = pd.read_csv('titanic_test.csv') train.head() sns.heatmap(train.isnull(), yticklabels=False, cbar=False, cmap='viridis') ##There is maximum number of data po...
github_jupyter
## In this notebook we are going to Predict the Growth of Google Stock using LSTM Model and CRISP-DM. ``` #importing the libraries import math import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from keras.models import Sequential from keras.layers import Dense, LSTM import matplotlib...
github_jupyter
# Training a dense neural network The handwritten digit recognition is a classification problem. We will start with the simplest possible approach for image classification - a fully-connected neural network (which is also called a *perceptron*). We use `pytorchcv` helper to load all data we have talked about in the pr...
github_jupyter
# Gather HTML from Newsrooms After confirming all of the newsroom links, the next step is to figure out how to best iterate through the pages/tabs of these links, and collect all of the HTML from each page/tab of the company's newsroom. This HTML will contain the links to the press releases, which can then be used to ...
github_jupyter
![data-x](http://oi64.tinypic.com/o858n4.jpg) --- # Pandas Introduction ### with Stock Data and Correlation Examples **Author list:** Alexander Fred-Ojala & Ikhlaq Sidhu **References / Sources:** Includes examples from Wes McKinney and the 10min intro to Pandas **License Agreement:** Feel free to do whatever yo...
github_jupyter
| Name | Surname | Student No | Department | |---|---|---|---| | Emin | Kartci | S014877 | EE Engineering | ## Emin Kartci #### Student ID: S014877 #### Department : Electrical & Electronics Engineering --- ### Semester Project - Foursquare & Restaurant Report --- #### This module is prepared for GUI --- ``...
github_jupyter
# CNN for Classification --- In this notebook, we define **and train** an CNN to classify images from the [Fashion-MNIST database](https://github.com/zalandoresearch/fashion-mnist). ### Load the [data](http://pytorch.org/docs/master/torchvision/datasets.html) In this cell, we load in both **training and test** datase...
github_jupyter
``` # This Python 3 environment comes with many helpful analytics libraries installed # It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python # For example, here's several helpful packages to load in import numpy as np # linear algebra import pandas as pd # data processing, CSV file...
github_jupyter
### Run in python console import nltk; nltk.download('stopwords') ### Run in terminal or command prompt python3 -m spacy download en ### Import Packages The core packages used in this tutorial are re, gensim, spacy and pyLDAvis. Besides this we will also using matplotlib, numpy and pandas for data handling and visua...
github_jupyter
<img src="https://upload.wikimedia.org/wikipedia/commons/4/47/Logo_UTFSM.png" width="200" alt="utfsm-logo" align="left"/> # MAT281 ### Aplicaciones de la Matemática en la Ingeniería ## Módulo 04 ## Laboratorio Clase 02: Regresión Lineal ### Instrucciones * Completa tus datos personales (nombre y rol USM) en siguie...
github_jupyter
``` import argparse import glob import io import os import random import numpy from PIL import Image, ImageFont, ImageDraw from scipy.ndimage.interpolation import map_coordinates from scipy.ndimage.filters import gaussian_filter SCRIPT_PATH = os.path.dirname(os.path.abspath('./hangul-WR')) # Default data paths. DEFAU...
github_jupyter
# PosTagging and Named Entity Recognition (NER) We consider some texts from QA SQuAD collection to annotate for its characterization with PosTagging and Named Entity Reconigtion (NER) open source frameworks: treetagger, Stanford CoreNLP, spacy, stanza ### Example texts ``` question_example = 'When was the Tower Thea...
github_jupyter
``` import sympy as sp from sympy.parsing.sympy_parser import parse_expr import pandas as pd def get_lines(filename): file = open(filename, 'r+') lines = file.readlines() # lines = map(lambda line : line[:-1],lines) file.close() return lines lines = get_lines('./tests/ejercicio1.txt') syntax = p...
github_jupyter
``` from os import environ environ['optimizer'] = 'Adam' environ['num_workers']= '2' environ['batch_size']= str(2048) environ['n_epochs']= '1000' environ['batch_norm']= 'True' environ['loss_func']='MAPE' environ['layers'] = '600 350 200 180' environ['dropouts'] = '0.1 '* 4 environ['log'] = 'False' environ['weight_deca...
github_jupyter
# "Intro til Anvendt Matematik og Python opfriskning" > "19 April 2021 - HA-AAUBS" - toc: true - branch: master - badges: true - comments: true - author: Roman Jurowetzki - categories: [intro, forelæsning] # Intro til Anvendt Matematik og Python opfriskning - Matematik bruges i finance, økonomistyring, data science...
github_jupyter
# Hyperparameter Optimization (HPO) of Machine Learning Models L. Yang and A. Shami, “On hyperparameter optimization of machine learning algorithms: Theory and practice,” Neurocomputing, vol. 415, pp. 295–316, 2020, doi: https://doi.org/10.1016/j.neucom.2020.07.061. ### **Sample code for regression problems** **Data...
github_jupyter
# Нейросети и вероятностные модели **Разработчик: Алексей Умнов** # Авторегрессионные модели Мы поработаем с авторегрессионными моделями на примере архитектуры PixelCNN. Мы обучим модель для задачи генерации изображений и для задачи дорисовывания недостающих частей изображения. ### LCD digits dataset В качестве пр...
github_jupyter
``` %reload_ext autoreload %autoreload 2 %matplotlib inline # enable outputs from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from tensorflow import keras from google.colab import file...
github_jupyter
<a href="https://colab.research.google.com/github/geansm2/PI2B/blob/master/Analise_Exploratoria_DIO.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` #Importando as bibliotecas import pandas as pd import matplotlib.pyplot as plt plt.style.use("sea...
github_jupyter
## 1. Winter is Coming. Let's load the dataset ASAP! <p>If you haven't heard of <em>Game of Thrones</em>, then you must be really good at hiding. Game of Thrones is the hugely popular television series by HBO based on the (also) hugely popular book series <em>A Song of Ice and Fire</em> by George R.R. Martin. In this n...
github_jupyter
## CNN on MNIST digits classification This example is the same as the MLP for MNIST classification. The difference is we are going to use `Conv2D` layers instead of `Dense` layers. The model that will be costructed below is made of: - First 2 layers - `Conv2D-ReLU-MaxPool` - 3rd layer - `Conv2D-ReLU` - 4th layer - `...
github_jupyter
<a href="https://colab.research.google.com/github/BNN-UPC/ignnition/blob/ignnition-nightly/notebooks/shortest_path.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # IGNNITION: Quick start tutorial ### **Problem**: Find the shortest path in graphs w...
github_jupyter
# Do IPAs Really Taste Better?? ## Introduction: The craft beer industry in the US has grown tremendously over the past decade. Of the types of beer that are new to the market, India Pale Ales (IPAs) seem to be the most popular. IPAs are known for their bold, bitter and hoppy taste, and while many fanatics can't get e...
github_jupyter
# Lecture 3: Optimize, print and plot [Download on GitHub](https://github.com/NumEconCopenhagen/lectures-2019) [<img src="https://mybinder.org/badge_logo.svg">](https://mybinder.org/v2/gh/NumEconCopenhagen/lectures-2019/master?urlpath=lab/tree/03/Optimize_print_and_plot.ipynb) 1. [The consumer problem](#The-consumer...
github_jupyter
## An example Python data analysis notebook This page illustrates how to use Python to perform a simple but complete analysis: retrieve data, do some computations based on it, and visualise the results. **Don't worry if you don't understand everything on this page!** Its purpose is to give you an example of things yo...
github_jupyter
# Advanced Logistic Regression in TensorFlow 2.0 ## Learning Objectives 1. Load a CSV file using Pandas 2. Create train, validation, and test sets 3. Define and train a model using Keras (including setting class weights) 4. Evaluate the model using various metrics (including precision and recall) 5. Try common te...
github_jupyter
# W207 Final Project Erika, Jen Jen, Geoff, Leslie (In Python 3) As of 3/35 Outline: * Data Pre-Processing * Simple Feature Selection * Basline Models * Possible Approaches # Section 1 Loading and Processing Data ``` ## Import Libraries ## import json from pprint import pprint from pandas import * from pandas.i...
github_jupyter
``` # Base Data Science snippet import pandas as pd import numpy as np import matplotlib.pyplot as plt import os import time from tqdm import tqdm_notebook %matplotlib inline %load_ext autoreload %autoreload 2 import sys sys.path.append("../") import westworld from westworld.assets import * from westworld.colors impo...
github_jupyter
# Step 1) Data Preparation ``` %run data_prep.py INTC import pandas as pd df = pd.read_csv("../1_Data/INTC.csv",infer_datetime_format=True, parse_dates=['dt'], index_col=['dt']) trainCount=int(len(df)*0.4) dfTrain = df.iloc[:trainCount] dfTest = df.iloc[trainCount:] dfTest.to_csv('local_test/test_dir/input/data/tr...
github_jupyter
This notebook is part of the `nbsphinx` documentation: https://nbsphinx.readthedocs.io/. # Installation Note that some packages may be out of date. You can always get the newest `nbsphinx` release from [PyPI](https://pypi.org/project/nbsphinx) (using `pip`). If you want to try the latest development version, have a l...
github_jupyter
# Building your Deep Neural Network: Step by Step Welcome to your week 4 assignment (part 1 of 2)! You have previously trained a 2-layer Neural Network (with a single hidden layer). This week, you will build a deep neural network, with as many layers as you want! - In this notebook, you will implement all the functio...
github_jupyter