text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
![NetworkX](networkx.png) https://networkx.github.io/ sources https://github.com/networkx ## Creating a graph Create an empty graph with no nodes and no edges. ``` import networkx as nx G = nx.Graph() ``` By definition, a `Graph` is a collection of nodes (vertices) along with identified pairs of nodes (called edg...
github_jupyter
# Stellar Initial Mass Function (IMF) We are going to use a Salpeter IMF to generate stellar IMF data and then use MCMC to guess the slope. The Salpeter IMF is given by: $\frac{dN}{dM} \propto \frac{M}{M_\odot}^{-\alpha} ~~ or ~~ \frac{dN}{dlogM} \propto \frac{M}{M_\odot}^{1-\alpha}$ ``` import numpy as np import mat...
github_jupyter
``` import scipy.io as sio import numpy as np import math import matplotlib.pyplot as plt from scipy.sparse import csc_matrix data = sio.loadmat('XwindowsDocData.mat') xtrain = data['xtrain']; xtest = data['xtest'] ytrain = data['ytrain']; ytest = data['ytest'] vocab = data['vocab'] ``` ### Naive Bayes classifiers - T...
github_jupyter
You can read an overview of this Numerical Linear Algebra course in [this blog post](http://www.fast.ai/2017/07/17/num-lin-alg/). The course was originally taught in the [University of San Francisco MS in Analytics](https://www.usfca.edu/arts-sciences/graduate-programs/analytics) graduate program. Course lecture vide...
github_jupyter
<div style="width:1000 px"> <div style="float:right; width:98 px; height:98px;"> <img src="https://raw.githubusercontent.com/Unidata/MetPy/master/src/metpy/plots/_static/unidata_150x150.png" alt="Unidata Logo" style="height: 98px;"> </div> <h1>XArray Introduction</h1> <h3>Unidata Python Workshop</h3> <div style="cle...
github_jupyter
**Note**: Click on "*Kernel*" > "*Restart Kernel and Run All*" in [JupyterLab](https://jupyterlab.readthedocs.io/en/stable/) *after* finishing the exercises to ensure that your solution runs top to bottom *without* any errors. If you cannot run this file on your machine, you may want to open it [in the cloud <img heigh...
github_jupyter
# Analitiche con Pandas ## [Scarica zip esercizi](../_static/generated/pandas.zip) [Naviga file online](https://github.com/DavidLeoni/softpython-it/tree/master/pandas) ## 1. Introduzione Python mette a disposizione degli strumenti potenti per l'analisi dei dati - uno dei principali è [Pandas](https://pandas.pydata...
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
# Parameter identification example Here is a simple toy model that we use to demonstrate the working of the inference package $\emptyset \xrightarrow[]{k_1} X \; \; \; \; X \xrightarrow[]{d_1} \emptyset$ ``` %matplotlib inline %config InlineBackend.figure_format = "retina" from matplotlib import rcParams rcParams["...
github_jupyter
<a href="https://colab.research.google.com/github/Aman211409/HackFest-21/blob/ML/tflite_conversion.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` import tensorflow as tf from tensorflow import keras import matplotlib.pyplot as plt impor...
github_jupyter
# Code Reference https://scikit-learn.org/stable/auto_examples/model_selection/plot_roc.html https://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html ``` import nibabel as nib import numpy as np import pandas as pd import os import torch import torch.nn as nn import torch.nn.functiona...
github_jupyter
``` #default_exp richext ``` # Extensions To rich > Extensions to [rich](https://github.com/willmcgugan/rich) for ghtop. ``` #export import time,random from collections import defaultdict from typing import List from collections import deque, OrderedDict, namedtuple from ghtop.all_rich import (Console, Color, FixedP...
github_jupyter
``` # default_exp sources from nbdev import * %load_ext autoreload %autoreload 2 from utilities.ipynb_docgen import * from nbdev.showdoc import show_doc ``` # Sources and weights > Define the PointSource class, code to load weight tables to combine with photon data ### Weight tables We use a full-sky catalog analys...
github_jupyter
Using a neural network to predict stock prices, using only basic data ``` %matplotlib inline from matplotlib import pyplot as plt import datetime import pandas_datareader.data as web import pandas as pd import numpy as np import seaborn as sns from sklearn.preprocessing import StandardScaler from sklearn.cross_valid...
github_jupyter
<table class="ee-notebook-buttons" align="left"> <td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/Image/convolutions.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td> <td><a target="_blank" href="htt...
github_jupyter
# NWB use-case pvc-7 --- Data courtesy of Aleena Garner, Allen Institute for Brain Sciences --- Here we demonstrate how data from the NWB pvc-7 use-case can be stored in NIX files. ### Context: - *In vivo* calcium imaging of layer 4 cells in mouse primary visual cortex. - Two-photon images sampled @ 30 Hz - Visual s...
github_jupyter
# Processing Dirty Data ## Background This is fake data generated to demonstrate the capabilities of `pyjanitor`. It contains a bunch of common problems that we regularly encounter when working with data. Let's go fix it! ### Load Packages Importing `pyjanitor` is all that's needed to give Pandas Dataframes extr...
github_jupyter
### Imports ``` import importlib from AIBind.import_modules import * from AIBind import AIBind importlib.reload(AIBind) ``` ### GPU Settings ``` str(subprocess.check_output('nvidia-smi', shell = True)).split('\\n') os.environ["CUDA_VISIBLE_DEVICES"] = "2" ``` ### VAENet #### Read In Test Datasets ``` targets_test...
github_jupyter
<p align="center"> <img width="100%" src="../../../multimedia/mindstorms_51515_logo.png"> </p> # `my_favorite_color` Python equivalent of the `My favorite color` program. Makes Charlie react differently depending on the color we show him. # Required robot * Charlie (with color sensor and color palette) <img src="....
github_jupyter
# Assignment 3: Question Answering Welcome to this week's assignment of course 4. In this you will explore question answering. You will implement the "Text to Text Transfer from Transformers" (better known as T5). Since you implemented transformers from scratch last week you will now be able to use them. <img src = ...
github_jupyter
# Za enunt use this ! https://inloop.github.io/sqlite-viewer/ --- ## Za recapitulare SOCKETS ``` #!/usr/bin/python # This is server.py file import socket # Import socket module s = socket.socket() # Create a socket object host = socket.gethostname() # Get local machine name port =...
github_jupyter
# Setting a Meaningful Index The index of a DataFrame provides a label for each of the rows. If not explicitly provided, pandas uses the sequence of consecutive integers beginning at 0 as the index. In this chapter, we learn how to set one of the columns of the DataFrame as the new index so that it provides a more mea...
github_jupyter
``` import os import pandas as pd import random import shutil import librosa import numpy as np import soundfile as sf # Freesound dataset # negative data로 삼을 소리의 유형을 고릅니다. # 여기서는 가정에서 날 법한 소리 위주로 선정했습니다. OtherSound_class = ['Cat', 'Bell', 'Applause', 'Bark', 'Computer_keyboard', 'Clock', 'Cellphone_buzz_and_vibrating...
github_jupyter
# Pytorch Example: Neural Network with Categorical Embeddings In this example we will demonstrate conversion of a Pytorch model that takes numeric and categorical inputs separately, and estimate the treatment effect using some simulated historical data. The model input data is sourced from this kaggle competition: htt...
github_jupyter
# Modeling and Simulation in Python Chapter 23 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
# Predicting Star Temperature with Elastic Net Linear Regression Using the Open Exoplanet Catalogue database: https://github.com/OpenExoplanetCatalogue/open_exoplanet_catalogue/ ## Data License Copyright (C) 2012 Hanno Rein Permission is hereby granted, free of charge, to any person obtaining a copy of this database ...
github_jupyter
# Visualizing Catalytic Potentials of Glycolytic Regulatory Kinases This notebook provides two examples on creating more sophisticated figures using MASSpy. Specifically, the two examples will reproduce the following from the publication by <cite data-cite="YAHP18">Yurkovich et al., 2018</cite> - Example **A**: Reprod...
github_jupyter
``` #export from nbexp_personal import sendEmail ``` ## utils ``` #export def itemgetter(*args): g = operator.itemgetter(*args) def f(*args2): return dict(zip(args, g(*args2))) return f #export def write_json(filename, content): with open(filename, 'w', encoding='UTF-8') as f: json.du...
github_jupyter
# Bayesian Parametric Survival Analysis with PyMC3 ``` %matplotlib inline from matplotlib import pyplot as plt from matplotlib.ticker import StrMethodFormatter import numpy as np import pymc3 as pm import scipy as sp import seaborn as sns from statsmodels import datasets from theano import shared, tensor as tt plt.s...
github_jupyter
# Transposed Convolution :label:`sec_transposed_conv` The CNN layers we have seen so far, such as convolutional layers (:numref:`sec_conv_layer`) and pooling layers (:numref:`sec_pooling`), typically reduce (downsample) the spatial dimensions (height and width) of the input, or keep them unchanged. In semantic segment...
github_jupyter
<table class="ee-notebook-buttons" align="left"> <td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/FeatureCollection/select_by_location.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td> <td><a target="...
github_jupyter
# Calculate molecular descriptors by graph neural net ``` %matplotlib inline import seaborn as sns import matplotlib.pyplot as plt import pandas as pd from sklearn.model_selection import train_test_split from rdkit import Chem import numpy as np #load database path="../database/small_db.csv" df=pd.read_csv(path) df #s...
github_jupyter
``` import cuml import cudf import nvcategory import xgboost as xgb import pandas as pd import numpy as np from sklearn.metrics import mean_squared_error, roc_auc_score #Read in the data. Notice how it decompresses as it reads the data into memory. gdf = cudf.read_csv('/rapids/Data/black-friday.zip') #Taking a look a...
github_jupyter
# COVID-19 and ACE inhibitors **This example does not use actual COVID-19 data and does not offer medical advice.** This notebook shows how to test whether ACI inhibitors explain higher mortality from COVID-19 among hypertensive patients. Suppose we have a machine learning model which predicts COVID-19 mortality bas...
github_jupyter
### Lyrics model. This notebook contains code for training the lyrics models, which is a built using a pretrained BERT model. ``` import pandas as pd import numpy as np import torch from tqdm.notebook import tqdm from transformers import BertTokenizer, BertForSequenceClassification, AdamW, get_linear_schedule_with_...
github_jupyter
``` cd .. # %matplotlib notebook # %matplotlib inline #import mpld3 #mpld3.enable_notebook() import StateModeling as stm import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from Corona.LoadData import loadData, preprocessData from Corona.CoronaModel import CoronaModel, plotTotalCases from bokeh....
github_jupyter
# The Matrix Profile ## Laying the Foundation At its core, the STUMPY library efficiently computes something called a <i><b>matrix profile</b>, a vector that stores the [z-normalized Euclidean distance](https://youtu.be/LnQneYvg84M?t=374) between any subsequence within a time series and its nearest neighbor</i>. To ...
github_jupyter
# Predict comparison ``` import vowpalwabbit def my_predict(vw, ex): pp = 0.0 for f, v in ex.iter_features(): pp += vw.get_weight(f) * v return pp def ensure_close(a, b, eps=1e-6): if abs(a - b) > eps: raise Exception( "test failed: expected " + str(a) ...
github_jupyter
# Analysis of model results To do: * write labels to geotiffs to dir data/test/predict_process or so * implement masks for selecting no_img pixels ``` %load_ext autoreload %autoreload 2 import sys sys.path.append("/mnt/hd_internal/hh/projects_DS/road_detection/roaddetection/") import numpy as np from keras.models...
github_jupyter
This Notebook creates the PNG surface figures for the sequential KL blueprint ``` import numpy as np import nibabel as nib import scipy.io as sio from scipy import stats import pandas as pd import h5py import nilearn import plotly from nilearn import plotting import seaborn as sn from math import pi import matplotlib ...
github_jupyter
[source](../../api/alibi_detect.od.llr.rst) # Likelihood Ratios for Outlier Detection ## Overview The outlier detector described by [Ren et al. (2019)](https://arxiv.org/abs/1906.02845) in [Likelihood Ratios for Out-of-Distribution Detection](https://arxiv.org/abs/1906.02845) uses the likelihood ratio (LLR) between ...
github_jupyter
``` !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/' MODEL_BASE_PA...
github_jupyter
## Requesting Data from Application Programming Interfaces (API's) This notebook demonstrates the fundamentals of interacting with a web-hosted API for the sake of data retrieval. Much of this functionality is made available through the **requests** library which should have already been installed on your machine as pa...
github_jupyter
# Value iteration This assignment is taken from awesome [__CS294__](http://rll.berkeley.edu/deeprlcourse/) as is. All credit goes to them. ## Introduction This assignment will review the two classic methods for solving Markov Decision Processes (MDPs) with finite state and action spaces. We will implement value iter...
github_jupyter
# MOSDBDiscrete In this module, we will have a brief overview of the `MOSDBDiscrete` class, which manages a transistor characterization database and provide methods for designers to query transistor small signal parameters. ## MOSDBDiscrete example To use the transistor characterization database, evaluate the followin...
github_jupyter
# Initiation à la Programmation Orientée Objet > Cours NSI Terminale - Thème 1. - toc: true - badges: true - comments: false - categories: [python, NSI, Terminale, Structure_donnees, POO, TP] - image: images/nsi1.png ## Introduction Objets et POO sont au centre de la manière Python fonctionne. Vous n'êtes pas obli...
github_jupyter
##### Copyright 2018 The TF-Agents Authors. ### Get Started <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://colab.research.google.com/github/tensorflow/agents/blob/master/tf_agents/colabs/4_drivers_tutorial.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px...
github_jupyter
``` %matplotlib inline import matplotlib.pyplot as plt import matplotlib font = {'family': 'normal', 'weight': 'bold', 'size': 15} matplotlib.rc('font', **font) plt.rcParams["figure.figsize"] = [15, 7] from os.path import expanduser SRC_PATH = expanduser("~") + '/SageMaker/mastering-ml-on-aws/chapter...
github_jupyter
# MMTL Basics Tutorial The purpose of this tutorial is to introduce the basic classes and flow of the MMTL package within Snorkel MeTaL (not necessarily to motivate or explain multi-task learning at large; we assume prior experience with MTL). For a broader understanding of the general Snorkel pipeline and Snorkel MeT...
github_jupyter
<div id="qe-notebook-header" align="right" style="text-align:right;"> <a href="https://quantecon.org/" title="quantecon.org"> <img style="width:250px;display:inline;" width="250px" src="https://assets.quantecon.org/img/qe-menubar-logo.svg" alt="QuantEcon"> </a> </div> # Wealth Distribut...
github_jupyter
[![image](https://binder.pangeo.io/badge_logo.svg)](https://gishub.org/leafmap-pangeo) Uncomment the following line to install [leafmap](https://leafmap.org) if needed. ``` # !pip install leafmap import leafmap.kepler as leafmap ``` If you are using a recently implemented leafmap feature that has not yet been releas...
github_jupyter
<a id='pd'></a> <div id="qe-notebook-header" align="right" style="text-align:right;"> <a href="https://quantecon.org/" title="quantecon.org"> <img style="width:250px;display:inline;" width="250px" src="https://assets.quantecon.org/img/qe-menubar-logo.svg" alt="QuantEcon"> </a> </div> #...
github_jupyter
# Assignment 1: Neural Machine Translation Welcome to the first assignment of Course 4. Here, you will build an English-to-German neural machine translation (NMT) model using Long Short-Term Memory (LSTM) networks with attention. Machine translation is an important task in natural language processing and could be ...
github_jupyter
# Now You Code 1: Data Analysis of Movie Goers In this assignment you will perform a data analysis of people who go to the movies. A movie theatre chain asked movie goers to fill out a quick survey in exchange for a 1/2 price ticket. The survey asked for basic demographics: age, gender, occupation and zip code. This...
github_jupyter
# Using Astropy Quantities and Units for astrophysical calculations ## Authors Ana Bonaca, Erik Tollerud, Jonathan Foster, Lia Corrales, Kris Stern, Stephanie T. Douglas ## Learning Goals * Use `Quantity` objects to estimate a hypothetical galaxy's mass * Take advantage of constants in the `astropy.constants` library...
github_jupyter
# 函数 - 函数可以用来定义可重复代码,组织和简化 - 一般来说一个函数在实际开发中为一个小功能 - 一个类为一个大功能 - 同样函数的长度不要超过一屏 Python中的所有函数实际上都是有返回值(return None), 如果你没有设置return,那么Python将不显示None. 如果你设置return,那么将返回出return这个值. ``` def HJN(): print('Hello') return 1000 b=HJN() print(b) HJN def panduan(number): if number % 2 == 0: print('O') e...
github_jupyter
# Reading and writing files, JSON ## Contents: * File Input/Output * Reading and writing JSON ## File Input/Output A huge portion of our input data will come from files that we have stored on our computer (on the file system). A lot of analysis of these files is done in memory in Python, when working with them. We ...
github_jupyter
# Optimizing mining operations This tutorial includes everything you need to set up IBM Decision Optimization CPLEX Modeling for Python (DOcplex), build a Mathematical Programming model, and get its solution by solving the model on Cloud with IBM ILOG CPLEX Optimizer. When you finish this tutorial, you'll have a foun...
github_jupyter
<a href="http://cocl.us/pytorch_link_top"> <img src="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DL0110EN/notebook_images%20/Pytochtop.png" width="750" alt="IBM Product " /> </a> <img src="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DL0110EN...
github_jupyter
# Multi-task recommenders **Learning Objectives** 1. Training a model which focuses on ratings. 2. Training a model which focuses on retrieval. 3. Training a joint model that assigns positive weights to both ratings & retrieval models. ## Introduction In the basic retrieval notebook we built a retrieval system ...
github_jupyter
# Equilibrium analysis Chemical reaction Number (code) of assignment: 2N4 Description of activity: H2 & H3 Report on behalf of: name : Pieter van Halem student number (4597591) name : Dennis Dane student number (4592239) Data of student taking the role of contact person: name : Pieter van Halem email address...
github_jupyter
# Gaussian Process Distribution of Relaxation Times ## In this tutorial we will reproduce Figure 7 of the article https://doi.org/10.1016/j.electacta.2019.135316 GP-DRT is our newly developed approach that can be used to obtain both the mean and covariance of the DRT from the EIS data by assuming that the DRT is a Ga...
github_jupyter
``` import pandas as pd import numpy as np from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split from sklearn.model_selection import train_test_split import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow import keras from tensorflow.keras i...
github_jupyter
``` #Load libraries import warnings warnings.filterwarnings("ignore") import numpy as np import pandas as pd from pandas import read_csv from pandas import set_option from matplotlib import pyplot from pandas import read_csv from pandas import set_option from matplotlib import pyplot as plt import seaborn HOME_PATH = '...
github_jupyter
``` import os os.getcwd() %cd .. from pathlib import Path from mimic.utils.experiment import MimicExperiment from mimic.utils.filehandling import set_paths from mimic.utils import plot from mimic.utils.text import tensor_to_text import json import torch from PIL import ImageFont try: font = ImageFont.truetype('Fr...
github_jupyter
![Callysto.ca Banner](https://github.com/callysto/curriculum-notebooks/blob/master/callysto-notebook-banner-top.jpg?raw=true) <a href="https://hub.callysto.ca/jupyter/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fcallysto%2Fcurriculum-notebooks&branch=master&subPath=Mathematics/StatisticsProject/statistic...
github_jupyter
# 課程重點: 利用Keras 建立神經網路模型 查看優化器的結果 # 範例目標: 使用CIFAR-10圖庫, 看看完整神經網路 ``` from __future__ import print_function import keras from keras.datasets import cifar10 from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.layers import Dense, Dropout, Ac...
github_jupyter
# The data block API ``` from fastai.gen_doc.nbdoc import * from fastai.tabular import * from fastai.text import * from fastai.vision import * np.random.seed(42) ``` The data block API lets you customize the creation of a [`DataBunch`](/basic_data.html#DataBunch) by isolating the underlying parts of that process in ...
github_jupyter
<!--BOOK_INFORMATION--> <img align="left" style="padding-right:10px;" src="figures/PDSH-cover-small.png"> *This notebook contains an excerpt from the [Python Data Science Handbook](http://shop.oreilly.com/product/0636920034919.do) by Jake VanderPlas; the content is available [on GitHub](https://github.com/jakevdp/Pytho...
github_jupyter
``` from google.colab import drive drive.mount('/content/drive') DATA_DIR='/content/drive/MyDrive/BIR_Workshop/model_mesh' !pip install livelossplot --quiet from google.colab import drive import os import matplotlib.pyplot as plt import pandas as pd import torch import numpy as np from sklearn.model_selection import tr...
github_jupyter
# Demo_Chris > Pure markup, demonstrate clustering work for detecting convoys. As we investigated the AIS ship tracking data, we became interested in automatically detecting emergent behavior from groups of ships. For instance: can we automatically detect container ships following a shipping lane? can we find groups o...
github_jupyter
# College Data Clustering > Learn about K-means clustering model. - toc: true - badges: true - comments: true - categories: [clustering] - image: images/collegeData.png ___ When using the Kmeans algorithm under normal circumstances, it is because you don't have labels. In this case we will use the labels to try to...
github_jupyter
``` from pyrep import PyRep import numpy as np from matplotlib import pyplot as plt from pyrep.objects.shape import Shape from pyrep.const import PrimitiveShape from pyrep.objects.vision_sensor import VisionSensor from IPython import display f = open("soma_cube.txt", "r") text = f.read() split_sols = text.split('soluti...
github_jupyter
# 10장. 회귀 분석으로 연속적 타깃 변수 예측하기 **아래 링크를 통해 이 노트북을 주피터 노트북 뷰어(nbviewer.jupyter.org)로 보거나 구글 코랩(colab.research.google.com)에서 실행할 수 있습니다.** <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://nbviewer.jupyter.org/github/rickiepark/python-machine-learning-book-2nd-edition/blob/mas...
github_jupyter
# Asking the right questions ### Business Task: *How can we use trends in smart device usage to produce actionable insights that guide Bellabeat's marketing efforts?* #### About BellaBeat Bellabeat is a wearable smart device company co-founded by Urška Sršen and Sando Mur. Their aim is to create fashionable, fitness...
github_jupyter
``` %load_ext autoreload %autoreload 2 import torch from UnarySim.sw.metric.metric import NormStability, NSbuilder, Stability, ProgressiveError from UnarySim.sw.stream.gen import RNG, SourceGen, BSGen from UnarySim.sw.kernel.relu import UnaryReLU import random import matplotlib.pyplot as plt from mpl_toolkits.mplot3d i...
github_jupyter
# Review of Day 1 ## Fundamentals ### Data Types Everything in Python is an object, and every object has a type. Let's review the most important ones. **Integers** – Whole Numbers ``` i = 3 i ``` **Floats** – Decimal Numbers ``` f = 3.4 f ``` **Strings** – Bits of Text ``` s = 'python' s ``` **Lists** – Orde...
github_jupyter
# データサイエンス100本ノック(構造化データ加工編) - SQL ## はじめに - データベースはPostgreSQL13です - 初めに以下のセルを実行してください - セルに %%sql と記載することでSQLを発行することができます - jupyterからはdescribeコマンドによるテーブル構造の確認ができないため、テーブル構造を確認する場合はlimitを指定したSELECTなどで代用してください - 使い慣れたSQLクライアントを使っても問題ありません(接続情報は以下の通り) - IPアドレス:Docker Desktopの場合はlocalhost、Docker toolboxの場合は192.168.99.1...
github_jupyter
# The basics Here we'll discuss how to instantiate spherical harmonic maps, manipulate them, plot them, and compute simple phase curves and occultation light curves. ``` %matplotlib inline %run notebook_setup.py import starry import matplotlib.pyplot as plt import numpy as np starry.config.lazy = False starry.config...
github_jupyter
# süntaktiline analüüs [deplacy](https://koichiyasuoka.github.io/deplacy/) kaudu ## [Stanza](https://stanfordnlp.github.io/stanza)-ga ``` !pip install deplacy stanza import stanza stanza.download("et") nlp=stanza.Pipeline("et") doc=nlp("Suuga teeb suure linna, käega ei tee kärbse pesagi.") import deplacy deplacy.rend...
github_jupyter
# BloodPressure example This example assumes that PyShEx has been installed in jupyter environment ``` from pyshex import ShExEvaluator from rdflib import Namespace shex = """ BASE <http://example.org/ex/> PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> PREFIX ex: <http://ex.example/#> PREFIX foaf: <http://xmlns.com/f...
github_jupyter
# Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementation of the neural network up to you (for the most part). After you've submitted this project, feel free to explore the data and...
github_jupyter
# Вычислительный практикум # Задание №2 ### Итерационные методы (простой итерации, Зейделя, верхней релаксации) решения СЛАУ. ## Ковальчуков Александр ### 321 группа ### Вариант №6 ``` import numpy as np ``` # Параметры задачи ``` A = np.array([[ 9.016024, 1.082197, -2.783575], [ 1.082197, 6.846595, ...
github_jupyter
# TensorFlow Basics ``` import tensorflow as tf import numpy as np import matplotlib.pyplot as plt %matplotlib inline tf.__version__ ``` ## Constants ``` h = tf.constant('Hello World') h h.graph is tf.get_default_graph() x = tf.constant(100) x # Create Session object in which we can run operations. # A session obje...
github_jupyter
## 1-3. 複数量子ビットの記述 ここまでは1量子ビットの状態とその操作(演算)の記述について学んできた。この章の締めくくりとして、$n$個の量子ビットがある場合の状態の記述について学んでいこう。テンソル積がたくさん出てきてややこしいが、コードをいじりながら身につけていってほしい。 $n$個の**古典**ビットの状態は$n$個の$0,1$の数字によって表現され、そのパターンの総数は$2^n$個ある。 量子力学では、これらすべてのパターンの重ね合わせ状態が許されているので、$n$個の**量子**ビットの状態$|\psi \rangle$はどのビット列がどのような重みで重ね合わせになっているかという$2^n$個の複素確率振幅で記...
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/reinforcement-learning/atari-on-distributed-compute/pong_rllib.png) # Reinforcement Learning in Azur...
github_jupyter
# Algorithm accuracy analysis - In order to test whether Compas scores do an accurate job of deciding whether an offender is Low, Medium or High risk, we ran a Cox Proportional Hazards model. Northpointe, the company that created COMPAS and markets it to Law Enforcement, also ran a Cox model in [their validation study...
github_jupyter
# cadCAD Template: Robot and the Marbles - Part 4 ![](images/Overview.jpeg) ![](images/Mech1.jpeg) ## Non-determinism Non-deterministic systems exhibit different behaviors on different runs for the same input. The order of heads and tails in a series of 3 coin tosses, for example, is non deterministic. Our robots ...
github_jupyter
``` #imports and helper functions import GPy import matplotlib.pyplot as plt import numpy as np %matplotlib inline def plot_hist(bins,bin_ranges,errs,alpha): """Plots a histogram""" assert len(bins)==(len(bin_ranges)-1) yvals = bins/(np.diff(bin_ranges)[:,None]) evals = 1.96*errs/(np.diff(bin_ranges)[...
github_jupyter
# Solving the Traveling Salesperson Problem with Azure Quantum QIO Hello and welcome! In this notebook we will walk you through how you (can) solve the traveling salesperson problem (also known as the traveling salesman problem) with the Azure Quantum quantum inspired optimization (QIO) service. ## Introduction The tr...
github_jupyter
# Deep Q-Network implementation This notebook shamelessly demands you to implement a DQN - an approximate q-learning algorithm with experience replay and target networks - and see if it works any better this way. ``` #XVFB will be launched if you run on a server import os if type(os.environ.get("DISPLAY")) is not str...
github_jupyter
# *Unsupervised learning: Latent Dirichlet allocation (LDA) topic modeling* ``` ## Install a Python package for LDA # http://pythonhosted.org/lda/getting_started.html !pip3 install lda ## Importing basic packages import os import numpy as np ## Downloading 'Essays' by Ralph Waldo Emerson os.chdir('/sharedfolder/') ...
github_jupyter
``` #export from fastai2.basics import * from fastai2.vision.core import * from fastai2.vision.data import * from fastai2.vision.augment import * from fastai2.vision import models #default_exp vision.learner from nbdev.showdoc import * ``` # Learner for the vision applications > All the functions necessary to build ...
github_jupyter
# Marginal Likelihood Implementation The `gp.Marginal` class implements the more common case of GP regression: the observed data are the sum of a GP and Gaussian noise. `gp.Marginal` has a `marginal_likelihood` method, a `conditional` method, and a `predict` method. Given a mean and covariance function, the functio...
github_jupyter
``` import numpy as np import pandas as pd import plotly.graph_objects as go df = pd.read_csv("/content/us_job_industry_data_2019.csv") # TO DO: MAP CITIES TO MASTER LIST def wrangle(X): """ Wrangles and cleans dataframe """ # Creating 2 copies to handle numeric and non-numeric data numeric = X.copy() no...
github_jupyter
# Alignment & Operatrions This notebook is more about *understanding* pandas, "going with the flow", than any particular method or operation. Alignment is a key part of many parts of pandas, including - binary operations (`+, -, *, /, **, ==, |, &`) between pandas objects - merges / joins / concats - constructors (`p...
github_jupyter
# Tutorial XX: Template This tutorial walks you through the process of *FILL IN*. The reason behind when and why this is important should be briefly described in the remainder of this paragraph. If possible, this should be further elucidated by a complementary figure, which can be placed in the folder *tutorials/img*....
github_jupyter
``` import pandas as pd import numpy as np from sklearn.feature_extraction.text import TfidfVectorizer,CountVectorizer import sklearn import boto3 from s3 import get_file from sklearn.decomposition import LatentDirichletAllocation import pyLDAvis import pyLDAvis.sklearn pyLDAvis.enable_notebook() from matplotlib impo...
github_jupyter
# Sign & Speak ML Instructions This notebook shows how to use Amazon SageMaker to run the training and inference scripts for the Sign & Speak project. Use the `conda_pytorch_p36` kernel to run the cells in this notebook. ## Training The following cell defines the training job to be run by Amazon SageMaker. It point...
github_jupyter
<h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Response-to-Thomas-Icard's-question-about-counterfactual-implementation-in-probability-trees." data-toc-modified-id="Response-to-Thomas-Icard's-question-about-counterfactual-implementation-in-probability-tr...
github_jupyter