code
stringlengths
2.5k
6.36M
kind
stringclasses
2 values
parsed_code
stringlengths
0
404k
quality_prob
float64
0
0.98
learning_prob
float64
0.03
1
# 1 Introducing 16S Microbiome Primary Analysis Amanda Birmingham, CCBB, UCSD (abirmingham@ucsd.edu) This document introduces a Standard Operating Procedure (SOP) that covers primary analysis of single-end, three-read, Golay-barcoded microbiome 16S sequencing data. <a name = "table-of-contents"></a> ## Table of Con...
github_jupyter
# 1 Introducing 16S Microbiome Primary Analysis Amanda Birmingham, CCBB, UCSD (abirmingham@ucsd.edu) This document introduces a Standard Operating Procedure (SOP) that covers primary analysis of single-end, three-read, Golay-barcoded microbiome 16S sequencing data. <a name = "table-of-contents"></a> ## Table of Con...
0.87851
0.8586
# Coding Paradigms for Device Control ``` %serialconnect ``` ## The Coding Challenge PD control for a Ball on beam device. The device is to sense the position of a ball on a 50cm beam, compare to a setpoint, and adjust beam position with servo motor. The setpoint and control constant is to be given by the device use...
github_jupyter
%serialconnect from machine import Pin, PWM import time class Servo(object): def __init__(self, gpio, freq=50): self.gpio = gpio self.pwm = PWM(Pin(gpio, Pin.IN)) self.pwm.freq(freq) self.pwm.duty_ns(0) def set_value(self, value): self.pulse_us = 500 + 20*max(0...
0.331552
0.75037
``` #default_exp suite ``` # Model Suite <br> ### Imports ``` #exports import yaml import numpy as np import pandas as pd from sklearn.ensemble import RandomForestRegressor from sklearn.model_selection import KFold, train_test_split from wpdhack import data, feature from tqdm import tqdm from random import randi...
github_jupyter
#default_exp suite #exports import yaml import numpy as np import pandas as pd from sklearn.ensemble import RandomForestRegressor from sklearn.model_selection import KFold, train_test_split from wpdhack import data, feature from tqdm import tqdm from random import randint from typing import Protocol from importlib ...
0.643329
0.734242
# **Image Recognition**: Neural Nets Source: [https://github.com/d-insight/code-bank.git](https://github.com/d-insight/code-bank.git) License: [MIT License](https://opensource.org/licenses/MIT). See open source [license](LICENSE) in the Code Bank repository. ------------- ## Overview In this demo we will perform...
github_jupyter
# Put all import statements at the top of your notebook import warnings warnings.simplefilter('ignore') # Standard imports import pandas as pd import numpy as np import itertools # Data science packages from sklearn.model_selection import learning_curve, validation_curve, StratifiedShuffleSplit, train_test_split, St...
0.839537
0.928991
# Gram-Schmidt process ## Instructions In this assignment you will write a function to perform the Gram-Schmidt procedure, which takes a list of vectors and forms an orthonormal basis from this set. As a corollary, the procedure allows us to determine the dimension of the space spanned by the basis vectors, which is e...
github_jupyter
A[0, 0] A[0, 1] A[0, 2] A[0, 3] A[1, 0] A[1, 1] A[1, 2] A[1, 3] A[2, 0] A[2, 1] A[2, 2] A[2, 3] A[3, 0] A[3, 1] A[3, 2] A[3, 3] A[n, m] A[n] A[:, m] u @ v # GRADED FUNCTION import numpy as np import numpy.linalg as la verySmallNumber = 1e-14 # That's 1×10⁻¹⁴ = 0.00000000000001 # Our first function wi...
0.579043
0.986455
# Contribute Before we can accept contributions, you need to become a CLAed contributor. E-mail a signed copy of the [CLAI](https://github.com/openpifpaf/openpifpaf/blob/main/docs/CLAI.txt) (and if applicable the [CLAC](https://github.com/openpifpaf/openpifpaf/blob/main/docs/CLAC.txt)) as PDF file to research@svenkrei...
github_jupyter
pip3 install numpy cython pip3 install --editable '.[dev,train,test]' pylint openpifpaf pycodestyle openpifpaf pytest cd guide python download_data.py pytest --nbval-lax --current-env *.ipynb import sys if sys.version_info >= (3, 8): import importlib.metadata extras = importlib.metadata.metadata('openpifpaf'...
0.274449
0.779532
# Lecture 7: Vectorized Programming CSCI 1360E: Foundations for Informatics and Analytics ## Overview and Objectives We've covered loops and lists, and how to use them to perform some basic arithmetic calculations. In this lecture, we'll see how we can use an external library to make these computations much easier a...
github_jupyter
import random x = [3, 7, 2, 9, 4] print("Maximum: {}".format(max(x))) print("Minimum: {}".format(min(x))) import random # For generating random numbers, as we've seen. import os # For interacting with the filesystem of your computer. import re # For regular expressions. Unrelated: https://xkcd.com/1171/...
0.45641
0.986165
# Quick Start Below is a sample demo of interaction with the environment. ``` from maro.simulator import Env from maro.simulator.scenarios.cim.common import Action, DecisionEvent env = Env(scenario="cim", topology="toy.5p_ssddd_l0.0", start_tick=0, durations=100) metrics: object = None decision_event: DecisionEvent...
github_jupyter
from maro.simulator import Env from maro.simulator.scenarios.cim.common import Action, DecisionEvent env = Env(scenario="cim", topology="toy.5p_ssddd_l0.0", start_tick=0, durations=100) metrics: object = None decision_event: DecisionEvent = None is_done: bool = False while not is_done: action: Action = None ...
0.725357
0.918553
<a id='header'></a> # Principal Component Analysis (PCA) In this notebook we present PCA-related functionalities from the ``reduction`` module. ### PCA functionalities - [**Section 1**](#global_local_pca): We present how *global and local PCA* can be performed using `PCA` class from the `reduction` module. - [**Sect...
github_jupyter
save_plots = False from PCAfold import preprocess from PCAfold import reduction from PCAfold import PCA import matplotlib.pyplot as plt from matplotlib import gridspec import numpy as np # Set some initial parameters: global_color = '#6a6e7a' k1_color = '#0e7da7' k2_color = '#ceca70' PC_color = '#000000' data_point =...
0.756717
0.944842
``` import nltk from nltk.corpus import twitter_samples nltk.download('twitter_samples') positive_tweets = twitter_samples.strings('positive_tweets.json') negative_tweets = twitter_samples.strings('negative_tweets.json') from nltk.tokenize import TweetTokenizer from nltk.corpus import stopwords from nltk.stem import Po...
github_jupyter
import nltk from nltk.corpus import twitter_samples nltk.download('twitter_samples') positive_tweets = twitter_samples.strings('positive_tweets.json') negative_tweets = twitter_samples.strings('negative_tweets.json') from nltk.tokenize import TweetTokenizer from nltk.corpus import stopwords from nltk.stem import Porter...
0.291687
0.329014
# 4 Classes ### 4.1 The `class` Statement The `class` statement starts a block of code and creates a new namespace. All namespace changes in the block, e.g. simple assignment and function definitions, are made in that new namespace. Finally it adds the class name to the namespace where the class statement appears....
github_jupyter
class Number: __version__ = '1.0' def __init__(self, amount): self.amount = amount def add(self, value): return self.amount + value Number Number.__name__ Number.__class__ Number.__version__ n1 = Number(1) Number.add n1.add n1.add(2) def init(self, amount): self.amount = am...
0.884757
0.879716
# Racial data vs. Congressional districts We are now awash with data from different sources, but pulling it all together to gain insights can be difficult for many reasons. In this notebook we show how to combine data of very different types to show previously hidden relationships: * **"Big data"**: 300 million poin...
github_jupyter
import holoviews as hv from holoviews import opts import geoviews as gv import datashader as ds import dask.dataframe as dd from cartopy import crs from holoviews.operation.datashader import datashade hv.extension('bokeh', width=95) opts.defaults( opts.Points(apply_ranges=False, ), opts.RGB(width=1200, heigh...
0.364438
0.989213
# Tensorflow Image Recognition Tutorial This tutorial shows how we can use MLDB's [TensorFlow](https://www.tensorflow.org) integration to do image recognition. TensorFlow is Google's open source deep learning library. We will load the [Inception-v3 model](http://arxiv.org/abs/1512.00567) to generate descriptive lab...
github_jupyter
from pymldb import Connection mldb = Connection() inceptionUrl = 'file://mldb/mldb_test_data/models/inception_dec_2015.zip' print mldb.put('/v1/functions/fetch', { "type": 'fetcher', "params": {} }) print mldb.put('/v1/functions/inception', { "type": 'tensorflow.graph', "params": { "modelFile...
0.345105
0.991836
## SVM model for 4class audio with 100ms frame size ## Important Libraries ``` import io import time from sklearn import metrics from scipy.stats import zscore from sklearn.model_selection import train_test_split from sklearn.model_selection import KFold from keras.models import Sequential from keras.layers.core impo...
github_jupyter
import io import time from sklearn import metrics from scipy.stats import zscore from sklearn.model_selection import train_test_split from sklearn.model_selection import KFold from keras.models import Sequential from keras.layers.core import Dense, Activation from keras.callbacks import EarlyStopping import tensorflow ...
0.587115
0.838878
### Import packages-libraries ``` import pandas as pd import numpy as np import urllib3 import requests from PIL import Image import matplotlib.pyplot as plt import seaborn as sns from wordcloud import WordCloud, STOPWORDS from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS from sklearn.preprocessing impo...
github_jupyter
import pandas as pd import numpy as np import urllib3 import requests from PIL import Image import matplotlib.pyplot as plt import seaborn as sns from wordcloud import WordCloud, STOPWORDS from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS from sklearn.preprocessing import StandardScaler from sklearn.prep...
0.331985
0.628322
``` from math import log import matplotlib.pyplot as plt %matplotlib inline #定义文本框和箭头格式 decisionNode = dict(boxstyle="sawtooth", fc="0.8") #定义判断节点形态 leafNode = dict(boxstyle="round4", fc="0.8") #定义叶节点形态 arrow_args = dict(arrowstyle="<-") #定义箭头 #绘制带箭头的注解 #nodeTxt:节点的文字标注, centerPt:节点中心位置, #parentPt:箭头...
github_jupyter
from math import log import matplotlib.pyplot as plt %matplotlib inline #定义文本框和箭头格式 decisionNode = dict(boxstyle="sawtooth", fc="0.8") #定义判断节点形态 leafNode = dict(boxstyle="round4", fc="0.8") #定义叶节点形态 arrow_args = dict(arrowstyle="<-") #定义箭头 #绘制带箭头的注解 #nodeTxt:节点的文字标注, centerPt:节点中心位置, #parentPt:箭头起点位置...
0.307774
0.483587
<p style="z-index: 101;background: #fde073;text-align: center;line-height: 2.5;overflow: hidden;font-size:22px;">Please <a href="https://www.pycm.ir/doc/#Cite" target="_blank">cite us</a> if you use the software</p> # Example-6 (Unbalanced data) ## Environment check Checking that the notebook is running on Google C...
github_jupyter
import sys try: import google.colab !{sys.executable} -m pip -q -q install pycm except: pass from pycm import ConfusionMatrix case1 = ConfusionMatrix(matrix={"Class1": {"Class1": 26900, "Class2":40}, "Class2": {"Class1": 25, "Class2": 500}}) case1.print_normalized_matrix() print('ACC:',case1.ACC) print('MCC:',c...
0.170784
0.88573
Notebook for converting models to onnx (Obsolete as this is now also implemented in the main codebase) ``` from transformers.convert_graph_to_onnx import convert from transformers import GPT2Tokenizer, GPT2LMHeadModel from onnxruntime_tools import optimizer from os import environ from psutil import cpu_count impor...
github_jupyter
from transformers.convert_graph_to_onnx import convert from transformers import GPT2Tokenizer, GPT2LMHeadModel from onnxruntime_tools import optimizer from os import environ from psutil import cpu_count import torch import torch.nn.functional as F import numpy as np from src.data_utils import encode, decode environ...
0.669529
0.519521
Comparing GOES XRS 15 and 16 - 1s from fido/sunpy and direct download of avg1min * 25-May-2020 IGH ``` import matplotlib import matplotlib.pyplot as plt from sunpy import timeseries as ts from sunpy.net import Fido from sunpy.net import attrs as a # Just setup plot fonts plt.rcParams.update({'font.size': 18,'font.f...
github_jupyter
import matplotlib import matplotlib.pyplot as plt from sunpy import timeseries as ts from sunpy.net import Fido from sunpy.net import attrs as a # Just setup plot fonts plt.rcParams.update({'font.size': 18,'font.family':"sans-serif",\ 'font.sans-serif':"Arial",'mathtext.default':"regular"}) #...
0.264833
0.674493
``` import sys,os os.chdir('.\..\..') import deep_nn.deep_nn_model as nn import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.preprocessing import MinMaxScaler from keras.models import Sequential from keras.layers import Dense from keras.wrappers.scikit_learn import KerasRegressor from ...
github_jupyter
import sys,os os.chdir('.\..\..') import deep_nn.deep_nn_model as nn import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.preprocessing import MinMaxScaler from keras.models import Sequential from keras.layers import Dense from keras.wrappers.scikit_learn import KerasRegressor from kera...
0.681939
0.487429
RNN for text generation We will create a language model based on Shakespear's writings, and use it to generate new text similar to that of Shakespear. ``` import torch import torch.nn as nn import torch.autograd as autograd import torch.cuda as cuda import torch.optim as optim from torch.autograd import Variable impo...
github_jupyter
import torch import torch.nn as nn import torch.autograd as autograd import torch.cuda as cuda import torch.optim as optim from torch.autograd import Variable import numpy as np import os class Dictionary(object): def __init__(self): self.word2idx = {} self.idx2word = [] def add_word(self...
0.87834
0.81309
# Parse Tracefiles to characterise variance You must change the location of the script dir if you want to use relative paths to the trace. Or , set the absolute path to the location of the directory containing the tracefiles. ``` import logging import pandas as pd import cx_Oracle import matplotlib.pyplot as plt impor...
github_jupyter
import logging import pandas as pd import cx_Oracle import matplotlib.pyplot as plt import os import re import glob #abspath = os.path.abspath(__file__) #dname = os.path.dirname(abspath) #os.chdir(f"{dname}/") os.chdir("C:\\Users\\David Olivari\\Documents\\ONGOING DB WORK\\carsprd\\tracefiles_stuff\\bin") trcs = glob.g...
0.240418
0.636466
``` ! pip install -U pip ! pip install -U torch==1.5.0 ! pip install -U torchtext==0.6.0 ! pip install -U matplotlib==3.2.1 ! pip install -U trains>=0.15.0 ! pip install -U tensorboard==2.2.1 import os import time import torch import torch.nn as nn import torch.nn.functional as F import torchtext from torchtext.datase...
github_jupyter
! pip install -U pip ! pip install -U torch==1.5.0 ! pip install -U torchtext==0.6.0 ! pip install -U matplotlib==3.2.1 ! pip install -U trains>=0.15.0 ! pip install -U tensorboard==2.2.1 import os import time import torch import torch.nn as nn import torch.nn.functional as F import torchtext from torchtext.datasets i...
0.846895
0.471649
# Canary Rollout with Seldon and Ambassador ## Setup Seldon Core Use the setup notebook to [Setup Cluster](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.html#Setup-Cluster) with [Ambassador Ingress](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.htm...
github_jupyter
!kubectl create namespace seldon !kubectl config set-context $(kubectl config current-context) --namespace=seldon from IPython.core.magic import register_line_cell_magic @register_line_cell_magic def writetemplate(line, cell): with open(line, "w") as f: f.write(cell.format(**globals())) VERSION=!cat ../.....
0.432063
0.941331
# Linear Systems Solving linear systems of the form $$ A \mathbf{x} = \mathbf{b} $$ where $A$ is symmetric positive definite is arguably one of the most fundamental computations in statistics, machine learning and scientific computation at large. Many problems can be reduced to the solution of one or many (large-scal...
github_jupyter
# Make inline plots vector graphics instead of raster graphics %matplotlib inline from IPython.display import set_matplotlib_formats set_matplotlib_formats('pdf', 'svg') # Plotting import matplotlib.pyplot as plt plt.style.use('../probnum.mplstyle') import numpy as np from scipy.sparse import diags # Random linear s...
0.735642
0.977543
<a href="https://colab.research.google.com/github/krakowiakpawel9/machine-learning-bootcamp/blob/master/unsupervised/01_clustering/06_clustering_comparison.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> * @author: krakowiakpawel9@gmail.com * @sit...
github_jupyter
!pip install scikit-learn !pip install --upgrade scikit-learn import numpy as np import pandas as pd import plotly.express as px from sklearn.datasets import make_blobs blobs_data = make_blobs(n_samples=1000, cluster_std=0.7, random_state=24, center_box=(-4.0, 4.0))[0] blobs = pd.DataFrame(blobs_data, columns=['x1'...
0.777046
0.960361
``` cuse = spark.read.csv('data/cuse_binary.csv', header=True, inferSchema=True) cuse.show(5) cuse.columns[0:3] # cuse.select('age').distinct().show() cuse.select('age').rdd.countByValue() # cuse.select('education').rdd.countByValue() # string index each categorical string columns from pyspark.ml.feature import StringI...
github_jupyter
cuse = spark.read.csv('data/cuse_binary.csv', header=True, inferSchema=True) cuse.show(5) cuse.columns[0:3] # cuse.select('age').distinct().show() cuse.select('age').rdd.countByValue() # cuse.select('education').rdd.countByValue() # string index each categorical string columns from pyspark.ml.feature import StringIndex...
0.558809
0.641099
``` import panel as pn pn.extension('plotly') ``` The ``Plotly`` pane renders Plotly plots inside a panel. It optimizes the plot rendering by using binary serialization for any array data found on the Plotly object, providing efficient updates. Note that to use the Plotly pane in a Jupyter notebook, the Panel extensio...
github_jupyter
import panel as pn pn.extension('plotly') import numpy as np import plotly.graph_objs as go xx = np.linspace(-3.5, 3.5, 100) yy = np.linspace(-3.5, 3.5, 100) x, y = np.meshgrid(xx, yy) z = np.exp(-(x-1)**2-y**2)-(x**3+y**4-x/5)*np.exp(-(x**2+y**2)) surface = go.Surface(z=z) layout = go.Layout( title='Plotly 3D P...
0.532182
0.950824
# Allowing storage of yaml file Here we will correct the model so that it can be stored in `.yml` format, and do some tests to check all is in place. Benjamín J. Sánchez, 2020-05-06 ## 1. Non-compliant notes ``` import cobra model = cobra.io.read_sbml_model("../model/p-thermo.xml") cobra.io.save_yaml_model(model,"....
github_jupyter
import cobra model = cobra.io.read_sbml_model("../model/p-thermo.xml") cobra.io.save_yaml_model(model,"../model/p-thermo.yml") model = cobra.io.read_sbml_model("../model/p-thermo.xml") cobra.io.save_yaml_model(model,"../model/p-thermo.yml") model.metabolites.pydx5p_c.notes model = cobra.io.read_sbml_model("../model/...
0.19046
0.788217
``` from iobjectspy import (Point2D, QueryParameter, open_datasource, create_datasource, SpatialQueryMode) import os # 设置示例数据路径 example_data_dir = '' # 设置结果输出路径 out_dir = os.path.join(example_data_dir, 'out') if not os.pat...
github_jupyter
from iobjectspy import (Point2D, QueryParameter, open_datasource, create_datasource, SpatialQueryMode) import os # 设置示例数据路径 example_data_dir = '' # 设置结果输出路径 out_dir = os.path.join(example_data_dir, 'out') if not os.path.ex...
0.283881
0.399665
# Auto-Generated Altair Examples All the following notebooks are auto-generated from the Python examples in the Altair source code repository here: https://github.com/altair-viz/altair/tree/master/altair/vegalite/v2/examples - [Aggregate Bar Chart](aggregate_bar_chart.ipynb) - [Airports](airports.ipynb) - [Anscombe ...
github_jupyter
# Auto-Generated Altair Examples All the following notebooks are auto-generated from the Python examples in the Altair source code repository here: https://github.com/altair-viz/altair/tree/master/altair/vegalite/v2/examples - [Aggregate Bar Chart](aggregate_bar_chart.ipynb) - [Airports](airports.ipynb) - [Anscombe ...
0.820218
0.905907
``` import numpy as np import panel as pn import xarray as xr import holoviews as hv import geoviews as gv import cartopy.crs as ccrs from earthsim.annotators import PolyAnnotator, PolyExporter, paths_to_polys from earthsim.grabcut import GrabCutPanel, SelectRegionPanel gv.extension('bokeh') ``` The GrabCut algorithm...
github_jupyter
import numpy as np import panel as pn import xarray as xr import holoviews as hv import geoviews as gv import cartopy.crs as ccrs from earthsim.annotators import PolyAnnotator, PolyExporter, paths_to_polys from earthsim.grabcut import GrabCutPanel, SelectRegionPanel gv.extension('bokeh') select_region = SelectRegionP...
0.400163
0.951414
# Linear Regression ``` %matplotlib inline import matplotlib.pyplot as plt import pandas as pd import numpy as np df = pd.read_csv('../data/weight-height.csv') df.head() df.plot(kind='scatter', x='Height', y='Weight', title='Weight and Height in adults') df.plot(kind='scatter', x='Heigh...
github_jupyter
%matplotlib inline import matplotlib.pyplot as plt import pandas as pd import numpy as np df = pd.read_csv('../data/weight-height.csv') df.head() df.plot(kind='scatter', x='Height', y='Weight', title='Weight and Height in adults') df.plot(kind='scatter', x='Height', y='Weight', ...
0.722918
0.908658
``` %%capture import os import site os.sys.path.insert(0, '/home/schirrmr/code/reversible/reversible2/') os.sys.path.insert(0, '/home/schirrmr/braindecode/code/braindecode/') os.sys.path.insert(0, '/home/schirrmr/code/explaining/reversible//') %cd /home/schirrmr/ %load_ext autoreload %autoreload 2 import numpy as np ...
github_jupyter
%%capture import os import site os.sys.path.insert(0, '/home/schirrmr/code/reversible/reversible2/') os.sys.path.insert(0, '/home/schirrmr/braindecode/code/braindecode/') os.sys.path.insert(0, '/home/schirrmr/code/explaining/reversible//') %cd /home/schirrmr/ %load_ext autoreload %autoreload 2 import numpy as np impo...
0.523908
0.273993
``` import sys from pathlib import Path portfolio_management_path = Path.cwd().parent sys.path.insert(0, str(portfolio_management_path)) import xarray as xr import numpy as np import pandas as pd from portfolio_management.database.manager import Manager from portfolio_management.database.retrieve import get_dataframe ...
github_jupyter
import sys from pathlib import Path portfolio_management_path = Path.cwd().parent sys.path.insert(0, str(portfolio_management_path)) import xarray as xr import numpy as np import pandas as pd from portfolio_management.database.manager import Manager from portfolio_management.database.retrieve import get_dataframe data...
0.391755
0.293664
``` import pandas as pd import os import re import json base_dir = 'data/mgnify/studies' def gen_study_dir_contents(): """Iterate over every study directory and yield all file paths within each one.""" for name in os.listdir(base_dir): study_dir = os.path.join(base_dir, name) file_paths = [] ...
github_jupyter
import pandas as pd import os import re import json base_dir = 'data/mgnify/studies' def gen_study_dir_contents(): """Iterate over every study directory and yield all file paths within each one.""" for name in os.listdir(base_dir): study_dir = os.path.join(base_dir, name) file_paths = [] ...
0.31542
0.162679
``` import csv import seaborn as sns from matplotlib import pyplot as plt import numpy as np import pandas as pd %matplotlib inline %load_ext autoreload %autoreload 2 from scipy.optimize import least_squares from scipy.stats import expon from scipy.stats import weibull_min as weibull # cdf(x, c, loc=0, scale=1) week_...
github_jupyter
import csv import seaborn as sns from matplotlib import pyplot as plt import numpy as np import pandas as pd %matplotlib inline %load_ext autoreload %autoreload 2 from scipy.optimize import least_squares from scipy.stats import expon from scipy.stats import weibull_min as weibull # cdf(x, c, loc=0, scale=1) week_rang...
0.163713
0.726256
``` #Import libraries import pandas as pd import matplotlib.pyplot as plt ``` # Domain Specific Dataset Analysis ## 1. Domain: COVID-19 Research Article Abstracts Source: COVID-19 Open Research Dataset Challenge ([CORD-19](https://www.kaggle.com/allen-institute-for-ai/CORD-19-research-challenge)). CORD-19 is a reso...
github_jupyter
#Import libraries import pandas as pd import matplotlib.pyplot as plt df1 = pd.read_csv('../datasets/CORD19/metadata_sample.csv', dtype=str) df1.head(2).abstract.values #sample import nltk nltk.download('punkt') word_tokens = nltk.word_tokenize(df1.iloc[0].abstract) '|'.join(word_tokens) from nltk.stem.snowball impo...
0.291384
0.88573
# OpenMP* Device Parallelism (Fortran) #### Sections - [Learning Objectives](#Learning-Objectives) - [Device Parallelism](#Device-Parallelism) - [GPU Architecture](#GPU-Architecture) - ["Normal" OpenMP constructs](#"Normal"-OpenMP-constructs) - [League of Teams](#League-of-Teams) - [Worksharing with Teams](#Worksharin...
github_jupyter
subroutine saxpy(a, x, y, sz) ! Declarations Omitted !$omp target map(to:x(1:sz)) map(tofrom(y(1:sz)) !$omp parallel do simd do i=1,sz y(i) = a * x(i) + y(i); end do !$omp end target end subroutine subroutine saxpy(a, x, y, sz) ! Declarations Omitted !$omp target teams distribut...
0.292393
0.914787
# DCGAN on MNIST Digits dataset Following the original GAN [1], Deep Convolutional Generative Adversarial Network (DCGAN) [2] is replacing some of the layers with convolutional layers. The result is similar but taking advantage of the properties of the convolutional layers: less parameters to train, space invariance....
github_jupyter
COLAB = True if COLAB: from google.colab import drive drive.mount('/content/drive') !pip install tensorview import sys import tensorflow as tf import numpy as np from tensorflow.keras import models, layers, losses, optimizers, metrics import tensorflow_datasets as tf_ds import tensorview as tv import matplotlib.py...
0.718199
0.943971
# Finding MetaCharacters Here’s a complete list of the metacharacters used in regular expressions: ```python . ^ $ * + ? { } [ ] \ | ( ) ``` As we mentioned in the previous lesson, these metacharacters are used to give special instructions and can't be searched for directly. If we want to search for these metacharac...
github_jupyter
. ^ $ * + ? { } [ ] \ | ( ) # Import re module import re # Sample text sample_text = 'Alice and Walter are walking to the store.' # Create a regular expression object with the regular expression '\.' regex = re.compile(r'\.') # Search the sample_text for the regular expression matches = regex.finditer(sample_text) ...
0.498779
0.964689
``` import graphlab products = graphlab.SFrame('Amazon_baby.sframe/') selected_words = ['awesome', 'great', 'fantastic', 'amazing', 'love', 'horrible', 'bad', 'terrible', 'awful', 'wow', 'hate'] products['words_count'] = graphlab.text_analytics.count_words(products['review']) def count_word(words_count,word): if wo...
github_jupyter
import graphlab products = graphlab.SFrame('Amazon_baby.sframe/') selected_words = ['awesome', 'great', 'fantastic', 'amazing', 'love', 'horrible', 'bad', 'terrible', 'awful', 'wow', 'hate'] products['words_count'] = graphlab.text_analytics.count_words(products['review']) def count_word(words_count,word): if word i...
0.182717
0.487063
<!--BOOK_INFORMATION--> <a href="https://www.packtpub.com/big-data-and-business-intelligence/machine-learning-opencv" target="_blank"><img align="left" src="data/cover.jpg" style="width: 76px; height: 100px; background: white; padding: 1px; border: 1px solid black; margin-right:10px;"></a> *This notebook contains an ex...
github_jupyter
<!--BOOK_INFORMATION--> <a href="https://www.packtpub.com/big-data-and-business-intelligence/machine-learning-opencv" target="_blank"><img align="left" src="data/cover.jpg" style="width: 76px; height: 100px; background: white; padding: 1px; border: 1px solid black; margin-right:10px;"></a> *This notebook contains an ex...
0.873498
0.877056
``` import pandas as pd import numpy as np import matplotlib.pyplot as plt #read the file df = pd.read_json (r'VZ.json') #print the head df df['t'] = pd.to_datetime(df['t'], unit='s') df = df.rename(columns={'c': 'Close', 'h': 'High', 'l':'Low', 'o': 'Open', 's': 'Status', 't': 'Date', 'v': 'Volume'}) df.head() ``` ...
github_jupyter
import pandas as pd import numpy as np import matplotlib.pyplot as plt #read the file df = pd.read_json (r'VZ.json') #print the head df df['t'] = pd.to_datetime(df['t'], unit='s') df = df.rename(columns={'c': 'Close', 'h': 'High', 'l':'Low', 'o': 'Open', 's': 'Status', 't': 'Date', 'v': 'Volume'}) df.head() #read th...
0.417509
0.773281
``` import easyocr import onnxruntime import os import string from matplotlib import pyplot as plt import difflib import sys sys.path.append('/home/tandonsa/PycharmProjects/side_project/ocr_mawaqif/') from src.utils import infer_utils # add NLP Models en_model = easyocr.Reader(['en']) ar_model = easyocr.Reader(['ar'])...
github_jupyter
import easyocr import onnxruntime import os import string from matplotlib import pyplot as plt import difflib import sys sys.path.append('/home/tandonsa/PycharmProjects/side_project/ocr_mawaqif/') from src.utils import infer_utils # add NLP Models en_model = easyocr.Reader(['en']) ar_model = easyocr.Reader(['ar']) nlp...
0.447702
0.209227
### ***Goal of this notebook:*** #### The purpose of this notebook is to show the different ways implemented to associate cluster catalogs. It is designed to associate the halos in cosmoDC2 and the clusters detected by redMaPPer in cosmoDC2, but can be tuned to work with other catalogues. ### ***Rationale:*** #### A...
github_jupyter
import GCRCatalogs import numpy as np import matplotlib.pyplot as plt from astropy.table import Table from astropy.coordinates import SkyCoord from astropy import units as u from astropy.cosmology import FlatLambdaCDM from cluster_validation.opening_catalogs_functions import * from cluster_validation.association_meth...
0.441432
0.953232
``` from rfm_deployment.rfm_model_V2_com import * from itertools import product import cx_Oracle import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import calendar import datetime import cairo import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk %matplotlib...
github_jupyter
from rfm_deployment.rfm_model_V2_com import * from itertools import product import cx_Oracle import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import calendar import datetime import cairo import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk %matplotlib inl...
0.118793
0.205575
# Training a CNN in Keras with Real-Time Data Augmentation ## Initial Setup ``` from __future__ import division from PIL import Image import os import numpy as np import matplotlib.pyplot as plt %matplotlib inline %load_ext autoreload %autoreload 2 ``` ## Load Images into a Matrix ``` base_dir = 'square_images128'...
github_jupyter
from __future__ import division from PIL import Image import os import numpy as np import matplotlib.pyplot as plt %matplotlib inline %load_ext autoreload %autoreload 2 base_dir = 'square_images128' image_width = 128 image_height = 128 classes = ['daffodil', 'snowdrop', 'lily_valley', 'bluebell', 'crocus', 'iris', ...
0.593138
0.771413
# A. **Simple Regresi Linier** Teknik ini digunakan untuk menyelesaikan permasalahan hubungan sebab akibat antara 2 variable. 2 variable itu adalah : 1. Variable Faktor Penyebab - biasanya disimbolkan dengan X. Ini disebut `predictor`. 2. Variable Akibat - biasanya disimbolkan dengan Y. Ini disebut `response`. Untuk...
github_jupyter
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns; sns.set() data = pd.read_csv('Salary_Data.csv') data data.keys() data.shape mydata = pd.DataFrame(data) mydata.head() mydata.tail() mydata.info() # slice from the beginning to 'Salary' data.loc[:, :'Salary'] x = data.il...
0.501465
0.946843
# Convolutional Layer In this notebook, we visualize four filtered outputs (a.k.a. activation maps) of a convolutional layer. In this example, *we* are defining four filters that are applied to an input image by initializing the **weights** of a convolutional layer, but a trained CNN will learn the values of these w...
github_jupyter
import cv2 import matplotlib.pyplot as plt %matplotlib inline # TODO: Feel free to try out your own images here by changing img_path # to a file path to another image on your computer! img_path = 'data/udacity_sdc.png' # load color image bgr_img = cv2.imread(img_path) # convert to grayscale gray_img = cv2.cvtColor(b...
0.626238
0.987092
# Practical use of HH-suite3 on the command line in Jupyter via MyBinder.org: Basics Run this in sessions launched from [my HH-suite3-binder repo](https://github.com/fomightez/hhsuite3-binder) because the software is already installed. This is the first notebook in my series of notebooks convering use if HH-suite3 ...
github_jupyter
!hhblits !hhsearch !hhmake %%bash cd ../../.. find . -type f -name "hhmakemodel.*" %run /srv/conda/envs/notebook/scripts/hhmakemodel.py %run /srv/conda/envs/notebook/scripts/hhsuitedb.py s='''>TvLDH MSEAAHVLITGAAGQIGYILSHWIASGELYGDRQVYLHLLDIPPAMNRLTALTMELEDCAFPHLAGFVATTDP KAAFKDIDCAFLVASMPLKPGQVRADLISSNSVIFKNTGEYLS...
0.162613
0.913599
# Build the speech model Now that we have created the spectrogram images its time to build the computer vision model. If you are following along with the learning path then you already created a computer vision model in the second module in this path. We will be using the [torchvision](https://pypi.org/project/torchvi...
github_jupyter
from torch.utils.data import DataLoader from torchvision import datasets, transforms import torch import torchaudio import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np import matplotlib.pyplot as plt from torch.utils.data import Dataset, DataLoader from torchvision impor...
0.884776
0.98191
<div style="display: flex; background-color: #3F579F;"> <h1 style="margin: auto; font-weight: bold; padding: 30px 30px 0px 30px; color:#fff;" align="center">Automatically classify consumer goods - P6</h1> </div> <div style="display: flex; background-color: #3F579F; margin: auto; padding: 5px 30px 0px 30px;" > <...
github_jupyter
## General import os import pandas as pd import numpy as np ## TensorFlow import tensorflow as tf from tensorboard.plugins import projector ## Own specific functions from functions import * %load_ext tensorboard # Path to save the embedding and checkpoints generated LOG_DIR = "./logs/projections/" df_text = pd.re...
0.488527
0.875574
# c05-??? *Purpose*: (Apply control charts, Pr modeling techniques) ``` import grama as gr import numpy as np import pandas as pd import time DF = gr.Intention() %matplotlib inline filename_data = "./data/c05-data.csv" ``` # Stang ``` from grama.data import df_stang df_stang.head() ( df_stang >> gr.pt_xbs(...
github_jupyter
import grama as gr import numpy as np import pandas as pd import time DF = gr.Intention() %matplotlib inline filename_data = "./data/c05-data.csv" from grama.data import df_stang df_stang.head() ( df_stang >> gr.pt_xbs(group="thick", var="E") ) from grama.models import make_plate_buckle md_plate = make_plate...
0.445771
0.820937
<a href="https://colab.research.google.com/github/Abhishek1236/computer-vision-models/blob/main/Alexnet_practice.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` #importing the libraries import keras from keras.models import Sequential from ke...
github_jupyter
#importing the libraries import keras from keras.models import Sequential from keras.layers import Dense, Activation, Dropout, Flatten,\ Conv2D, MaxPooling2D from keras.layers.normalization import BatchNormalization import numpy as np import tflearn.datasets.oxflower17 as oxflower17 import tensorflow as tf ...
0.759047
0.831759
# Time normalization of data > Marcos Duarte > Laboratory of Biomechanics and Motor Control ([http://demotu.org/](http://demotu.org/)) > Federal University of ABC, Brazil Time normalization is usually employed for the temporal alignment of cyclic data obtained from different trials with different duration (number...
github_jupyter
yn, tn, indie = tnorma(y, axis=0, step=1, k=3, smooth=0, mask=None, nan_at_ext='delete', show=False, ax=None) pip install tnorma conda install -c duartexyz tnorma # Import the necessary libraries import numpy as np %matplotlib inline import matplotlib.pyplot as plt y = [5, 4, 10, 8, 1, 10,...
0.667906
0.988154
### SET DATA Structure ``` st = set() print(type(st)) # creating a simple set st= {'pumar','kris','krish','bara','bara'} print(type(st)) print(st) # eliminated the duplicate values # add elemets to the set st.add('Gommu') print(st) # remove element from the set st.remove('Gommu') print(st) # Adding more than one or...
github_jupyter
st = set() print(type(st)) # creating a simple set st= {'pumar','kris','krish','bara','bara'} print(type(st)) print(st) # eliminated the duplicate values # add elemets to the set st.add('Gommu') print(st) # remove element from the set st.remove('Gommu') print(st) # Adding more than one or more values in the set simu...
0.429669
0.800185
``` %run data.py ``` ### Read the zipcode data. ``` zipcode_data = fetchData(nyc_zcta_url) zipcode_data.head(10) zipcode_old_df = spark.createDataFrame(zipcode_data) zipcode_df = zipcode_old_df.select(zipcode_old_df.MODZCTA.cast("integer").alias("zipcode"), zipcode_old_df["Positive"],...
github_jupyter
%run data.py zipcode_data = fetchData(nyc_zcta_url) zipcode_data.head(10) zipcode_old_df = spark.createDataFrame(zipcode_data) zipcode_df = zipcode_old_df.select(zipcode_old_df.MODZCTA.cast("integer").alias("zipcode"), zipcode_old_df["Positive"], zipcode_old_df["Total"]) zipcode_df = ...
0.379608
0.766031
<a href="https://colab.research.google.com/github/BandaruDheeraj/TTSModel/blob/main/waveglow.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ### This notebook requires a GPU runtime to run. ### Please select the menu option "Runtime" -> "Change runt...
github_jupyter
%%bash pip install numpy scipy librosa unidecode inflect librosa apt-get update apt-get install -y libsndfile1 import torch waveglow = torch.hub.load('NVIDIA/DeepLearningExamples:torchhub', 'nvidia_waveglow', model_math='fp32') waveglow = waveglow.remove_weightnorm(waveglow) waveglow = waveglow.to('cuda') waveglow.ev...
0.580114
0.982237
#1. Install Dependencies First install the libraries needed to execute recipes, this only needs to be done once, then click play. ``` !pip install git+https://github.com/google/starthinker ``` #2. Get Cloud Project ID To run this recipe [requires a Google Cloud Project](https://github.com/google/starthinker/blob/mast...
github_jupyter
!pip install git+https://github.com/google/starthinker CLOUD_PROJECT = 'PASTE PROJECT ID HERE' print("Cloud Project Set To: %s" % CLOUD_PROJECT) CLIENT_CREDENTIALS = 'PASTE CREDENTIALS HERE' print("Client Credentials Set To: %s" % CLIENT_CREDENTIALS) FIELDS = { 'auth_read': 'user', # Credentials used for readin...
0.371935
0.715349
# Developing an AI application Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall appli...
github_jupyter
# Imports here import torch from torch import nn from torch import optim import torch.nn.functional as F from torchvision import datasets, transforms, models import numpy as np from PIL import Image data_dir = 'flowers' train_dir = data_dir + '/train' valid_dir = data_dir + '/valid' test_dir = data_dir + '/test' # TO...
0.665628
0.969957
![MLU Logo](../data/MLU_Logo.png) # <a name="0">Machine Learning Accelerator - Natural Language Processing - Lecture 3</a> ## Neural Networks with PyTorch In this notebook, we will build, train and validate a Neural Network using PyTorch. 1. <a href="#1">Implementing a neural network with PyTorch</a> 2. <a href="#2"...
github_jupyter
import torch from torch import nn net = nn.Sequential( nn.Linear(in_features=3, # Input size of 3 is expected out_features=64), # Linear layer-1 with 64 units nn.Tanh(), # Tanh activation is applied nn.Dropout(p=.4), # Apply random 40%...
0.919004
0.987935
### Note * Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps. ``` # Dependencies and Setup import pandas as pd # File to Load (Remember to Change These) file_to_load = "Resources/purchase_data.csv" # Read Purchasing Fil...
github_jupyter
# Dependencies and Setup import pandas as pd # File to Load (Remember to Change These) file_to_load = "Resources/purchase_data.csv" # Read Purchasing File and store into Pandas data frame purchase_df = pd.read_csv(file_to_load) purchase_df age_df = pd.read_csv(file_to_load) purchase_df #locates the three columns fr...
0.48438
0.832849
# Fashion MNIST mit Neuronalen Netzen In diesem Arbeitsblatt wollen wir uns erneut den Fashion MNIST Datensatz vornehmen, den wir schon aus dem 7. Arbeitsblatt kennen. Dort haben wir das Problem mit Multinomialer Logistischer Regression gelöst. Hier wollen wir ein Multi-Layer Perceptron einsetzen, also ein recht einfa...
github_jupyter
import tensorflow as tf #Datensatz aus Keras laden (X_train, y_train), (X_test, y_test) = tf.keras.datasets.fashion_mnist.load_data() #Pixelwerte nach [0,1] skalieren X_train = X_train / 255.0 X_test = X_test / 255.0 # Mache aus den 2D Bildern 1D Vektoren X_train = X_train.reshape(-1,28*28,1)[:,:,0] X_test = X_test....
0.680772
0.92617
# Why Fugue Does NOT Want To Be Another Pandas-Like Framework Fugue fully utilizes Pandas for computing tasks, but **Fugue is NOT a Pandas-like computing framework, and it never wants to be.** In this article we are going to explain the reason for this critical design decision. ## Benchmarking PySpark Pandas (Koalas)...
github_jupyter
def gen(n): np.random.seed(0) return pd.DataFrame(dict( a=np.random.choice(["aa","abcd","xyzzzz","tttfs"],n), b=np.random.randint(0,100,n), c=np.random.choice(["aa","abcd","xyzzzz","tttfs"],n), d=np.random.randint(0,10000,n), )) df.sort_values(["a", "b", "c", "d"]).drop_dupl...
0.202325
0.965446
# Amazon SageMaker Multi-Model Endpoints using XGBoost With [Amazon SageMaker multi-model endpoints](https://docs.aws.amazon.com/sagemaker/latest/dg/multi-model-endpoints.html), customers can create an endpoint that seamlessly hosts up to thousands of models. These endpoints are well suited to use cases where any one o...
github_jupyter
import numpy as np import pandas as pd import time NUM_HOUSES_PER_LOCATION = 1000 LOCATIONS = ['NewYork_NY', 'LosAngeles_CA', 'Chicago_IL', 'Houston_TX', 'Dallas_TX', 'Phoenix_AZ', 'Philadelphia_PA', 'SanAntonio_TX', 'SanDiego_CA', 'SanFrancisco_CA'] PARALLEL_TRAINING_JOBS = 4 # len(LOCATIO...
0.42477
0.956063
# Train a gesture recognition model for microcontroller use This notebook demonstrates how to train a 20kb gesture recognition model for [TensorFlow Lite for Microcontrollers](https://tensorflow.org/lite/microcontrollers/overview). It will produce the same model used in the [magic_wand](https://github.com/tensorflow/t...
github_jupyter
%tensorflow_version 2.x # Clone the repository from GitHub !git clone --depth 1 -q https://github.com/tensorflow/tensorflow # Copy the training scripts into our workspace !cp -r tensorflow/tensorflow/lite/experimental/micro/examples/magic_wand/train train # Download the data we will use to train the model !wget http:...
0.657098
0.987508
# Project summary In this project, I used machine learning to predicting the operating conditions of a waterpoint using data from the Tanzanian Ministry of Water. The algorithm used was Random Forest for multiclassification between three outcomes: "Functional", "Functional needs repair", and "Nonfunctional". # Data i...
github_jupyter
#Importing external libraries import math import numpy as np import pandas as pd import re import matplotlib.pyplot as plt import seaborn as sns from collections import OrderedDict from scipy.stats import chi2_contingency from scipy.stats import chi2 import statsmodels.api as sm from statsmodels.formula.api import ols ...
0.398406
0.927429
# Concluding Thoughts Congratulations! You've made it! If you have worked through all of the notebooks to this point, then you have joined the small, but growing group of people that are able to harness the power of deep learning to solve real problems. You may not feel that way yet—in fact you probably don't. We have...
github_jupyter
# Concluding Thoughts Congratulations! You've made it! If you have worked through all of the notebooks to this point, then you have joined the small, but growing group of people that are able to harness the power of deep learning to solve real problems. You may not feel that way yet—in fact you probably don't. We have...
0.368633
0.620507
# What's New - Internal ## Summary This new edition of `made-with-gs-quant` is tailored exclusively for our internal users and showcases some of the latest features of the internal gs-quant toolkit. In this notebook we find solutions for some the most popular questions we get such as: + How do I generate an FX dual ...
github_jupyter
from gs_quant.session import GsSession GsSession.use() import gs_quant_internal.tdapi as tdapi from IPython.display import Image Image(filename='images/tdapi_package.png') from gs_quant.markets.portfolio import Portfolio def FXDualBinaryOption(pair_1, pair_2, strikes_1, strikes_2, expiry, size): portfolio = Port...
0.441191
0.949763
<a href="https://colab.research.google.com/github/ayulockin/LossLandscape/blob/master/Visualizing_Function_Space_Similarity_SmallCNN.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Setups, Imports and Installations ``` ## This is so that I can sa...
github_jupyter
## This is so that I can save my models. from google.colab import drive drive.mount('gdrive') %%capture !pip install wandb import tensorflow as tf from tensorflow import keras from tensorflow.keras.datasets import cifar10 from tensorflow.keras.applications import resnet50 import os os.environ["TF_DETERMINISTIC_OPS"] =...
0.602763
0.850096
# Star with toruses This is an example of a synthesized three dimensional volume that is not easy to visualize using only two dimenaional projections. The calculation to generate the volume array is not optimized and it takes a while to complete. ``` import numpy as np from numpy.linalg import norm def vec(*args): ...
github_jupyter
import numpy as np from numpy.linalg import norm def vec(*args): return np.array(args, dtype=np.float) def normalize(V, epsilon=1e-12): nm = norm(V) if nm < epsilon: return vec(1, 0, 0) # whatever return (1.0 / nm) * V def point_segment_distance(P, segment, epsilon=1e-4): A = segment[0] ...
0.452778
0.93337
``` # Load dependencies import numpy as np import pandas as pd pd.options.display.float_format = '{:,.1e}'.format import sys sys.path.insert(0, '../../statistics_helper') from CI_helper import * from excel_utils import * ``` # Estimating the total biomass of terrestrial deep subsurface archaea and bacteria We use our...
github_jupyter
# Load dependencies import numpy as np import pandas as pd pd.options.display.float_format = '{:,.1e}'.format import sys sys.path.insert(0, '../../statistics_helper') from CI_helper import * from excel_utils import * results = pd.read_excel('terrestrial_deep_subsurface_prok_biomass_estimate.xlsx') results # Calculate...
0.49585
0.839603
``` %matplotlib inline ``` 파이프라인 병렬화로 트랜스포머 모델 학습시키기 ============================================== **Author**: `Pritam Damania <https://github.com/pritamdamania87>`_ **번역**: `백선희 <https://github.com/spongebob03>`_ 이 튜토리얼은 파이프라인(pipeline) 병렬화(parallelism)를 사용하여 여러 GPU에 걸친 거대한 트랜스포머(transformer) 모델을 어떻게 학습시키는지 보여줍...
github_jupyter
%matplotlib inline import sys import math import torch import torch.nn as nn import torch.nn.functional as F import tempfile from torch.nn import TransformerEncoder, TransformerEncoderLayer if sys.platform == 'win32': print('Windows platform is not supported for pipeline parallelism') sys.exit(0) if torch.cud...
0.611962
0.958402
# Tutorial: topic modeling to analyze the EGC conference EGC is a French-speaking conference on knowledge discovery in databases (KDD). In this notebook we show how to use TOM for inferring latent topics that pervade the corpus of articles published at EGC between 2004 and 2015 using non-negative matrix factorization....
github_jupyter
from tom_lib.structure.corpus import Corpus from tom_lib.visualization.visualization import Visualization corpus = Corpus(source_file_path='input/egc_lemmatized.csv', language='french', vectorization='tfidf', max_relative_frequency=0.8, min_absolute_frequ...
0.590307
0.983375
<a href="https://colab.research.google.com/github/Lilchoto3/DS-Unit-2-Linear-Models/blob/master/module3-ridge-regression/LS_DS_213.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Lambda School Data Science *Unit 2, Sprint 1, Module 3* --- # Ridge...
github_jupyter
%%capture import sys # If you're on Colab: if 'google.colab' in sys.modules: DATA_PATH = 'https://raw.githubusercontent.com/LambdaSchool/DS-Unit-2-Applied-Modeling/master/data/' !pip install category_encoders==2.* # If you're working locally: else: DATA_PATH = '../data/' import numpy as np import pandas ...
0.243283
0.987104
# Modelagem de Hiperparâmetros ``` import numpy as np import pandas as pd import math import matplotlib.pyplot as plt import clf_vAngra_lib as vCLF from astropy.stats import mad_std from sklearn.preprocessing import StandardScaler from sklearn.neural_network import MLPClassifier from sklearn.model_selection import KF...
github_jupyter
import numpy as np import pandas as pd import math import matplotlib.pyplot as plt import clf_vAngra_lib as vCLF from astropy.stats import mad_std from sklearn.preprocessing import StandardScaler from sklearn.neural_network import MLPClassifier from sklearn.model_selection import KFold from sklearn.model_selection imp...
0.469763
0.832747
# LNet in TF #### Dependencies ``` import numpy as np np.random.seed(42) import tensorflow as tf tf.set_random_seed(42) from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) ``` #### Set hyperparameters ``` display_progress = 40 epochs = 10 batch_s...
github_jupyter
import numpy as np np.random.seed(42) import tensorflow as tf tf.set_random_seed(42) from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) display_progress = 40 epochs = 10 batch_size = 128 wt_init = tf.contrib.layers.xavier_initializer() # input laye...
0.76769
0.919462
``` import sys sys.path.append('..') import torch import pandas as pd import numpy as np import pickle import argparse import networkx as nx from torch_geometric.utils import dense_to_sparse, degree import matplotlib.pyplot as plt from src.gcn import GCNSynthetic from src.utils.utils import normalize_adj, get_neighbour...
github_jupyter
import sys sys.path.append('..') import torch import pandas as pd import numpy as np import pickle import argparse import networkx as nx from torch_geometric.utils import dense_to_sparse, degree import matplotlib.pyplot as plt from src.gcn import GCNSynthetic from src.utils.utils import normalize_adj, get_neighbourhood...
0.561575
0.683672
``` import numpy as np import cv2 as cv img = cv.imread('data_hierarchy2.png') img_white_bg = cv.imread('data_hierarchy4.png') """缩小图像,方便看效果 """ def resizeImg(src): height, width = src.shape[:2] size = (int(width * 0.3), int(height * 0.3)) # bgr img = cv.resize(src, size, interpolation=cv.INTER_AREA) ...
github_jupyter
import numpy as np import cv2 as cv img = cv.imread('data_hierarchy2.png') img_white_bg = cv.imread('data_hierarchy4.png') """缩小图像,方便看效果 """ def resizeImg(src): height, width = src.shape[:2] size = (int(width * 0.3), int(height * 0.3)) # bgr img = cv.resize(src, size, interpolation=cv.INTER_AREA) re...
0.162979
0.363252
If you're opening this Notebook on colab, you will probably need to install the most recent versions of 🤗 Transformers and 🤗 Datasets. We will also need `scipy` and `scikit-learn` for some of the metrics. Uncomment the following cell and run it. We will also need `scipy` and `scikit-learn` for some of the metrics. W...
github_jupyter
! pip install transformers ! pip install datasets ! pip install huggingface-hub ! pip install wandb import wandb # Log in to your W&B account wandb.login() task = "sst2" model_checkpoint = "distilbert-base-uncased" batch_size = 16 from datasets import load_dataset dataset = load_dataset("glue", "sst2") from transfo...
0.732113
0.975296
# dislib tutorial This tutorial will show the basics of using [dislib](https://dislib.bsc.es). ## Requirements Apart from dislib, this notebook requires [PyCOMPSs 2.5](https://www.bsc.es/research-and-development/software-and-apps/software-list/comp-superscalar/). ## Setup First, we need to start an interactive P...
github_jupyter
import pycompss.interactive as ipycompss ipycompss.start(graph=True, monitor=1000) import dislib as ds x = ds.random_array(shape=(500, 500), block_size=(100, 100)) print(x.shape) x x._blocks[0][0] x.collect() x1 = ds.array([[1, 2, 3], [4, 5, 6]], block_size=(1, 3)) x1 from scipy.sparse import csr_matrix sp = csr...
0.46393
0.991263
``` !pip install wget !pip install --upgrade scikit-learn import util X1, y1, X2, y2 = util.mnist_init('small') util.image_peek(X1[1], 5 if y1[1] == 1 else 8) util.image_peek(X1[3], 5 if y1[3] == 1 else 8) import numpy as np class Perceptron(object): def __init__(self, dataset, labels, max_iter, lr): sel...
github_jupyter
!pip install wget !pip install --upgrade scikit-learn import util X1, y1, X2, y2 = util.mnist_init('small') util.image_peek(X1[1], 5 if y1[1] == 1 else 8) util.image_peek(X1[3], 5 if y1[3] == 1 else 8) import numpy as np class Perceptron(object): def __init__(self, dataset, labels, max_iter, lr): self.b ...
0.472927
0.597549
<a href="https://colab.research.google.com/github/ren1406/startbootstrap-freelancer/blob/master/08_sentiment_analysis_with_bert.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Sentiment Analysis with BERT > TL;DR In this tutorial, you'll learn ho...
github_jupyter
#@title Watch the video tutorial from IPython.display import YouTubeVideo YouTubeVideo('8N-nM3QW7O0', width=720, height=420) !nvidia-smi !pip install -q -U watermark !pip install -qq transformers %reload_ext watermark %watermark -v -p numpy,pandas,torch,transformers #@title Setup & Config import transformers from tra...
0.819533
0.986258
<a href="https://colab.research.google.com/github/pedroescobedob/DS-Unit-2-Linear-Models/blob/master/Pedro_Escobedo_assignment_regression_classification_2.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Lambda School Data Science *Unit 2, Sprint 1,...
github_jupyter
%%capture import sys # If you're on Colab: if 'google.colab' in sys.modules: DATA_PATH = 'https://raw.githubusercontent.com/LambdaSchool/DS-Unit-2-Applied-Modeling/master/data/' !pip install category_encoders==2.* # If you're working locally: else: DATA_PATH = '../data/' # Ignore this Numpy warning w...
0.390127
0.974018
<a href="https://colab.research.google.com/github/falconlee236/handson-ml2/blob/master/chapter3.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` from sklearn.datasets import fetch_openml mnist = fetch_openml('mnist_784', version=1) mnist.keys() X...
github_jupyter
from sklearn.datasets import fetch_openml mnist = fetch_openml('mnist_784', version=1) mnist.keys() X, y = mnist['data'], mnist['target'] X.shape y.shape import matplotlib as mpl import matplotlib.pyplot as plt some_digit = X[0] some_digit_image = some_digit.reshape(28, 28) plt.imshow(some_digit_image, cmap='binary')...
0.850407
0.870652
``` import os import numpy as np import pandas as pd home_folder = os.path.expanduser("~") data_folder = os.path.join(home_folder, "Data", "basketball") data_filename = os.path.join(data_folder, "leagues_NBA_2014_games_games.csv") results = pd.read_csv(data_filename) results.ix[:5] # Don't read the first row, as it is ...
github_jupyter
import os import numpy as np import pandas as pd home_folder = os.path.expanduser("~") data_folder = os.path.join(home_folder, "Data", "basketball") data_filename = os.path.join(data_folder, "leagues_NBA_2014_games_games.csv") results = pd.read_csv(data_filename) results.ix[:5] # Don't read the first row, as it is blan...
0.523177
0.28613
# Weakly imposing a Dirichlet boundary condition This tutorial shows how to implement the weak imposition of a Dirichlet boundary condition, as proposed in the paper <a href='https://bempp.com/publications.html#Betcke2019'>Boundary Element Methods with Weakly Imposed Boundary Conditions (2019)</a>. First, we import B...
github_jupyter
import bempp.api import numpy as np h = 0.3 grid = bempp.api.shapes.sphere(h=h) p1 = bempp.api.function_space(grid, "P", 1) dual0 = bempp.api.function_space(grid, "DUAL", 0) beta = 0.1 multi = bempp.api.BlockedOperator(2,2) multi[0,0] = -bempp.api.operators.boundary.laplace.double_layer(p1, p1, dual0, assembler="fmm"...
0.282295
0.980581
# Traitement de signal ## Atelier \#1 : Initiation à Jupyter ### Support de cours disponible à l'adresse : [https://www.github.com/a-mhamdi/isetbz](https://www.github.com/a-mhamdi/isetbz) --- **Objectifs** 1. Apprendre à programmer en **Python**; 2. Se servir de l'environnement **Jupyter Notebook**; 3. Utiliser les ...
github_jupyter
a = 1 # Un entier print('La variable a = {} est de type {}'.format(a, type(a))) b = -1.25 # Un nombre réel print('La variable b = {} est de type {}'.format(b, type(b))) c = 1+0.5j # Un nombre complexe print('La variable c = {} est de type {}'.format(c, type(c))) msg = "Mon Premier TP !" print(msg, type(msg), sep = '\n...
0.121751
0.913368
# Strings In previous lectures we have seen strings being used numerous times. Today we are going to go into a bit more detail. First, some terminology: * 'single-quote character' refers to unicode character 34, --> { ' } * 'double-quote character' refers to unicode character 39, --> { " } * and if I say 'quote-cha...
github_jupyter
# wrapping text with double quotes... cool_story_bro = ""Ahhh!!!! spiders!", cried the monster. "Do not worry" said our hero, "I have a sharp spoon"." print(cool_story_bro) # wrapping text with single quotes... cool_story_bro = '"Ahhh!!!! spiders!", cried the monster."Do not worry" said our hero, "I have a sharp spoon"...
0.227555
0.910147
``` from pomegranate import * import seaborn %pylab inline seaborn.set_style('whitegrid') numpy.set_printoptions(suppress=True) ``` # Naive Bayes and Bayes Classifiers: A Tutorial author: Jacob Schreiber <br> contact: jmschreiber91@gmail.com Bayes classifiers are some of the simplest machine learning models that exi...
github_jupyter
from pomegranate import * import seaborn %pylab inline seaborn.set_style('whitegrid') numpy.set_printoptions(suppress=True) X = numpy.concatenate((numpy.random.normal(3, 1, 200), numpy.random.normal(10, 2, 1000))) y = numpy.concatenate((numpy.zeros(200), numpy.ones(1000))) x1 = X[:200] x2 = X[200:] plt.figure(figsiz...
0.562417
0.957118
# Time sequence primer using Pytorch ``` import torch torch.__version__ from torch.utils import data import torch.nn as nn import numpy as np from matplotlib import pyplot as plt %matplotlib inline from torch.utils.tensorboard import SummaryWriter from IPython import embed import pandas as pd ``` ## Time varying sign...
github_jupyter
import torch torch.__version__ from torch.utils import data import torch.nn as nn import numpy as np from matplotlib import pyplot as plt %matplotlib inline from torch.utils.tensorboard import SummaryWriter from IPython import embed import pandas as pd N = 1000 t = np.arange(N) x = np.sin(0.01*t) + 0.2 * np.random.nor...
0.878705
0.943504
# 上下文无关文法分析 **分析器**根据文法产生式处理输入的句子,并建立一个或多个符合文法的组成结构。文法是一个格式良好的声明规范,它实际上只是一个字符串,而不是程序。分析器是文法的解释程序,它搜索符合文法的所有树的空间找出一棵边缘有所需句子的树。 在本节中,我们将看到两个简单的分析算法,一种自上而下的方法成为递归下降分析,一种自下而上的方法成为移进-规约分析。我们也将看到一些更复杂的算法,一种带自下而上过滤的自上而下的方法称为左角落分析,一种动态规划技术称为图表分析。 ## 递归下降分析 一种最简单的分析器将一个文法作为如何将一个高层次的目标分解成几个低层次的子目标的规范来解释。顶层的目标是找到一个 S,S -> NP ...
github_jupyter
import nltk grammar1 = nltk.CFG.fromstring(""" S -> NP VP VP -> V NP | V NP PP PP -> P NP V -> "saw" | "ate" | "walked" NP -> "John" | "Mary" | "Bob" | Det N | Det N PP Det -> "a" | "an" | "the" | "my" N -> "man" | "dog" | "cat" | "telescope" | "park" P -> "in" | "on" | "by" | "with" ""...
0.272702
0.777596
# 批量规范化 :label:`sec_batch_norm` 训练深层神经网络是十分困难的,特别是在较短的时间内使他们收敛更加棘手。 在本节中,我们将介绍*批量规范化*(batch normalization) :cite:`Ioffe.Szegedy.2015`,这是一种流行且有效的技术,可持续加速深层网络的收敛速度。 再结合在 :numref:`sec_resnet`中将介绍的残差块,批量规范化使得研究人员能够训练100层以上的网络。 ## 训练深层网络 为什么需要批量规范化层呢?让我们来回顾一下训练神经网络时出现的一些实际挑战。 首先,数据预处理的方式通常会对最终结果产生巨大影响。 回想一下我们应用多层感知机来预测房...
github_jupyter
import tensorflow as tf from d2l import tensorflow as d2l def batch_norm(X, gamma, beta, moving_mean, moving_var, eps): # 计算移动方差元平方根的倒数 inv = tf.cast(tf.math.rsqrt(moving_var + eps), X.dtype) # 缩放和移位 inv *= gamma Y = X * inv + (beta - moving_mean * inv) return Y class BatchNorm(tf.keras.layer...
0.754192
0.769946
# Naive Bayes model Naive Bayes is a classification technique used to build classifier using the Bayes Theorem. It assumes that predictors are different. In simple word sit assumes that the presence of a particular feature is not related in any way to the presence of another. There are 3 type sof Naive Bayes models ...
github_jupyter
from sklearn.datasets import load_breast_cancer data = load_breast_cancer() label_names = data['target_names'] labels = data['target'] feature_names = data['feature_names'] features = data['data'] from sklearn.model_selection import train_test_split train_data, test_data, train_label, test_label = train_test_split...
0.615435
0.992647
``` from IPython.core.display import display, HTML display(HTML("<style>.container { width:100% !important; }</style>")) import pandas as pd import numpy as np import warnings warnings.filterwarnings("ignore") ``` ### LSTMs for Human Activity Recognition Human Activity Recognition (HAR) using smartphones dataset and...
github_jupyter
from IPython.core.display import display, HTML display(HTML("<style>.container { width:100% !important; }</style>")) import pandas as pd import numpy as np import warnings warnings.filterwarnings("ignore") # Activities are the class labels # It is a 6 class classification ACTIVITIES = { 0: 'WALKING', 1: 'WALK...
0.690142
0.921287
<h1><center>Assignment 3</center></h1> <h1><center>Data Classification</center></h1> <br><br><br><br> ## Names: ### 1. Amr Hendy (46) ### 2. Abdelrhman Yasser (37) ## Introduction to MAGIC Gamma Telescope DataSet The data are MC generated to simulate registration of high energy gamma particles in a ground-based at...
github_jupyter
import numpy as np import pandas as pd import matplotlib.pyplot as plt from time import time import matplotlib.patches as mpatches def load_dataset(): url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/magic/magic04.data' attribute_names = ['fLength', 'fWidth', 'fSize', 'fConc', 'fConc1', 'fAsym', 'f...
0.59749
0.987326
4 fold * 6 epochs ---- I was trying to clean some of my code so I can add more models. However, this can never happen without the awesome kernels from other talented Kagglers. Forgive me if I missed any. * Based on SRK's kernel: https://www.kaggle.com/sudalairajkumar/a-look-at-different-embeddings * Vladimir Demido...
github_jupyter
# This Python 3 environment comes with many helpful analytics libraries installed # It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python # For example, here's several helpful packages to load in import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O...
0.767777
0.599749
# Simulación Montecarlo > El método de Montecarlo es un método no determinista o estadístico numérico, usado para aproximar expresiones matemáticas complejas y costosas de evaluar con exactitud. El método se llamó así en referencia al Casino de Montecarlo (Mónaco) por ser “la capital del juego de azar”, al ser la rulet...
github_jupyter
from IPython.display import YouTubeVideo YouTubeVideo('Y77WnkLbT2Q') # Importar librería random import random help(random.choice) # Escribir una función que genere el resultado # de una caminata aleatoria de N pasos def caminata_aleatoria(N): s = [0] for i in range(N): Z = random.choice((-1,1)) ...
0.135032
0.980618
``` %load_ext autoreload %autoreload 2 import tensorflow as tf import numpy as np import random from tensorflow import keras from tensorflow.keras import utils as np_utils from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Flatten, Conv2D, AveragePooling2D, MaxPooling2D, Dropout, ...
github_jupyter
%load_ext autoreload %autoreload 2 import tensorflow as tf import numpy as np import random from tensorflow import keras from tensorflow.keras import utils as np_utils from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Flatten, Conv2D, AveragePooling2D, MaxPooling2D, Dropout, Batc...
0.795181
0.586079