text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
```
from IPython import get_ipython
IS_COLAB = False
if "google.colab" in str(get_ipython()):
# Make sure to go to Runtime > Change runtime type > Hardware Accelerator: GPU
IS_COLAB = True
!pip install fastai --upgrade -q
!pip install wandb
!pip freeze | grep fast
if IS_COLAB:
from google.colab... | github_jupyter |
# Using Experimental Data to Find a Soil's Weight Function
As described in Section 2.3 of the article, finding a given soil's weight functions is achieved through a set of experiments in which we measure soil degradation and "first order reversal curves" (FORCs).
This notebook shows how to process the data from these ... | github_jupyter |
# SciPy - Library of scientific algorithms for Python
Adapted from a lecture by J.R. Johansson (jrjohansson at gmail.com)
The original version of this [IPython notebook](http://ipython.org/notebook.html) lecture is available at [http://github.com/jrjohansson/scientific-python-lectures](http://github.com/jrjohansson/s... | github_jupyter |
```
from nornir import InitNornir
nr = InitNornir(config_file="config.yaml")
```
# Executing tasks
Now that you know how to initialize nornir and work with the inventory let's see how we can leverage it to run tasks on groups of hosts.
Nornir ships a bunch of tasks you can use directly without having to code them yo... | github_jupyter |
## Extraindo características com a VGG16, usando Transfer Learning
<b>Importando as bibliotecas</b>
```
import matplotlib.pyplot as plt
%matplotlib inline
import os
from keras.applications.vgg16 import VGG16, preprocess_input
from keras.preprocessing import image
from skimage.io import imread, imsave
import numpy as ... | github_jupyter |
```
import numpy as np
import os,sys
sys.path.append('../../RL_lib/Agents')
sys.path.append('../../RL_lib/Policies/PPO')
sys.path.append('../../RL_lib/Policies/Common')
sys.path.append('../../RL_lib/Utils')
sys.path.append('../../Env')
sys.path.append('../../Imaging')
%load_ext autoreload
%load_ext autoreload
%auto... | github_jupyter |
# Read annotations from CoNLL
The folder `annotations-pickle` contains all documents in the corpus with its annotations as pickled Python objects (created with the script `read_annotations.py`). This notebook illustrates how to load and use these objects in Python.
Note: to be able to unpickle the files, you should m... | github_jupyter |
[](https://colab.research.google.com/github/uwsampl/tutorial/blob/master/notebook/01_TVM_Tutorial_Intro.ipynb)
Welcome to the TVM tutorial. First we are going to get you setup so you can run the tutorial completely in the Cloud.
Google's Colab ... | github_jupyter |
# Tensorboard
## Add image
```
import matplotlib.pyplot as plt
from torchvision import datasets, models, transforms
import torch.optim as optim
import torch.nn as nn
import torchvision
from torchvision.transforms import *
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
import... | github_jupyter |
<a href="https://colab.research.google.com/github/gumdropsteve/intro_to_machine_learning/blob/main/day_03/01_hyper.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
import pandas as pd
df = pd.read_csv('https://github.com/gumdropsteve/datasets/... | github_jupyter |
Appendix plots for describing the Gaussian process model
```
from Starfish.emulator import Emulator, PCAGrid
from Starfish.utils import saveall
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.inset_locator import inset_... | github_jupyter |
# Install basic requirements
```
pip install -U whylogs pandas
import whylogs
import pandas as pd
```
# Load example data batches
The example data is prepared from our public S3 bucket. You can use your own data if you want if you have multiple batches of data.
```
pdfs = []
for i in range(1, 8):
path = f"https... | github_jupyter |
```
#################
#### IMPORTS ####
#################
# Arrays
import numpy as np
import cytoolz
# Deep Learning stuff
import torch
import torchvision
import torchvision.transforms as transforms
# Images display and plots
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from ... | github_jupyter |
This notebook contains all of the necessary code to reproduce all of the figures used in the paper.
It is sectioned into a section for required auxiliary methods and variables followed by different sections for each figure.
# Import modules
```
import sqlite3
import pandas as pd
import geopandas
import matplotlib
im... | github_jupyter |
# Dirichlet process mixtures for density estimation
Author: [Austin Rochford](https://github.com/AustinRochford/)
## Dirichlet processes
The [Dirichlet process](https://en.wikipedia.org/wiki/Dirichlet_process) is a flexible probability distribution over the space of distributions. Most generally, a probability distr... | github_jupyter |
<table class="ee-notebook-buttons" align="left">
<td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/Image/clipping.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td>
<td><a target="_blank" href="https:/... | github_jupyter |
<a href="https://colab.research.google.com/github/pachterlab/CWGFLHGCCHAP_2021/blob/master/notebooks/CellAtlasAnalysis/pseudoBulkStarvation.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
!date
```
### **Download Data**
```
import requests
fro... | github_jupyter |
<div class="contentcontainer med left" style="margin-left: -50px;">
<dl class="dl-horizontal">
<dt>Title</dt> <dd> Scatter Element</dd>
<dt>Dependencies</dt> <dd>Matplotlib</dd>
<dt>Backends</dt> <dd><a href='./Scatter.ipynb'>Matplotlib</a></dd> <dd><a href='../bokeh/Scatter.ipynb'>Bokeh</a></dd>
</dl>
</div>
``... | github_jupyter |
<table>
<tr align=left><td><img align=left src="./images/CC-BY.png">
<td>Text provided under a Creative Commons Attribution license, CC-BY. All code is made available under the FSF-approved MIT license. (c) Kyle T. Mandli</td>
</table>
Note: The presentation below largely follows part I in "Finite Difference Method... | github_jupyter |
# Differential equation resolution
## Introduction
We present here a Perceval implementation of a Quantum Machine Learning algorithm for solving differential equations. Its aims is to approximate the solution to the differential equation considered in \[1\]:
$$
\frac{d f}{d x}+\lambda f(x)(\kappa+\tan (\lambda x))=0... | github_jupyter |
```
import numpy as np
import matplotlib.pyplot as plt
import rl2
from scipy.optimize import fsolve
import numba
from pyswarm import pso
%matplotlib notebook
run = rl2.run
@numba.njit(cache=True)
def solver(struct):
sin = np.sin
cos = np.cos
sqrt = np.sqrt
i = 0
Dt = struct[i].Dt
N_ste... | github_jupyter |
# 9 - Advanced topics - 1 axis torque tube Shading for 1 day (Research Documentation)
## Recreating JPV 2019 / PVSC 2018 Fig. 13
Calculating and plotting shading from torque tube on 1-axis tracking for 1 day, which is figure 13 in:
Ayala Pelaez S, Deline C, Greenberg P, Stein JS, Kostuk RK. Model and va... | github_jupyter |
# Named input
* **Difficulty level**: easy
* **Time need to learn**: 10 minutes or less
* **Key points**:
* Use dictionary or keyword arguments to specify labels of input
* `_input[name]` return subset of `_input `label `name`
## Named inputs
Let us first create a few temporary files as inputs of the examples
`... | github_jupyter |
# Generate a training set of images and annotations
We'll use the [PASCAL VOC2012](http://host.robots.ox.ac.uk/pascal/VOC/voc2012/) and [PASCAL-Part](http://www.stat.ucla.edu/~xianjie.chen/pascal_part_dataset/pascal_part.html) images and annotations as a training set for UNet.
Let's download both datasets first:
```... | github_jupyter |
# Dependencies
```
import os, warnings, shutil, re
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from transformers import AutoTokenizer
from sklearn.utils import shuffle
from sklearn.model_selection import StratifiedKFold
SEED = 0
warnings.filterwarnings("ignore")
pd.se... | 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.
# Notebook authors: Kevin P. Murphy (murphyk@gmail.com)
# and Mahmoud Soliman (mjs@aucegypt.edu)
# This notebook reproduces figures for chap... | github_jupyter |
## Hello World with cuDF and Streamz
This notebook demonstrates use of cuDF to perform streaming word-count using a small portion of the [Streamz API](https://streamz.readthedocs.io/en/latest/).
This notebook was tested using the `rapidsai/rapidsai-dev-nightly:0.10-cuda10.0-devel-ubuntu18.04-py3.7` container from [Do... | github_jupyter |
# WorkFlow
## Classes
## Load the data
## Test Modelling
## Modelling
**<hr>**
## Classes
```
NAME = "change the conv2d"
BATCH_SIZE = 32
import os
import cv2
import torch
import numpy as np
def load_data(img_size=112):
data = []
index = -1
labels = {}
for directory in os.listdir('./data/'):
... | github_jupyter |
1. [Value-based join of two Matrices](#JoinMatrices)
* [Filter Matrix to include only Frequent Column Values](#FilterMatrix)
* [Construct (sparse) Matrix from (rowIndex, colIndex, values) triplets](#Construct_sparse_Matrix)
* [Find and remove duplicates in columns or rows](#Find_and_remove_duplicates)
* [Set based Inde... | github_jupyter |
```
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... | github_jupyter |
# 1 - dataset_loaders.yaml
* This configuration file stores the settings of all datasets that will be utilized during the execution of an experiment, as can be seen in the example below for the **MovieLens 1M** dataset.
<!-- Which one is better? -->
<!-- * This configuration file stores the settings of all datasets r... | github_jupyter |
```
# default_exp models.MINIROCKET
```
# MINIROCKET
> A Very Fast (Almost) Deterministic Transform for Time Series Classification.
```
#export
from tsai.imports import *
from tsai.utils import *
from tsai.data.external import *
from tsai.models.layers import *
create_scripts
#export
from sktime.transformations.pane... | github_jupyter |
# The Forest Fire Model
## A rapid introduction to Mesa
The [Forest Fire Model](http://en.wikipedia.org/wiki/Forest-fire_model) is one of the simplest examples of a model that exhibits self-organized criticality.
Mesa is a new, Pythonic agent-based modeling framework. A big advantage of using Python is that it a grea... | github_jupyter |
# Saving and Loading Models
In this notebook, I'll show you how to save and load models with PyTorch. This is important because you'll often want to load previously trained models to use in making predictions or to continue training on new data.
```
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
i... | github_jupyter |
```
import pandas as pd
import numpy as np
import os
import datetime
from __future__ import division
airport_data = pd.read_csv('../../Datasets/airports.csv', delimiter=',')
airlines_data = pd.read_csv('../../Datasets/airlines.csv', delimiter=',')
print "Completed Processing"
data = pd.read_csv('../../Datasets/flights... | github_jupyter |
<img src='https://assets.leetcode.com/uploads/2020/11/07/search1.jpg'>
```
from collections import defaultdict
class TrieNode:
def __init__(self):
self.child = defaultdict(TrieNode)
self.isWord = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):... | github_jupyter |
# Sentiment Analysis with an RNN
In this notebook, you'll implement a recurrent neural network that performs sentiment analysis. Using an RNN rather than a feedfoward network is more accurate since we can include information about the *sequence* of words. Here we'll use a dataset of movie reviews, accompanied by label... | github_jupyter |
# Fake News Capstone Project Data Wrangling and Preprocessing
```
import s3fs
import pandas as pd
pd.set_option('display.max_columns', 100000)
pd.set_option('display.max_row', 1000000)
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import re
import tldextract
from tqdm.autonotebook import tqd... | github_jupyter |
# Libraries used in this project
```
import posenet
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import cv2 as cv
import array
import os
import argparse
from sklearn.preprocessing import LabelEncoder
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import confusion_m... | github_jupyter |
```
import os
from glob import glob
import pandas as pd
import numpy as np
from pathlib import Path
from scipy import stats
from matplotlib import pyplot as plt
from matplotlib.colors import Normalize
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib import gridspec
import json
import torch
import gp... | github_jupyter |
```
# time series for weather
import os
import datetime
import IPython
import IPython.display
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import tensorflow as tf
mpl.rcParams['figure.figsize'] = (8, 6)
mpl.rcParams['axes.grid'] = False
from IPy... | github_jupyter |
# The Guandu water supply system
CEDAE is the coorporation that provides drinking water and wastewater services for the Rio de Janeiro State.
They provide plenty of data regarding the quality of the water for the press and for the population, due to laws imposed by the Ministry of Health of Brazil.
Amongst the ETAs (... | github_jupyter |
## Midterm test and practice session
### 1. Questions.
Please, answer the following questions briefly. Two or three sentences with main idea would be enough.
Do not use external resourses in this part, please. Answer with you own words. If you forgot something, don't worry, we will discuss it later.
#### 1.0.
Pleas... | github_jupyter |
```
# Import Libraries
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
from bs4 import BeautifulSoup
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import string
import time
import re
import os
from functools import reduce
trim = ... | github_jupyter |
# RAPA MVP Description
With RAPA, we plan to provide a robust, freely usable, and shareable tool for automated parsimony analysis.
RAPA will initially be developed on top of DataRobot’s Python API to use DataRobot as a "model-running engine." In the RAPA MVP, we will provide two primary features:
* Initial feature f... | github_jupyter |
# Regression Tutorial
This guide will show how to use Tribuo’s regression models to predict wine quality based on the [UCI Wine Quality](https://archive.ics.uci.edu/ml/datasets/Wine+Quality) data set. We’ll experiment with several different regression trainers: two for training linear models (SGD and Adagrad) and one ... | github_jupyter |
# 横向联邦学习任务示例
这是一个使用Delta框架编写的横向联邦学习的任务示例。
数据是分布在多个节点上的[MNIST数据集](http://yann.lecun.com/exdb/mnist/),每个节点上只有其中的一部分样本。任务是训练一个卷积神经网络的模型,进行手写数字的识别。
本示例可以直接在Deltaboard中执行并查看结果。<span style="color:#FF8F8F;font-weight:bold">在点击执行之前,需要修改一下个人的Deltaboard API的地址,具体请看下面第4节的说明。</span>
## 1. 引入需要的包
我们的计算逻辑是用torch写的。所以首先引入```nump... | github_jupyter |
We will use Naive Bayes to model the "Pima Indians Diabetes" data set. This model will predict which people are likely to develop diabetes.
This dataset is originally from the National Institute of Diabetes and Digestive and Kidney Diseases. The objective of the dataset is to diagnostically predict whether or not a pa... | github_jupyter |
```
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O... | github_jupyter |
# 重试
```
# from rtsp.rtsp_server import setup_server
#
# setup_server()
from retrying import retry
import random
import time
def retry_if_error(exception):
return exception.__class__ in {ValueError, TimeoutError}
def retry_if_not_result(result):
if result in [5, 10]:
print("result success {}".form... | github_jupyter |
# Pandas fast mutate architecture
## Problem: users may need to define their own functions for SQL or pandas
In siuba, much of what users do involves expressions using `_`.
Depending on the backend they're using, these expressions are then transformed and executed.
However, sometimes no translation exists for a metho... | github_jupyter |
```
import sys
sys.version
sys.version_info
import subprocess
```
## call example
```
# returns return code only
subprocess.call(["ls", "-lha"])
```
note that no exception is raised if the underlying command errors:
`bash-script-with-bad-syntax` is a shell script with bad syntax.
```
subprocess.call(["./bash-scrip... | github_jupyter |
# Expected models on binned contact maps
* For intrachromosomal arm regions: P(s) by diagonal
* For interchromosomal regions: Average contact frequency by block
```
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib as mpl
import seaborn as sns
import multiprocess as mp
import numpy as np
import pa... | github_jupyter |
# Cross-validation and hyperparameter tuning
In the previous notebooks, we saw two approaches to tune hyperparameters:
via grid-search and randomized-search.
In this notebook, we will show how to combine such hyperparameters search
with a cross-validation.
## Our predictive model
Let us reload the dataset as we did... | github_jupyter |
```
import sys
import numpy as np
import pandas as pd
import scipy.sparse
import tqdm
import xswap
sys.path.insert(0, '../')
import analysis
n_perms = 1000
allow_antiparallel = False
allow_self_loops = False
directed = False
```
# 2. BioRxiv network
```
biorxiv_df = pd.read_csv('../../../data/task3/3.all_nodes/bio... | github_jupyter |
Introduction to Unsupervised Learning
======
In earlier labs we learned how to use linear regression to study whether certain features are useful in predicting an observed outcome. Then we used ensemble methods to refine our predictions.
In this notebook, we shift from prediction to pattern finding.
What we'll be d... | github_jupyter |
# Protecting against Cross-Site Scripting
This notebook provides an example to showcase the methods we use to protect against Cross-Site Scripting (XSS).
In particular, to protect against it we escape some symbols in the JSON output and we add some extra headers which further ensure that the browser won't misidentify ... | github_jupyter |
# Multi-Tissue NODDI: Including S0 responses in regular MC models
It is well known that different tissues in the brain have different T1, T2 times and proton densities. This causes the contrast that can be seen in any usual b0 image, as the bone below.
```
from dmipy.data import saved_data
scheme_hcp, data_hcp = save... | github_jupyter |
### 008 DataMaker
This is a notebook to make a data sets for the 008 relationship plots for the tutorial and the in-class exercise. It makes:
#### two related numeric variables
* linear relationship for tutorial
* non-linear " " "
* linear for exercise
* non-lin for exercise
```
import numpy as np
import pandas as ... | github_jupyter |
# Batch Normalization – Lesson
1. [What is it?](#theory)
2. [What are it's benefits?](#benefits)
3. [How do we add it to a network?](#implementation_1)
4. [Let's see it work!](#demos)
5. [What are you hiding?](#implementation_2)
# What is Batch Normalization?<a id='theory'></a>
Batch normalization was introduced in ... | github_jupyter |
# Crunch
Crunching as defined in `eodag` is a way to filter the EO products contained in a [SearchResult](../../api_reference/searchresult.rst#eodag.api.search_result.SearchResult) object. Several filters are available and further described in this document.
A [SearchResult](../../api_reference/searchresult.rst#eodag... | github_jupyter |
# Lab 01 : MNIST multi-layer -- demo
```
# For Google Colaboratory
import sys, os
if 'google.colab' in sys.modules:
# mount google drive
from google.colab import drive
drive.mount('/content/gdrive')
# find automatically the path of the folder containing "file_name" :
file_name = 'mnist_multilayer_d... | github_jupyter |
# 15 Classes et objets
Dans cette section nous abordons la **programmation orienté objet** (POO).
## Types définis par le programmeur
Nous avons utilisés des nombreux types internes (int, float, str, bool, etc.); maintant nous allons définir un nouveau type. A titre d'example nous allons créer un type ``Point`` qui ... | github_jupyter |
```
import mido
from midiutil.MidiFile import MIDIFile
import matplotlib
import pandas as pd
import string
import os
import sys
import pandas as pd
import IPython.display as ipd
import librosa.display
import pretty_midi
from matplotlib import pyplot as plt
import numpy as np
def postprocessing(arr2):
x=arr2.shape[0]
... | github_jupyter |
# Training metrics
*Metrics* for training fastai models are simply functions that take `input` and `target` tensors, and return some metric of interest for training. You can write your own metrics by defining a function of that type, and passing it to [`Learner`](/basic_train.html#Learner) in the [code]metrics[/code] ... | github_jupyter |
Introduction
============
Workshop description
--------------------
- This is an intermediate/advanced R course
- Appropriate for those with basic knowledge of R
- This is not a statistics course!
- Learning objectives:
- Learn the R formula interface
- Specify factor contrasts to test specific hypotheses
- Per... | github_jupyter |
# Meraki Python SDK Demo: Uplink Preference Restore
*This notebook demonstrates using the Meraki Python SDK to restore Internet (WAN) and VPN traffic uplink preferences, as well as custom performance classes, from an Excel file. If you have hundreds of WAN/VPN uplink preferences, they can be a challenge to manipulate.... | github_jupyter |
##### Copyright 2019 The TensorFlow Hub Authors.
Licensed under the Apache License, Version 2.0 (the "License");
```
# Copyright 2018 The TensorFlow Hub Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
... | github_jupyter |
This is the third blog post of [Object Detection with YOLO blog series](https://fairyonice.github.io/tag/object-detection-using-yolov2-on-pascal-voc2012-series.html). This blog discusses the YOLO's model architecture. I will use PASCAL VOC2012 data. This blog assumes that the readers have read the previous two blog pos... | github_jupyter |
```
%matplotlib inline
import numpy as np
from numpy.fft import fft2, ifft2, fftshift, ifftshift
from scipy.stats import multivariate_normal
import matplotlib.pyplot as plt
import menpo.io as mio
from menpo.image import Image
from menpo.feature import hog, no_op
from menpo.shape import PointCloud
from menpo.visuali... | github_jupyter |
# Value in equities
#### by Gustavo Soares
In this notebook you will apply a few things you learned in our Python lecture [FinanceHub's Python lectures](https://github.com/Finance-Hub/FinanceHubMaterials/tree/master/Python%20Lectures):
* You will use and manipulate different kinds of variables in Python such as text... | github_jupyter |
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Gradient-Boosting-Machine-(GBM)" data-toc-modified-id="Gradient-Boosting-Machine-(GBM)-1"><span class="toc-item-num">1 </span>Gradient Boosting Machine (GBM)</a></span><ul class="toc-item"><li><s... | github_jupyter |
```
from glob import glob
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import display, Markdown
%load_ext autoreload
%autoreload 2
from pymedphys.msq import (
mosaiq_connect, delivery_data_from_mosaiq, get_patient_fields,
get_qcls_by_date, multi_mosaiq_connect, g... | github_jupyter |
In the first 2 learning units, we saw the so-called **Bag of Words** vectorization of text. Text is transformed in vectors, constituted by counts or frequencies of words. This representation has the advantage of being simple and lasted for a very long time.
A possible improvement to this idea is, instead of considerin... | github_jupyter |
ERROR: type should be string, got "https://github.com/d2l-ai/d2l-en/issues/1116\n\n```\nfrom d2l import torch as d2l\nimport torch\nfrom torch import nn\nimport numpy as np\nimport math\nmax_degree = 20 # Maximum degree of the polynomial\nn_train, n_test = 100, 100 # Training and test dataset sizes\ntrue_w = np.zeros(max_degree) # Allocate lots of empty space\ntrue_w[0:4] = np.array([5, 1.2, -3.4, 5.6])\n\nfeatures = np.random.normal(size=(n_train + n_test, 1))\nnp.random.shuffle(features)\npoly_features = np.power(features, np.arange(max_degree).reshape(1, -1))\nfor i in range(max_degree):\n poly_features[:, i] /= math.gamma(i + 1) # `gamma(n)` = (n-1)!\n# Shape of `labels`: (`n_train` + `n_test`,)\nlabels = np.dot(poly_features, true_w)\nlabels += np.random.normal(scale=0.1, size=labels.shape)\nfeatures[:2].T, poly_features[:2, :], labels[:2]\n# Convert from NumPy to PyTorch tensors\ntrue_w, features, poly_features, labels = [torch.from_numpy(x).type(\n torch.float32) for x in [true_w, features, poly_features, labels]]\ndef evaluate_loss(net, data_iter, loss): #@save\n \"\"\"Evaluate the loss of a model on the given dataset.\"\"\"\n metric = d2l.Accumulator(2) # Sum of losses, no. of examples\n for X, y in data_iter:\n l = loss(net(X), y)\n metric.add(l.sum(), l.numel())\n return metric[0] / metric[1]\ndef train(train_features, test_features, train_labels, test_labels,\n num_epochs=400):\n loss = nn.MSELoss()\n input_shape = train_features.shape[-1]\n # Switch off the bias since we already catered for it in the polynomial\n # features\n net = nn.Sequential(nn.Linear(input_shape, 1, bias=False))\n batch_size = min(10, train_labels.shape[0])\n train_iter = d2l.load_array((train_features, train_labels.reshape(-1,1)),\n batch_size)\n test_iter = d2l.load_array((test_features, test_labels.reshape(-1,1)),\n batch_size, is_train=False)\n trainer = torch.optim.SGD(net.parameters(), lr=0.01)\n animator = d2l.Animator(xlabel='epoch', ylabel='loss', yscale='log',\n xlim=[1, num_epochs], ylim=[1e-3, 1e2],\n legend=['train', 'test'])\n for epoch in range(num_epochs):\n d2l.train_epoch_ch3(net, train_iter, loss, trainer)\n if epoch == 0 or (epoch + 1) % 20 == 0:\n animator.add(epoch + 1, (evaluate_loss(net, train_iter, loss),\n evaluate_loss(net, test_iter, loss)))\n print('weight:', net[0].weight.data.numpy())\n# Pick the first four dimensions, i.e., 1, x, x^2/2!, x^3/3! from the\n# polynomial features\ntrain(poly_features[:n_train, :4], poly_features[n_train:, :4],\n labels[:n_train], labels[n_train:])\n# Pick from the original `features` for linear function fitting\ntrain(features[:n_train, :], features[n_train:, :], labels[:n_train],\n labels[n_train:])\n# Pick all the dimensions from the polynomial features\ntrain(poly_features[:n_train, :], poly_features[n_train:, :],\n labels[:n_train], labels[n_train:], num_epochs=1500)\n```\n\n" | github_jupyter |
# Catalyst classification tutorial
## Requirements
Download and install the latest version of catalyst and other libraries required for this tutorial.
```
!pip install -U catalyst
!pip install albumentations
!pip install pretrainedmodels
```
### Colab extras
First of all, do not forget to change the runtime type t... | github_jupyter |
# Loading Image Data
So far we've been working with fairly artificial datasets that you wouldn't typically be using in real projects. Instead, you'll likely be dealing with full-sized images like you'd get from smart phone cameras. In this notebook, we'll look at how to load images and use them to train neural network... | github_jupyter |
```
Copyright 2021 IBM Corporation
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
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, softwa... | github_jupyter |
<a href="https://colab.research.google.com/github/praveentn/hgwxx7/blob/master/ampligraph/Clustering_And_Classification_With_Embeddings.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
---
# Clustering and Classification using Knowledge Graph Embeddi... | github_jupyter |
<table class="ee-notebook-buttons" align="left">
<td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/AssetManagement/export_TimeSeries2.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 |
## Hierarchical Regression
Hierarchical models enable sharing of features among groups. The parameters of the model are assumed to be sampled from a common distribution that models similarity between groups. The figure below shows three different scenarios that illustrate the benefit of hierarchical modeling. In the f... | github_jupyter |
# Think Bayes: Chapter 5
This notebook presents code and exercises from Think Bayes, second edition.
Copyright 2016 Allen B. Downey
MIT License: https://opensource.org/licenses/MIT
```
from __future__ import print_function, division
% matplotlib inline
import warnings
warnings.filterwarnings('ignore')
import nump... | github_jupyter |
```
# Running %env without any arguments
# lists all environment variables
# The line below sets the environment
# variable CUDA_VISIBLE_DEVICES
%env CUDA_VISIBLE_DEVICES =
import numpy as np
import pandas as pd
import io
import time
from datetime import datetime
import bson # this is installed... | github_jupyter |
<a href="https://colab.research.google.com/github/MIT-LCP/hack-aotearoa/blob/master/04_timeseries.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# eICU Collaborative Research Database
# Notebook 4: Timeseries for a single patient
This notebook ex... | github_jupyter |
<a href="https://colab.research.google.com/github/sweetpand/Algorithms/blob/master/marathone_day6.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
1. Подсчитать, сколько было выделено памяти под переменные в ранее разработанных программах в рамках пе... | github_jupyter |
```
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
```
# Create data
```
import copy
from liegroups import SE2, SO2
params_true = {'T_1_0': SE2.identity(),
'T_2_0': SE2(SO2.identity(), -np.array([0.5, 0])),
'T_3_0': SE2(SO2.identity(), -np.array([1, 0])),
... | github_jupyter |
# TensorFlow tutorial
In this tutorial we'll show how to build deep learning models in Tribuo, using Tribuo's [TensorFlow](https://tensorflow.org) interface. Tribuo uses [TensorFlow-Java](https://github.com/tensorflow/java) which is build by the TensorFlow [SIG-JVM group](https://github.com/tensorflow/community/blob/m... | github_jupyter |
# Numpy
___
[](http://www.youtube.com/watch?v=NVTWjd_UpzM "Numpy Playlist")
**Numpy features**
___
1. sorting data
2. mutable iterable object
3. can be indexed
4. slicing operation can be perform
**diff between list and numpy array**
____
list = different da... | github_jupyter |
```
#import libraries
import networkx as nx
import matplotlib.pyplot as plt
```
# Erdos-Renyi graph
```
# a random erdos-renyi graph with 100 nodes and a edge probability of 0.3
graph = nx.erdos_renyi_graph(100, 0.3, seed=None, directed=False)
nx.draw(graph)
plt.title("A random erdos-renyi graph with 100 nodes and a ... | github_jupyter |
# Data Mining Challange: *Reddit Gender Text-Classification*
### Modules
```
# Numpy & matplotlib for notebooks
%pylab inline
# Pandas for data analysis and manipulation
import pandas as pd
# Sparse matrix package for numeric data.
from scipy import sparse
# Module for word embedding (word2vector)
import gensi... | github_jupyter |
# Getting Started
```
''' Required for Google Colab'''
# Mount GDrive
# from google.colab import drive
# drive.mount('/content/drive')
# # Upload Kaggle json
# !pip install -q kaggle
# !pip install -q kaggle-cli
# !mkdir -p ~/.kaggle
# !cp "/content/drive/My Drive/Kaggle/kaggle.json" ~/.kaggle/
# !cat ~/.kaggle/kag... | github_jupyter |
# Study of Glassdoor Data
The purpose of this study is too quickly present the Glassdoor data with the different attributes
The datasets have been cleaned with cleaning functions written in python
We will after studied missing data siginification
## Import packages and constants and helpers
```
# Packages
impor... | github_jupyter |
# Keras for Text Classification
**Learning Objectives**
1. Learn how to tokenize and integerize a corpus of text for training in Keras
1. Learn how to do one-hot-encodings in Keras
1. Learn how to use embedding layers to represent words in Keras
1. Learn about the bag-of-word representation for sentences
1. Learn how ... | github_jupyter |
```
library(ggplot2)
library(dplyr)
library(reshape2)
library(Matrix)
library(gridExtra)
# You may need to set these to your own local paths.
project_directory <- file.path(Sys.getenv("GIT_REPO_LOC"), "MicrocreditLRVB/inst/simulated_data")
raw_data_directory <- file.path(Sys.getenv("GIT_REPO_LOC"), "microcredit_vb/dat... | github_jupyter |
```
%matplotlib inline
from pathlib import Path
import requests
DATA_PATH = Path("data")
PATH = DATA_PATH / "mnist"
PATH.mkdir(parents=True, exist_ok=True)
URL = "http://deeplearning.net/data/mnist/"
FILENAME = "mnist.pkl.gz"
if not (PATH / FILENAME).exists():
content = requests.get(URL + FILENAME).content
... | github_jupyter |
# Introduction to Generative ML with Pyro
```
import matplotlib.pyplot as plt
import torch
import pyro
pyro.set_rng_seed(101)
```
Our goal is to understand causal modeling within the context of generative machine learning. We just examined one generative machine learning framework called Bayesian networks (BNs) and ... | github_jupyter |
## Tabular data handling
This module defines the main class to handle tabular data in the fastai library: [`TabularDataBunch`](/tabular.data.html#TabularDataBunch). As always, there is also a helper function to quickly get your data.
To allow you to easily create a [`Learner`](/basic_train.html#Learner) for your data... | github_jupyter |
# Gaussian Mixture Model
This is a brief tutorial on training mixture models in Pyro. We'll focus on the mechanics of `config_enumerate()` and setting up mixture weights. To simplify matters, we'll train a trivial 1-D Gaussian model on a tiny 5-point dataset.
```
from __future__ import print_function
import os
from c... | github_jupyter |
# Custom DataLoader for Imbalanced dataset
* In this notebook we will use the higly imbalanced Protein Homology Dataset from [KDD cup 2004](https://www.kdd.org/kdd-cup/view/kdd-cup-2004/Data)
```
* The first element of each line is a BLOCK ID that denotes to which native sequence this example belongs. There is a uniq... | github_jupyter |
# Cowell's formulation
For cases where we only study the gravitational forces, solving the Kepler's equation is enough to propagate the orbit forward in time. However, when we want to take perturbations that deviate from Keplerian forces into account, we need a more complex method to solve our initial value problem: o... | github_jupyter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.