text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
Before you turn this problem in, make sure everything runs as expected. First, **restart the kernel** (in the menubar, select Kernel$\rightarrow$Restart) and then **run all cells** (in the menubar, select Cell$\rightarrow$Run All). Make sure you fill in any place that says `YOUR CODE HERE` or "YOUR ANSWER HERE", as we...
github_jupyter
# Homework 3 - Neural Network Post-Training Static Quantization ## STUDENT NAME: [full name here] ## STUDENT PURDUE USERNAME: [username here] # Setup > **TASKS:** > 1. Run these cells to grab the PyPI packages and import the dependencies for the notebook. You can click into the "Files" explorer on the sidebar to conf...
github_jupyter
Team Members - Shubhendu Vimal - 11915067 - Dharani Kiran Kavuri - 11915033 - Anmol More - 11915043 <H2> ReadMe :</H2> - Data Preparation through python script - Convert raw data csv and then to libsvm in R - Run spark ML algos in jupyter notebook ``` import pandas as pd import glob from pyspark.ml.classification...
github_jupyter
``` import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy import stats dt = np.dtype([('instance_no', int), ('exp_no', int), ('method', int), # 1 = white box, 2 = euclidean_PCA, 3 = hog, 4 = euclidean_PCA category, 5 = hog category, 6 = ais ('pca...
github_jupyter
TSG037 - Determine master pool pod hosting primary replica ========================================================== Description ----------- Determine the pod that hosts the primary replica for the Big Data Cluster when master pool high availability is enabled. For BDC deployed with High availability, the master po...
github_jupyter
<table class="ee-notebook-buttons" align="left"> <td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/FeatureCollection/extract_image_by_polygon.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td> <td><a ta...
github_jupyter
## Dependencies ``` import os import cv2 import shutil import random import warnings import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import imgaug as ia from imgaug import augmenters as iaa from sklearn.utils import class_weight, shuffle from sklearn.model_selection import ...
github_jupyter
## Uygulamalı Veri Bilimi ve Makine Öğrenimi Eğitim Kampı ### Kodluyoruz Ağustos-Eylül 2019 Ankara ### 3. hafta Geçtiğimiz hafta istatistik temellerine değindik Anahtar kelimeler: * Z Table * Normal dağılım (Gaussian) (çan) * Uniform dağılım * Poisson dağılımı * Probability Density Function (PDF) * Cumulative Dist...
github_jupyter
``` import numpy as np import pandas as pd from sklearn.model_selection import train_test_split, GridSearchCV from matplotlib import pyplot as plt import seaborn as sns from sklearn.preprocessing import StandardScaler, MinMaxScaler from sklearn.linear_model import Ridge, Lasso, ElasticNet, LinearRegression from sklea...
github_jupyter
# Option pricing with the Heston / Hull White model ##The model The Heston / Hull-White model is a Heston model, where the dynamic of the risk-free rate is governed by a Hull-White one-factor model: \begin{align} \frac{dS}{S}& = (r_t - \nu) dt + \sqrt{V_t} dZ_t \\ dV_t& = \kappa_V(\theta_V - V_t) dt + \sigma_V \sqrt...
github_jupyter
Jupyter Notebooks ================== A notebook consists in a set of cells. These cells are interpreted either as text instruction (i.e. **markdown**) or as Python **code**. * Each cell can be edited using ``[Enter]`` key (i.e. *edit mode*). To return to the *navigation mode*, use the ``[Esc]`` key. * To switch chan...
github_jupyter
# MNIST keras model This notebook is part of this [post](https://www.stupid-projects.com/machine-learning-on-embedded-part-1) which is part a series of post about using ML and NN in embedded MCUs. I've taken this notebook has been taken from this github repo and just added a few stuff: https://github.com/fchollet/dee...
github_jupyter
``` import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn import preprocessing from sklearn import metrics import os, sys from time import time from phm08ds.models import experiment ``` ## Load Dataset ``` folderpath = '../../../data/interim/' data_op_05 = pd.read_csv(folderpath + 'dat...
github_jupyter
## Scientific Python ### Matrices Dealing with vectors and matrices efficiently requires the **numpy** library. For the sake of brevity we will import this with a shorter name: ``` import numpy as np ``` The numpy supports arrays and matrices with many of the features that would be familiar to matlab users. See here...
github_jupyter
# Integration with Simpson's rule In this notebook we look at a more efficient method for numerical integraiton: Simpon's rule ``` import numpy as np import matplotlib.pyplot as plt # The below commands make the font and image size bigger plt.rcParams.update({'font.size': 22}) plt.rcParams["figure.figsize"] = (15,10)...
github_jupyter
# JSON and HTML Processing In this tutorial it is covered basic operations with HTML and JSON. For more informations about related stuff see: * <a href="https://en.wikipedia.org/wiki/JSON">JavaScript Object Notation</a> * <a href="https://en.wikipedia.org/wiki/HTML">HyperText Markup Language (HTML)</a> ## HTML (XML) ...
github_jupyter
``` # default_exp capture ``` # Capture > Wrapper class and example code for getting images from the OpenHSI using a ximea detetor (with IMX252 sensor, e.g. MX031CG-SY).Wrapper class and example code for getting images from the OpenHSI using a ximea detetor (with IMX252 sensor, e.g. [MX031CG-SY](https://www.ximea.com...
github_jupyter
# Deep Learning Bootcamp November 2017, GPU Computing for Data Scientists <img src="../images/bcamp.png" align="center"> ## Using CUDA, Jupyter, PyCUDA and PyTorch ### 01 PyCUDA verify CUDA 8.0 Web: https://www.meetup.com/Tel-Aviv-Deep-Learning-Bootcamp/events/241762893/ Notebooks: <a href="https://github.com/Quan...
github_jupyter
# Process manager The process manager allows the construction of sets of tasks to be run, which can be (but are not limited to) launch files or ROS nodes to bring up a system that may include an instance of Gazebo. Each instance of the process manager can be set with a different `ROS_MASTER_URI` and `GAZEBO_MASTER_URI...
github_jupyter
## Demonstrating the Workflow of the Online_IO Class: Implicit Update ### Stephanie Allen, *AMSC PhD, UMD-College Park* We will demonstrate through the Markdown and code blocks below the workflow of the `Online_IO` class for the `Dong_implicit_update` option. We will be replicating an experiment from Dong, Chen, & ...
github_jupyter
``` from google.colab import drive drive.mount('/content/gdrive') import os os.chdir('/content/gdrive/My Drive/finch/tensorflow1/multi_turn_rewrite/chinese/main') %tensorflow_version 1.x !pip install texar import tensorflow as tf import texar.tf as tx import numpy as np import pprint import logging from pathlib impor...
github_jupyter
<a href="https://colab.research.google.com/github/parament-integrator/examples/blob/master/Convergence_Plot.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Convergence plot In this example we will recreate the convergence plot from our paper. A ...
github_jupyter
##### Copyright 2021 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
# BadSensorFinder Demo - Plotting the SVM Hyperplane ``` import os os.chdir('../optidrift/') import badsensorfinder import pickle import numpy as np from mpl_toolkits.mplot3d import Axes3D import pandas as pd import matplotlib.pyplot as plt import getdata %matplotlib inline ``` ## Build the model you want to plot the...
github_jupyter
# Blockdiag Package Diagrams The [`blockdiag`](http://blockdiag.com/en/) package provides tools for generating several types of diagram, from simple box and arrows diagrams to various diagrams familiar to communications and system engineers. The diagrams are defined using simple text structures. Various IPython block...
github_jupyter
# Simple Time Series Example This tutorial shows how a simple time series simulation is performed with the timeseries and control module in pandapower. A time series calculation requires the minimum following inputs: * pandapower net * the time series (in a pandas Dataframe for example) First we need some imports. Sp...
github_jupyter
``` import glob import pandas as pd import os import csv import matplotlib.pyplot as plt from scipy.stats import norm, kstest, shapiro, ranksums import numpy as np from itertools import combinations ``` # Gets Data ``` #store all data, from all configs, in a dict with key config and value dataframe converted to dict ...
github_jupyter
``` # Remember: library imports are ALWAYS at the top of the script, no exceptions! import sqlite3 import os import pandas as pd import numpy as np from datetime import datetime from sklearn.impute import KNNImputer from pandas_profiling import ProfileReport ``` # Context The data we will be using through the pratical...
github_jupyter
# 7.6 Transformerモデル(分類タスク用)の実装 - 本ファイルでは、クラス分類のTransformerモデルを実装します。 ※ 本章のファイルはすべてUbuntuでの動作を前提としています。Windowsなど文字コードが違う環境での動作にはご注意下さい。 # 7.6 学習目標 1. Transformerのモジュール構成を理解する 2. LSTMやRNNを使用せずCNNベースのTransformerで自然言語処理が可能な理由を理解する 3. Transformerを実装できるようになる # 事前準備 書籍の指示に従い、本章で使用するデータを用意します ``` import math import num...
github_jupyter
``` import SimpleITK as sitk import numpy as np import pandas as pd import matplotlib.pyplot as plt import math from scipy import signal from numpy import * from pylab import * import cv2 import random from random import randrange from numpy import linalg from scipy import signal from pylab import * from PIL import...
github_jupyter
# Python for Environmental Science Day 3 ## Topics * Functions in Python * Catching Errors in Python ## What the heck is a function? Functions are time savers. A good programmer is a lazy programmer. If you have the possibility to not write something, it is usually a good idea to do so. And this is where functions com...
github_jupyter
<center> <img src="https://habrastorage.org/web/677/8e1/337/6778e1337c3d4b159d7e99df94227cb2.jpg"/> ## Специализация "Машинное обучение и анализ данных" <center>Автор материала: программист-исследователь Mail.Ru Group, старший преподаватель Факультета Компьютерных Наук ВШЭ Юрий Кашницкий # <center> Capstone проект №1....
github_jupyter
# Sphere function, vectorized In the previous example, we solved the constrained Rosenbrock problem. This was a 2-dimensional problem, so we created two variables: $x$ and $y$. However, imagine we had a problem with 100 variables. It'd be pretty tedious to create these variables individually and do the math on each v...
github_jupyter
# Test instantiating PypIt parameter sets ``` # import import os from configobj import ConfigObj from pypit.par import pypitpar ``` ## General usage ``` # To get the default parameters, declare the parameters set # without arguments p = pypitpar.ProcessImagesPar() # Use print() to get a short-form representation pri...
github_jupyter
``` try: import settings assert type(settings.CENSUS_KEY) == str or type(settings.CENSUS_KEY) == unicode except Exception as e: print ("error in importing settings to get at settings.CENSUS_KEY", e) from census import Census from us import states c = Census(settings.CENSUS_KEY) ``` Does the `census` modul...
github_jupyter
.. meta:: :description: A guide which introduces the most important steps to get started with pymoo, an open-source multi-objective optimization framework in Python. .. meta:: :keywords: Multi-objective Optimization, Python, Evolutionary Computation, Optimization Test Problem, Hypervolume ## Getting Started In...
github_jupyter
# Learn to manage data collections using the generic list type *This tutorial teaches you C# interactively, using your browser to write C# code and see the results of compiling and running your code. It contains a series of lessons that create, modify, and explore collections and arrays.* ## Create lists Run the fol...
github_jupyter
# Sparse Approximations The `gp.MarginalSparse` class implements sparse, or inducing point, GP approximations. It works identically to `gp.Marginal`, except it additionally requires the locations of the inducing points (denoted `Xu`), and it accepts the argument `sigma` instead of `noise` because these sparse approx...
github_jupyter
<a href="https://colab.research.google.com/github/Shahid-coder/python-colab/blob/main/04_list_and_tuples_methods.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # List methods Lists are used to store multiple items in a single variable. Lists are ...
github_jupyter
# Computational Astrophysics ## Partial Differential Equations. 06 ## Multidimensional Advection Equation --- ## Eduard Larrañaga Observatorio Astronómico Nacional\ Facultad de Ciencias\ Universidad Nacional de Colombia --- ### About this notebook In this notebook we present some of the techniques used to solve th...
github_jupyter
# The Basics: Variables and Printing This notebook is based on materials kindly provided by the [IN1900]( https://www.uio.no/studier/emner/matnat/ifi/IN1900/h19/) team. Programming is a way of telling the computer what to do. Computer programs are a kind of recipe, like cooking or knitting recipes. However, cooking r...
github_jupyter
``` #@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 agreed to in writing, software # distributed u...
github_jupyter
``` import numpy as np import os from scipy.spatial.transform import Rotation as R from sys import argv, exit np.random.seed(42) np.set_printoptions(formatter={'float': lambda x: "{0:0.5f}".format(x)}) def frobNorm(P1, P2, str1="mat1", str2="mat2"): np.set_printoptions(suppress=True) val = np.linalg.norm(P1 ...
github_jupyter
# Numpy (Часть 3) > 🚀 В этой практике нам понадобятся: `numpy==1.21.2` > 🚀 Установить вы их можете с помощью команды: `!pip install numpy==1.21.2` # Содержание <a name="content"></a> * [Broadcasting (трансляция)](#Broadcasting_(transljatsija)) * [Изменение размеров массива (Reshape)](#Izmenenie_razmerov_massiva_...
github_jupyter
``` !nvidia-smi !pip --quiet install transformers !pip --quiet install tokenizers from google.colab import drive drive.mount('/content/drive') !cp -r '/content/drive/My Drive/Colab Notebooks/Tweet Sentiment Extraction/Scripts/.' . COLAB_BASE_PATH = '/content/drive/My Drive/Colab Notebooks/Tweet Sentiment Extraction/' M...
github_jupyter
``` %pylab inline from parcels import FieldSet, Field, ParticleSet, JITParticle, AdvectionRK4, ErrorCode, Variable import matplotlib.patches as mpatches import cartopy from datetime import timedelta as delta import matplotlib.pyplot as plt from glob import glob import numpy as np import xarray as xr from os import envi...
github_jupyter
``` import numpy as np import matplotlib.pyplot as plt import pandas as pd import base LENGTH = 30 def lengths_of_searches(): grouped_users = base.get_dataset_and_group_by_user() each_user_lengths_success = {} each_user_lengths_fail = {} for username, group in grouped_users: this_user_length_su...
github_jupyter
# Lagrangian mechanics in generalized coordinates > Marcos Duarte > Laboratory of Biomechanics and Motor Control ([http://demotu.org/](http://demotu.org/)) > Federal University of ABC, Brazil ## Generalized coordinates The direct application of Newton's laws to mechanical systems results in a set of equations of...
github_jupyter
# TIME SERIES IN LSTM ### ILLUSTRATION WITH SINE AND COS FUNCTIONS ``` %matplotlib inline import numpy as np from matplotlib import pyplot as plt #from tensorflow.nn.rnn import * from tensorflow.python.ops import * %load_ext autoreload %autoreload 2 import numpy as np import pandas as pd import tensorflow as tf fro...
github_jupyter
``` import sys sys.path.append("/Users/sklim/Projects/DamGeophysics/codes/") from Readfiles import getFnames from DCdata import readReservoirDC #from SimPEG import DCIP as DC #from SimPEG import TDEM from SimPEG.EM.Static import DC from SimPEG import EM from SimPEG import Mesh, Utils %pylab inline fname = "/Users/skli...
github_jupyter
# Identify Worker Labeling Efficiency using SageMaker GroundTruth ### Introduction Welcome to our example on identifying worker labeling efficiency for a SageMaker GroundTruth Labeling job. Before running this notebook, please make sure that all the instructions prior to the section 'Setup the Automated Accuracy Logic...
github_jupyter
Before you turn this problem in, make sure everything runs as expected. First, **restart the kernel** (in the menubar, select Kernel$\rightarrow$Restart) and then **run all cells** (in the menubar, select Cell$\rightarrow$Run All). Make sure you fill in any place that says `YOUR CODE HERE` or "YOUR ANSWER HERE", as we...
github_jupyter
## Setup Data Fetching ``` import ta import pandas as pd import tensortrade.env.default as default from tensortrade.data.cdd import CryptoDataDownload from tensortrade.feed.core import Stream, DataFeed, NameSpace from tensortrade.oms.instruments import USD, BTC, ETH, LTC from tensortrade.oms.wallets import Wallet, P...
github_jupyter
## Comparison between the iterative Image Space Restoration Algorithm (ISRA) and the Richardson-Lucy Algorithm (RLA) Using the generated Voigt functions ``` #required libraries %matplotlib qt import numpy as np import hyperspy.api as hs from ncempy.io import dm import matplotlib.pyplot as plt from scipy.signal import...
github_jupyter
``` %matplotlib inline ``` # Balance model complexity and cross-validated score This example balances model complexity and cross-validated score by finding a decent accuracy within 1 standard deviation of the best accuracy score while minimising the number of PCA components [1]. The figure shows the trade-off betw...
github_jupyter
# Get table and use a function to convert to dates ## Example bankruptcies This weekly StatBank table has a break in the time series from 2010-2018.It is suitable for displaying the date conversion function. Here figures are shown both with the x-axis as categories and as date. Source: [12972](https://www.ssb.no/en/st...
github_jupyter
``` import torch from torch import nn, optim from torch.utils.data import DataLoader, Dataset from torchvision import datasets, transforms from torchvision.utils import make_grid from matplotlib import pyplot as plt import seaborn as sns from IPython import display import numpy as np from PIL import Image import torchm...
github_jupyter
Hurricane Tracker with NHC Data =============================== By: Aodhan Sweeney This program is a recreation of the 2014 hur_tracker.py originally written by Unidata Intern Florita Rodriguez. The 2019 version comes with updated interface and functionality, as well as changing certain dependencies. ``` import gzip...
github_jupyter
<a name="top"></a><img src="images/chisel_1024.png" alt="Chisel logo" style="width:480px;" /> # Module 4.4: A FIRRTL Transform Example **Prev: [Common Pass Idioms](4.3_firrtl_common_idioms.ipynb)**<br> This AnalyzeCircuit Transform walks a `firrtl.ir.Circuit`, and records the number of add ops it finds, per module. ...
github_jupyter
<a href="https://colab.research.google.com/drive/1KrMIELsuGSoTdT5pV2CBUCulArgbGjGc?authuser=1#scrollTo=hMypMs2KDmK3"> <img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/> </a> ## 1. Google Play Store apps and reviews <p>Mobile apps are everywhere. They are easy to create and can ...
github_jupyter
### IMPORTS ``` import cv2 import numpy as np import time from collections import deque import img2pdf import os import glob ``` ### CONSTANTS ``` # Colors colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255)] counter = 0 PATH = r"C:/Users/rajat/Desktop/" # Where to save ? # Define the upper and lower boundaries for a...
github_jupyter
``` %matplotlib notebook import matplotlib.pyplot as plt import pandas as pd import numpy as np import requests import time import random from scipy import stats pop_data = pd.read_csv('../Inputs/POPSTATSInputs/population_estimates_project1.csv') pop_data pop_data = pop_data.loc[[2, 6, 38, 48]] pop_data pop_data = pop_...
github_jupyter
**Chapter 16 – Natural Language Processing with RNNs and Attention** _This notebook contains all the sample code in chapter 16._ <table align="left"> <td> <a target="_blank" href="https://colab.research.google.com/github/rickiepark/handson-ml2/blob/master/16_nlp_with_rnns_and_attention.ipynb"><img src="https://...
github_jupyter
# Assingment 1 - Malaria Cell Image Classification ### Course: Convolutional Neural Networks with Applications in Medical Image Analysis Office hours: Alternating weeks on Thursdays 13.15--16.00 (Minh) and Wednesdays 08.15--12.00 (Attila). See the course web page for details and potential changes. The first assignmen...
github_jupyter
### Baseline model (returns the survived value based on its probability in training data set) ##### Import processed training data for baseline model ``` import pandas as pd import numpy as np import os as os import sklearn processed_dir_path=os.path.join(os.pardir,"data", "processed") processed_data_path=os.path.joi...
github_jupyter
## Quick check of target preference profiles and corrsponding utility space ``` ## pip install git+https://github.com/SifanSong/trackgenius.git import numpy as np %matplotlib inline ## only Background required to be imported from trackgenius.utilities.background import Background ## Basic configuration ## DOMAIN_Pa...
github_jupyter
<table align="center"> <td align="center"><a target="_blank" href="http://introtodeeplearning.com"> <img src="http://introtodeeplearning.com/images/colab/mit.png" style="padding-bottom:5px;" /> Visit MIT Deep Learning</a></td> <td align="center"><a target="_blank" href="https://colab.research.google.c...
github_jupyter
# Multi Layer Perceptron - PyTorch * load mnist data set * define network * set loss and optimiser * train and validate ``` import torch import numpy as np from torchvision import datasets # to load mnist dataset import torchvision.transforms as transforms # dataset transformations such as totensor num_workers = 0 ba...
github_jupyter
# Color cycle analysis The training process takes several hours. ``` import csv import gzip import itertools import logging import os import random import shutil import sqlite3 import sys import time import numpy as np import colorspacious from tensorflow.keras.models import Model from tensorflow.keras.layers import ...
github_jupyter
``` import os import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader from torch.autograd import Variable import torchvision.transforms as transforms from torchvision.utils import save_image from torchvision import datasets num_eps=10 bsize=32 lra...
github_jupyter
# Exercise Set 3: Strings, requests and APIs *Morning, August 13, 2019* In this exercise set you will be working with collecting from the web. We will start out with some basic string operations and build on that to make a query for fetching data. In addition to DataCamp, you might find [this page](https://pythonpro...
github_jupyter
``` import collections import glob import re import tarfile import math from pprint import pprint import os import spacy import pandas as pd from collections import Counter def read_archive(path): tar = tarfile.open(path, "r:gz") files = {} for filename in tar.getnames(): f = tar.extractfile(file...
github_jupyter
<table style="border: none" align="left"> <tr style="border: none"> <th style="border: none"><font face="verdana" size="4" color="black"><b>Use Spark ML and Python to detect network intrusions</b></font></th> <th style="border: none"><img src="https://github.com/pmservice/customer-satisfaction-prediction...
github_jupyter
``` import requests import pandas as pd from bs4 import BeautifulSoup # if we did no have requests then we would install it manually: # !pip install requests from Jupyter notebook # pip install requests from command line url = "https://www.ss.com/lv/real-estate/wood/" req = requests.get(url) req.status_code len(req.tex...
github_jupyter
# Foundations of Computational Economics #27 by Fedor Iskhakov, ANU <img src="_static/img/dag3logo.png" style="width:256px;"> ## Dynamic programming in discrete world <img src="_static/img/lecture.png" style="width:64px;"> <img src="_static/img/youtube.png" style="width:65px;"> [https://youtu.be/kpNGDQnDpmU](http...
github_jupyter
<a href="https://colab.research.google.com/github/shridharshukla/TSF_DataScienceAndBusinessAnalytics_II/blob/main/Task_2_KMeans_Clustering.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Prediction using Unsupervised ML ### Workshop - 1: K- Means...
github_jupyter
<a href="https://colab.research.google.com/github/IsraelAbebe/Personal-Projects-and-Exercises/blob/master/AIMS-Assignments/Deep-Learning/ExerciseOne.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` import torch ``` # Question 1 ``` a = torch.fu...
github_jupyter
``` import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error from sklearn.metrics import mean_absolute_error import joblib import tensorflow as tf import math pd.set_option('display.max_rows', 10000) %matplo...
github_jupyter
# Classifying Fashion-MNIST Now it's your turn to build and train a neural network. You'll be using the [Fashion-MNIST dataset](https://github.com/zalandoresearch/fashion-mnist), a drop-in replacement for the MNIST dataset. MNIST is actually quite trivial with neural networks where you can easily achieve better than 9...
github_jupyter
``` #################################################################################################### # Copyright 2019 Srijan Verma and EMBL-European Bioinformatics Institute # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License...
github_jupyter
*** # 数据清洗: > # 对占中新闻进行数据清洗 *** *** 王成军 wangchengjun@nju.edu.cn 计算传播网 http://computational-communication.com ``` # 使用with open读取每一行数据 with open("/Users/chengjun/github/cjc/data/occupycentral/zz-hk-2014-10.rtf") as f: news = f.readlines() # 查看总共有多少行 len(news) # 注意:标题和版面之间存在一个空行!所以title是block的第4个元素。 for i in rang...
github_jupyter
# Introduction In this article, we show how to represent basic poker elements in Python, e.g., Hands and Combos, and how to calculate poker odds, i.e., likelihood of win/tie/lose in No-Limit Texas Hold'em. We provide a practical analysis based on a real story in a *Night at the Venetian*. We will use the package **p...
github_jupyter
# A few notes on tensor operations in numpy To calculate the "convolution" operation defined by the lecture note, which is indeed more often referred as cross-correlation, can be done with the function `signal.correlate2d` in `scipy`. ``` import numpy as np from scipy import signal a = np.arange(9).reshape((3,3)) b = ...
github_jupyter
# Practice Exercise Linear Regression ## We will be using the Boston house price dataset for this exercise. #### This dataset is in-built in Python in the Sci-kit learn library. But for this exercise, we have already downloaded this dataset in the form of a csv file. **Importing Libraries** ``` from sklearn.datasets...
github_jupyter
``` %load_ext Cython %%cython from pycalphad.core.rksum import RedlichKisterSum from pycalphad import Database cimport numpy as np import numpy as np from tinydb import where from sympy import Symbol cdef np.ndarray[ndim=1, dtype=np.float64_t] _eval_rk_matrix_gradient(double[:,:] coef_mat, double[:,:] symbol_mat, ...
github_jupyter
https://discourse.julialang.org/t/help-to-get-my-slow-julia-code-to-run-as-fast-as-rust-java-lisp/65741 ``` # download dictionary if !isfile("dictionary.txt") dictionary_url = "https://raw.githubusercontent.com/renatoathaydes/prechelt-phone-number-encoding/julia/dictionary.txt" Downloads.download(dictionary_ur...
github_jupyter
``` %%capture from dask_jobqueue import SLURMCluster from dask.distributed import Client import xarray as xr import os import gsw import time import numpy as np import pandas as pd from scipy.interpolate import interp1d, PchipInterpolator cluster = SLURMCluster(queue='any2', cores=24, memory='48GB', processes=2) cluste...
github_jupyter
## Variational Inference The dataset required is small and is available preprocessed here: - https://drive.google.com/drive/folders/1Tg_3SlKbdv0pDog6k2ys0J79e1-vgRyd?usp=sharing ``` import torch import numpy as np from gpytorch.optim import NGD from torch.optim import Adam from torch.nn import Parameter from matplot...
github_jupyter
# Example of use ``` import LMIPy LMIPy.__version__ ``` ## Collection objects: Searching If you don't know what data you are interested in advance, you can search by keywords and return a list of objects. ``` c = LMIPy.Collection('tree cover', object_type=['layer','dataset'], app=['gfw'], limit=10) c ``` Searching...
github_jupyter
# Simple data exploration In this notebook we will explore a dataset from an article by a team at autodesk (which I link to below). We can think of this as the simple data exploration you might do when you first start working with a new dataset. First, we will load pandas and numpy, and read the comma-separated-value...
github_jupyter
``` %matplotlib inline from os import listdir from os.path import isfile, join import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten from keras.optimizers import Adam from keras.layers.normali...
github_jupyter
# Exercise 3: Parallel ETL ``` %load_ext sql from time import time import configparser import matplotlib.pyplot as plt import pandas as pd ``` # STEP 1: Get the params of the created redshift cluster - We need: - The redshift cluster <font color='red'>endpoint</font> - The <font color='red'>IAM role ARN</fon...
github_jupyter
<a href="https://colab.research.google.com/github/Tessellate-Imaging/monk_v1/blob/master/study_roadmaps/1_getting_started_roadmap/2_elemental_features_of_monk/1)%20Feature%20-%20Experiment%20Summaries.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ...
github_jupyter
# SQLクエリによるデータの取得 🐇 このノートブックでは SELECT 文を使ったデータの取得方法について確認していきます。 ## 1. 初期設定 Jupyter Notebook を再起動した場合などはここから実行してください ``` ! pip install ipython-sql pymysql %load_ext sql ``` ## 2. 接続確認 ``` %%sql mysql+pymysql://hello:world@10.0.1.100/employees select 'hello' as world ``` ## 3. テーブル構成の調査 まずはどんなテーブルが存在するか調べてみましょう。...
github_jupyter
``` %load_ext autoreload %autoreload 2 %matplotlib inline import sys sys.path.insert(0, '../') import numpy as np import tensorflow as tf import functools from matplotlib import pyplot as plt import os os.environ["CUDA_VISIBLE_DEVICES"]="1" from gantools import utils, plot from gantools.gansystem import GANsystem from...
github_jupyter
``` import numpy from scipy import ndimage import pandas from geoh5 import kea from geoh5.kea import common as kc # https://github.com/sixy6e/image-processing from image_processing.segmentation import Segments ``` In this example we'll create a segmented array, and compute some basic statistics for every segment (min...
github_jupyter
# 5. Joining Tables This is the fifth in a series of notebooks related to astronomy data. As a continuing example, we will replicate part of the analysis in a recent paper, "[Off the beaten path: Gaia reveals GD-1 stars outside of the main stream](https://arxiv.org/abs/1805.00425)" by Adrian M. Price-Whelan and Ana B...
github_jupyter
``` # import libraries import torch import torch.nn as nn import torch.optim as optim import torchvision import torchvision.transforms as transforms import numpy as np from torch.utils.data.sampler import SubsetRandomSampler from torch.utils.tensorboard import SummaryWriter from utils import device, get_num_correct, ...
github_jupyter
# LOCCNet: A Machine Learning Framework for LOCC Protocols <em> Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved. </em> ## Overview Quantum entanglement is an essential physical resource for quantum communication, quantum computation, and many other quantum technologies. Therefore, ...
github_jupyter
##### Copyright 2020 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