text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
# Store tracts and points in PostGIS ...for a fast spatial-join of points to tracts. First, install postgres, postgis, and psycopg2. Then create the database from command prompt if it doesn't already exist: ``` createdb -U postgres points_tracts psql -U postgres -d points_tracts -c "CREATE EXTENSION postgis;" ``` M...
github_jupyter
# Load PyTorch model In this tutorial, you learn how to load an existing PyTorch model and use it to run a prediction task. We will run the inference in DJL way with [example](https://pytorch.org/hub/pytorch_vision_resnet/) on the pytorch official website. ## Preparation This tutorial requires the installation of...
github_jupyter
# Chapter 4 : Statistics and Linear Algebra # basic descriptive statistics ``` %matplotlib inline import numpy as np from scipy.stats import scoreatpercentile import pandas as pd data = pd.read_csv("co2.csv", index_col=0, parse_dates=True) co2 = np.array(data.co2) print("The statistical valus for amounts of co2 in...
github_jupyter
``` import pandas as pd import numpy as np df = pd.read_csv('Z_sani.csv') # 1: oh 2: or 3:mm 4: std 5:target encode_list = [3,3,3,1,3,1,1,1,1,1,1,1,1,1,1,1,1,3,3, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 4,4,4,4,4,4,4,3,3,3,4,4,3,4,4,1,2,5] df.head() from sklearn.model_selection import train_test_spli...
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
##**Gender-speech-duration-calculator** Here you will find a tool to calculate the percentage of time of female voice speech and male voice speech in a video/movie. You can either choose to paste a youtube link or you can upload your video. Install the program, choose one option and calculate the percentage of female a...
github_jupyter
# SciPy (documentação oficial: [docs.scipy.org](docs.scipy.org)) <img src="img/scipy.png" alt="ícone do pacote scipy - uma cobra branca desenhada num círculo azul" width=350> O pacote **SciPy** é uma coleção de algoritmos e funções matemáticas construídos sobre o pacote <b><a style color="red">Numpy</a></b> do Python...
github_jupyter
# En este ejercicio vamos a optimizar parámetros # (Credits to https://github.com/codiply/blog-ipython-notebooks/blob/master/scikit-learn-estimator-selection-helper.ipynb ) Para optimizar los parámetros usaremos un GridSearch. Y comparar clasificadores. <div class="alert alert-danger" role="alert"> Este ejemplo e...
github_jupyter
<a href="https://colab.research.google.com/github/ariG23498/G-SimCLR/blob/master/Imagenet_Subset/Vanilla_SimCLR/Linear_Evaluation.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ## Imports and setup ``` import tensorflow as tf print(tf.__version__)...
github_jupyter
# Evolutionnary Hierarchical Dirichlet Processes for Multiple Correlated Time Varying Corpora ## Introduction ----------------- Le notebook suivant est l'implémentation du code de l'article EvoHDP, réalisé par J.Zhang,Y.Song & al et est testé : <br\> - sur les données synthétiques indiqués par l'article - sur des co...
github_jupyter
## 1. Importing important price data <p>Every time I go to the supermarket, my wallet weeps a little. But how expensive is food around the world? In this notebook, we'll explore time series of food prices in Rwanda from the <a href="https://data.humdata.org/dataset/wfp-food-prices">United Nations Humanitarian Data Exch...
github_jupyter
``` import numpy as np import matplotlib import matplotlib.pyplot as plt from decimal import * import scipy.special import scipy.stats import scipy import numpy import math import itertools import sys sys.version ``` # Out-of-band P2W attack evaluation ## P2W attack success probability within $ N $ total blocks (no ...
github_jupyter
``` import re from tqdm import tqdm from collections import defaultdict, Counter, UserDict from itertools import product from cached_property import cached_property from litecoder.models import session, City from litecoder import logger def keyify(text): text = text.lower() text = text.strip() text ...
github_jupyter
``` %pylab inline from numpy.lib.recfunctions import append_fields ### Excluding the AGB stars with dust spheres around. x = np.load("../data/GDR3/gaiadr3_0ext.npy") cut = (x['log_lum'] <5.) & (x['log_lum'] >3.) & (x['log_teff'] <3.7) & (x['gaia_g'] > 0.5) print(len(x), len(x[cut])) x = np.load("../data/TMASS/2mass_0ex...
github_jupyter
# Circuit optimization using PatternManager - example of QAOA for MaxCut This notebook provides an example of minimizing the duration of a quantum circuit. In this notebook, a quantum circuit implementing an instance of Q.A.O.A. is used and the `PatternManager` tool will be used to minimize the duration of this circui...
github_jupyter
# Simple Reinforcement Learning in Tensorflow Part 1: ## The Multi-armed bandit This tutorial contains a simple example of how to build a policy-gradient based agent that can solve the multi-armed bandit problem. For more information, see this [Medium post](https://medium.com/@awjuliani/super-simple-reinforcement-lear...
github_jupyter
# B2: TCA 13C MFA demo # Intro # Setup First, we need to set the path and environment variable properly: ``` quantmodelDir = '/users/hgmartin/libraries/quantmodel' ``` This is the only place where the jQMM library path needs to be set. ``` %matplotlib inline import sys, os pythonPath = quantmodelDir+"/code/core"...
github_jupyter
``` import pandas as pd com2 = pd.read_csv('artist_m_extracted.csv') com2.shape com4 = com2.copy() com4.lyricist_m = com4.lyricist_m.str.replace("'", '', regex=False).str.replace("[", '', regex=False).str.replace("]", '', regex=False) com4.composer_m = com4.composer_m.str.replace("'", '', regex=False).str.replace("[", ...
github_jupyter
## Largest Product of Three from List Given a list of integers, return the largest product that can be made by multiplying any three integers. For example, if the list is [-10,-10,5,2] you should return 500. You can assume that the list has at least three integers. ``` # If the list is all positive, then it's trivial...
github_jupyter
# 1.PaddleGAN实现精准唇形合成-- 物理学界大佬们再次合唱 ## 1.1 宋代著名诗人苏轼「动起来」的秘密 坐拥百万粉丝的**独立艺术家大谷Spitzer老师**利用深度学习技术使**宋代诗人苏轼活过来,穿越千年,为屏幕前的你们亲自朗诵其著名古诗~** [点击量](https://www.bilibili.com/video/BV1mt4y1z7W8)近百万,同时激起百万网友热议,到底是什么技术这么牛气? ![](https://ai-studio-static-online.cdn.bcebos.com/c21d8a1de3084b6ca599bc2cda373d3fef4b1a0ae98646f4b629dae1...
github_jupyter
``` import pandas as pd import datetime as dt from pathlib import Path import json print("Importing Complete") # Let's take a look at the past sp500 tickers. def get_sp500_constituents_records(filepath): '''Gets SP500 constituents records from the specified filepath. Args: filepath: string of where the SP50...
github_jupyter
``` import tensorflow as tf import numpy as np import matplotlib.pyplot as plt %matplotlib inline import ram tf.enable_eager_execution() train = ram.dataset.train('~/data/mnist/') batch_size = 5 ram_model = ram.RAM(batch_size=batch_size) optimizer = tf.train.MomentumOptimizer(momentum=0.9, learning_rate=0.001) batch =...
github_jupyter
``` import json import numpy as np import pandas as pd from sklearn.feature_extraction import text from sklearn.linear_model import LogisticRegression import sklearn.model_selection as modsel import sklearn.preprocessing as preproc ``` ## Load and prep Yelp reviews data ``` ## Load Yelp Business data biz_f = open('da...
github_jupyter
``` import seaborn as sns; sns.set(color_codes=True) tips = sns.load_dataset("tips") print(tips[:5]) print(len(tips)) ax = sns.regplot(x="total_bill", y="tip", data=tips) import matplotlib.pyplot as plt g = sns.FacetGrid(tips, hue="sex", size=6, aspect=2) g.map(plt.scatter, "total_bill", "tip") g.add_legend() import ra...
github_jupyter
# Generating CLEAN Results ## Load environment ``` %matplotlib inline import sys # Directories and paths lib_path = '/gpfswork/rech/xdy/uze68md/GitHub/' data_path = '/gpfswork/rech/xdy/uze68md/data/' model_dir = '/gpfswork/rech/xdy/uze68md/trained_models/model_cfht/' # Add library path to PYTHONPATH path_alphatrans...
github_jupyter
# Importing the libraries ``` import numpy as np import pandas as pd import statsmodels.formula.api as sm ``` # Load Data ``` dataset=pd.read_csv('OnlineRetail.csv',encoding='latin1') dataset.head() dataset.describe() dataset.info() ``` # Data Preprocessing We are going to analysis the Customers based on below 3 ...
github_jupyter
``` import time import toml import numpy as np import matplotlib.pyplot as plt from ref_trajectory import generate_trajectory as traj %matplotlib inline ``` There are a lot of configuration parameters. It is a good idea to separate it from the main code. At some point you will be doing parameter tuning. We will use ...
github_jupyter
# Lab One - Climatic Averages ## *Analyzing the Global Temperatures Divergence from Average from 1880 - 2018* In this lab we learn part 1 basics of Python (the programming commands) for data analysis through utilizing the Jupyter environment (this display) to analyze data. You will learn how to: - Use Jupyter -...
github_jupyter
# AutoGluon Tabular with SageMaker [AutoGluon](https://github.com/awslabs/autogluon) automates machine learning tasks enabling you to easily achieve strong predictive performance in your applications. With just a few lines of code, you can train and deploy high-accuracy deep learning models on tabular, image, and text...
github_jupyter
``` import plaidml.keras plaidml.keras.install_backend() import os os.environ["KERAS_BACKEND"] = "plaidml.keras.backend" # Importing useful libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn.preprocessing import MinMaxScaler from keras.models import Sequential from keras.layer...
github_jupyter
# Q-learning applied to FrozenLake #### **Remember**: Q-learning is a model free, off-policy algorithm that can be used to find an optimal action using a Q function. Q can be represented as a table that contains a value for each pair state-action To review Q-learning watch [Q learning explained by Siraj](https://...
github_jupyter
<img style="float: center;" src="images/CI_horizontal.png" width="600"> <center> <span style="font-size: 1.5em;"> <a href='https://www.coleridgeinitiative.org'>Website</a> </span> </center> Rayid Ghani, Frauke Kreuter, Julia Lane, Adrianne Bradford, Alex Engler, Nicolas Guetta Jeanrenaud, Graham Henke,...
github_jupyter
# Object oriented programming # Lab 03 ## February 23, 2018 ## 1. Basic exercises ### 1.1 Define a class named A with a contructor that takes a single parameter and stores it in an attribute named `value`. Add a `print_value` method to the class. Instantiate the class and call the `print_value` method. ### 1.2 R...
github_jupyter
``` %load_ext autoreload %autoreload 2 %matplotlib inline import sys import casadi as ca import os import matplotlib.pyplot as plt sys.path.insert(0, '../../src') from pymoca.backends.xml import model, sim_scipy, analysis from pymoca.backends.xml import parser as parse_xml from pymoca.backends.xml.generator import gen...
github_jupyter
# Interactive Widget: Front End Code: Bagging Classifier This is our official final version of the widget. Throughout this workbook, we used steps from the following web pages to inform our widgets. - https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20Basics.html - https://ipywidgets.readthedocs.io/en/late...
github_jupyter
``` import pandas as pd import numpy as np df = pd.read_csv('WeNoGetPresident.csv') del df['Unnamed: 0'] #Delete column df.rename(columns={"created_at":"Time_Posted", "text":"Tweet", "source":"Tweet_Source", "description":"Bio"}, inplace=True) #Rename Created_at, Tw...
github_jupyter
# Using an SBML model ## Getting started ### Installing libraries Before you start, you will need to install a couple of libraries: The [ModelSeedDatabase](https://github.com/ModelSEED/ModelSEEDDatabase) has all the biochemistry we'll need. You can install that with `git clone`. The [PyFBA](http://linsalrob....
github_jupyter
# JavaScript and HTML Tricks in a Jupyter Notebook Normally I use [JSFiddle](https://jsfiddle.net/) to mock up JavaScript concepts but at work we use Jupyter Notebooks for design and documentation so it is handy to be able to demonstrate new web client features within a particular notebook. ### Custom CSS Use `%%htm...
github_jupyter
``` import pandas as pd import numpy as np import time import seaborn as sns import matplotlib.pyplot as plt from sklearn import preprocessing as pp from sklearn.model_selection import StratifiedKFold from sklearn.metrics import accuracy_score from sklearn import preprocessing import xgboost as xgb from sklearn.ensembl...
github_jupyter
## MinMaxScaler ``` from pandas import Series from sklearn.preprocessing import MinMaxScaler data = [10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0] series = Series(data) print(series) values = series.values values = values.reshape((len(values), 1)) print(values) print(values.shape) scaler = MinMaxScaler(...
github_jupyter
## Tools for CSV FIle Processing ### Gather Phase Tools This importable notebook provides the tooling necessary to handle the processing for the **Gather Phases** in the ETL process for the NOAA HDTA project. This tooling supports Approaches 1 and 2 using **CSV files**. Each of the process phases require a dictiona...
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
# Getting Started with CLX and Streamz This is a guide on how [CLX](https://github.com/rapidsai/clx) and [Streamz](https://streamz.readthedocs.io/en/latest/) can be used to build a streaming inference pipeline. Streamz has the ability to read from [Kafka](https://kafka.apache.org/) directly into [Dask](https://dask.o...
github_jupyter
# About OCR approach1: Through ocr1.py script we are targeting to train a small Convolutional Neurl Network (CNN) with the data we generated using random_string_data_gen.py. Network should be able to recognize the random string in a given image and provide it as ouput. In the first phase we will be testing it using ...
github_jupyter
# TV Script Generation In this project, I have tried to generate my own [Seinfeld](https://en.wikipedia.org/wiki/Seinfeld) TV scripts using RNNs. I have used part of the [Seinfeld dataset](https://www.kaggle.com/thec03u5/seinfeld-chronicles#scripts.csv) of scripts from 9 seasons. The Neural Network will generate a ne...
github_jupyter
``` import panel as pn pn.extension('plotly') ``` The ``HoloViews`` pane renders HoloViews plots with one of the plotting backends supported by HoloViews. It supports the regular HoloViews widgets for exploring the key dimensions of a ``HoloMap`` or ``DynamicMap``, but is more flexible than the native HoloViews widget...
github_jupyter
``` import pandas as pd #Loading data from the Github repository to colab notebook filename = 'https://raw.githubusercontent.com/PacktWorkshops/The-Data-Science-Workshop/master/Chapter15/Dataset/crx.data' # Loading the data using pandas credData = pd.read_csv(filename,sep=",",header = None,na_values = "?") credData.he...
github_jupyter
# scatter_selector widget A set of custom matplotlib widgets that allow you to select points on a scatter plot as use that as input to other interactive plots. There are three variants that differ only in what they pass to their callbacks: 1. {obj}`.scatter_selector`: callbacks will receive `index, (x, y)` where `ind...
github_jupyter
``` # Dependencies and Setup import matplotlib.pyplot as plt import pandas as pd import numpy as np import requests import time from scipy.stats import linregress # Import API key from api_keys import weather_api_key # Incorporated citipy to determine city based on latitude and longitude from citipy import citipy # ...
github_jupyter
<h4>Unit 1 <h1 style="text-align:center"> Chapter 4</h1> --- ## Normalization > Normalization is the task of putting words/tokens in a standard format.Normalization is benefecial despite the spelling information that is lost. #### Case folding --- > Mapping everything to the same case is called case folding. ...
github_jupyter
# Calculating Thermodynamics Observables with a quantum computer ``` # imports import numpy as np import pandas as pd import matplotlib.pyplot as plt from functools import partial from qiskit.utils import QuantumInstance from qiskit import Aer from qiskit.algorithms import NumPyMinimumEigensolver, VQE from qiskit_na...
github_jupyter
# PICES Regional Ecosystem Tool ## Data acquisition, analysis, plotting & saving to facilitate IEA report ### Developed by Chelle Gentemann (cgentemann@gmail.com) & Marisol Garcia-Reyes (marisolgr@gmail.com) *** *** # Instructions ## To configure: ### In the cell marked by <b>`* Configuration *`</b>, specify: Regio...
github_jupyter
# August 2021 CVE Data This notebook will pull all [JSON Data](https://nvd.nist.gov/vuln/data-feeds#JSON_FEED) from the NVD and performs some basic data analysis of CVEd data. ## Getting Started ### Collecting Data This cell pulls all JSON files from the NVD that we will be working with. ``` %%capture !mkdir -p js...
github_jupyter
## Explore The Data: Explore Continuous Features Using the Titanic dataset from [this](https://www.kaggle.com/c/titanic/overview) Kaggle competition. This dataset contains information about 891 people who were on board the ship when departed on April 15th, 1912. As noted in the description on Kaggle's website, some p...
github_jupyter
# Get vaccine coverage by ZIP Codes data from CDPH ``` %load_ext lab_black import pandas as pd import datetime as dt import json import os import glob import urllib.request pd.options.display.max_columns = 50 pd.options.display.max_rows = 1000 pd.set_option("display.max_colwidth", None) today = dt.datetime.today().str...
github_jupyter
## This notebook contains prototyping work for implementing the viterbi decode algorithm ``` import numpy as np import librosa import matplotlib.pyplot as plt def redistribute_trans_table(A): for i in range(5,A.shape[1]): current_col = A[:,i] idx = (-current_col).argsort()[:2] second_max_v...
github_jupyter
# Two Degree-of-Freedom Caldera Model ## Introduction Dynamical matching is an interesting chemical dynamical phenomenon that occurs in a variety of organic chemical reactions. A caldera PES arises in many organic chemical reactions, such as the vinylcyclopropane-cyclopentene rearrangement \cite{baldwin2003,gold1...
github_jupyter
``` import numpy as np import pandas as pd amplifiers = np.genfromtxt('amplifiers_0.csv',delimiter=',').astype(int) print(amplifiers) normals = 1-amplifiers print(normals) weights_biased = np.atleast_2d(np.genfromtxt('weights-biased_0.csv', delimiter=',')) weights_unbiased = np.atleast_2d(np.genfromtxt('weights-unbiase...
github_jupyter
# Example: CanvasXpress scatter2d Chart No. 4 This example page demonstrates how to, using the Python package, create a chart that matches the CanvasXpress online example located at: https://www.canvasxpress.org/examples/scatter2d-4.html This example is generated using the reproducible JSON obtained from the above p...
github_jupyter
# MNIST ``` import torch from torch import nn, optim from torchvision import datasets, transforms import numpy as np %matplotlib inline from matplotlib import pyplot as plt ``` ### Description Classification of hand-written digits (MNIST dataset) using a simple multi-layer perceptorn architecture implemented in PyTo...
github_jupyter
# MLflow Training Tutorial This `train.pynb` Jupyter notebook is an example for using elastalert with mlflow together. > This is the Jupyter notebook version of the `train.py` example ``` from sklearn.svm import OneClassSVM ES_URL = "http://192.168.122.3:9200" ES_INDEX = "logs-endpoint-winevent-sysmon-*" COLUMNS = ...
github_jupyter
## Baysian Ridge and Lasso regression ``` import matplotlib.pyplot as plt import numpy as np from scipy.stats import norm import pymc import sys %matplotlib inline n = 10000 x1 = norm.rvs(0, 1, size=n) + norm.rvs(0, 10**-3, size=n) x2 = -x1 + norm.rvs(0, 10**-3, size=n) x3 = norm.rvs(0, 1, size=n) X = np.column_sta...
github_jupyter
![Callysto.ca Banner](https://github.com/callysto/curriculum-notebooks/blob/master/callysto-notebook-banner-top.jpg?raw=true) <a href="https://hub.callysto.ca/jupyter/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fcallysto%2Fcurriculum-notebooks&branch=master&subPath=Mathematics/CombinedLogLaw/combined-log...
github_jupyter
# Confounding Example: Finding causal effects from observed data Suppose you are given some data with treatment and outcome. Can you determine whether the treatment causes the outcome, or the correlation is purely due to another common cause? ``` import os, sys sys.path.append(os.path.abspath("../../")) import numpy ...
github_jupyter
# 수학 ## 1) 나머지 연산 C++ - int: 2^31-1 - long long: 2^63-1 - 10^18 정도, 따라서 정답을 나눈 값을 return하도록 함 - **답을 M으로 나눈 나머지 출력** 1) 덧셈 곱셈(https://www.acmicpc.net/problem/10430) ~~~ # mod = % (A + B) % M = {(A % C) + (B % C)} % C (A X B) % M = {(A % C) X (B % C)} % C ~~~ 2) 뺄셈: 더해주고 나눔 ~~~ 0 <= A % C <= C 0 <= B % C <= C -C < A ...
github_jupyter
# Serve a Pytorch model trained on SageMaker The model for this example was trained using this sample notebook on sagemaker - https://github.com/awslabs/amazon-sagemaker-examples/blob/master/sagemaker-python-sdk/pytorch_mnist/pytorch_mnist.ipynb It is certainly easiler to do estimator.deploy() using the standard Sage...
github_jupyter
``` import pandas as pd import itertools file = 'legacy_data/Amtsblatt_1918.xlsx' res_type_scheme, _ = SkosConceptScheme.objects.get_or_create(dc_title='res_type') archiv, _ = Institution.objects.get_or_create( written_name='Wiener Stadt- und Landesarchiv', abbreviation="WStLA", institution_type="Archiv" ) ...
github_jupyter
## Dependencies ``` import json, glob from tweet_utility_scripts import * from tweet_utility_preprocess_roberta_scripts import * from transformers import TFRobertaModel, RobertaConfig from tokenizers import ByteLevelBPETokenizer from tensorflow.keras import layers from tensorflow.keras.models import Model ``` # Load ...
github_jupyter
# Inference only Text Models in `arcgis.learn` <h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"> <ul class="toc-item"> <li><span><a href="#Introduction" data-toc-modified-id="Introduction-1">Introduction</a></span></li> <li><span><a href="#Transformer-Basics" data-toc-modified-id="Transformer-B...
github_jupyter
##### Copyright &copy; 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 ...
github_jupyter
``` import numpy as np import xarray as xr from matplotlib import pyplot as plt %matplotlib inline plt.rcParams['figure.figsize'] = (8,5) from scipy.interpolate import * x = np.linspace(0, 2*np.pi, 11)[0:-1] y = np.sin(x) # analytic derivative: dydxa = np.cos(x) # numpy derivatives: dydx1 = np.diff(y)/np.diff(x) np.s...
github_jupyter
# MNIST Dataset & Database In the [MNIST tutorial](https://github.com/caffe2/caffe2/blob/master/caffe2/python/tutorials/MNIST.ipynb) we use an lmdb database. You can also use leveldb or even minidb by changing the type reference when you get ready to read from the dbs. In this tutorial, we will go over how to download...
github_jupyter
![Bring Schrodinger out of the woodwork](../linkedFiles/HpsiEpsiCarlos.jpg "Courtesy of Prof. Carlos Cardenas at the Univ. of Chile") # The Schr&ouml;dinger Equation >The underlying physical laws necessary for the mathematical theory of a large part of physics and the whole of chemistry are thus completely known, an...
github_jupyter
# Machine Learning Foundation ## Section 2, Part d: Regularization and Gradient Descent ## Introduction We will begin with a short tutorial on regression, polynomial features, and regularization based on a very simple, sparse data set that contains a column of `x` data and associated `y` noisy data. The data file i...
github_jupyter
## Please input your directory for the top level folder folder name : SUBMISSION MODEL ``` dir_ = 'INPUT-PROJECT-DIRECTORY/submission_model/' # input only here ``` #### setting other directory ``` raw_data_dir = dir_+'2. data/' processed_data_dir = dir_+'2. data/processed/' log_dir = dir_+'4. logs/' model_dir = dir_...
github_jupyter
``` from __future__ import print_function import os import pandas as pd import numpy as np %matplotlib inline from matplotlib import pyplot as plt #Read dataset into pandas DataFrame df = pd.read_csv('datasets/chemical-concentration-readings.csv') #Let's see the shape of the dataset print('Shape of the dataset:', df.sh...
github_jupyter
``` import sys sys.path.append(r"D:\work\nlp") from fennlp.datas import dataloader import tensorflow as tf from fennlp.datas.checkpoint import LoadCheckpoint from fennlp.datas.dataloader import TFWriter, TFLoader from fennlp.metrics import Metric from fennlp.metrics.crf import CrfLogLikelihood from fennlp.models import...
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 03 ## Laboratorio Clase 02: Visualización Imperativa ### Instrucciones * Completa tus datos personales (nombre y rol USM) e...
github_jupyter
# Basic training functionality ``` from fastai.basic_train import * from fastai.gen_doc.nbdoc import * from fastai.vision import * from fastai.distributed import * ``` [`basic_train`](/basic_train.html#basic_train) wraps together the data (in a [`DataBunch`](/basic_data.html#DataBunch) object) with a pytorch model to...
github_jupyter
``` import pyspark import os from datetime import date import functools from IPython.core.display import display, HTML #import findspark #findspark.init() from pyspark.sql import SparkSession import pyspark.sql.functions as F import pyspark.sql.types as T from pyspark.sql.functions import to_timestamp, count, isnan, ...
github_jupyter
# Table of Contents <div class="toc" style="margin-top: 1em;"><ul class="toc-item" id="toc-level0"><li><span><a href="http://localhost:8889/notebooks/19-full-res-model-all-angles-vertical-cut-no-bbox.ipynb#Load-libraries" data-toc-modified-id="Load-libraries-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Load libra...
github_jupyter
<small><small><i> All the IPython Notebooks in this **Python Examples** series by Dr. Milaan Parmar are available @ **[GitHub](https://github.com/milaan9/90_Python_Examples)** </i></small></small> # Python Program to Make a Simple Calculator In this example you will learn to create a simple calculator that can add, s...
github_jupyter
# COVID-19 Analysis ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt # Read the data confirmed = pd.read_csv('data/time_series_covid19_confirmed_global.csv') confirmed.rename(columns={'Country/Region':'country'}, inplace=True) confirmed = confirmed.drop(columns=['Province/State']) confirmed ...
github_jupyter
# Building Model for MALARIA DETECTION ### Lets take a look at how we are gonna make our model #### Step 1: Loading and Splitting of the Dataset - The first step is to load the data and scaling the images to binary 0 and 1 from Parasitized and Uninfected. - Then we will resize the images to 50 x 50 - After that s...
github_jupyter
``` ########################################################## # Relative Imports ########################################################## import sys from os.path import isfile from os.path import join def find_pkg(name: str, depth: int): if depth <= 0: ret = None else: d = [".."] * depth ...
github_jupyter
``` from dataretrieval import nwis ``` The dataRetrieval package was created as a python equivalent to the R dataRetrieval tool. The following shows python equivalents for methods outlined in the R dataRetrieval Vignette with the equivalent R code in comments ``` ''' library(dataRetrieval) # Choptank River near Gree...
github_jupyter
``` # default_exp inference ``` # Inference > This contains the code required for inference. ``` # export from fastai.learner import load_learner from fastai.callback.core import GatherPredsCallback from fastai.learner import Learner from fastcore.basics import patch from fastcore.meta import delegates #export @patc...
github_jupyter
# Writing Down Qubit States ``` from qiskit import * ``` In the previous chapter we saw that there are multiple ways to extract an output from a qubit. The two methods we've used so far are the z and x measurements. ``` # z measurement of qubit 0 measure_z = QuantumCircuit(1,1) measure_z.measure(0,0); # x measureme...
github_jupyter
# Archivos y Bases de datos La idea de este taller es manipular archivos (leerlos, parsearlos y escribirlos) y hacer lo mismo con bases de datos estructuradas. ## Ejercicio 1 Baje el archivo de "All associations with added ontology annotations" del GWAS Catalog. + https://www.ebi.ac.uk/gwas/docs/file-downloads Desc...
github_jupyter
# [deplacy](https://koichiyasuoka.github.io/deplacy/)을 사용한 문법 분석 ## [Camphr-Udify](https://camphr.readthedocs.io/en/latest/notes/udify.html)로 분석 ``` !pip install deplacy camphr 'unofficial-udify>=0.3.0' en-udify@https://github.com/PKSHATechnology-Research/camphr_models/releases/download/0.7.0/en_udify-0.7.tar.gz impo...
github_jupyter
# Lightweight Networks and MobileNet We have seen that complex networks require significant computational resources, such as GPU, for training, and also for fast inference. However, it turns out that a model with significanly smaller number of parameters in most cases can still be trained to perform resonably well. In...
github_jupyter
## This notebook Contains: - Taking scraped input(HTML formatted code) - Cleaning, Data Preprocessing and Feature Engineering on the data set - Importing the Cleaned CSV File ``` # imoporting libraries import pandas as pd import os from bs4 import BeautifulSoup import re # Reading the list of files inside the HTML_FIL...
github_jupyter
# AutoEncoders --- The following code was created by Aymeric Damien. You can find some of his code in <a href="https://github.com/aymericdamien">here</a>. We made some modifications for us to import the datasets to Jupyter Notebooks. Let's call our imports and make the MNIST data available to use. ``` #from __future...
github_jupyter
# 4장 판다스 데이터프레임 Part1 ## 4.2 데이터프레임 인덱스 ``` from pandas import DataFrame data = [ ["037730", "3R", 1510, 7.36], ["036360", "3SOFT", 1790, 1.65], ["005670", "ACTS", 1185, 1.28] ] columns = ["종목코드", "종목명", "현재가", "등락률"] df = DataFrame(data=data, columns=columns) df from pandas import DataFrame data = [ ...
github_jupyter
``` import re import os from misc import * import numpy as np import pandas as pd import pickle as pkl import os.path as op from tqdm import tqdm from copy import deepcopy import matplotlib.pyplot as plt from matplotlib.patches import Patch from scipy.stats import ks_2samp, median_test from sklearn.metrics import roc_a...
github_jupyter
# Torch Hub Detection Inference Tutorial In this tutorial you'll learn: - how to load a pretrained detection model using Torch Hub - run inference to detect actions in a demo video ## NOTE: At the moment tutorial only works if ran on local clone from the directory `pytorchvideo/tutorials/video_detection_example` #...
github_jupyter
## What is a Variable? A variable is any characteristic, number, or quantity that can be measured or counted. The following are examples of variables: - Age (21, 35, 62, ...) - Gender (male, female) - Income (GBP 20000, GBP 35000, GBP 45000, ...) - House price (GBP 350000, GBP 570000, ...) - Country of birth (China, ...
github_jupyter
# Scrapy: part 1 **Scrapy** is a powerful web scraping framework for Python. A framework is still a library ("an API of functions") yet with more powerful built-in features. It can be described as the combination of all we learnt till now including requests, BeautifulSoup, lxml and RegEx. To install **Scrapy**, open t...
github_jupyter
``` # Imports import csv import pandas as pd import itertools import math from nltk.corpus import stopwords from nltk.stem.porter import PorterStemmer import spacy import string import re import nltk import random import praw from google.colab import files import seaborn as sns import numpy as np from sklearn.feature_...
github_jupyter
# Supplementary Material: Analyse AdaptiveAttention AdaptiveAttention is from the paper by Lu et al. (2017): ``` @inproceedings{lu2017knowing, title={Knowing when to look: Adaptive attention via a visual sentinel for image captioning}, author={Lu, Jiasen and Xiong, Caiming and Parikh, Devi and Socher, Richard}, ...
github_jupyter