text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
# QDAE (Quantized Distribution Auto Encoder) Basic question: Can we learn latent variable probability distribution? Here we have single scalar value AE, so a very rudimentary problem. x -> qd(h) -> h' -> x_bar qd(h) is a quantized probability distribution of the latent variable h h' is a weighted sum of qd(h) where ...
github_jupyter
``` %matplotlib inline import numpy as np import time import tensorflow as tf from tensorflow import keras import sys sys.path.append("..") import d2lzh_tensorflow2 as d2l def get_data_ch7(): # 本函数已保存在d2lzh_tensorflow2包中方便以后使用 data = np.genfromtxt('../../data/airfoil_self_noise.dat', delimiter='\t') data = (...
github_jupyter
# note: * [covariance matrix](http://docs.scipy.org/doc/numpy/reference/generated/numpy.cov.html) * [multivariate_normal](http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.multivariate_normal.html) * [seaborn bivariate kernel density estimate](https://stanford.edu/~mwaskom/software/seaborn/generated/sea...
github_jupyter
# Lists The data structures that we use most often in data science are: * arrays, from `numpy`; * data frames, from `pandas`. There is another data structure for containing sequences of values - the `list`. You have already seen these in passing, when we created arrays. Now we cover them in more detail. ## Creati...
github_jupyter
# Deep Neural Network for Image Classification: Application When you finish this, you will have finished the last programming assignment of Week 4, and also the last programming assignment of this course! You will use use the functions you'd implemented in the previous assignment to build a deep network, and apply i...
github_jupyter
# Scraping Elsevier Metadata This notebook is used for pulling metadata from articles via Scopus' literature search. It can technically be used to scrape abstracts from anywhere within Scopus' database, but we've specifically limited it to Elsevier journals as that is the only journal that we have access to the fullte...
github_jupyter
``` import torch from torch import nn import torchvision from torchvision.datasets import ImageFolder from torchvision import transforms from torch.utils.data import DataLoader from pathlib import Path from torchvision.models import resnet101 import sys sys.path.append("..") from video_classification.datasets import...
github_jupyter
``` import os os.chdir("..") """ Iterate over the PubMED articles that mention infecious diseases from the disease ontology. """ import rdflib from pylru import lrudecorator import pubcrawler.article as pubcrawler from annotator.keyword_annotator import KeywordAnnotator from annotator.annotator import AnnoDoc import re...
github_jupyter
## Preliminaries ``` %matplotlib inline import pandas as pd import matplotlib.pyplot as plt import numpy as np import math # Set ipython's max row display pd.set_option('display.max_row', 1000) # Set iPython's max column width to 50 pd.set_option('display.max_columns', 50) ``` ## Create dataframe ``` df = pd.read_...
github_jupyter
# About This Notebook This notebook shows how to implement **Low-Rank Tensor Completion with Truncated Nuclear Norm minimization (LRTC-TNN)** on some real-world data sets. For an in-depth discussion of LRTC-TNN, please see our article [1]. <div class="alert alert-block alert-info"> <font color="black"> <b>[1]</b> Xin...
github_jupyter
# Sequence Parameters ## *Sequence Type*: predefined sequence or waveform upload? Many use cases require the freedom to define waveforms on a sample-basis. The `"Simple"` sequence type provided by the `zhinst-toolkit` allows for exactly that. If the *Simple* sequence is configured, the user can add waveforms to a que...
github_jupyter
# ChainerRL Quickstart Guide This is a quickstart guide for users who just want to try ChainerRL for the first time. If you have not yet installed ChainerRL, run the command below to install it: ``` pip install chainerrl ``` If you have already installed ChainerRL, let's begin! First, you need to import necessary m...
github_jupyter
``` import os import fnmatch import pprint import csv from tqdm import tqdm import numpy as np import pandas as pd import scipy.io as sio from scipy.linalg import sqrtm from analysis_clustering_helpers import get_cvfold_crossmodal_recon cvsets_pth = './data/results/patchseq/reconstructions/' metadata_file = './data/...
github_jupyter
``` import tensorflow as tf import tensorflow.contrib.layers as layers from sklearn import datasets import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error from sklearn.metrics import r2_score imp...
github_jupyter
# Portfolio Management with Amazon SageMaker RL Portfolio management is the process of constant redistribution of a capital into a set of different financial assets. Given the historic prices of a list of stocks and current portfolio allocation, the goal is to maximize the return while restraining the risk. In this de...
github_jupyter
<a href="https://colab.research.google.com/github/Katonokatono/Term-Deposit-Project/blob/Hypothesis-Testing/Term_Deposit_Hypothesis_Testing_Module1_Prj.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` #Import right libraries import scipy.stats a...
github_jupyter
``` %load_ext autoreload %autoreload 2 from pathlib import Path import sys parent_path = str(Path().joinpath('..').resolve()) sys.path.append(parent_path) from triple_agent.parsing.replay.get_parsed_replays import get_parsed_replays from triple_agent.constants.paths import REPLAY_PICKLE_FOLDER from triple_agent.classes...
github_jupyter
# idftshift function ### Undoes the effects of iafftshift. HS = dftshift(H). HS: Image. H: Image. DFT image with (0,0) in the center. ``` %matplotlib inline import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import sys,os ia898path = os.path.abspath('/etc/jupyterhub/ia898_1s2017/')...
github_jupyter
# Breaking daily ranges ``` import pandas as pd from datetime import timedelta, date start_date = date(year=2021, month=9, day=1) end_date = date(year=2021, month=11, day=1) d1=pd.date_range(start_date, end_date, freq="W-FRI") d1 d2=pd.date_range(start_date, end_date, freq="W-MON") d2 ranges=[] ranges.append((pd.Times...
github_jupyter
# Midterm #2 Solution ``` import numpy as np import pandas as pd import statsmodels.api as sm data = pd.read_excel('data/assetclass_data_monthly_2009.xlsx',index_col='Dates').loc['2012-01-31':] exret = (data.subtract(data['Cash'],axis=0)).drop('Cash',axis=1) exret # 1.1.a means = exret.mean()*12 display(means) stds = ...
github_jupyter
# Debug ``` # trying to find a potential bug --> but things look correct # #!!! # check that Protein_2_Function_and_Score_DOID_BTO_GOCC_STS_backtracked.txt has no redundant ENSP 2 function associations with different Scores # ENSP = "9606.ENSP00000340944" # funcName = "GO:0016020" # membrane # # PTPN11 (ENSP000003409...
github_jupyter
## Train a Scikit-Learn Model using SageMaker Script Mode #### Bring Your Own Script (BYOS) ### Create Train Script ``` %%file train.py from sklearn.neighbors import KNeighborsClassifier from os.path import join from io import BytesIO import pandas as pd import numpy as np import argparse import logging import pickle...
github_jupyter
# Stiffness in Initial Value Problems Copyright (C) 2020 Andreas Kloeckner <details> <summary>MIT License</summary> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including ...
github_jupyter
# Python Text Basics Assessment Welcome to your assessment! Complete the tasks described in bold below by typing the relevant code in the cells.<br> You can compare your answers to the Solutions notebook provided in this folder. ## f-Strings #### 1. Print an f-string that displays `NLP stands for Natural Language Pro...
github_jupyter
``` import pandas as pd import numpy as np import datetime import matplotlib.pyplot as plt from sqlalchemy import create_engine, inspect engine = create_engine("sqlite:///../Resources/hawaii.sqlite") #Data inspection inspector = inspect(engine) print(inspector.get_table_names()) columns = inspector.get_columns("measur...
github_jupyter
# Interactome Construction and Analysis Get data from local database and create the interactome ``` #Include libraries import MySQLdb import networkx as nx from matplotlib import pylab as plt import numpy as np %matplotlib inline def get_ppi(lcc): ''' Main function to extract the PPI from our local database. ...
github_jupyter
## What is Datashader? **Datashader turns even the largest datasets into images, faithfully preserving the data's distribution.** Datashader is an [open-source](https://github.com/bokeh/datashader/) Python 2 and 3 library for analyzing and visualizing large datasets. Specifically, Datashader is designed to "rasterize...
github_jupyter
<h1>Understanding the Computation for Alpha and creating a function</h1> ``` import numpy as np import matplotlib.pyplot as plt from scipy import fft import netCDF4 as nc import cftime import matplotlib.animation as animation %matplotlib widget # Get Data set from mission due to better notes on when in breaking miss...
github_jupyter
``` # Copyright 2020 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
``` import pandas as pd import numpy as np import missingno as msno import matplotlib.pyplot as plt ``` ### Load training data (from the starter notebook) ``` # this bit thanks to Brendon Hall s3_train_csv = 's3://zarr-depot/wells/FORCE: Machine Predicted Lithology/train.csv' data = pd.read_csv(s3_train_csv, sep=';')...
github_jupyter
# QUESTIONS TO SUBJECT CLASSIFICATION ### Link to the Dataset: [Questions Data](https://www.kaggle.com/mrutyunjaybiswal/iitjee-neet-aims-students-questions-data) ### Importing Libraries ``` import pandas as pd from sklearn import preprocessing import nltk nltk.download('stopwords') # download the st...
github_jupyter
``` from matplotlib import pyplot as plt import numpy as np from scipy.optimize import curve_fit ``` # Task 1 Данные: ``` urea = np.array([0, 3e-4, 5e-4, 1e-3, 2e-3, 3e-3, 5e-3]) mid_speed = np.array([0, 0.5, 0.77, 1.2, 1.57, 1.8, 1.9]) delta_speed = np.array([0, 0.05, 0.06, 0.08, 0.08, 0.09, 0.2]) ``` График завис...
github_jupyter
# Time Series Prediction **Objectives** 1. Build a linear, DNN and CNN model in Keras. 2. Build a simple RNN model and a multi-layer RNN model in Keras. In this lab we will with a linear, DNN and CNN model Since the features of our model are sequential in nature, we'll next look at how to build various RNN model...
github_jupyter
# Counterfactual explanations with one-hot encoded categorical variables Real world machine learning applications often handle data with categorical variables. Explanation methods which rely on perturbations of the input features need to make sure those perturbations are meaningful and capture the underlying structure...
github_jupyter
# {glue:text}`jupyter_github_org` **Activity from {glue:}`jupyter_start` to {glue:}`jupyter_stop`** ``` from datetime import date from dateutil.relativedelta import relativedelta from myst_nb import glue import seaborn as sns import pandas as pd import numpy as np import altair as alt from markdown import markdown fr...
github_jupyter
# XOR Prediction Neural Network #### A simple neural network which will learn the XOR logic gate. I will provide you with any links necessary so that you can read about the different aspects of this NN(Neural Network). ## Neural Network Info #### All information regarding the neural network: - Input Layer Units = 2...
github_jupyter
# Word segmentation of Lao bibliographic data Install packages not available in Google Colab. ``` #!pip install laonlp #!pip install pyicu #!pip install pythainlp #!pip install botok import sys import regex as re import pandas as pd from laonlp.tokenize import word_tokenize as lao_wt from pythainlp.tokenize import wo...
github_jupyter
# Predict rating of review using BoardGameGeek Reviews dataset **The goal of this project is to use the corpus of reviews present in this dataset, learn the reviews and their corresponding rating.** **Once the model is trained using the review data, we ask the user to input a new review and predict the rating of that...
github_jupyter
## 疫情数据分析和预测 疫情数据分析和预测是医学和流行病学应对大范围流行病时的重要判断手段,在医治隔离、预防响应、物资生产调配等抗疫措施上起到参考作用。 以下将通过已知模型尝试寻找合适拟合模型并对目前全球疫情发展作出一定程度的预测。 ### 一、逻辑斯蒂模型(Logistic) (1)模型描述:当一个物种迁入到一个新生态系统中后,其数量会发生变化。假设该物种的起始数量小于环境的最大容纳量,则数量会增长。该物种在此生态系统中有天敌、食物、空间等资源也不足(非理想环境),则增长函数满足逻辑斯谛方程,图像呈S形,此方程是描述在资源有限的条件下种群增长规律的一个最佳数学模型。 (2)一般疾病的传播是S型增长的过程,因为疾病传播的...
github_jupyter
# Leave-K-Studies-Out Analysis - This jupyter notebook is available on-line at: - https://github.com/spisakt/RPN-signature/blob/master/notebooks/4_leave-k-studies-out.ipynb - Input data for the notebook and non-standard code (PAINTeR library) is available in the repo: - https://github.com/spisakt/RPN-signature - Ra...
github_jupyter
# Taylor Problem 16.14 version A We'll plot at various times a wave $u(x,t)$ that is defined by its initial shape at $t=0$ from $x=0$ to $x=L$, using a Fourier sine series to write the result at a general time t: $\begin{align} u(x,t) = \sum_{n=1}^{\infty} B_n \sin(k_n x)\cos(\omega_n t) \;, \end{align}$ with $...
github_jupyter
``` import ipywidgets as widgets from ipywidgets import Accordion, HBox from ipywidgets import FileUpload, Button from ipyfilechooser import FileChooser import json import html metadata={} def _observe_elec_config(change): print('_observe_elec_config') metadata[ widget_elec_config.description] = widget_elec_co...
github_jupyter
``` import numpy as np from scipy.stats import norm from scipy.optimize import curve_fit import matplotlib.pyplot as plt # Beginning in one dimension: # mean = 0; Var = 1; N = 100 # scatter = np.random.normal(mean,np.sqrt(Var),N) # scatter = np.sort(scatter) t = [189.6071000099182, 191.2862000465393, 191.9226999282837...
github_jupyter
# Lecture 06: Examples and overview [Download on GitHub](https://github.com/NumEconCopenhagen/lectures-2021) [<img src="https://mybinder.org/badge_logo.svg">](https://mybinder.org/v2/gh/NumEconCopenhagen/lectures-2021/master?urlpath=lab/tree/06/Examples_and_overview.ipynb) 1. [Recap](#Recap) 2. [The consumer problem...
github_jupyter
# Computing the Bayesian Hilbert Transform-DRT In this tutorial example, we will illustrate how the BHT-DRT model works for impedance data that is unbounded. The real experimental data was from the following article: Wu et al. Dual-phase MoS2 as a high-performance sodium-ion battery anode. Journal of Materials Chemist...
github_jupyter
# Document retrieval from wikipedia data # Fire up GraphLab Create ``` import graphlab ``` # Load some text data - from wikipedia, pages on people ``` people = graphlab.SFrame('people_wiki.gl/') ``` Data contains: link to wikipedia article, name of person, text of article. ``` people.head() len(people) ``` # Ex...
github_jupyter
# Genotype data preprocessing This section documents output from the genotype section (colored in light yellow) of command generator MWE and explained the purpose for each of the command. The file used in this page can be found at [here](https://drive.google.com/drive/folders/16ZUsciZHqCeeEWwZQR46Hvh5OtS8lFtA?usp=shari...
github_jupyter
# Lesson 7 Class Exercises: Matplotlib With these class exercises we learn a few new things. When new knowledge is introduced you'll see the icon shown on the right: <span style="float:right; margin-left:10px; clear:both;">![Task](../media/new_knowledge.png)</span> ## Get Started Import the Numpy, Pandas, Matplotli...
github_jupyter
``` import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from math import ceil import sklearn.datasets def prepare_swissroll_data(BATCH_SIZE=1000): ''' This is derived from https://github.com/lukovnikov/improved_wgan_training/blob/master/gan_toy.py Copyright (c) 2017 Ishaan Gulrajani...
github_jupyter
# Tutorial de Python Tutorial de Python 3.6 ## Tipos de dados Em python você não precisa declarar as variaveis e nem especificar o tipo dela. Uma mesma variável também pode receber dados de tipos diferentes. ``` # Mesma variável recebendo tipos diferentes var = 5 print(var) var = "oi" print(var) var = 3.14 print...
github_jupyter
# Make sentence evaluation sample dataset We want to sanity check the accuracy of the [ArgumenText](https://api.argumentsearch.com/en/doc) API. One way to do this is spot checks on the results, and using those spot checks to estimate precision and recall. **Precision** Also known as "positive predictive value." O...
github_jupyter
``` import matplotlib.pyplot as plt from sklearn import datasets from sklearn.decomposition import PCA from sklearn.discriminant_analysis import LinearDiscriminantAnalysis iris = datasets.load_iris() X = iris.data #raw data Y = iris.target #known groups (only for supervised analysis, I think) target_names = iris.targ...
github_jupyter
#Video Overlay Add images, text, and audio to videos. #License Copyright 2020 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 req...
github_jupyter
# __DATA 5600: Introduction to Regression and Machine Learning for Analytics__ ## __Notes on the Bayesian Beta-Bernoulli Conjugate Model__ <br> Author: Tyler J. Brough <br> Last Update: September 13, 2021 <br> <br> ``` import numpy as np from scipy import stats import seaborn as sns import matplotlib.pyplot as...
github_jupyter
<a href="https://colab.research.google.com/github/predicthq/phq-data-science-docs/blob/master/academic-events/part_1_data_engineering.ipynb" target="_blank"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ##### Academic Events Data Science Guides # Part 1: Data Engineerin...
github_jupyter
# Using sci-analysis From the python interpreter or in the first cell of a Jupyter notebook, type: ``` import warnings warnings.filterwarnings("ignore") import numpy as np import scipy.stats as st from sci_analysis import analyze ``` This will tell python to import the sci-analysis function ``analyze()``. > Note: A...
github_jupyter
# Using `astropy.coordinates` to Match Catalogs and Plan Observations ## Authors Erik Tollerud, Kelle Cruz ## Learning Goals * TBD ## Keywords coordinates, catalog matching, observational astronomy, astroquery ## Summary In this tutorial, we will explore how the `astropy.coordinates` package and related astropy fun...
github_jupyter
# Simple SPACE model example Written by Charles M. Shobe to accompany the following publication: Shobe, C.M., Tucker, G.E., and Barnhart, K.B.: The SPACE 1.0 model: A Landlab component for 2-D calculation of sediment transport, bedrock erosion, and landscape evolution, submitted to Geoscientific Model Development. T...
github_jupyter
# Classes Variables, Lists, Dictionaries etc in python is a object. Without getting into the theory part of Object Oriented Programming, explanation of the concepts will be done along this tutorial. A class is declared as follows class class_name: Functions ``` class FirstClass: pass ``` **pass** in pytho...
github_jupyter
<a href="https://colab.research.google.com/github/GabrielLourenco12/python_exercises/blob/main/Exercicios5.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ## Exercícios 5 Ler uma temperatura em graus Celsius e apresentá-la convertida em graus Fahre...
github_jupyter
## Numpy ``` %matplotlib inline %load_ext autoreload %autoreload 2 import os import sys p = os.path.join(os.path.dirname('__file__'), '..') sys.path.append(p) from common import * ``` ### Init ``` np.ones(10).astype(int) np.zeros(10) np.arange(1,10) # Gaussian normal distribution np.random.randn(2,2) # Random unifor...
github_jupyter
# Creating Python Virtual Environments with conda - [Overview](#conda-virual-env-overview) - [Setting Up a Virtual Environment Using conda](#setting-up-a-virtual-environment-using-conda) - [Creating a conda Virtual Environment from a File](#creating-a-conda-environment-from-a-file) - [Setting Up a RAPIDS conda Envir...
github_jupyter
# Description ## This notebok provides set of commands to install Spark NLP for offline usage. It contains 4 sections: 1) Download all dependencies for Spark NLP 2) Download all dependencies for Spark NLP (enterprise/licensed) 3) Download all dependencies for Spark NLP OCR 4) Download all models/embeddings for offli...
github_jupyter
Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. ![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/classification-bank-marketing-all-features/auto-ml-classification-bank-mar...
github_jupyter
# Example notebook ``` import perfume import perfume.analyze import pandas as pd import bokeh.io bokeh.io.output_notebook() ``` ## Setup To start, set up some functions to benchmark. ``` import time import numpy as np def test_fn_1(): good = np.random.poisson(20) bad = np.random.poisson(100) msec = np....
github_jupyter
``` %matplotlib inline # %config InlineBackend.figure_format = 'svg' %reload_ext autoreload %autoreload 2 from __future__ import division import sys import os sys.path.append('../') from modules.basics import * from sklearn.model_selection import train_test_split from lumin.plotting.data_viewing import plot_rank_ord...
github_jupyter
``` import numpy as np import os from skimage import io from skimage import color, exposure, transform from PIL import Image import cv2 import matplotlib import matplotlib.pyplot as plt import sys from shutil import copyfile from skimage import data, img_as_float from skimage import exposure import shutil import kera...
github_jupyter
## Subplots with table and traces with different realtive position ## ``` from plotly.offline import download_plotlyjs, init_notebook_mode, iplot, plot init_notebook_mode(connected=True) import pandas as pd import datetime df=pd.read_excel('Mining-BTC-180.xls') df.head() df.columns ``` Convert each string in `df['D...
github_jupyter
``` from collections import defaultdict from sortedcontainers import SortedDict import math import pandas as pd import numpy as np from copy import copy from pyqstrat.pq_utils import str2date from pyqstrat.pq_types import ContractGroup def calc_trade_pnl(open_qtys, open_prices, new_qtys, new_prices, multiplier): ''...
github_jupyter
``` import os import sys module_path = os.path.abspath(os.path.join('..')) sys.path.append(module_path) import matplotlib import matplotlib.pyplot as plt import seaborn as sns sns.set_style('whitegrid') color = sns.color_palette() %matplotlib inline matplotlib.style.use('ggplot') import time import numpy as np import...
github_jupyter
# #2 Discovering Butterfree - Spark Functions and Window Welcome to Discovering Butterfree tutorial series! This is the second tutorial of this series: its goal is to cover spark functions and windows definition. Before diving into the tutorial make sure you have a basic understanding of these main data concepts: fe...
github_jupyter
# Calculate Coverage You have a large region of interest. You need to identify an AOI for your study. One of the inputs to that decision is the coverage within the region. This notebook will walk you through that process. In this notebook, we create the coverage map for PS Orthotiles collected in 2017 through August ...
github_jupyter
<a href="https://colab.research.google.com/github/kalz2q/mycolabnotebooks/blob/master/arabic01.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # メモ コードセルでは %%html とすると、html が書けるのでそれを利用すると、 文字に色をつけたり、大きくしたりができる。 それを利用してアラビア語の勉強をする、というアイデア。 うまく表示できた...
github_jupyter
# Topic Modeling with DARIAH topics We use this python library to do topic modeling on the AO3 corpus: https://dariah-de.github.io/Topics/ Issue: the library is designed to work with simple .txt files, while we have an R environment. We need to convert the R environment into .txt files: this can be done directly v...
github_jupyter
``` import urllib.request, json with urllib.request.urlopen( "https://api.steinhq.com/v1/storages/5e736c1db88d3d04ae0815b3/Raw_Data" ) as url: data = json.loads(url.read().decode()) import pandas as pd import re from tqdm import tqdm tqdm.pandas() df = pd.DataFrame(data) df["Notes"][30:35] import spacy nlp = s...
github_jupyter
``` import sys sys.path.append('..') import os import torch import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.preprocessing import LabelEncoder, MinMaxScaler, KBinsDiscretizer from sklearn.impute import SimpleImputer from sklearn.model_selection import cross_val_score from sklearn.tree...
github_jupyter
<h2>Fashion MNIST dataset in Keras library</h2> ## Imports ``` # - TensorFlow import tensorflow as tf # - Dataset from tensorflow.keras.datasets import fashion_mnist # - Helper libraries import numpy as np import pandas as pd import time from sklearn.metrics import confusion_matrix from tensorflow.keras.utils import ...
github_jupyter
# Demo: Using VGG with Keras Below, you'll be able to check out the predictions from an ImageNet pre-trained VGG network with Keras. ### Load some example images ``` # Load our images first, and we'll check what we have from glob import glob import matplotlib.image as mpimg import matplotlib.pyplot as plt # Visualiz...
github_jupyter
<img src="../../images/qiskit-heading.gif" alt="Note: In order for images to show up in this jupyter notebook you need to select File => Trusted Notebook" width="500 px" align="left"> # Qiskit Aer: Simulators The latest version of this notebook is available on https://github.com/Qiskit/qiskit-tutorials. ## Introduct...
github_jupyter
# Example 3: Normalize data to MNI template This example covers the normalization of data. Some people prefer to normalize the data during the preprocessing, just before smoothing. I prefer to do the 1st-level analysis completely in subject space and only normalize the contrasts for the 2nd-level analysis. But both ap...
github_jupyter
## Practice: Mastering Kung-Fu and A2C *This part is based on [Practical RL week08 practice](https://github.com/yandexdataschool/Practical_RL/tree/master/week08_pomdp). All rights belong to the original authors.* ``` import sys if 'google.colab' in sys.modules: !pip install scipy==1.0.1 !wget https://raw.gith...
github_jupyter
``` import pandas as pd import numpy as np import datetime as dt ``` # **Task** **1** ``` #dummy data for task 1 df = pd.read_csv('data.csv') df = df.drop([1693,1694],axis=0) def date_difference(dataframe): # Note***/// This function will do the job for any format of date values in column however i tried but c...
github_jupyter
``` import digits import tensorflow as tf from time import time import itertools as it import numpy as np from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score, precision_score, f1_score, \ recall_score, classification_report, confusion_matrix DATA_PATH = 'digits.csv' LEAR...
github_jupyter
# Creating structures in pyiron This section gives a brief introduction about some of the tools available in pyiron to construct atomic structures. For the sake of compatibility, our structure class is written to be compatible with the popular Atomistic Simulation Environment package ([ASE](https://wiki.fysik.dtu.dk/...
github_jupyter
# Problem Set 2 See “Check Your Understanding” from [collections](../python_fundamentals/collections.ipynb) and [control flow](../python_fundamentals/control_flow.ipynb) Note: unless stated otherwise, the timing of streams of payoffs is immediately at time `0` where appropriate. For example, dividends $ \{d_1, d_2,...
github_jupyter
# Collect all data ``` import struct def get_byte_list(lbl_file_name, img_file_name): ''' Returns a list of tuples, each tuple contains a label and an image, both in bytes. ''' tuples = [] with open(lbl_file_name, 'rb') as lbl_file, open(img_file_name, 'rb') as img_file: magic_number...
github_jupyter
``` from result_records import TFRecordLoader ds = TFRecordLoader('memorization_results.tfrecords') ``` # Loading Data > consists of 4063300 records ``` data = [] indicies = [] import numpy as np from tqdm import tqdm for i,(res,idx) in tqdm(enumerate(ds)): res,idx = res.numpy(),idx.numpy() if(not (np.isnan(...
github_jupyter
``` ## Import Libraies import pandas as pd %pylab inline import numpy as np import re import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline from math import sqrt from sklearn.ensemble import RandomForestRegressor from sklearn import preprocessing import sklearn.model_selection as ms import sklearn.me...
github_jupyter
# Analysis of the loads acting on the building ## *Matteo Franzoi* - Academic Year 2019/2020 ### matricola 166788 (triennale) --- ``` from engineering_notation import EngNumber import math import numpy as np from decimal import Decimal ``` --- #### Snow Load ``` qsk = 1.39*(1+(788/728)**2); print(qsk, 'kN/m^2\n~=') ...
github_jupyter
# Notes (IFE - template) ### `{{cookiecutter.project_name}}::{{cookiecutter.session_id}}` ## 1. Usage ### 1.1. Jupyter *You can fill inn the MarkDown cells (the cells without "numbering") by double-clicking them. Also remember, press `shift + enter` to execute a cell.* A couple of useful links: - [How to write ...
github_jupyter
#Crime Data Collection Methodology -Eric Ramon- Labs 21 Crime Data is available from several official sources. UCR (uniform crime report), NIBRS (National Incident-Based Reporting System) and SRS (Summary Reporting System) are reported on the FBI website. The NIBRS is a newer standard that will be THE new standard by...
github_jupyter
``` import matplotlib.pyplot as plt import scipy.sparse as sp import _pickle as pk from helpers import load_data from collaborativeFiltering import * from cross_validation import k_fold_split, split_matrix %matplotlib inline %load_ext autoreload %autoreload 2 def save(obj, path): print('Saving at path : {}'.forma...
github_jupyter
# Project 2: Transistors and Amplifiers This project will introduce two basic techniques for using currents and voltages to control currents and voltages. Why would you want to do that? It turns out that many times the physical system we're working with is not *directly* compatable with the tools we have to control or...
github_jupyter
<img width="200" src="https://mmlspark.blob.core.windows.net/graphics/Readme/cog_services_on_spark_2.svg" /> # Cognitive Services [Azure Cognitive Services](https://azure.microsoft.com/en-us/services/cognitive-services/) are a suite of APIs, SDKs, and services available to help developers build intelligent applicati...
github_jupyter
# Fitting the distribution of heights data ## Instructions In this assessment you will write code to perform a steepest descent to fit a Gaussian model to the distribution of heights data that was first introduced in *Mathematics for Machine Learning: Linear Algebra*. The algorithm is the same as you encountered in *...
github_jupyter
# Mean Shift using Robust Scaler This Code template is for the Cluster analysis using a simple Mean Shift(Centroid-Based Clustering using a flat kernel) Clustering algorithm along with feature scaling using Robust Scaler and includes 2D and 3D cluster visualization of the Clusters. ### Required Packages ``` !pip ins...
github_jupyter
# This notebook explores the Energy Preserving Neural Network Idea! ------------------------------------------------------------------------------------------------------------------- # Dataset used => MNIST ----------------------------------------------------------------------------------------------------------------...
github_jupyter
### Load preprocessed data Run the script that downloads and processes the MovieLens data. Uncomment it to run the download & processing script. ``` # !python ../src/download.py import numpy as np from sklearn.model_selection import train_test_split from torch import from_numpy from torch.utils.data import DataLoader...
github_jupyter
``` import numpy as np import pandas as pd import scipy as sp import sklearn as sl import seaborn as sns; sns.set() import matplotlib as mpl from sklearn.linear_model import LinearRegression from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import axes3d from matplotlib import cm %matplotlib inline ``` # ...
github_jupyter
# Adding Object Detection Predictions to a Voxel51 Dataset This notebook will add predictions from an object detection model to the samples in a Voxel51 Dataset. Adapted from: https://voxel51.com/docs/fiftyone/recipes/model_inference.html ``` model_path = '/tf/model-export/lb-400images-efficientdet-d0-model/image_ten...
github_jupyter