text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
```
#export
import io,sys,json,glob
from fastscript import call_parse,Param
from nbdev.imports import Config
from pathlib import Path
# default_exp clean
#hide
#For tests only
from nbdev.imports import *
```
# Clean notebooks
> Strip notebooks from superfluous metadata
To avoid pointless conflicts while working with... | github_jupyter |
```
from google.colab import drive
drive.mount('/content/drive')
cd /content/drive/My\ Drive/Transformer-master/
```
# ライブラリ読み込み
```
!apt install aptitude
!aptitude install mecab libmecab-dev mecab-ipadic-utf8 git make curl xz-utils file -y
!pip install mecab-python3==0.6
!pip install japanize_matplotlib
import numpy... | github_jupyter |
# YOLOV3 training example
```
from yolo import YOLO, detect_video
from PIL import Image
import matplotlib.pyplot as plt
from yolo3.model import yolo_eval, yolo_body, tiny_yolo_body
from keras.layers import Input
import numpy as np
import keras.backend as K
from keras.layers import Input, Lambda
from keras.models impor... | github_jupyter |
# Feature Representation Methods in ChemML
To build a machine learning model, raw chemical data is first converted into a numerical representation. The representation contains spatial or topological information that defines a molecule. The resulting features may either be in continuous (molecular descriptors) or discr... | github_jupyter |
# linear model to classify the MNIST data set
In this second tutorial, we will continue to work on image classification and try a linear classification model. This kind of model have the same number of parameters as the input images (64 here) plus one bias. They work by trying to with the parameters so that we minimiz... | github_jupyter |
<div style="width:1000 px">
<div style="float:right; width:98 px; height:98px;">
<img src="https://raw.githubusercontent.com/Unidata/MetPy/master/metpy/plots/_static/unidata_150x150.png" alt="Unidata Logo" style="height: 98px;">
</div>
<h1>Introduction to MetPy</h1>
<h3>Unidata Python Workshop</h3>
<div style="clear... | github_jupyter |
# Text models, data, and training
```
from fastai.gen_doc.nbdoc import *
```
The [`text`](/text.html#text) module of the fastai library contains all the necessary functions to define a Dataset suitable for the various NLP (Natural Language Processing) tasks and quickly generate models you can use for them. Specifical... | github_jupyter |
# Recreating Ling _IMMI_ (2017)
In this notebook, we will recreate some key results from [Ling et al. _IMMI_ (2017)](https://link.springer.com/article/10.1007/s40192-017-0098-z), which studied the application of random-forest-based uncertainties to materials design. We will show that the errors produced from the Random... | github_jupyter |
```
%matplotlib inline
```
如何在PyTorch中使用VisualDL
=====================
下面我们演示一下如何在PyTorch中使用VisualDL,从而可以把PyTorch的训练过程以及最后的模型可视化出来。我们将以PyTorch用卷积神经网络(CNN, Convolutional Neural Network)来训练 [Cifar10](https://www.cs.toronto.edu/~kriz/cifar.html) 数据集作为例子。
程序的主体来自PyTorch的 [Tutorial](http://pytorch.org/tutorials/beginner... | github_jupyter |
## Convolutional neural networks
```
%matplotlib inline
import tensorflow as tf
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from ipywidgets import FloatProgress
from IPython.display import display
import time
from tensorflow.examples.tutorials.mnist import input_data
mn... | github_jupyter |
## Color FID Benchmark (HQ)
```
import os
os.environ['CUDA_VISIBLE_DEVICES']='3'
os.environ['OMP_NUM_THREADS']='1'
import statistics
from fastai import *
from deoldify.visualize import *
import cv2
from fid.fid_score import *
from fid.inception import *
import imageio
plt.style.use('dark_background')
torch.backends.cu... | github_jupyter |
```
import tensorflow as tf
import script_config as sc
import pandas as pd
import heapq as hq
import numpy as np
import csv
data_folder = sc._config_data_folder
hops = sc._config_hops
max_list_size = sc._config_relation_list_size_neighborhood
users = pd.read_csv(data_folder+"filtered_users.cs... | github_jupyter |
# News Classifier
Implementation of a news classifier model using Scikit Learn's Naive Bayes implementation.
Since this model is implemented using Scikit Learn, we can deploy it using [one of Seldon's pre-built re-usable server](https://docs.seldon.io/projects/seldon-core/en/latest/servers/sklearn.html).
## Training
... | github_jupyter |
# Задание 1.2 - Линейный классификатор (Linear classifier)
В этом задании мы реализуем другую модель машинного обучения - линейный классификатор. Линейный классификатор подбирает для каждого класса веса, на которые нужно умножить значение каждого признака и потом сложить вместе.
Тот класс, у которого эта сумма больше,... | github_jupyter |
# Extract LAT Data
This thread shows how to extract LAT data from the FERMI Science Support Center (FSSC) [archive](http://fermi.gsfc.nasa.gov/cgi-bin/ssc/LAT/LATDataQuery.cgi) and perform further selection cuts using the Fermitools.
## Synopsis
This thread leads you through extracting your LAT data files from the F... | github_jupyter |
# Few-Shot Learning
<!-- **Challenge:** [Omniglot](https://github.com/brendenlake/omniglot), the "transpose" of MNIST, with 1,623 character classes, each with 20 examples. Is it possible to build a few-shot classifier with a target of <35% error rate? -->
Humans exhibit a strong ability to acquire and recognize new p... | github_jupyter |
# NETCONF/YANG
This notebook goes through a set of examples with a live platform. The platform should be running IOS-XE 16.3.2. The goal is to show how NETCONF/YANG can be leveraged to perform a range of tasks. We will cover topics like:
* Basic connectivity
* Why we really want to use some form of client library
* Get... | github_jupyter |
# Lab 5: Simulations
Welcome to lab 5! This week, we will go over iteration and simulations, and introduce the concept of randomness. All of this material is covered in [Chapter 9](https://www.inferentialthinking.com/chapters/09/randomness.html) and [Chapter 10](https://www.inferentialthinking.com/chapters/10/sampling... | github_jupyter |
## 2.1: Creating Interactive Plots
```
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib.widgets import Slider
%matplotlib notebook
TWOPI = 2*np.pi
fig, ax = plt.subplots()
t = np.arange(0.0, TWOPI, 0.001)
initial_amp = .5
s = initial_amp*np.sin(t)
l, ... | github_jupyter |
<a href="https://colab.research.google.com/github/NeuromatchAcademy/course-content/blob/master/tutorials/W2D3_BiologicalNeuronModels/W2D3_Tutorial3.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Tutorial 3: Synaptic transmission - Models of stati... | github_jupyter |
# MCMC algorithm - fitting spectral line
```
# Importing Libraries
import numpy as np
import matplotlib.pyplot as plt
import corner
import emcee
import warnings
warnings.filterwarnings('ignore')
%matplotlib inline
# We create and artificial spectral line
def get_val(x, p):
m, b, sigma, C, lamb_0 = p
return m*... | github_jupyter |
```
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import multivariate_normal
```
# Part a
```
# Loading Dataset
x = []
f = open("data/data/faithful/faithful.txt",'r')
for line in f.readlines():
x.append([float(i) for i in line.strip().split(" ")])
x = np.array(x)
x.shape
#Normalise the da... | github_jupyter |
```
%matplotlib inline
from fastai.gen_doc.nbdoc import *
from fastai.text import *
import matplotlib as mpl
mpl.rcParams['figure.dpi']= 300
```
# Writing the book
```python
def is_cat(x): return x[0].isupper()
dls = ImageDataLoaders.from_name_func(
path, get_image_files(path), valid_pct=0.2, seed=42,
label_f... | github_jupyter |
<a href="https://colab.research.google.com/github/PacktPublishing/Modern-Computer-Vision-with-PyTorch/blob/master/Chapter04/Image_augmentation.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
%%capture
!pip install -U imgaug
import imgaug
print(i... | github_jupyter |
# 23. K-Means Clustering
[](https://colab.research.google.com/github/rhennig/EMA6938/blob/main/Notebooks/23.K-MeansClustering-MP.ipynb)
(Based on https://medium.com/@arifromadhan19/step-by-step-to-understanding-k-means-clustering-and-implementa... | github_jupyter |
# Word2Vec v2: "Mistake Not"
### Connect to Database
```
! pip3 install psycopg2-binary --user
import pandas as pd
import psycopg2
import numpy as np
from getpass import getpass
# connect to database
connection = psycopg2.connect(
database = "postgres",
user = "postgres",
password = getpass(),
... | github_jupyter |
##### Let's change gears and talk about Game of thrones or shall I say Network of Thrones.
It is suprising right? What is the relationship between a fatansy TV show/novel and network science or python(it's not related to a dragon).
If you haven't heard of Game of Thrones, then you must be really good at hiding. Game ... | github_jupyter |
```
%matplotlib inline
import time
import numpy as np
import pandas as pd
import imageio as io
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
from os import listdir, makedirs, getcwd, remove
from os.path import isfile, join, abspath, exists, isdir, expanduser
!ls MURA-v1.0/
data_dir = jo... | github_jupyter |
```
"""
You can run either this notebook locally (if you have all the dependencies and a GPU) or on Google Colab.
Instructions for setting up Colab are as follows:
1. Open a new Python 3 notebook.
2. Import this notebook from GitHub (File -> Upload Notebook -> "GITHUB" tab -> copy/paste GitHub URL)
3. Connect to an in... | github_jupyter |
# Hidden State Activation : Ungraded Lecture Notebook
In this notebook you'll take another look at the hidden state activation function. It can be written in two different ways.
I'll show you, step by step, how to implement each of them and then how to verify whether the results produced by each of them are same or ... | github_jupyter |
##### 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 |
#### Installation of R packages
```
#install.packages("ISwR")
```
#### Package loading
```
library(ISwR)
```
#### Variable definition and assignment
```
weight <- 60
height = 1.75
subject <- "A"
healthy <- TRUE
```
#### Variable evaluation
```
weight
```
#### Functions for type checking
```
is.numeric(weight) ... | github_jupyter |
# Dummy Variables Exercise
In this exercise, you'll create dummy variables from the projects data set. The idea is to transform categorical data like this:
| Project ID | Project Category |
|------------|------------------|
| 0 | Energy |
| 1 | Transportation |
| 2 | Health ... | github_jupyter |
# Visualization of template experiment
This notebook plots the gene expression data of the template experiment in order to confirm the strength of the differential signal, since we will be performing a DE analysis downstream.
```
%load_ext autoreload
%autoreload 2
import os
import sys
import pandas as pd
import numpy... | github_jupyter |
# 'River meanders and the theory of minimum variance'
# and 'Up a lazy river'
The issue is not how the channel guides the river but how the river carves the channel. Rivers meander even when they carry no sediment, and even when they have no banks (Hayes, 2006)!
### Reference
- Von Schelling, H. (1951). Most frequen... | github_jupyter |
```
# db = int(input('Database ID (2 for 4 chamber and 17 for short axis): '))
# basedir = input('Base directory (e.g. D:/ML_data/PAH): ')
# scale = int(input('Scale (16, 8, 4, or -1): '))
# mask_id = int(input('Mask ID (1-5): '))
# level = int(input('Preprocessing level (1-4): '))
import os
import h5py
import numpy as... | github_jupyter |
```
# Analyze Orcas Queries in Anchor Context
!pip3 install nltk termcolor
def normalize(text):
import nltk
nltk.data.path = ['/mnt/ceph/storage/data-in-progress/data-research/web-archive/EMNLP-21/emnlp-web-archive-questions/cluster-libs/nltk_data']
from nltk.stem import PorterStemmer
from nltk.tokeniz... | github_jupyter |
# Creating Graphs from Folder Structures with Python
In this notebook you will see how to use the [folderstats](https://github.com/njanakiev/folderstats) Python module to explore and analyze folder structures visualy as a graph.
# Installation
For this notebook you'll want to install the [folderstats](https://github... | github_jupyter |
```
rcParams['figure.figsize'] = (16, 4) #wide graphs by default
```
# Segmentation
## Structural segmentation
Tzanetakis, G., & Cook, P. (1999). Multifeature audio segmentation for browsing and annotation. IEEE Workshop on Applications of Signal Processing to Audio and Acoustics, 1–4. Retrieved from http://ieeexplo... | github_jupyter |
# TV Script Generation
In this project, you'll generate your own [Simpsons](https://en.wikipedia.org/wiki/The_Simpsons) TV scripts using RNNs. You'll be using part of the [Simpsons dataset](https://www.kaggle.com/wcukierski/the-simpsons-by-the-data) of scripts from 27 seasons. The Neural Network you'll build will gen... | github_jupyter |
# Predicting Boston Housing Prices
## Using XGBoost in SageMaker (Deploy)
_Deep Learning Nanodegree Program | Deployment_
---
As an introduction to using SageMaker's Low Level Python API we will look at a relatively simple problem. Namely, we will use the [Boston Housing Dataset](https://www.cs.toronto.edu/~delve/d... | github_jupyter |
# First Programming Language Tweets, etc
There is a Twitter meme that is currently circulating that was started (I think) by [@cotufa82](https://twitter.com/cotufa82) where you list programming languages by particular categories including:
* first language
* had difficulties
* most used
* totally hate
* most loved
* ... | github_jupyter |
# Pipeline: Heterogenous data
This notebook implements a pipeline for heterogeneous data.
sources:
Sample pipeline for text feature extraction and evaluation: https://scikit-learn.org/stable/auto_examples/model_selection/grid_search_text_feature_extraction.html
Metrics and scoring: quantifying the quality of predic... | github_jupyter |
# Recurrent Neural Networks
- Sequence data
- Natural Language
- Speech ...
### RNN model

### RNN example

### LSTM (Long Short-Term Memory models)

Определение (definition) функции - описание её "интерфейса" (сигнатуры, возвращаемого типа и квалификаторов) И реализации.
```c++
float abs(float x)
{
... | github_jupyter |
```
import os
import random
import tensorflow as tf
import shutil
import matplotlib.pyplot as plt
from tensorflow import keras
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from shutil import copyf... | github_jupyter |
```
# Erasmus+ ICCT project (2018-1-SI01-KA203-047081)
# Toggle cell visibility
from IPython.display import HTML
tag = HTML('''<script>
code_show=true;
function code_toggle() {
if (code_show){
$('div.input').hide()
} else {
$('div.input').show()
}
code_show = !code_show
}
$( document... | github_jupyter |
```
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))
```
# AWS Kinesis - Python + Spark
* Pre-requisites
* Introduction
* Installation
* CLI - useage
## Pre-requisites
* AWS Account
* Your own IAM role
* Python3 installed on system
## Introduction... | github_jupyter |
<img width="10%" alt="Naas" src="https://landen.imgix.net/jtci2pxwjczr/assets/5ice39g4.png?w=160"/>
# Plaid - Get transactions
<a href="https://app.naas.ai/user-redirect/naas/downloader?url=https://raw.githubusercontent.com/jupyter-naas/awesome-notebooks/master/Plaid/Plaid_Get_transactions.ipynb" target="_parent"><img... | github_jupyter |
```
%load_ext autoreload
%autoreload 2
import glob
import nibabel as nib
import os
import time
import pandas as pd
import numpy as np
import cv2
from skimage.transform import resize
from mricode.utils import log_textfile, createPath, data_generator
from mricode.utils import copy_colab
from mricode.utils import return... | github_jupyter |
# GPU-Accelerated Tree SHAP on AWS
With the release of XGBoost 1.3 comes an exciting new feature for model interpretability — GPU accelerated SHAP values. SHAP values are a technique for local explainability of model predictions. That is, they give you the ability to examine the impact of various features on model out... | github_jupyter |
# Running Tune experiments with Skopt
In this tutorial we introduce Skopt, while running a simple Ray Tune experiment. Tune’s Search Algorithms integrate with Skopt and, as a result, allow you to seamlessly scale up a Skopt optimization process - without sacrificing performance.
Scikit-Optimize, or skopt, is a simple... | github_jupyter |
## The basics: interactive NumPy on GPU and TPU
---
```
import jax
import jax.numpy as jnp
from jax import random
key = random.PRNGKey(0)
key, subkey = random.split(key)
x = random.normal(key, (5000, 5000))
print(x.shape)
print(x.dtype)
y = jnp.dot(x, x)
print(y[0, 0])
x
import matplotlib.pyplot as plt
plt.plot(x[0... | github_jupyter |
```
import plaidml.keras
plaidml.keras.install_backend()
import os
os.environ["KERAS_BACKEND"] = "plaidml.keras.backend"
# Importing useful libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layer... | github_jupyter |
<a href="https://colab.research.google.com/github/butchland/fastai_xla_extensions/blob/master/explore_nbs/AWD_LSTM_small_patched_GPU_butch_colab.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
!curl -s https://course.fast.ai/setup/colab | bash... | github_jupyter |
# Cyberinfrastructure Exploration
In this segment you will take a few minutes to explore how you can get involved in cyberinfastructure as you build your own cyber literacy.
While this might sound daunting, luckily there are a number of cyberinfrastructure projects that are ready to help you at any stage. From the ve... | github_jupyter |
# Pilatus on a goniometer at ID28
Nguyen Thanh Tra who was post-doc at ESRF-ID28 enquired about a potential bug in pyFAI in October 2016: he calibrated 3 images taken with a Pilatus-1M detector at various detector angles: 0, 17 and 45 degrees.
While everything looked correct, in first approximation, one peak did not ... | github_jupyter |
# Building your Deep Neural Network: Step by Step
Welcome to your week 4 assignment (part 1 of 2)! You have previously trained a 2-layer Neural Network (with a single hidden layer). This week, you will build a deep neural network, with as many layers as you want!
- In this notebook, you will implement all the functio... | github_jupyter |
This notebook was prepared by Marco Guajardo. Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).
# Solution Notebook
## Problem: Implement a binary search tree with insert, delete, different traversals & max/min node values
* [Constraints](#Constraints)
* [Test Cases... | github_jupyter |
```
# default_exp Core
!which python
#hide
%load_ext autoreload
%autoreload 2
```
# Core module
> API details
### 1. parameters
```
from SEQLinkage.Main import *
```
args = Args().parser.parse_args(['--fam','../sample_i/rare_positions/sample_i_coding.hg38_multianno.fam',
'--vcf', ... | github_jupyter |
##### Copyright 2018 The AdaNet 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 agre... | github_jupyter |
```
from __future__ import division
import pickle
import os
from sklearn import metrics
import numpy as np
import pandas as pd
from lentil import evaluate
from lentil import models
import mem
from matplotlib import pyplot as plt
import seaborn as sns
%matplotlib inline
import matplotlib as mpl
mpl.rc('savefig', dpi... | github_jupyter |
```
!wget https://zenodo.org/record/3824876/files/SignalTrain_LA2A_Dataset_1.1.tgz?download=1
!tar -xvf SignalTrain_LA2A_Dataset_1.1.tgz?download=1
!ls
from google.colab import drive
drive.mount('/content/drive')
!mv SignalTrain_LA2A_Dataset_1.1/ "/content/drive/My Drive"
!mv ssh.tar.gz "/content/drive/My Drive"
!rm -r... | github_jupyter |
```
# This code works till numpy version 1.19.5
# Please look for a solution if you want it to work wwith numpy version 1.20
import pandas as pd
import tensorflow as tf
df = pd.read_csv('fake-news/train.csv')
df.head()
#check if the gpu is accessible here or not
tf.test.is_gpu_available(cuda_only=True)
# checking for n... | github_jupyter |
```
%load_ext autoreload
%autoreload
%matplotlib inline
import pandas as pd
import numpy as np
from IPython.core.debugger import set_trace
from tqdm import tqdm_notebook
import texcrapy
#from konlpy.corpus import word
from ckonlpy.tag import Twitter, Postprocessor
import json
from soynlp.word import WordExtractor
from... | github_jupyter |
```
import tiledb
import tiledb.cf
import netCDF4
import numpy as np
import matplotlib.pyplot as plt
netcdf_file = "../data/simple1.nc"
group_uri = "arrays/simple_netcdf_to_group_1"
array_uri = "arrays/simple_netcdf_to_array_1"
import shutil
# clean up any previous runs
try:
shutil.rmtree(group_uri)
shutil.... | github_jupyter |
# Train a Simple Audio Recognition model for microcontroller use
This notebook demonstrates how to train a 20kb [Simple Audio Recognition](https://www.tensorflow.org/tutorials/sequences/audio_recognition) model for [TensorFlow Lite for Microcontrollers](https://tensorflow.org/lite/microcontrollers/overview). It will p... | github_jupyter |
```
import numpy as np
import pandas as pd
from sklearn import model_selection
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
fr... | github_jupyter |
```
from bs4 import BeautifulSoup
import requests
import pandas as pd
import time
import progressbar
# Let's get started: scrape main page
url = "https://daphnecaruanagalizia.com"
response = requests.get(url)
daphne = BeautifulSoup(response.text, 'html.parser')
# Get structural information based on developer tools in G... | github_jupyter |
```
import os
import re
import json
import utils
import random
import gensim
import warnings
import numpy as np
import pandas as pd
from tasks import *
from pprint import pprint
from tqdm.notebook import tqdm
from sklearn.cluster import KMeans
from sklearn.neighbors import NearestNeighbors
from yellowbrick.cluster im... | github_jupyter |
# Table of Contents
<p><div class="lev1 toc-item"><a href="#A-brief-tutorial-for-the-WormBase-Enrichment-Suite,-Python-interface" data-toc-modified-id="A-brief-tutorial-for-the-WormBase-Enrichment-Suite,-Python-interface-1"><span class="toc-item-num">1 </span>A brief tutorial for the WormBase Enrichment Sui... | github_jupyter |
# IndShockConsumerType Documentation
## Consumption-Saving model with Idiosyncratic Income Shocks
```
# Initial imports and notebook setup, click arrow to show
from HARK.ConsumptionSaving.ConsIndShockModel import IndShockConsumerType
from HARK.utilities import plot_funcs_der, plot_funcs
import matplotlib.pyplot as plt... | github_jupyter |
# Discrete Choice Models
## Fair's Affair data
A survey of women only was conducted in 1974 by *Redbook* asking about extramarital affairs.
```
%matplotlib inline
import numpy as np
import pandas as pd
from scipy import stats
import matplotlib.pyplot as plt
import statsmodels.api as sm
from statsmodels.formula.api i... | github_jupyter |
```
import numpy as np
import pandas as pd
import re
import os
import random
import pprint
from collections import defaultdict
def remove_nan(df:pd.DataFrame) -> dict:
"""
Rimuove i valori nulli da una lista
"""
lookup_dict = df.to_dict('list')
for k, v in lookup_dict.items():
while ... | github_jupyter |
```
# load data from PostgreSQL to csv
import pandas
import pickle
import numpy
import time
import psycopg2
t_host = "localhost"
t_port = "5432"
t_dbname = "postgres"
t_user = "postgres"
t_pw = "postgres"
db_conn = psycopg2.connect(host=t_host, port=t_port, dbname=t_dbname, user=t_user, password=t_pw)
db_cursor = db_c... | github_jupyter |
# Purpose
The purpose of this notebook is to generate movie poster urls for each movie_id we observe in our interactions dataset. These movie poster urls will be utilized in the front-end visualization tool we build for understanding recommender performance.
```
cd ../
%matplotlib inline
%config InlineBackend.figure_... | github_jupyter |
### What is Pyspark?
<img src="PySpark.png">
>Spark is the name of the engine to realize cluster computing while PySpark is the Python's library to use Spark.PySpark is a great language for performing exploratory data analysis at scale, building machine learning pipelines, and creating ETLs for a data platform. If yo... | github_jupyter |
# Combine a Matplotlib Basemap with IPython Widgets
This is an experiment in creating a [Jupyter](https://jupyter.org) notebook showing a world map with different parameters (including map projection) by combining a [Matplotlib Basemap](http://matplotlib.org/basemap/index.html) and [IPython widgets](https://ipywidgets... | github_jupyter |
# Generating spatial weights
`momepy` is using `libpysal` to handle spatial weights, but also builds on top of it. This notebook will show how to use different weights.
```
import momepy
import geopandas as gpd
import matplotlib.pyplot as plt
```
We will again use `osmnx` to get the data for our example and after pr... | github_jupyter |
# Hyperparameter tuning with Cloud ML Engine
**Learning Objectives:**
* Improve the accuracy of a model by hyperparameter tuning
```
import os
PROJECT = 'cloud-training-demos' # REPLACE WITH YOUR PROJECT ID
BUCKET = 'cloud-training-demos-ml' # REPLACE WITH YOUR BUCKET NAME
REGION = 'us-central1' # REPLACE WITH YOUR... | github_jupyter |
```
from __future__ import division, print_function
import numpy as np
from collections import OrderedDict
import logging
from IPython.display import display
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
from astropy.io import fits
import astropy.wcs
from astropy import coordinates
import astro... | github_jupyter |
Figure(s) in the manuscript created by this notebook: Fig.4C, 3D, 3E.
This notebook fits and plots FRAP data both from clustered proteins and diffuse (unclustered) proteins. The data that this notebook parses comes from the outputs of the "Extract_two_radii_TrackMate.ijm" and "Manual_FRAP_ROI.ijm" ImageJ macros.
```
... | github_jupyter |
# L8 - Inheritance
---
As in any object-oriented programming language, you can inherit from other classes when creating a new one.
For example, imagine you want to create both a `Fish` class and a `Bird` class. Both of these classes will probably have many things in common, since both are animals.
Instead of duplica... | github_jupyter |
# Creation of synthetic data for a stroke thrombolysis pathway data set using CTGAN Generative Advesarial Network (GAN). Tested using a logistic regression model.
## Aim
To test CT-Generative Advesarial Network (GAN) for synthesising data that can be used to train a logistic regression machine learning model.
Genera... | github_jupyter |
```
import featuretools as ft
from featuretools.primitives import Percentile
import composeml as cp
import pandas as pd
```
# Load in data
```
cyber_df = pd.read_csv("data/CyberFLTenDays.csv").sample(10000)
cyber_df.index.name = "log_id"
cyber_df.reset_index(inplace=True, drop=False)
cyber_df['label'] = cyber_df['lab... | github_jupyter |
```
import tensorflow as tf
import numpy as np
import time
import os
from sklearn.preprocessing import LabelEncoder
import re
import collections
import random
import pickle
maxlen = 20
location = os.getcwd()
num_layers = 3
size_layer = 256
learning_rate = 0.0001
batch = 100
with open('dataset-emotion.p', 'rb') as fopen... | github_jupyter |
# Beginner's Python—Session Three and Four Finance/Economics Exercises
## Inflation in Leamington
Run the code in the cell below to display Table 1. This table below contains 2016-2020 price data on the five products purchased by Leamington students that serve as a
representative “typical basket of goods”. We will us... | github_jupyter |
<figure>
<center>
<img src='https://raw.githubusercontent.com/alexsnowschool/Python-Basics/master/cover-ppt.png' width = '800px'/>
</center>
</figure>
## Assignment 1 (Pass >= 7)
**Assigned Date - 5 July 2020 (9:00 PM)**
**Self-Interactive Due Date - 11 July 2020 (11:59:59 AM)**
**Self-Paced Due Date - Infinity**
#... | github_jupyter |
# Qcodes+broadbean example with Tektronix AWG5208
```
%matplotlib notebook
from qcodes.instrument_drivers.tektronix.AWG5208 import AWG5208
import broadbean as bb
ramp = bb.PulseAtoms.ramp
sine = bb.PulseAtoms.sine
```
## Part 1: Make a complicated sequence
Keeping in mind that no waveform can be shorter than 2400 p... | github_jupyter |
# Astronomy 8824 - Numerical and Statistical Methods in Astrophysics
## Statistical Methods Topic V. Hypothesis Testing
These notes are for the course Astronomy 8824: Numerical and Statistical Methods in Astrophysics. It is based on notes from David Weinberg with modifications and additions by Paul Martini.
David's o... | github_jupyter |
- https://storage.googleapis.com/deepmind-media/dqn/DQNNaturePaper.pdf
- https://ai.intel.com/demystifying-deep-reinforcement-learning/
- https://danieltakeshi.github.io/2016/11/25/frame-skipping-and-preprocessing-for-deep-q-networks-on-atari-2600-games/
- https://github.com/AndersonJo/dqn-pytorch/blob/master/dqn.py
-... | github_jupyter |
# Torch Core
This module contains all the basic functions we need in other modules of the fastai library (split with [`core`](/core.html#core) that contains the ones not requiring pytorch). Its documentation can easily be skipped at a first read, unless you want to know what a given fuction does.
```
from fastai.gen_... | github_jupyter |
```
import tensorflow as tf
import tensorflow_probability as tfp
import numpy as np
import matplotlib.pyplot as plt
tfd = tfp.distributions
tfb = tfp.bijectors
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense
```
# Discretized Logistic Mixture Distribution
## Single Logistic Distri... | github_jupyter |
# Функции, распаковка аргументов
Функция в python - объект, принимающий аргументы и возвращающий значение. Обычно функция определяется с помощью инструкции def.
Определим простейшую функцию:
```
def add(x, y):
return x + y # Инструкция return возвращает значение.
print(add(1, 10))
print(add('abc', 'd... | github_jupyter |
# Autoencoder for Anomaly Detection with scikit-learn, Keras and TensorFlow
This script trains an autoencoder for anomaly detection. We use Python, scikit-learn, TensorFlow and Keras to prepare the data and train the model.
The input data is sensor data. Here is one example:
"Time","V1","V2","V3","V4","V5","V6","V7"... | github_jupyter |
```
import numpy as np
import pandas as pd
import torch
import torchvision
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from matplotlib import pyplot as plt
%matplotlib inline
from google.c... | github_jupyter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.