text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
##### Copyright 2018 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
# Your structured data into Tensorflow. ML training often expects _flat_ data, like a line in a CSV. [tf.Example](https://www.tensorflow.org/api_docs/python/tf/train/Example) was designed to represent flat data. But the data you care about and want to predict things about usually starts out _structured_. Over and ove...
github_jupyter
# 1A.0 - Premiers pas en Python (correction) La partie 1 ne nécessite pas de correction. ``` from jyquickhelper import add_notebook_menu add_notebook_menu() ``` ### Partie 2 Les erreurs sont corrigées de telle sorte que la ligne fautive est mise en commentaires ou que le commentaire indique la correction. **Un oub...
github_jupyter
``` import sys import warnings if not sys.warnoptions: warnings.simplefilter('ignore') import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import seaborn as sns import pandas as pd from sklearn.preprocessing import MinMaxScaler from datetime import datetime from datetime import timedelta fro...
github_jupyter
## Using SGD on MNIST ## Background ### ... about machine learning (a reminder from lesson 1) The good news is that modern machine learning can be distilled down to a couple of key techniques that are of very wide applicability. Recent studies have shown that the vast majority of datasets can be best modeled with ju...
github_jupyter
# Building streaming pipelines in Toloka Let's solve the following task: find the goods in the online-store by given image and aggange found results by relevance. It can be solved in 3 steps: * For given image find corresponding goods in the online shop; * Verfiy that the selected goods are correct; * Arrange found g...
github_jupyter
**Several case studies from https://people.iee.ihu.gr/~vkostogl/en/Epixeirisiaki/Linear%20Programming_case%20studies_EN_29-5-2012.pdf** Many thanks to Prof. Vassilis Kostoglou # Case Study: Portfolio Selection - Select portfolio package from set of investments - Maximize expected return or minimize risk ## Data Exp...
github_jupyter
# Downloading and studying my message behavior - toc: false - branch: master - badges: true - comments: false - categories: [data science] The message data from Facebook is organized like this: * inbox/ * chat1/ * message1.json * message2.json * audio/ * files/ * gifs/ ...
github_jupyter
# Take sample of tweets based on classification scores for Covid-19 myths @authors: Jaren Haber, Alexander Chen, Kornraphop Kawintiranon<br> @affiliation: Massive Data Institute, McCourt School of Public Policy, Georgetown University<br> @date: November 2, 2020 ''' Uses classifiers trained on labeled tweets (about a ...
github_jupyter
``` # Copyright 2021 Google LLC # Use of this source code is governed by an MIT-style # license that can be found in the LICENSE file or at # https://opensource.org/licenses/MIT. # Author(s): Kevin P. Murphy (murphyk@gmail.com) and Mahmoud Soliman (mjs@aucegypt.edu) ``` <a href="https://opensource.org/licenses/MIT" t...
github_jupyter
# Playing Simple Catch Videogame with RL and QLearning using Keras Eder Santana blog post: http://edersantana.github.io/articles/keras_rl/ Eder Santana GitHub gist repo: https://gist.github.com/EderSantana/c7222daa328f0e885093 Small correction and addition of this iPython Notebook by Claude COULOMBE - PhD candidate -...
github_jupyter
The purpose of this notebook is to look at the genres available in the decades and the genres datasets. If the distribution is normal(-ish) in a particular dataset than it is a good candidate for the project. All other things being equal, I would prefer to use the genres dataset as it is bigger and the lyrics have no...
github_jupyter
# ElasticNet AND MonteCarlo Importing required packages ``` import pandas_datareader as web import datetime import numpy as np from scipy.optimize import minimize import matplotlib.pyplot as plt from matplotlib.pyplot import figure import pandas as pd import warnings warnings.filterwarnings('ignore') %matplotlib inli...
github_jupyter
# Testing Code with pytest In this lesson we will be going over some of the things we've learned so far about testing and demonstrate how to use pytest to expand your tests. We'll start by looking at some functions which have been provided for you, and then move on to testing them. In your repo you should find a Pyth...
github_jupyter
# Exp 143 analysis See `./informercial/Makefile` for experimental details. ``` import os import numpy as np from pprint import pprint from IPython.display import Image import matplotlib import matplotlib.pyplot as plt %matplotlib inline %config InlineBackend.figure_format = 'retina' import seaborn as sns sns.set_...
github_jupyter
<h1>2b. Machine Learning using tf.estimator </h1> In this notebook, we will create a machine learning model using tf.estimator and evaluate its performance. The dataset is rather small (7700 samples), so we can do it all in-memory. We will also simply pass the raw data in as-is. ``` !sudo chown -R jupyter:jupyter /...
github_jupyter
# CNN para reconhecimento de imagens ## Dataset Dogs & Cats - Kaggle *Cleuton Sampaio* [Dataset Dogs & cats](https://www.kaggle.com/c/dogs-vs-cats) Baixe o arquivos e descompacte conforme as variáveis **dir_treino** e **dir_teste**. Coloque labels em pelo menos 30 imagens de teste, para poder validar (é só renomear os...
github_jupyter
<a href="https://colab.research.google.com/github/arjunparmar/VIRTUON/blob/main/Prashant/Training_notebook.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` from google.colab import drive drive.mount('/content/drive') !cp /content/drive/Shareddriv...
github_jupyter
## AI for Medicine Course 3 Week 1 lecture notebook ## Logistic Regression Model Interpretation Welcome to this exercise! You'll review how to interpret the coefficients in a logistic regression model. - The logistic regression is considered a **Generalized Linear Model**. - In general, you would employ one of the...
github_jupyter
``` %matplotlib inline from keras.engine import Layer from keras.applications.inception_v3 import InceptionV3, preprocess_input from keras.layers import Input, Dense, Dropout, TimeDistributed, Bidirectional, Flatten from keras.layers.recurrent import LSTM from keras.layers import Conv1D, Dense, AveragePooling1D, Flatte...
github_jupyter
# Linear Regression Stanford CS229 - Machine Learning by Andrew Ng. Programming exercise 2 with solutions. Please check out [the repository on GitHub](https://github.com/rickwierenga/CS229-Python/). If you spot any mistakes or inconcistencies, please create an issue. For questions you can find me on Twitter: [@rickwi...
github_jupyter
## Deep Causal Variational Inference ### Introduction: To train a supervised variational autoencoder using Deepmind's [dSprites](https://github.com/deepmind/dsprites-dataset) dataset. dSprites is a dataset of sprites, which are 2D shapes procedurally generated from 5 ground truth independent "factors." These factors ...
github_jupyter
``` import os import datamart import json from datamart_isi import rest from d3m.container.dataset import Dataset, D3MDatasetLoader from common_primitives.datamart_augment import Hyperparams as hyper_augment, DataMartAugmentPrimitive from common_primitives.datamart_download import Hyperparams as hyper_download, DataMa...
github_jupyter
# Classical ciphers ## Hill cipher We will try to decrypt the ciphertext `rbqdoobweruuis` if we know that the Hill cipher was used and the plaintext starts with `help`. Let us first define some helper functions. ``` encode = lambda s: list(ord(x) - ord('a') for x in s) decode = lambda v: ''.join(chr(c + ord('a')) f...
github_jupyter
``` !pip3 install tqdm requests dill import requests from tqdm import tqdm import os def download_from_url(url, dst): file_size = int(requests.head(url).headers["Content-Length"]) if os.path.exists(dst): first_byte = os.path.getsize(dst) else: first_byte = 0 if first_byte >= file_size: ...
github_jupyter
``` %matplotlib inline import sympy import numpy as np import matplotlib.pyplot as plt import math ``` ## Generalizing the Plotting Function Let's now use the power of Python to generalize the code we created to plot. In Python, you can pass functions as parameters to other functions. We'll utilize this to pass the ma...
github_jupyter
<a href="https://colab.research.google.com/github/anirbrhm/CIFAR-10/blob/main/CIFAR_10.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` import matplotlib.pyplot as plt import numpy as np import torch import torchvision import torchvision.transfo...
github_jupyter
[@LorenaABarba](https://twitter.com/LorenaABarba) 12 steps to Navier–Stokes ===== *** Up to now, all of our work has been in one spatial dimension (Steps [1](./01_Step_1.ipynb) to [4](./05_Step_4.ipynb)). We can learn a lot in just 1D, but let's grow up to flatland: two dimensions. In the following exercises, you w...
github_jupyter
# ART for TensorFlow v2 - Keras API This notebook demonstrate applying ART with the new TensorFlow v2 using the Keras API. The code follows and extends the examples on www.tensorflow.org. ``` import warnings warnings.filterwarnings('ignore') import tensorflow as tf tf.compat.v1.disable_eager_execution() import numpy ...
github_jupyter
# Rank Most Similar Movies Using various distance metrics, rank the most similar movies to a query movie. ``` %matplotlib inline import pandas as pd import json actor_name_map = {} movie_actor_map = {} with open("../data/imdb_recent_movies.json", "r") as in_file: for line in in_file: this_movie...
github_jupyter
``` # Зависимости import pandas as pd import numpy as np import matplotlib.pyplot as plt import random from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler from sklearn.compose import ColumnTransformer from sklearn.svm import SVR, SVC from sklearn.metrics import mean_sq...
github_jupyter
# Geostatistical Variogram Tutorial in R for Engineers and Geoscientists ### Michael Pyrcz, Associate Professor, University of Texas at Austin, #### Contacts: [Twitter/@GeostatsGuy](https://twitter.com/geostatsguy) | [GitHub/GeostatsGuy](https://github.com/GeostatsGuy) | [www.michaelpyrcz.com](http://michaelpyrcz.co...
github_jupyter
# Udemy Grabber ``` import requests from requests.utils import urlparse from bs4 import BeautifulSoup, NavigableString from bs4.element import Tag import pandas as pd from random import randint from time import sleep import re from datetime import datetime, timedelta from urllib.parse import parse_qs, unquote import j...
github_jupyter
# Input Widgets and Geospatial Data Analysis In addition to ipywidgets 5.0.0, and pythreejs, this example requires GDAL **GDAL installation:** ```bash conda install gdal conda install krb5 ``` ``` from __future__ import print_function from ipywidgets import Controller, FloatText, HTML, VBox from pythreejs.install i...
github_jupyter
### A presentation to the Jupyter Conference JupyterCon2020. These notebooks are designed to be run interactively (not viewed statically with nbviewer or GitHub). # Using WebGL2 Transform Feedback in Jupyter Widgets for advanced computations and graphics <h4>Aaron Watters, PhD, <br> Senior Software Engineer <b...
github_jupyter
# Venture Funding with Deep Learning You work as a risk management associate at Alphabet Soup, a venture capital firm. Alphabet Soup’s business team receives many funding applications from startups every day. This team has asked you to help them create a model that predicts whether applicants will be successful if fun...
github_jupyter
``` import time def timeit(): time.ctime() return time.strftime('%l:%M%p %Z on %b %d, %Y') timeit() from collections import namedtuple from collections import defaultdict import re import json LogLine = namedtuple('LogLine', ['ts', 'msg', 'processed', 'dictionary', ...
github_jupyter
![](https://scikit-learn.org/stable/_static/scikit-learn-logo-small.png "SciKit Learn") ## Classification with [Decision Tree example from Scikit-Learn](https://scikit-learn.org/stable/modules/tree.html) Modified for Interactive Notebook by Github@ChristinaB 5/15/2020 ``` import sklearn import sklearn.tree as tree ...
github_jupyter
# Assignment 06 *Due date: 04.05.2022* This week's assignment has to be returned **in the form a jupyter notebook**. Don't forget the [instructions](../assignments)! ## 01 - Linear regression function **Write a function that computes the parameters $a$ und $b$ from the [simple linear regression](https://en.wikipe...
github_jupyter
# Unsupervised learning Overview of today's topics: - linear discriminant analysis - principal component analysis - k-means clustering - DBSCAN clustering - hierarchical clustering - t-sne projection In unsupervised learning, we use an algorithm to discover structure in and extract information from data...
github_jupyter
``` import torchaudio as ta import torch from torch.utils.data import DataLoader import torch.nn as nn import torch.nn.functional as F import torch.autograd.profiler as profiler # import pytorch_lightning as pl import numpy as np import os import IPython.display as ipd import numpy as np import math import glob f...
github_jupyter
<table class="ee-notebook-buttons" align="left"> <td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/ImageCollection/get_image_centroid.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td> <td><a target="_b...
github_jupyter
**[Intermediate Machine Learning Home Page](https://www.kaggle.com/learn/intermediate-machine-learning)** --- Most people find target leakage very tricky until they've thought about it for a long time. So, before trying to think about leakage in the housing price example, we'll go through a few examples in other app...
github_jupyter
``` import pandas as pd #查看2010和2016的区别 raw2010 = pd.read_csv("2018_MCMProblemC_DATA/ACS_10_5YR_DP02/ACS_10_5YR_DP02_with_ann.csv", header =1) raw2016 = pd.read_csv("2018_MCMProblemC_DATA/ACS_16_5YR_DP02/ACS_16_5YR_DP02_with_ann.csv", header =1) deleted_2010 = [] new_added_2016 = [] for k in raw2010.columns: if k n...
github_jupyter
``` %matplotlib inline import numpy as np from numpy import exp, pi from scipy.integrate import quad from scipy.linalg import expm ``` # Our Strategy We are faced with the serious problem that Rigatoni's drivetrain is inheretly non-linear: we must switch from using the motor to accelerate the car to using the brakes t...
github_jupyter
<a href="https://colab.research.google.com/github/yoyoyo-yo/DeepLearningMugenKnock/blob/master/pytorch/VGG16_CIFAR100_pytorch.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # VGG16, CIFAR100 ``` !pip install numpy matplotlib opencv-python torch to...
github_jupyter
<details> <summary><strong>Correct answer:</strong></summary> ```python # TODO: import WandB import wandb ``` ------ ```python # TODO: import WandB Alert and timedelta from wandb import AlertLevel from datetime import timedelta ``` </details> ``` # TODO: import WandB import torch, torchvision, os import nu...
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
# Signal Autoencoder ``` import numpy as np import scipy as sp import scipy.stats import itertools import logging import matplotlib.pyplot as plt import pandas as pd import torch.utils.data as utils import math import time import tqdm import torch import torch.optim as optim import torch.nn.functional as F from argpa...
github_jupyter
## Severe Weather Forecasting with Python and Data Science Tools: Interactive Demo David John Gagne, University of Oklahoma and NCAR ## Introduction Severe weather forecasting has entered an age of unprecedented access to large model and observational datasets with even greater hordes of data in the pipeline. With mul...
github_jupyter
# Rendering Demo Rendering utilities for ContactPose are defined in [utilities/rendering.py](utilities/rendering.py). Rendering requires [pyrender](https://pyrender.readthedocs.io/en/latest/#), which offers headless rendering. **First, follow the [pyrender setup instructions](docs/rendering.md).** Basic imports. ```...
github_jupyter
# 處理 outliers * 新增欄位註記 * outliers 或 NA 填補 1. 平均數 (mean) 2. 中位數 (median, or Q50) 3. 最大/最小值 (max/min, Q100, Q0) 4. 分位數 (quantile) ``` # Import 需要的套件 import os import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline # 設定 data_path dir_data = './data/' f_app = os.path.jo...
github_jupyter
# Using DALI in PyTorch Lightning ### Overview This example shows how to use DALI in PyTorch Lightning. Let us grab [a toy example](https://pytorch-lightning.readthedocs.io/en/latest/introduction_guide.html) showcasing a classification network and see how DALI can accelerate it. The DALI_EXTRA_PATH environment vari...
github_jupyter
``` import pandas as pd import numpy as np from tqdm import tqdm def shrink_df(df): df.user_id = df.user_id.astype(np.uint16) df.movie_id = df.movie_id.astype(np.uint16) df.rating = df.rating.astype(np.uint8) return df df_train = pd.read_csv("data/new_pp/udata_train_100k.csv") df_train.head() df_te...
github_jupyter
# Example of `InferenceData` schema in PyMC3 The description of the `InferenceData` structure can be found [here](schema.html). ``` import arviz as az import pymc3 as pm import pandas as pd import numpy as np import xarray xarray.set_options(display_style="html"); #read data data = pd.read_csv("linear_regression_data....
github_jupyter
# Statistics There are many specialized packages for dealing with data analysis and statistical programming. One very important code that you will see in MATH1024, Introduction to Probability and Statistics, is [R](http://www.r-project.org/). A Python package for performing similar analysis of large data sets is [pand...
github_jupyter
# Purpose 😇 This is a brief notebook to demonstrate how you can save a learner once your model has been trained for later inference (to generate predictions) or to continue training it when new samples become available. # Install and load libraries 📚 ``` # **************** UNCOMMENT AND RUN THIS CELL IF YOU NEED T...
github_jupyter
### Venn diagram for methods ``` library(data.table) library(VennDiagram) library(RColorBrewer) library(scales) tissues = c("Whole_Blood", "Muscle_Skeletal", "Thyroid", "Skin_Sun_Exposed_Lower_leg") method = c("lrt", "skat", "vt", "acat.o") qvals = lapply(unlist(lapply(paste("./data/qvals", tissues, sep="/"), function...
github_jupyter
## Plotting of profile results ``` #!/usr/bin/env python # -*- coding: utf-8 -*- # common import os import os.path as op # pip import numpy as np import pandas as pd import xarray as xr import matplotlib.pyplot as plt from matplotlib import gridspec # DEV: override installed teslakit import sys sys.path.insert(0, o...
github_jupyter
In psychology, when it comes to methodology and data analysis, you can't miss a vocal movement that advocates adoption effect sizes as an replacement for p-values. This movement has been labeled new statistics by Geoff Cumming (2013). Cumming acknowledges, that their ideas are not new. There is nothing new about the c...
github_jupyter
# Step 4.1: Cluster stations __Step goals:__ Clustering of metro stations with Gaussian Mixture Model based on their entry traffic over the day. __Step overview:__ 1. Load the data; 2. Prepare features; 3. Perform GMM; 4. Evaluate the performance; 5. Save the result. ``` import matplotlib.pyplot as plt import pandas...
github_jupyter
# Idomatic Pandas > Q: How do I make my pandas code faster with parallelism? > A: You don’t need parallelism, you can use Pandas better. > -- Matthew Rocklin Now that we have been exposed to the basic functionality of pandas, lets explore some more advanced features that will be useful when addressing more complex ...
github_jupyter
# Reducing loss/ optimization as learning Author: Adam Rivers Some material modified from the [Google ML Crash Course](https://developers.google.com/machine-learning/crash-course/reducing-loss/an-iterative-approach) # What are Loss and Error? In the previous section we looked at ordinary least squares (OLS) linear...
github_jupyter
# Template: Forecasting - based on empirical data ``` alias Chi2fit.Utilities, as: U alias Chi2fit.Distribution, as: D alias Chi2fit.Fit, as: F alias Gnuplotlib, as: P ``` #### Using this template Follow these steps to start with forecasting based on your team's capability to deliver: 1. Extract the delivery dates ...
github_jupyter
``` #rdkit imports import rdkit from rdkit import Chem from rdkit.Chem import Draw from rdkit.Chem.EState import Fingerprinter from rdkit.Chem import Descriptors from rdkit.Chem import rdFMCS from rdkit.Chem.rdmolops import RDKFingerprint from rdkit.Chem.Fingerprints import FingerprintMols from rdkit import DataStructs...
github_jupyter
# Documentation for processed Census data This notebook walks through the steps to arrive at the processed Census data used in `zipbiaschecker`. ## Sources of original reference data One challenge of mapping zip codes to demographic data is that one accessible source of demographic data from Census surveys is report...
github_jupyter
``` #hide !nvidia-smi #hide import sys if 'google.colab' in sys.modules: !pip install -Uqq fastai einops datasets axial_positional_embedding wandb !pip install -qq git+git://github.com/arampacha/reformer_fastai.git #import os; os.kill(os.getpid(), 9) #hide %load_ext autoreload %autoreload 2 #all_slow ``` #...
github_jupyter
``` ## Genomic Cloud import os, sys, gzip, glob, string import numpy as np import pandas as pd from shutil import copyfile from subprocess import call from collections import Counter from wordcloud import WordCloud from geopy.geocoders import ArcGIS from sklearn.manifold import TSNE from sklearn.cluster import KMeans i...
github_jupyter
``` from ontopy import get_ontology from ontopy.graph import OntoGraph, cytoscapegraph import ipywidgets as widgets import owlready2 def en(s): """Returns `s` as an English location string.""" return owlready2.locstr(s, lang='en') # Create Team 4.0 from ontopy import World world = World() emmo = world.get_ont...
github_jupyter
# Part 11 - Secure Deep Learning Classification ## Your data matters, your model too Data is the driver behind Machine Learning. Organizations who create and collect data are able to build and train their own machine learning models. This allows them to offer the use of such models as a service (MLaaS) to outside ...
github_jupyter
# Replication - Resource comparision (Runtime only) Here we provide a notebook that showcases how to replicate the resource results. (This is not exact as hardware etc. will be differnt). We also cannot provide the memory footprint as we cannot measure it for the R scripts. For simplicity we also do not provide the P...
github_jupyter
### **Import Google Drive** ``` from google.colab import drive drive.mount('/content/drive') ``` ### **Import Library** ``` import glob import numpy as np import os import shutil np.random.seed(42) from sklearn.preprocessing import LabelEncoder import cv2 import tensorflow as tf import keras import shutil import ran...
github_jupyter
# Augmentation Strategies In this notebook we explore different augmentation strategies for neural differential equations. This time, we'll make use of the 3D `concentric spheres` dataset. ``` import sys sys.path.append('../') from torchdyn.models import *; from torchdyn.datasets import * from torchdyn import * ``` ...
github_jupyter
## Loading Libraries ``` library('ggplot2') library('gridExtra') library(reshape2) library(RColorBrewer) library(grid) ``` ## Set working directory and output directories ``` projectdir="../" setwd(projectdir) paperfigdir="figures" supfigdir="figures/supfigures" ``` ## Plotting Functions ``` add_corner_label <- fu...
github_jupyter
# Save padded image Given an image path (`im_pth`), the code below will extract its file name (`file_name`) and generate the following images in the `transformed_images` directory: * unpadded original image: `{file_name}_no_pad.png` * padded image to fit into square dimensions: `{file_name}_pad.png` ``` import os from...
github_jupyter
## Summary ### Submitting jobs **Note:** These jobs must be submitted from the <code>./notebooks</code> folder. **Cedar:** ```bash NOTEBOOK_PATH=$(realpath 01_process_pdb_cbeta_stats.ipynb) sbatch --array=1-300 --time=24:00:00 --nodes=1 --ntasks-per-node=48 --mem=0 --job-name=process-pdb-cbeta-stats --account=rrg-p...
github_jupyter
###### Content provided under a Creative Commons Attribution license, CC-BY 4.0; code under BSD 3-Clause license. (c)2014 Lorena A. Barba, Olivier Mesnard. Thanks: NSF for support via CAREER award #1149784. # Source & Sink in a Freestream You have reached the second notebook of the [*AeroPython*](https://github.com/b...
github_jupyter
# Example computations for TFIDF using pandas data frames Looking at the words in the next code cell, which words best distinguish the three documents? ``` import pandas as pd from collections import Counter import numpy as np d1 = "the new new york times" # (repeated new) d2 = "the new york post" d3 = "the los ange...
github_jupyter
``` # reload packages %load_ext autoreload %autoreload 2 ``` ### Choose GPU ``` %env CUDA_DEVICE_ORDER=PCI_BUS_ID %env CUDA_VISIBLE_DEVICES=0 import tensorflow as tf gpu_devices = tf.config.experimental.list_physical_devices('GPU') if len(gpu_devices)>0: tf.config.experimental.set_memory_growth(gpu_devices[0], Tr...
github_jupyter
# Text classification with Transformer **Author:** [Apoorv Nandan](https://twitter.com/NandanApoorv)<br> **Date created:** 2020/05/10<br> **Last modified:** 2020/05/10<br> **Description:** Implement a Transformer block as a Keras layer and use it for text classification. ## Setup ``` import tensorflow as tf from ten...
github_jupyter
``` import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline from sklearn.linear_model import LogisticRegression ``` # Load Data ``` # Load Data data = pd.read_csv('data1.txt', header=None) X = data.iloc[:, [0, 1]] y = data.iloc[:, [2]] data.head() ``` ### Plot Data ``` def plotDat...
github_jupyter
# Illustration of w-imaging ``` %matplotlib inline import sys sys.path.append('../..') from matplotlib import pylab pylab.rcParams['figure.figsize'] = 12, 10 import functools import numpy import scipy import scipy.special from crocodile.clean import * from crocodile.synthesis import * from crocodile.simulate impo...
github_jupyter
# Image Classification Model - Serving Function This notebook demonstrates how to deploy a Tensorflow model using MLRun & Nuclio. **In this notebook you will:** * Write a Tensorflow-Model class to load and predict on the incoming data * Deploy the model as a serverless function * Invoke the serving endpoint with data...
github_jupyter
Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. ![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/regression-car-price-model-explaination-and-featurization/auto-ml-regressi...
github_jupyter
# Tensor Train layers for neural networks In this section, the TT layers are introduced. Imports: ``` import torch as tn import torch.nn as nn import datetime try: import torchtt as tntt except: print('Installing torchTT...') %pip install git+https://github.com/ion-g-ion/torchTT import torchtt as tnt...
github_jupyter
``` # -*- coding: utf-8 -*- """ EVCで変換する. 詳細 : https://pdfs.semanticscholar.org/cbfe/71798ded05fb8bf8674580aabf534c4dbb8bc.pdf Converting by EVC. Check detail : https://pdfs.semanticscholar.org/cbfe/71798ded05fb8bf8674580abf534c4dbb8bc.pdf """ from __future__ import division, print_function import os from shutil imp...
github_jupyter
# Measurement Error Mitigation ``` from qiskit import * ``` ### Introduction The effect of noise is to give us outputs that are not quite correct. The effect of noise that occurs throughout a computation will be quite complex in general, as one would have to consider how each gate transforms the effect of each error...
github_jupyter
TSG045 - The maximum number of data disks allowed to be attached to a VM of this size (AKS) =========================================================================================== Steps ----- ### Common functions Define helper functions used in this notebook. ``` # Define `run` function for transient fault hand...
github_jupyter
# [LEGALST-123] Lab 23: Topic Models This lab will cover latent dirichlet allocation and topic models using `gensim` and `scikit-learn`. *Estimated Time: 35 Minutes * ### Table of Contents [The Data](#section data)<br> 1 - [Using Gensim to Implement a LDA Model](#section 1)<br> 2 - [Using scikit-learn](#section 2)<b...
github_jupyter
``` from __future__ import print_function import keras from keras.models import Sequential, Model, load_model from keras import backend as K import isolearn.keras as iso import tensorflow as tf import os import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm from aparent....
github_jupyter
<a href="https://colab.research.google.com/github/titsitits/Python_Data_Science/blob/master/Completed_notebooks/3_Advanced_Python.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Mickaël Tits CETIC mickael.tits@cetic.be # Chapitre 3 - Concepts avanc...
github_jupyter
# <span style="color:Maroon">Short Term Random Forest (RF) Model __Summary:__ <span style="color:Blue">In this code we shall build and test a short term rf Model using Technical Indicators ``` # Import required libraries import warnings warnings.filterwarnings('ignore') import pandas as pd import numpy as np import m...
github_jupyter
``` import keras keras.__version__ ``` # Classifying movie reviews: a binary classification example This notebook contains the code samples found in Chapter 3, Section 5 of [Deep Learning with Python](https://www.manning.com/books/deep-learning-with-python?a_aid=keras&a_bid=76564dff). Note that the original text feat...
github_jupyter
``` # from mnist import MNIST # mnist = MNIST('/home/bnapp/datasets/mnist/') # images, labels = mnist.load_training() import numpy as np import cv2 import misc ``` import importlib importlib.reload(misc) ``` """ Convolutional Neural Network. Build and train a convolutional neural network with TensorFlow. This exampl...
github_jupyter
# Taller 003 - PyLadies Madrid # "Estructuras de control y Funciones" &nbsp; <div style="text-align: center">Mabel Delgado, María Medina </div> <div style="text-align: center">Alicia Pérez, Vicky Cortés </div> &nbsp; <center><img src="images/pyladiesmadrid_alargado.png" style="width:220px;"/> </center> ## ¿...
github_jupyter
``` import os import cv2 import sys # Change path specificly to your directories sys.path.insert(1, '/home/codahead/Fishial/FishialReaserch') import pandas as pd import warnings warnings.filterwarnings('ignore') from os import listdir from os.path import isfile, join from shapely.geometry import Polygon pd.options.disp...
github_jupyter
# Optimization Methods Until now, you've always used Gradient Descent to update the parameters and minimize the cost. In this notebook, you will learn more advanced optimization methods that can speed up learning and perhaps even get you to a better final value for the cost function. Having a good optimization algorit...
github_jupyter
# Data Science Interview Questions ## Machine Learning ### What is the difference between supervised and unsupervised learning? - Supervised learning - train labelled dataset with inputs and known outcomes - Unsupervised learning - input data doesn't have labelled outputs ### What is the bias-variance trade off? S...
github_jupyter
# Example Q1 - Qubit rotation This notebook demonstrates PennyLane's "Hello world!" example for qubit-based architectures, using the default qubit backend. The task is to optimize two rotation gates in order to flip a single qubit from state $|0\rangle$ to state $|1\rangle $. ## Imports First we need to import Pen...
github_jupyter
# [Multi-class classification with focal loss for imbalanced datasets](https://www.dlology.com/blog/multi-class-classification-with-focal-loss-for-imbalanced-datasets/) ## Baseline model ``` import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) from tensorflow impor...
github_jupyter