code
stringlengths
2.5k
150k
kind
stringclasses
1 value
<table class="ee-notebook-buttons" align="left"> <td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/FeatureCollection/column_statistics_by_group.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td> <td><a ...
github_jupyter
# Making journal-quality figures using Matplotlib ``` import numpy as np import pandas as pd import seaborn as sns sns.set(font_scale=1.4) %matplotlib inline import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.patches import ConnectionPatch import matplotlib.gridspec as gridspec from matplotlib...
github_jupyter
# <div align="center">BERT (Bidirectional Encoder Representations from Transformers) Explained: State of the art language model for NLP</div> --------------------------------------------------------------------- <img src='asset/9_6/main.png'> you can Find me on Github: > ###### [ GitHub](https://github.com/lev1khacha...
github_jupyter
# Customised Kernel of the ACBC (only trained with the score tensor generated from Integrated model.ipynb) ``` from sklearn.metrics import classification_report class MyModel: def __init__(self, w, lr): self.w = w self.size = w.shape[0] self.lr = lr def predict(self, x): ...
github_jupyter
``` """ Main application and routing logic """ # Standard imports import os # Database + Heroku + Postgres from dotenv import load_dotenv from flask import Flask, jsonify, request from flask_sqlalchemy import SQLAlchemy import psycopg2 from .models import DB, Strain from flask_cors import CORS # import model #from n...
github_jupyter
<a href="https://colab.research.google.com/github/mahfuz978/DS-Unit-1-Sprint-2-Data-Wrangling-and-Storytelling/blob/master/module1-join-and-reshape-data/Mahfuzur_Join_and_Reshape_Data_Assignment.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> _Lambd...
github_jupyter
# Real World Example: ### AI, Machine Learning & Data Science --- # What is the Value for your Business? - By seeing acutal examples you'll be empowered to ask the right questions (and get fair help from consultants, startups, or data analytics companies) - This will help you make the correct decisions for your b...
github_jupyter
# CW10: Ordinary Differential Equations Notes: - solution to a differential equation is a function or set of functions - Euler's Method serves as the basis for all others - The names of each method gives insight to how the functions look/behave graphically Solving a differential equation with initial condition: $dy...
github_jupyter
``` from sklearn.base import clone from itertools import combinations import numpy as np from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split class SBS(): def __init__(self, estimator, k_features, scoring=accuracy_score, test_size=0.25, random_state=1): ...
github_jupyter
## Importing Libraries ``` import numpy as np import pandas as pd import math import matplotlib.pyplot as plt import matplotlib as mpl import seaborn as sns from matplotlib.offsetbox import (AnchoredOffsetbox, TextArea) import statsmodels.formula.api as smf import requests import sklearn as skl from sklearn import dat...
github_jupyter
## Neural Networks in PyMC3 estimated with Variational Inference (c) 2016 by Thomas Wiecki ## Current trends in Machine Learning There are currently three big trends in machine learning: **Probabilistic Programming**, **Deep Learning** and "**Big Data**". Inside of PP, a lot of innovation is in making things scale us...
github_jupyter
This notebook is broken into two sections, firstly an introduction to the NumPy package and secondly a breakdown of the NumPy random package. # The NumPy Package ## What is it? NumPy is a Python package used for scientific computing. Often cited as a fundamental package in this area, this is for good reason. It pro...
github_jupyter
# 1.1 Getting started ## Prerequisites ### Installation This tutorial requires **signac**, so make sure to install the package before starting. The easiest way to do so is using conda: ```$ conda config --add channels conda-forge``` ```$ conda install signac``` or pip: ```pip install signac --user``` Please re...
github_jupyter
<a href="https://colab.research.google.com/github/DJCordhose/ml-workshop/blob/master/notebooks/tf-intro/2020-01-rnn-basics.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Sequences Basics Example, some code and a lot of inspiration taken from: ht...
github_jupyter
``` %load_ext autoreload %autoreload 2 !nvidia-smi from argparse import Namespace import sys import os home = os.environ['HOME'] os.environ['CUDA_VISIBLE_DEVICES'] = '0,1' print(os.environ['CUDA_VISIBLE_DEVICES']) os.chdir(f'{home}/pycharm/automl') # os.chdir(f'{home}/pycharm/automl/search_policies/rnn') sys.path.appe...
github_jupyter
SOP036 - Install kubectl command line interface =============================================== Steps ----- ### Common functions Define helper functions used in this notebook. ``` # Define `run` function for transient fault handling, suggestions on error, and scrolling updates on Windows import sys import os impor...
github_jupyter
<img align="left" src="https://lever-client-logos.s3.amazonaws.com/864372b1-534c-480e-acd5-9711f850815c-1524247202159.png" width=200> <br></br> <br></br> ## *Data Science Unit 4 Sprint 3 Assignment 1* # Recurrent Neural Networks and Long Short Term Memory (LSTM) ![Monkey at a typewriter](https://upload.wikimedia.org...
github_jupyter
``` """ A randomly connected network learning a sequence This example contains a reservoir network of 500 neurons. 400 neurons are excitatory and 100 neurons are inhibitory. The weights are initialized randomly, based on a log-normal distribution. The network activity is stimulated with three different inputs (A, B, ...
github_jupyter
## shuffle ### 计算机如何生成素数 只简单介绍一种方法,**线性同余法** $$N_{j+1} = (A*N_j + B) mod M $$ 其中A,B,M是设定的常数。$N_0$被叫做随机种子,是计算机主板的计数器在内存中的记数值。 从公式中可以看出$N_{j+1}$ 与 $N_j$ 存在线性。 线性同余法生成的是均匀分布,如果需要生成其他分布则是据此进行采样。 ### 那么如何随机打乱一个数组 1. 考虑一种方法:对于一个长度为n的数组,每次随机选取两个index,交换这两个index对应的数字。并将他们标记。循环直到数组中所有元素被处理 ``` import random def shuffl...
github_jupyter
# Basics ``` print("Hello World!") # This is comment! bread=10 print(bread) bread=input() bread 43+5 '43'+5 ``` **Find out the reason behind the above error.** **Tip**: Copy the error and search in [Google](https://www.google.com/). ``` 8 8+3 ``` ### Data Types Integers: -2, -1, 0, 1, 2, 3, 4, 5 Floating-point ...
github_jupyter
# Google form analysis visualizations ## Table of Contents ['Google form analysis' functions checks](#funcchecks) ['Google form analysis' functions tinkering](#functinkering) ``` %run "../Functions/1. Google form analysis.ipynb" ``` ## 'Google form analysis' functions checks <a id=funcchecks /> ## 'Google form a...
github_jupyter
``` from xml.etree import ElementTree from xml.dom import minidom from xml.etree.ElementTree import Element, SubElement, Comment, indent def prettify(elem): """Return a pretty-printed XML string for the Element. """ rough_string = ElementTree.tostring(elem, encoding="ISO-8859-1") reparsed = minidom.par...
github_jupyter
<a href="https://colab.research.google.com/github/NeuromatchAcademy/course-content/blob/master/tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Neuromatch Academy: Week 3, Day 2, Tutorial 1 # Neuronal N...
github_jupyter
``` import xarray as xr import pandas as pd from joblib import load import os import math from datetime import datetime,timedelta from sklearn import preprocessing def redondeo(coordenadas, base=1/12): """ Devuelve las coordenadas pasadas redondeadas Parametros: coordenadas -- lista de latitud y lo...
github_jupyter
# `sourmash tax` submodule ### for integrating taxonomic information The sourmash tax (alias `taxonomy`) commands integrate taxonomic information into the results of sourmash gather. tax commands require a properly formatted taxonomy csv file that corresponds to the database used for gather. For supported databases (...
github_jupyter
``` def preprocess_string(s): plaintext = '' for i in s: temp = ord(i) if ((temp < 123 and temp > 96) or (temp < 91 and temp > 64) or (temp < 58 and temp > 47) or temp == 32): plaintext += i return plaintext def char_to_bits(s, char_size = 4): if (char_size == 4):...
github_jupyter
# Import Libraries ``` import sys import pandas as pd import numpy as np from sklearn import preprocessing from sklearn.decomposition import PCA from sklearn import random_projection from sklearn.preprocessing import StandardScaler from sklearn.metrics import fbeta_score, roc_curve, auc from sklearn import svm impor...
github_jupyter
# AMPL Model Colaboratory Template [![colab.ipynb](https://img.shields.io/badge/github-%23121011.svg?logo=github)](https://github.com/ampl/amplcolab/blob/master/template/colab.ipynb) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/ampl/amplcolab/blob...
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
# Random Signals and LTI-Systems *This jupyter notebook is part of a [collection of notebooks](../index.ipynb) on various topics of Digital Signal Processing. Please direct questions and suggestions to [Sascha.Spors@uni-rostock.de](mailto:Sascha.Spors@uni-rostock.de).* ## Measurement of Acoustic Impulse Responses Th...
github_jupyter
``` import json import os import re import tqdm import random from PIL import Image %matplotlib inline from pycocotools.coco import COCO from pycocotools import mask as cocomask import numpy as np import skimage.io as io import matplotlib.pyplot as plt import pylab import random import os pylab.rcParams['figure.figsiz...
github_jupyter
# Lab 01 - Modelling and Systems Dynamics ``` import math, pandas from matplotlib import pyplot ``` ## Section 01 - Starting Jupyter Notebook ``` print(math.sin(4)) ``` ## Section 02 - Number and Arithmetic ``` print(5 / 8) print(5 / 8.0) # or print(5 / float(8)) print(5 * 8) print((1 / 2.0) ** 2) ``` ### Review ...
github_jupyter
# Visualize real data Get to know the real data ``` import pandas as pd import os import numpy as np import matplotlib.pyplot as plt import seaborn as sns savefolder = 'figures_real_data' folder = 'data' df = pd.read_excel(os.path.join(folder, '20211128 - Full DART Data (Model & Test).xlsx'), header=2) df.head() impo...
github_jupyter
``` import pandas as pd import matplotlib.pyplot as plt ppd_df = pd.read_csv("policedata/ppd_complaints.csv") display(ppd_df.head()) # Add date of complaint date_pattern = r"(\d{1,2}-\d{1,2}-\d{2,4})" #parentheses is to treat all characters as a "group", making extract work complaint_str_series = ppd_df['summary'].str....
github_jupyter
``` # Dependencies and Setup import pandas as pd import numpy as np # Load the file and set up the path for it purchase_data = "Resources/purchase_data.csv" # Read Purchasing File, store it in Panda frame, read the head of the file (first 5 items) purchase_data_df = pd.read_csv(purchase_data) purchase_data_df.head() pu...
github_jupyter
## TCLab Function Help ![connections.png](attachment:connections.png) #### Connect/Disconnect ```lab = tclab.TCLab()``` Connect and create new lab object, ```lab.close()``` disconnects lab. #### LED ```lab.LED()``` Percentage of output light for __Hot__ Light. #### Heaters ```lab.Q1()``` and ```lab.Q2()``` Percenta...
github_jupyter
# Face Generation In this project, you'll use generative adversarial networks to generate new images of faces. ### Get the Data You'll be using two datasets in this project: - MNIST - CelebA Since the celebA dataset is complex and you're doing GANs in a project for the first time, we want you to test your neural netwo...
github_jupyter
# Modeling and Simulation in Python Chapter 21 Copyright 2017 Allen Downey License: [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0) ``` # Configure Jupyter so figures appear in the notebook %matplotlib inline # Configure Jupyter to display the assigned value after an a...
github_jupyter
**Important**: This notebook is different from the other as it directly calls **ImageJ Kappa plugin** using the [`scyjava` ImageJ brige](https://github.com/scijava/scyjava). Since Kappa uses ImageJ1 features, you might not be able to run this notebook on an headless machine (need to be tested). ``` from pathlib impor...
github_jupyter
<a href="https://colab.research.google.com/github/NeuromatchAcademy/course-content-dl/blob/main/tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Tutorial 1: PyTorch **Week 1, Day 1: Basics and ...
github_jupyter
### 1 - e-posta baten histograma Ahalik eta funtzio gehien sortuko ditugu, azpiproblema bakoitza funtzio beten bidez adierazteko. Adibidez: * e-posta batetako testua, ilara zerrenda moduan (goiburua deskartatu) * hitz batetako ertzetatik puntuazio zeinuak kendu * hitz bat soilik karaktere alfabetikoez osotua ote dago...
github_jupyter
# Classification metrics Author: Geraldine Klarenberg Based on the Google Machine Learning Crash Course ## Tresholds In previous lessons, we have talked about using regression models to predict values. But sometimes we are interested in **classifying** things: "spam" vs "not spam", "bark" vs "not barking", etc. Log...
github_jupyter
``` from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap from matplotlib import animation from IPython.display import HTML import numpy as np from sklearn.datasets import make_blobs from sklearn.cluster import KMeans %matplotlib inline # Set up colors: color_map = ListedColormap(['#1b9e77',...
github_jupyter
``` # Name: example_analysis_data_creation.ipynb # uthors: Stephan Meighen-Berger # Example how to construct a data set to use for later analyses # General imports import numpy as np import matplotlib.pyplot as plt import sys from tqdm import tqdm import pickle # Adding path to module sys.path.append("../") # picture p...
github_jupyter
# Case: Impact of p_negative Situation: - 70% agent availability on weekdays and weekends Task: - Evaluate Shift Coverage over p_negative: [.001, .0025, .005, .0075, .01, .02, .03, .05, .1, .2] - Evaluate Agent Satisfaction over p_negative: [.001, .0025, .005, .0075, .01, .02, .03, .05, .1, .2] ``` import abm_sched...
github_jupyter
# First Attempt batch size 256 lr 1e-3 ### Import modules ``` %matplotlib inline from __future__ import division import sys import os os.environ['MKL_THREADING_LAYER']='GNU' sys.path.append('../') from Modules.Basics import * from Modules.Class_Basics import * ``` ## Options ``` classTrainFeatures = basic_features ...
github_jupyter
# Programming Assignment ## Готовим LDA по рецептам Как вы уже знаете, в тематическом моделировании делается предположение о том, что для определения тематики порядок слов в документе не важен; об этом гласит гипотеза <<мешка слов>>. Сегодня мы будем работать с несколько нестандартной для тематического моделирования к...
github_jupyter
# Reading Notebooks * https://nbformat.readthedocs.io/en/latest/api.html ## Read a .ipynb file A notebook consists of metadata, format info, and a list of cells. Very simple. ``` import nbformat from nbformat.v4.nbbase import new_code_cell, new_markdown_cell, new_notebook # read notebook file filename = "02.01-Tag...
github_jupyter
# Paginación El objetivo es crear una lista de páginas a mostrar. Se mostrará la página actual y las 3 siguientes y las 3 anteriores, y además la primera y la última. El algoritmo debe calcular qué numeros se muestran, y crear una lista con ellos. Además se pondrán espacios en blanco en el lugar donde irán los puntos ...
github_jupyter
``` #Author: Eren Ali Aslangiray, Meryem Şahin import pandas as pd import os import time import sys path1 = "/Users/erenmac/Desktop/NEW_DATA/Text/text_emotion.csv" path2 = "/Users/erenmac/Desktop/NEW_DATA/Text/primary-plutchik-wheel-DFE.csv" path3 = "/Users/erenmac/Desktop/NEW_DATA/Text/ssec-aggregated/train-combined-...
github_jupyter
``` %matplotlib inline import matplotlib from matplotlib import pyplot as plt import seaborn as sns from IPython.display import set_matplotlib_formats set_matplotlib_formats('retina') sns.set(rc={'figure.figsize':(11.7,8.27)}) sns.set_palette(sns.color_palette()) import pandas as pd import pickle from mcmcjoint.sampl...
github_jupyter
``` import os, re import pandas as pd import numpy as np import requests from bs4 import BeautifulSoup import time import json URL_LIST_BASE = "https://www.dogbreedslist.info/all-dog-breeds/list_1_{}.html" # {} in [1, 19] def get_dog_list_page(n): r = requests.get(URL_LIST_BASE.format(n)) soup = BeautifulSoup(...
github_jupyter
## Dependencies ``` import json, glob from tweet_utility_scripts import * from tweet_utility_preprocess_roberta_scripts_aux import * from transformers import TFRobertaModel, RobertaConfig from tokenizers import ByteLevelBPETokenizer from tensorflow.keras import layers from tensorflow.keras.models import Model ``` # L...
github_jupyter
``` %matplotlib inline from refer import REFER import numpy as np import skimage.io as io import matplotlib.pyplot as plt ``` # Load Refer Dataset ``` data_root = '../../data' # contains refclef, refcoco, refcoco+, refcocog and images dataset = 'refcoco' splitBy = 'unc' refer = REFER(data_root, dataset, splitBy) ```...
github_jupyter
# Binary trees ``` import matplotlib.pyplot as plt from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor from dtreeviz.trees import * from lolviz import * import numpy as np import pandas as pd %config InlineBackend.figure_format = 'retina' ``` ## Setup Make sure to install stuff: ``` pip install...
github_jupyter
``` # reload packages %load_ext autoreload %autoreload 2 ``` ### Choose GPU (this may not be needed on your computer) ``` %env CUDA_DEVICE_ORDER=PCI_BUS_ID %env CUDA_VISIBLE_DEVICES='' ``` ### load packages ``` from tfumap.umap import tfUMAP import tensorflow as tf import numpy as np import matplotlib.pyplot as plt...
github_jupyter
# Train and hyperparameter tune with RAPIDS ## Prerequisites - Create an Azure ML Workspace and setup environmnet on local computer following the steps in [Azure README.md](https://gitlab-master.nvidia.com/drobison/aws-sagemaker-gtc-2020/tree/master/azure/README.md ) ``` # verify installation and check Azure ML SDK ...
github_jupyter
``` import sys sys.executable ``` [Optional]: If you're using a Mac/Linux, you can check your environment with these commands: ``` !which pip3 !which python3 !ls -lah /usr/local/bin/python3 ``` ``` !pip3 install -U pip !pip3 install torch==1.3.0 !pip3 install seaborn import torch torch.cuda.is_available() # IPython ...
github_jupyter
``` import pandas as pd import numpy as np from math import sqrt from numpy import concatenate from matplotlib import pyplot from pandas import read_csv from pandas import DataFrame from pandas import concat from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import LabelEncoder from sklearn.metri...
github_jupyter
``` import matplotlib.pyplot as plt import pandas as pd import numpy as np import xarray as xr import scipy import os from sklearn.decomposition import PCA from sklearn.linear_model import LinearRegression from sklearn.linear_model import QuantileRegressor from sklearn.metrics import mean_absolute_error from sklearn.me...
github_jupyter
# DBSCAN without Libraries ``` import time import warnings import queue import numpy as np import pandas as pd from sklearn import cluster, datasets, mixture from sklearn.neighbors import kneighbors_graph from sklearn import datasets # from sklearn.datasets import make_blobs from sklearn.preprocessing import Standar...
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
<h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Preamble" data-toc-modified-id="Preamble-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Preamble</a></span><ul class="toc-item"><li><span><a href="#Some-general-parameters" data-toc-modified-id="Some-gen...
github_jupyter
# BiDirectional LSTM classifier in keras #### Load dependencies ``` import keras from keras.datasets import imdb from keras.preprocessing.sequence import pad_sequences from keras.models import Sequential from keras.layers import Embedding, SpatialDropout1D, Dense, Flatten, Dropout, LSTM from keras.layers.wrappers imp...
github_jupyter
``` import numpy as np import matplotlib.pyplot as plt from skimage.color import rgb2gray from skimage.filters import gaussian import scipy import cv2 from scipy import ndimage import Image_preperation as prep import FitFunction as fit import FileManager as fm import Image_preperation as prep def calc_mean(points)...
github_jupyter
# Homework (15 pts) - Classification ``` # Questions are based on the mouse cortex protein expression level dataset used in lecture. # The Data_Cortex_Nuclear.csv file is available in the same folder as this notebook # or at https://www.kaggle.com/ruslankl/mice-protein-expression import pandas as pd import numpy as np...
github_jupyter
# Assignment 2: Parts-of-Speech Tagging (POS) Welcome to the second assignment of Course 2 in the Natural Language Processing specialization. This assignment will develop skills in part-of-speech (POS) tagging, the process of assigning a part-of-speech tag (Noun, Verb, Adjective...) to each word in an input text. Tag...
github_jupyter
### Dependencies for this notebook: * pip install spacy, pandas, matplotlib * python -m spacy.en.download ``` from IPython.display import SVG, display import spacy import pandas as pd import matplotlib.pyplot as plt from datetime import datetime %matplotlib inline #encode some text as uncode text = u"I'm executing thi...
github_jupyter
``` from IPython.core.display import display, HTML display(HTML("<style>.container { width:100% !important; }</style>")) ``` # Unpacking the paper - CATEGORICAL REPARAMETERIZATION WITH GUMBEL-SOFTMAX * https://arxiv.org/pdf/1611.01144.pdf ## Introduction * Not much to get here ## THE GUMBEL-SOFTMAX Distribution ...
github_jupyter
# Sentiment Analysis ## Using XGBoost in SageMaker _Deep Learning Nanodegree Program | Deployment_ --- As our first example of using Amazon's SageMaker service we will construct a random tree model to predict the sentiment of a movie review. You may have seen a version of this example in a pervious lesson although ...
github_jupyter
``` __name__ = "k1lib.callbacks" #export from .callbacks import Callback, Callbacks, Cbs import k1lib, os, torch __all__ = ["Autosave", "DontTrainValid", "InspectLoss", "ModifyLoss", "Cpu", "Cuda", "DType", "InspectBatch", "ModifyBatch", "InspectOutput", "ModifyOutput", "Beep"] #export @k1lib.pat...
github_jupyter
# DataFrame & Series Di Pandas terdapat 2 kelas data baru yang digunakan sebagai struktur dari spreadsheet: 1. Series: satu kolom bagian dari tabel dataframe yang merupakan 1 dimensional numpy array sebagai basis datanya, terdiri dari 1 tipe data (integer, string, float, dll). 2. DataFrame: gabungan dari Series, be...
github_jupyter
``` from aide_design.play import* from aide_design import floc_model as floc from aide_design import cdc_functions as cdc from aide_design.unit_process_design.prefab import lfom_prefab_functional as lfom from pytexit import py2tex import math ``` # 1 L/s Plants in Parallel # CHANCEUX ## Priya Aggarwal, Sung Min Kim, ...
github_jupyter
``` import sqlite3 conn = sqlite3.connect('nominations.db') #Checking Schema schema = conn.execute("pragma table_info(nominations)") schema.fetchall() first_ten = conn.execute("select * from nominations limit 10").fetchall() for i in first_ten: print(i) #Creating a ceremonies table that contains the list of tuples...
github_jupyter
``` ''' # IoU_old usage of loss func criterion = nn.NLLLoss() def step(x, y, is_train=True): x = x.reshape(-1, 28 * 28) y_pred = model(x) loss = criterion(y_pred, y) if is_train: opt.zero_grad() loss.backward() opt.step() return loss, y_pred ''' torch.nn.Module class IoU_old(n...
github_jupyter
``` import h5py import keras import numpy as np import json import os import uuid import yaml from attlayer import AttentionWeightedAverage #from avglayer import MaskAverage from copy import deepcopy #from finetuning import (sampling_generator, finetuning_callbacks) from operator import itemgetter #from global_variabl...
github_jupyter
**Import libraries** ``` import os import logging import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import Subset, DataLoader from torch.backends import cudnn import torch.utils.data import torchvision from torchvision import transforms from torchvision.models import alexnet from t...
github_jupyter
# Reset Put Option A reset put option is similar to a standard put option except that the exercise price is reset equal to the stock price on the pre-specified reset date if this stock price exceeds the original exercise price. Unlike the standard put option, a Reset put option has a stochastic strike price. On issue ...
github_jupyter
``` from pysead import Truss_2D import numpy as np from random import random import matplotlib.pyplot as plt # initialize node dictionary nodes = {} # compute distances distances_1 = np.arange(0,5*240,240) distances_2 = np.arange(0,9*120,120) # from node 1 to node 5 for i, distance in enumerate(distances_1): node...
github_jupyter
``` import os import sys import keras import numpy as np import tensorflow as tf from keras import datasets import matplotlib import matplotlib.pyplot as plt sys.path.append(os.getcwd() + "/../") from bfcnn import BFCNN, collage, get_conv2d_weights # setup environment os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" tf.compa...
github_jupyter
### OkCupid DataSet: Classify using combination of text data and metadata ### Meeting 5, 03- 03- 2020 ### Recap last meeting's decisions: <ol> <p>Meeting 4, 28- 01- 2020</p> <li> Approach 1: </li> <ul> <li>Merge classs 1, 3 and 5</li> <li>Under sample class 6 </li> <li> Merge classes 6, 7, 8</li>...
github_jupyter
# Task 4: Classification _All credit for the code examples of this notebook goes to the book "Hands-On Machine Learning with Scikit-Learn & TensorFlow" by A. Geron. Modifications were made and text was added by K. Zoch in preparation for the hands-on sessions._ # Setup First, import a few common modules, ensure Matp...
github_jupyter
# "Build Your First Neural Network with PyTorch" * article <https://curiousily.com/posts/build-your-first-neural-network-with-pytorch/> * dataset <https://www.kaggle.com/jsphyg/weather-dataset-rattle-package> requires `torch 1.4.0` ``` import os from os.path import dirname import numpy as np import pandas as p...
github_jupyter
# Scraping transfermarkt by html ``` from selenium.webdriver import (Chrome, Firefox) import time import requests from bs4 import BeautifulSoup from html_scraper import db players = db['players'] player_urls = db['player_urls'] browser = Firefox() url = 'https://www.transfermarkt.co.uk/primera-division/startseite/wet...
github_jupyter
``` import itertools import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import NullFormatter import pandas as pd import numpy as np import matplotlib.ticker as ticker from sklearn import preprocessing %matplotlib inline # Load Data From CSV File df = pd.read_csv('AnimeList.csv') cols_id = list(df...
github_jupyter
``` import pandas as pd import numpy as np import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout,Activation,BatchNormalization from tensorflow.keras.callbacks import ModelCheckpoint import matplotlib.pyplot as plt %mat...
github_jupyter
``` import collections import json import pprint from datetime import datetime import pandas as pd # Notebook to generate attack tree Graphviz file and Emacs Org mode # table for attack tree analysis configuration. The input is itemized # list of attack tree nodes with mark modifiers. # Should use Python3.4+ # Name ...
github_jupyter
``` "Uni Face mask model" #some important packages from tensorflow.keras.applications.mobilenet_v2 import preprocess_input from tensorflow.keras.preprocessing.image import img_to_array from tensorflow.keras.models import model_from_json from tensorflow.keras.models import load_model from imutils.video import VideoStrea...
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
# Convolutional Neural Networks: Application Welcome to Course 4's second assignment! In this notebook, you will: - Implement helper functions that you will use when implementing a TensorFlow model - Implement a fully functioning ConvNet using TensorFlow **After this assignment you will be able to:** - Build and t...
github_jupyter
``` %matplotlib inline import pandas as pd import xgboost as xgb import numpy as np from sklearn.metrics import accuracy_score import matplotlib.pyplot as plt import graphviz from sklearn.preprocessing import LabelEncoder data = pd.read_csv("data/telco-churn.csv") data.head() data.shape data.drop('customerID', axis = 1...
github_jupyter
# Slow Stochastic ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import warnings warnings.filterwarnings("ignore") # yfinance is used to fetch data import yfinance as yf yf.pdr_override() # input symbol = 'AAPL' start = '2018-08-01' end = '2019-01-01' # Read data df = yf.download(symbo...
github_jupyter
# ロジスティック写像 $$ f(x, a) = a x (1 - x) $$ ``` import numpy as np import pathfollowing as pf import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline sns.set('poster', 'whitegrid', 'dark', rc={"lines.linewidth": 2, 'grid.linestyle': '-'}) def func(x, a): return np.array([a[0] * x[0] * (1.0 - x[0])]) ...
github_jupyter
## Part 2: Introduction to Feed Forward Networks ### 1. What is a neural network? #### 1.1 Neurons A neuron is software that is roughly modeled after the neuons in your brain. In software, we model it with an _affine function_ and an _activation function_. One type of neuron is the perceptron, which outputs a bina...
github_jupyter
``` import gc import locale import pickle import os import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from matplotlib.colors import ListedColormap from all_stand_var import conv_dict, lab_cols, used_cols from all_own_funct import cnfl, value_filtering,y_modelling,x_modelling,...
github_jupyter
<h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Scale-heights-for-typical-atmospheric-soundings" data-toc-modified-id="Scale-heights-for-typical-atmospheric-soundings-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Scale heights for typical atmospheric...
github_jupyter
``` import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import warnings warnings.filterwarnings("ignore") %matplotlib inline sns.set_style('whitegrid') from sklearn.linear_model import LogisticRegression from sklearn.metrics import classification_report from sklearn.metrics impo...
github_jupyter
``` import tensorflow as tf print(tf.__version__) import tensorflow_datasets as tfds print(tfds.__version__) ``` # Get dataset ``` SPLIT_WEIGHTS = (8, 1, 1) splits = tfds.Split.TRAIN.subsplit(weighted=SPLIT_WEIGHTS) (raw_train, raw_validation, raw_test), metadata = tfds.load('cats_vs_dogs', ...
github_jupyter
``` #default_exp tabular.core #export from fastai2.torch_basics import * from fastai2.data.all import * from nbdev.showdoc import * #export pd.set_option('mode.chained_assignment','raise') ``` # Tabular core > Basic function to preprocess tabular data before assembling it in a `DataLoaders`. ## Initial preprocessing...
github_jupyter
# Optimización Author: Jesús Cid-Sueiro Jerónimo Arenas-García Versión: 0.1 (2019/09/13) 0.2 (2019/10/02): Solutions added ## Exercise: compute the minimum of a real-valued function The goal of this exercise is to implement and test optimization algorithms for the minimization o...
github_jupyter