Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
3,000 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Distributed Training with Keras
Learning Objectives
How to define distribution strategy and set input pipeline.
How to create the Keras model.
How to define the callbacks.
How to train and e... | Python Code:
# Import TensorFlow and TensorFlow Datasets
import tensorflow_datasets as tfds
import tensorflow as tf
import os
# Here we'll show the currently installed version of TensorFlow
print(tf.__version__)
Explanation: Distributed Training with Keras
Learning Objectives
How to define distribution strategy and set... |
3,001 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Speci... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'nims-kma', 'sandbox-1', 'atmoschem')
Explanation: ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era: CMIP6
Institute: NIMS-KMA
Source ID: SANDBOX-1
Topic: Atmoschem
Sub-Topics: Transp... |
3,002 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Working with time series data
Some imports
Step1: Case study
Step2: I downloaded and preprocessed some of the data (python-airbase)
Step3: As you can see, the missing values are indicated... | Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
try:
import seaborn
except:
pass
pd.options.display.max_rows = 8
Explanation: Working with time series data
Some imports:
End of explanation
from IPython.display import HTML
HTML('<iframe src=http://www.eea.eu... |
3,003 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lending Club Loan Data
Step1: 2. Loan Book Distribution across the U.S. States (D3 Choropleths by leveraging the "Bokeh" library)
Here, we provide two choropleth maps concerning the Loan Bo... | Python Code:
# Required Libraries
import os
import pandas as pd
import numpy as np
# Path Definitions of Required Data Sets
loan_df_path = os.path.join('/media/ML_HOME/ML-Data_Repository/data', 'loan_df')
us_states_GeoJSON = os.path.join('/media/ML_HOME/ML-Data_Repository/maps', 'us_states-albersUSA-Geo.json')
Explanat... |
3,004 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Shear Wave Splitting for the Novice
When a shear wave encounters an anisotropic medium, it splits its energy into orthogonally polarised wave sheets. The effect is easily measured on wavefo... | Python Code:
import sys
sys.path.append("..")
import splitwavepy as sw
import matplotlib.pyplot as plt
import numpy as np
data = sw.Pair(noise=0.05,pol=40,delta=0.1)
data.plot()
Explanation: Shear Wave Splitting for the Novice
When a shear wave encounters an anisotropic medium, it splits its energy into orthogonally po... |
3,005 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Random Sampling
Copyright 2015 Allen Downey
License
Step1: Suppose we want to estimate the average weight of men and women in the U.S.
And we want to quantify the uncertainty of the estimat... | Python Code:
from __future__ import print_function, division
import numpy
import scipy.stats
import matplotlib.pyplot as pyplot
from IPython.html.widgets import interact, fixed
from IPython.html import widgets
# seed the random number generator so we all get the same results
numpy.random.seed(18)
# some nicer colors fr... |
3,006 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Session 5
Step2: <a name="part-1---generative-adversarial-networks-gan--deep-convolutional-gan-dcgan"></a>
Part 1 - Generative Adversarial Networks (GAN) / Deep Convolutional GAN (DC... | Python Code:
# First check the Python version
import sys
if sys.version_info < (3,4):
print('You are running an older version of Python!\n\n',
'You should consider updating to Python 3.4.0 or',
'higher as the libraries built for this course',
'have only been tested in Python 3.4 and hi... |
3,007 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Personal implementation of arXiv
Step1: gathering_game class test
Step3: DQN class
Just take it from [2]
Step6: Experience replay memory
This will be used during the training when the los... | Python Code:
# General import
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from collections import namedtuple
from itertools import count
#from copy import deepcopy
#from PIL import Image
import math
import random
import torch
import torch.nn as nn
import torch.optim as optim
import torch.autogr... |
3,008 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Multiprocessing and scarplet
This simple example shows how to use the match_template and compare methods with a multiprocessing worker pool.
It is available as a Jupyter notebook (link) in t... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
from functools import partial
from multiprocessing import Pool
import scarplet as sl
from scarplet.datasets import load_synthetic
from scarplet.WindowedTemplate import Scarp
data = load_synthetic()
# Define parmaters for search
scale = 10
age = 10.
angles ... |
3,009 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
IDX2016B - Week 2 presentations
Classifiers in machine learning - which should I choose and how do I use it?
Kyle Willett
14 June 2016
Step1: Logistic regression
Logistic regression is a me... | Python Code:
%matplotlib inline
# Setup - import some packages we'll need
import numpy as np
import matplotlib.pyplot as plt
Explanation: IDX2016B - Week 2 presentations
Classifiers in machine learning - which should I choose and how do I use it?
Kyle Willett
14 June 2016
End of explanation
from sklearn import datasets... |
3,010 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lesson 49
Step1: This lesson will control all the keyboard controlling functions in the module.
The typewrite() function will type text into a given textbox. It may be useful to use the mou... | Python Code:
import pyautogui
Explanation: Lesson 49:
Controlling the Keyboard with Python
Python can be used to control the keyboard and mouse, which allows us to automate any program that uses these as inputs.
Graphical User Interface (GUI) Automation is particularly useful for repetative clicking or keyboard entry.... |
3,011 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Iris Demo
Check any null and invalid values
Ensure the properties of features and labels
Convert the string value into computational forms
PCA -> Cluster Verification (optional)
Logistic Reg... | Python Code:
from sklearn.datasets import load_iris
irisdata = load_iris()
Explanation: Iris Demo
Check any null and invalid values
Ensure the properties of features and labels
Convert the string value into computational forms
PCA -> Cluster Verification (optional)
Logistic Regreesion/SVM (optional)
Import Iris DataSet... |
3,012 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using numpy
The foundation for numerical computation in Python is the numpy package, and essentially all scientific libraries in Python build on this - e.g. scipy, pandas, statsmodels, sciki... | Python Code:
x = np.array([1,2,3,4,5,6])
print(x)
print('dytpe', x.dtype)
print('shape', x.shape)
print('strides', x.strides)
x.shape = (2,3)
print(x)
print('dytpe', x.dtype)
print('shape', x.shape)
print('strides', x.strides)
x = x.astype('complex')
print(x)
print('dytpe', x.dtype)
print('shape', x.shape)
print('strid... |
3,013 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Using CAD-Based Geometries
In this notebook we'll be exploring how to use CAD-based geometries in OpenMC via the DagMC toolkit. The models we'll be using in this notebook have already... | Python Code:
import urllib.request
fuel_pin_url = 'https://tinyurl.com/y3ugwz6w' # 1.2 MB
teapot_url = 'https://tinyurl.com/y4mcmc3u' # 29 MB
def download(url):
Helper function for retrieving dagmc models
u = urllib.request.urlopen(url)
if u.status != 200:
raise RuntimeError("Failed t... |
3,014 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Evaluate impact of kernel activation and initialization
1. Generate random training data
Step3: 2. Build a simple fully connected model
Step4: 3. Weights initialization
http
Step5: b) Sig... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%pylab inline
%matplotlib inline
pylab.rcParams['figure.figsize'] = (5, 3)
# Create random train data
X_train = np.random.normal(size=(1000, 100))
Y_train = (X_train.sum(axis=1) > 0) * 1
print Y_train.mean()
print X_train.shape
print Y_train.shape
# Normal... |
3,015 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Multiclass Support Vector Machine exercise
Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet) with your assignment submiss... | Python Code:
import os
os.chdir(os.getcwd() + '/..')
# Run some setup code for this notebook
import random
import numpy as np
import matplotlib.pyplot as plt
from utils.data_utils import load_CIFAR10
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpol... |
3,016 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Filtrado eventos de seguridad en forma conservativa con Learninspy
<img style="display
Step1: Carga de datos
Step2: Procesamiento y etiquetado de datos
Step3: Configuración del modelo y s... | Python Code:
# Librerias de Python
import time
import copy
# Dependencias internas
from learninspy.core.autoencoder import StackedAutoencoder
from learninspy.core.model import NetworkParameters
from learninspy.core.optimization import OptimizerParameters
from learninspy.core.stops import criterion
from learninspy.utils... |
3,017 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Functions
Functions are defined as
def function_name(parameters)
Step1: Recursive function
recursive function is an easy way to solve some mathemtical problems but performance varies. The f... | Python Code:
def hello(a,b):
return a+b
hello(1,1)
hello('a','b')
Explanation: Functions
Functions are defined as
def function_name(parameters):
End of explanation
def Fibonacci(n):
if n < 2:
return n
else:
return Fibonacci(n-1)+Fibonacci(n-2)
print Fibonacci(10)
def Fibonacci(n):
retu... |
3,018 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Hypothesis testing for number of mixture components
Step1: Load data, downsample, and keep only first 96 features
Step2: Perform model selection using BIC to find the most likely number of... | Python Code:
import itertools
import csv
import numpy as np
from scipy import linalg
from scipy.stats import cumfreq
import matplotlib.pyplot as plt
import matplotlib as mpl
from sklearn import mixture
%matplotlib inline
np.random.seed(1)
Explanation: Hypothesis testing for number of mixture components
End of explanati... |
3,019 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Применение машины опорных векторов к выявлению фальшивых купюр
Подключим необходимые библиотеки.
Step1: Данные были взяты из репозитория UCI Machine Learning Repository по адресу http
Step2... | Python Code:
import numpy as np, pandas as pd
import matplotlib.pyplot as plt
from sklearn import *
%matplotlib inline
random_state = np.random.RandomState( None )
def collect_result( grid_, names = [ ] ) :
df = pd.DataFrame( { "2-Отклонение" : [ np.std(v_[ 2 ] ) for v_ in grid_.grid_scores_ ],
... |
3,020 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MNIST Convolutional Neural Network - 2nd model
This time we are going to implement a model similar to the one used by Dan Ciresan, Ueli Meier and Jurgen Schmidhuber in 2012. The model should... | Python Code:
import tensorflow as tf
# We don't really need to import TensorFlow here since it's handled by Keras,
# but we do it in order to output the version we are using.
tf.__version__
Explanation: MNIST Convolutional Neural Network - 2nd model
This time we are going to implement a model similar to the one used ... |
3,021 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Messy modelling
Step1: Introducing kNN
Step2: Let's examine the shape of the dataset (the number of rows and columns), the types of features it contains, and some summary statistics for ea... | Python Code:
import wget
import pandas as pd
# Import the dataset
data_url = 'https://raw.githubusercontent.com/nslatysheva/data_science_blogging/master/datasets/spam/spam_dataset.csv'
dataset = wget.download(data_url)
dataset = pd.read_csv(dataset, sep=",")
# Take a peak at the data
dataset.head()
Explanation: Messy m... |
3,022 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Check whether a SMIRNOFF-format force field is able to parametrize a dataset of interest
This notebook runs a quick initial analysis of whether a molecule set can be simulated by a gi... | Python Code:
from openff.toolkit.topology import Molecule, Topology
from openff.toolkit.typing.engines.smirnoff import (ForceField,
UnassignedValenceParameterException, BondHandler, AngleHandler,
ProperTorsionHandler, ImproperTorsionHandler,
vdWHandler)
from simtk import unit
import numpy as np
from rdkit import Chem
... |
3,023 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lab of data analysis with python
In this lab we will introduce some of the modules that we will use in the rest of the labs of the course.
The usual beginning of any python module is a list ... | Python Code:
%matplotlib inline
# The line above is needed to include the figures in this notebook, you can remove it if you work with a normal script
import numpy as np
import csv
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsRegressor
from sklearn.preprocessing import StandardScaler
f... |
3,024 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Automatic Differentiation with autograd
Technically, autograd is layer that wraps and extends numpy. Hence it is most often imported as follows
Step1: The function sigmoid implements the s... | Python Code:
import autograd
import autograd.numpy as np
Explanation: Automatic Differentiation with autograd
Technically, autograd is layer that wraps and extends numpy. Hence it is most often imported as follows:
End of explanation
def S(x):
return 1.0 / (1.0 + np.exp(-x))
def Q(x):
return np.multiply(x, x)
... |
3,025 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href='http
Step1: The Data
There are some fake data csv files you can read in as dataframes
Step2: Style Sheets
Matplotlib has style sheets you can use to make your plots look a little ... | Python Code:
import numpy as np
import pandas as pd
%matplotlib inline
Explanation: <a href='http://www.pieriandata.com'> <img src='../../Pierian_Data_Logo.png' /></a>
Pandas Built-in Data Visualization
In this lecture we will learn about pandas built-in capabilities for data visualization! It's built-off of matplotlib... |
3,026 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Array manipulation routines
Step1: Q1. Let x be a ndarray [10, 10, 3] with all elements set to one. Reshape x so that the size of the second dimension equals 150.
Step2: Q2. Let x be array... | Python Code:
import numpy as np
np.__version__
Explanation: Array manipulation routines
End of explanation
x = np.ones([10, 10, 3])
out = np.reshape(x, [-1, 150])
print out
assert np.allclose(out, np.ones([10, 10, 3]).reshape([-1, 150]))
Explanation: Q1. Let x be a ndarray [10, 10, 3] with all elements set to one. Resh... |
3,027 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
베이지안 모수 추정의 예
베이지안 모수 추정(Bayesian parameter estimation) 방법은 모수의 값에 해당하는 특정한 하나의 숫자를 계산하는 것이 아니라 모수의 값이 가질 수 있는 모든 가능성, 즉 모수의 분포를 계산하는 작업이다.
이때 계산된 모수의 분포를 표현 방법은 두 가지가 있다.
비모수적(non-parametri... | Python Code:
theta0 = 0.6
a0, b0 = 1, 1
print("step 0: mode = unknown")
xx = np.linspace(0, 1, 1000)
plt.plot(xx, sp.stats.beta(a0, b0).pdf(xx), label="initial");
np.random.seed(0)
x = sp.stats.bernoulli(theta0).rvs(50)
N0, N1 = np.bincount(x, minlength=2)
a1, b1 = a0 + N1, b0 + N0
plt.plot(xx, sp.stats.beta(a1, b1).pd... |
3,028 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Visualization with Matplotlib
Learning Objectives
Step1: Overview
The following conceptual organization is simplified and adapted from Benjamin Root's AnatomyOfMatplotlib tutorial.
Figures ... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
Explanation: Visualization with Matplotlib
Learning Objectives: Learn how to make basic plots using Matplotlib's pylab API and how to use the Matplotlib documentation.
This notebook focuses only on the Matplotlib API, rather that the bro... |
3,029 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step3: Functions for angular velocity & integration
The particle is an ellipsoid. The reference state (corresponding to no rotation) is that the ellipsoid is axis-aligned and the axis length... | Python Code:
def jeffery_omega(L, K, n1, n2, n3, Omega, E):
Compute Jeffery angular velocity
L: (lambda^2-1)/(lambda^2+1)
K: (kappa^2-1)/(kappa^2+1)
n1,n2,n3: vector triplet representing current orientation
Omega: vorticity (lab frame)
E: strain matrix (lab frame)
Returns (3,) nda... |
3,030 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Recommender System
The Netflix Challenge
The principle of this recommander system is the same as the Netflix Challenge
Step1: Scale all the grade between 0 (with lowest value) and 10 (the o... | Python Code:
authorID_to_titles_stem = utils.load_pickle("../pmi_data/authorID_to_titles_stem.p")
score_by_author = utils.load_pickle("../pmi_data/score_by_author_by_document.p")
Explanation: Recommender System
The Netflix Challenge
The principle of this recommander system is the same as the Netfli... |
3,031 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Save & Restore with a minist example
Minist예제를 수행하면 알겠지만, Train에 생각보다는 꽤 많은 시간이 소요됩니다.
이 이유만이 아니라 평가시에는 trainnig후에 model의 parameter를 저장했다가 평가시에는 그 parameter를 불러들여서 사용하는 것이 일반적입니다.
여기에 사용되는 함... | Python Code:
%matplotlib inline
Explanation: Save & Restore with a minist example
Minist예제를 수행하면 알겠지만, Train에 생각보다는 꽤 많은 시간이 소요됩니다.
이 이유만이 아니라 평가시에는 trainnig후에 model의 parameter를 저장했다가 평가시에는 그 parameter를 불러들여서 사용하는 것이 일반적입니다.
여기에 사용되는 함수는 torch.save, torch.load와 model.state_dict(), model.load_state_dict()입니다.
사실 4장의 tut... |
3,032 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Indirection
They say "all problems in computer science can be solved with an extra level of indirection."
It certainly provides some real leverage in data wrangling. Rather than write a bu... | Python Code:
health_map = Table(["raw label", "label", "encoding", "Description"]).with_rows(
[["hhidpn", "id", None, "identifier"],
["r8agey_m", "age", None, "age in years in wave 8"],
["ragender", "gender", ['male','female'], "1 = male, 2 = female)"],
["raracem", "race", ['white','... |
3,033 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Adding a Reduction Operation
This notebook will show you how to add a new reduction operation last_date to the existing backend SQLite.
A reduction operation is a function that maps $N$ rows... | Python Code:
import ibis.expr.datatypes as dt
import ibis.expr.rules as rlz
from ibis.expr.operations import Reduction
class LastDate(Reduction):
arg = rlz.column(rlz.date)
where = rlz.optional(rlz.boolean)
output_dtype = rlz.dtype_like('arg')
output_shape = rlz.Shape.SCALAR
Explanation: Adding a Reduct... |
3,034 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Land
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify do... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'test-institute-2', 'sandbox-3', 'land')
Explanation: ES-DOC CMIP6 Model Properties - Land
MIP Era: CMIP6
Institute: TEST-INSTITUTE-2
Source ID: SANDBOX-3
Topic: Land
Sub-Topics: Soil,... |
3,035 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A comparison of methods of random choice
random.choice vs. a random.multinomial based implementation of the same weighted choice. Also compare with a GNU Scientific Library based implementat... | Python Code:
import numpy as np
%load_ext Cython
Explanation: A comparison of methods of random choice
random.choice vs. a random.multinomial based implementation of the same weighted choice. Also compare with a GNU Scientific Library based implementation.
Context: random.choice is only available in numpy >= 1.7, so I ... |
3,036 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Getting started
Step1: Authenticate your GCP account
If you are using AI Platform Notebooks, your environment is already
authenticated. Skip this step.
If you are using Colab, run the cell ... | Python Code:
PROJECT_ID = "<your-project-id>" #@param {type:"string"}
! gcloud config set project $PROJECT_ID
Explanation: Getting started: Training and prediction with Keras in AI Platform
<img src="https://storage.googleapis.com/cloud-samples-data/ai-platform/census/keras-tensorflow-cmle.png" alt="Keras, TensorFlow, ... |
3,037 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Explore with Sqlite databases
Step1: Get utterances from certain time periods in each experiment or for certain episodes
Step2: Get mutual information between words used in referring expre... | Python Code:
import sys
sys.path.append("../python/")
import pentoref.IO as IO
import sqlite3 as sqlite
# Create databases if required
if False: # make True if you need to create the databases from the derived data
for corpus_name in ["TAKE", "TAKECV", "PENTOCV"]:
data_dir = "../../../pentoref/{0}_PENTORE... |
3,038 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.
Running External Command
Step1: Capturing Output
The stand... | Python Code:
import subprocess
completed = subprocess.run(['ls', '-l'])
completed
Explanation: The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.
Running External Command
End of explanation
completed = subprocess.run(['ls', '-l'], stdout=su... |
3,039 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
LINEAR REGRESSION
is the simplest machine learning model
is used for finding linear relationship between target and one or more predictors
there are two types of linear regression
Step1: Ev... | Python Code:
import pandas as pd
import numpy as np
import json
import graphviz
import matplotlib.pyplot as plt
from sklearn import linear_model
pd.set_option("display.max_rows",6)
%matplotlib inline
df_data = pd.read_csv('varsom_ml_preproc.csv', index_col=0)
X = df_data.filter(['mountain_weather_wind_speed_num', 'moun... |
3,040 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Matrix generation
Init symbols for sympy
Step1: Lame params
Step2: Metric tensor
${\displaystyle \hat{G}=\sum_{i,j} g^{ij}\vec{R}_i\vec{R}_j}$
Step3: ${\displaystyle \hat{G}=\sum_{i,j} g_... | Python Code:
from sympy import *
from geom_util import *
from sympy.vector import CoordSys3D
N = CoordSys3D('N')
alpha1, alpha2, alpha3 = symbols("alpha_1 alpha_2 alpha_3", real = True, positive=True)
init_printing()
%matplotlib inline
%reload_ext autoreload
%autoreload 2
%aimport geom_util
Explanation: Matrix generati... |
3,041 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
First read in the original data
Step1: repeat the processing with all_encounter_data in ICO.py
Step2: After setting up the standard range of outliers, we lost at most 600 points for each v... | Python Code:
import re
data = pd.read_pickle(os.getcwd() + '/data/all_encounter_data.pickle')
Explanation: First read in the original data
End of explanation
d_enc = data.drop(["Enc_ID","Person_ID"], axis=1)
pattern0= re.compile("\d+\s*\/\s*\d+")
index1 = d_enc['Glucose'].str.contains(pattern0, na=False)
temp = d_enc.l... |
3,042 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
With rerun = True, all experiments are executed again (takes several hours). With False, the data are taken from the *.csv files
Step1: The generate function may be used to generate random ... | Python Code:
rerun = False
%%bash
ltl3ba -v
ltl3tela -v
ltl2tgba --version
delag --version
ltl2dgra --version # Rabinizer 4
Explanation: With rerun = True, all experiments are executed again (takes several hours). With False, the data are taken from the *.csv files:
End of explanation
def generate(n=1000,func=(lambda x... |
3,043 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Preamble
Step1: Feature Union with Heterogeneous Data Sources
Polynomial basis function
The polynomial basis function is provided by scikit-learn in the sklearn.preprocessing module.
Step2:... | Python Code:
import numpy as np
from scipy.spatial.distance import cdist
from scipy.special import expit
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.pipeline import make_pipeline, make_union
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
... |
3,044 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Features of BIDMat and Scala
BIDMat is a multi-platform matrix library similar to R, Matlab, Julia or Numpy/Scipy. It takes full advantage of the very powerful Scala Language. Its intended p... | Python Code:
import BIDMat.{CMat,CSMat,DMat,Dict,IDict,FMat,FND,GMat,GDMat,GIMat,GLMat,GSMat,GSDMat,
HMat,IMat,Image,LMat,Mat,ND,SMat,SBMat,SDMat}
import BIDMat.MatFunctions._
import BIDMat.SciFunctions._
import BIDMat.Solvers._
import BIDMat.JPlotting._
Mat.checkMKL
Mat.checkCUDA
Mat.setInline
if (Mat.h... |
3,045 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="../../../images/qiskit-heading.png" alt="Note
Step1: Quantum walk, phase I/II on $N=4$ lattice$(t=8)$
Step2: Below is the result when executing the circuit on the simulator.
Step... | Python Code:
#initialization
import sys
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing QISKit
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import Aer, IBMQ, execute
from qiskit.wrapper.jupyter import *
from qiskit.backends.ibmq import least_busy
fr... |
3,046 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Project Euler
Step2: Now write a set of assert tests for your number_to_words function that verifies that it is working as expected.
Step4: Now define a count_letters(n) that return... | Python Code:
def number_to_words(n):
Given a number n between 1-1000 inclusive return a list of words for the number.
# YOUR CODE HERE
# English name of each digit/ place in dictionary
one = {
0: '',
1: 'one',
2: 'two',
3: 'three',
4: 'four',
... |
3,047 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Installation
pip install https
Step1: Importing data
For this tutorial, we are using anthropometric data from the Genetic Investigation of ANthropometric Traits (GIANT) consortium
Step2: M... | Python Code:
%matplotlib inline
#Here we set the dimensions for the figures in this notebook
import matplotlib as mpl
mpl.rcParams['figure.dpi']=150
mpl.rcParams['savefig.dpi']=150
mpl.rcParams['figure.figsize']=7.375, 3.375
Explanation: Installation
pip install https://github.com/khramts/assocplots/archive/master.zip
... |
3,048 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Seaice
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify ... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'fio-ronm', 'sandbox-3', 'seaice')
Explanation: ES-DOC CMIP6 Model Properties - Seaice
MIP Era: CMIP6
Institute: FIO-RONM
Source ID: SANDBOX-3
Topic: Seaice
Sub-Topics: Dynamics, Therm... |
3,049 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Initialise the libs
Step1: Load the data
Step2: Data exploration
Step3: Helper functions
Step4: Ridge regression model fitting
Step5: Ridge regression on subsets
Using ridge regression ... | Python Code:
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import linear_model
import numpy as np
from math import ceil
Explanation: Initialise the libs
End of explanation
dtype_dict = {'bathrooms':float, 'waterfront':int, 'sqft_above':int, 'sqft_living15':float, 'grade':int, 'yr_renovated':int, 'pri... |
3,050 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Integración numérica Montecarlo
Referencia
Step1: Integración Montecarlo tipo 1
Se basa en la definición de valor promedio de una función y en el valor esperado de una variable aleatoria un... | Python Code:
from IPython.display import YouTubeVideo
YouTubeVideo('Ti5zUD08w5s')
YouTubeVideo('jmsFC0mNayM')
Explanation: Integración numérica Montecarlo
Referencia:
- https://ocw.mit.edu/courses/mechanical-engineering/2-086-numerical-computation-for-mechanical-engineers-fall-2014/nutshells-guis/MIT2_086F14_Monte_Carl... |
3,051 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Schelling Segregation Model
Background
The Schelling (1971) segregation model is a classic of agent-based modeling, demonstrating how agents following simple rules lead to the emergence of q... | Python Code:
import matplotlib.pyplot as plt
%matplotlib inline
from Schelling import model
Explanation: Schelling Segregation Model
Background
The Schelling (1971) segregation model is a classic of agent-based modeling, demonstrating how agents following simple rules lead to the emergence of qualitatively different ma... |
3,052 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tasa atractiva mínima (MARR)
Notas de clase sobre ingeniería economica avanzada usando Python
Juan David Velásquez Henao
jdvelasq@unal.edu.co
Universidad Nacional de Colombia, Sede Medellín... | Python Code:
import cashflows as cf
##
## Se tienen cuatro fuentes de capital con diferentes costos
## sus datos se almacenarar en las siguientes listas:
##
monto = [0] * 4
interes = [0] * 4
## emision de acciones
## --------------------------------------
monto[0] = 4000
interes[0] = 25.0 / 1.0 # tasa de descueto ... |
3,053 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
if,elif,else Statements
if Statements in Python allows us to tell the computer to perform alternative actions based on a certain set of results.
Verbally, we can imagine we are telling the c... | Python Code:
if True:
print 'It was true!'
Explanation: if,elif,else Statements
if Statements in Python allows us to tell the computer to perform alternative actions based on a certain set of results.
Verbally, we can imagine we are telling the computer:
"Hey if this case happens, perform some action"
We can then e... |
3,054 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Basic Manipulation
Splipy implements all affine transformations like translate (move), rotate, scale etc. These should be available as operators where this makes sense. To start, we need to ... | Python Code:
import splipy as sp
import numpy as np
import matplotlib.pyplot as plt
import splipy.curve_factory as curve_factory
Explanation: Basic Manipulation
Splipy implements all affine transformations like translate (move), rotate, scale etc. These should be available as operators where this makes sense. To start,... |
3,055 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lab exercises
Simplicial complex in Dionysus is just a list of its simplices. See how we define a full triangle spanned on vertices labeled with 0, 1 and 2 in the following example.
Step1: ... | Python Code:
from dionysus import Simplex
complex = [Simplex([0]), Simplex([1]), Simplex([2]), Simplex([0, 1]),
Simplex([0, 2]), Simplex([2, 1]), Simplex([0, 1, 2])]
complex
Explanation: Lab exercises
Simplicial complex in Dionysus is just a list of its simplices. See how we define a full triangle spanned o... |
3,056 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
VIX S&P500 Volatility
In this notebook, we'll take a look at the VIX S&P500 Volatility dataset, available on the Quantopian Store. This dataset spans 02 Jan 2004 through the current day. Thi... | Python Code:
# For use in Quantopian Research, exploring interactively
from quantopian.interactive.data.quandl import cboe_vix as dataset
# import data operations
from odo import odo
# import other libraries we will use
import pandas as pd
# Let's use blaze to understand the data a bit using Blaze dshape()
dataset.dsha... |
3,057 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interact Exercise 4
Imports
Step2: Line with Gaussian noise
Write a function named random_line that creates x and y data for a line with y direction random noise that has a normal distribut... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from IPython.html.widgets import interact, interactive, fixed
from IPython.display import display
Explanation: Interact Exercise 4
Imports
End of explanation
def random_line(m, b, sigma, size=10):
Create a line y = m*x + b + N(0,sigm... |
3,058 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using ReNA to find supervoxels
The aims of the notebook is to provide an illustration of how to use ReNA
to build superpixels. This corresponds to clustering voxels.
Here we use the Haxby ... | Python Code:
from nilearn import datasets
dataset = datasets.fetch_haxby(subjects=1)
import numpy as np
from nilearn.input_data import NiftiMasker
masker = NiftiMasker(mask_strategy='epi', smoothing_fwhm=6, memory='cache')
X_masked = masker.fit_transform(dataset.func[0])
X_train = X_masked[:100, :]
X_data = masker.inve... |
3,059 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Infinite Hidden Markov Model
authors
Step1: First we define the possible states in the model. In this case we make them all have normal distributions.
Step2: We then create the HMM object,... | Python Code:
from pomegranate import *
import itertools as it
import numpy as np
Explanation: Infinite Hidden Markov Model
authors:<br>
Jacob Schreiber [<a href="mailto:jmschreiber91@gmail.com">jmschreiber91@gmail.com</a>]<br>
Nicholas Farn [<a href="mailto:nicholasfarn@gmail.com">nicholasfarn@gmail.com</a>]
This examp... |
3,060 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In the above cell, I have used the first element of the array for calculating 'yactual' value
Step1: The .fit function is throwing out an error saying that first argument in that function m... | Python Code:
len(Amatrix[0])
#performing multiple simple linear regression for only the a,Amatrix, because of error of the .fit function
from sklearn import linear_model
regr=linear_model.LinearRegression()#performing the simple linear regression
regr.fit(a[0].reshape(len(a),1),yactual.reshape(len(yactual),1))
Explanat... |
3,061 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: Embeddings de Palavras
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: Usando a camada Embe... | Python Code:
#@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
# dist... |
3,062 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Formatting csv data for loading into atlasbiowork Postgres database
First, get column names set up. Implement foreign keys FIRST, as csv, and then by join operation with site table.
Then use... | Python Code:
import pandas as pd
import numpy as np
import json
#fields for csv
site_fields = ['id', 'name', 'geometry','accuracy']
observation_fields = ['entered', 'values','observer_id', 'site_id', 'type_id', 'parentobs_id']
Explanation: Formatting csv data for loading into atlasbiowork Postgres database
First, get c... |
3,063 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1 Make a request from the Forecast.io API for where you were born (or lived, or want to visit!)
Tip
Step1: 2. What's the current wind speed? How much warmer does it feel than it actually is... | Python Code:
#https://api.forecast.io/forecast/APIKEY/LATITUDE,LONGITUDE,TIME
response = requests.get('https://api.forecast.io/forecast/4da699cf85f9706ce50848a7e59591b7/12.971599,77.594563')
data = response.json()
#print(data)
#print(data.keys())
print("Bangalore is in", data['timezone'], "timezone")
timezone_find = da... |
3,064 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Setup
Step1: Prepare Vectors
Step2: Use Scikit's semisupervised learning
There are two semisupervised methods that scikit has. Label Propagation and Label Spreading. The difference is in h... | Python Code:
import tsvopener
import pandas as pd
import numpy as np
from nltk import word_tokenize
from sklearn.feature_extraction.text import CountVectorizer
from scipy.sparse import csr_matrix, vstack
from sklearn.semi_supervised import LabelPropagation, LabelSpreading
regex_categorized = tsvopener.open_tsv("categor... |
3,065 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Experiment
Step1: Load and check data
Step2: ## Analysis
Experiment Details
Step3: What is the impact of removing connections with highest coactivation
Step4: What is the optimal combina... | Python Code:
%load_ext autoreload
%autoreload 2
import sys
sys.path.append("../../")
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import glob
import tabulate
import pprint
import click
import numpy as np
import pandas as pd
from ray.tune.commands... |
3,066 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pandas querying and metadata with Epochs objects
Demonstrating pandas-style string querying with Epochs metadata.
For related uses of
Step1: We can use this metadata attribute to select su... | Python Code:
# Authors: Chris Holdgraf <choldgraf@gmail.com>
# Jona Sassenhagen <jona.sassenhagen@gmail.com>
# Eric Larson <larson.eric.d@gmail.com>
# License: BSD (3-clause)
import mne
import numpy as np
import matplotlib.pyplot as plt
# Load the data from the internet
path = mne.datasets.kiloword.da... |
3,067 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Landice
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'uhh', 'sandbox-2', 'landice')
Explanation: ES-DOC CMIP6 Model Properties - Landice
MIP Era: CMIP6
Institute: UHH
Source ID: SANDBOX-2
Topic: Landice
Sub-Topics: Glaciers, Ice.
Proper... |
3,068 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Seaice
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify ... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'ec-earth-consortium', 'ec-earth3-hr', 'seaice')
Explanation: ES-DOC CMIP6 Model Properties - Seaice
MIP Era: CMIP6
Institute: EC-EARTH-CONSORTIUM
Source ID: EC-EARTH3-HR
Topic: Seaice... |
3,069 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<font size='5' face='Courier New'><h1 align="center"><i>The Primal & Dual Linear Programming Problems
Step1: <font size='7' face='Times New Roman'><b>1. <u>Primal</u></b></font>
Step2: <fo... | Python Code:
# Imports
import numpy as np
import gurobipy as gbp
import datetime as dt
# Constants
Aij = np.random.randint(5, 50, 25)
Aij = Aij.reshape(5,5)
AijSum = np.sum(Aij)
Cj = np.random.randint(10, 20, 5)
CjSum = np.sum(Cj)
Bi = np.random.randint(10, 20, 5)
BiSum = np.sum(Bi)
# Matrix Shape
rows = range(len(Aij... |
3,070 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interact Exercise 01
Import
Step2: Interact basics
Write a print_sum function that prints the sum of its arguments a and b.
Step3: Use the interact function to interact with the print_sum ... | Python Code:
%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
from IPython.html.widgets import interact, interactive, fixed
from IPython.display import display
Explanation: Interact Exercise 01
Import
End of explanation
def print_sum(a, b):
Print the sum of the arguments a and b.
print... |
3,071 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Regression Algorithms
Step1: PCA
Step2: PCA Algorithm Basics
The PCA Algorithm relies heavily on the Spectral (eigenvalue) related properties of a matrix.
Dumb question $ -$ what are the e... | Python Code:
# Can't find good material for this...
Explanation: Regression Algorithms
End of explanation
# Can't find good material for this.
Explanation: PCA
End of explanation
# Let us see what this would look like in numpy.
# First make choose m and n such that m != n
m = 5
n = 10
# Make the matrix A
A = np.random.... |
3,072 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Projecting terrestrial biodiversity using PREDICTS and LUH2
This notebook shows how to use rasterset to project a PREDICTS model using the LUH2 land-use data.
You can set three parameters be... | Python Code:
import click
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import numpy.ma as ma
import rasterio
from rasterio.plot import show, show_hist
Explanation: Projecting terrestrial biodiversity using PREDICTS and LUH2
This notebook shows how to use rasterset to project a PREDICTS model us... |
3,073 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Table of Contents
<p><div class="lev1 toc-item"><a href="#Generating-Fractal-From-Random-Points---The-Chaos-Game" data-toc-modified-id="Generating-Fractal-From-Random-Points---The-Chaos-Game... | Python Code:
import pickle,glob
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
%pylab inline
Explanation: Table of Contents
<p><div class="lev1 toc-item"><a href="#Generating-Fractal-From-Random-Points---The-Chaos-Game" data-toc-modified-id="Generating-Fractal-From-Random-Points---The-Chaos-Game... |
3,074 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Libraries and Packages
Step1: Connecting to National Data Service
Step2: Extracting Data of Midwestern states of the United states from 1992 - 2016.
The following query will extract data f... | Python Code:
import pymongo
from pymongo import MongoClient
import time
import pandas as pd
import numpy as np
import seaborn as sns
from matplotlib.pyplot import *
import matplotlib.pyplot as plt
import folium
import datetime as dt
import random as rnd
import warnings
import datetime as dt
import csv
%matplotlib inlin... |
3,075 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Non-parametric embedding with UMAP.
This notebook shows an example of a non-parametric embedding using the same training loops as are used with a parametric embedding.
load data
Step1: cre... | Python Code:
from tensorflow.keras.datasets import mnist
(train_images, Y_train), (test_images, Y_test) = mnist.load_data()
train_images = train_images.reshape((train_images.shape[0], -1))/255.
test_images = test_images.reshape((test_images.shape[0], -1))/255.
Explanation: Non-parametric embedding with UMAP.
This noteb... |
3,076 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data Loading
Get some data to play with
Step1: Data is always a numpy array (or sparse matrix) of shape (n_samples, n_features)
Split the data to get going
Step2: Exercises
Load the iris d... | Python Code:
from sklearn.datasets import load_digits
import numpy as np
digits = load_digits()
digits.keys()
digits.data.shape
digits.target.shape
digits.target
np.bincount(digits.target)
import matplotlib.pyplot as plt
%matplotlib notebook
# you can also use matplotlib inline
plt.matshow(digits.data[0].reshape(8, 8),... |
3,077 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 DeepMind Technologies Limited.
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 ... | Python Code:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
import collections
import os
from google.colab import auth
auth.authenticate_user()
#@title Choices about the dataset you want to load.
# Make choices abou... |
3,078 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
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 implementat... | Python Code:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
Explanation: 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 t... |
3,079 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Skill Clustering by Matrix Factorization
Steps of skill clustering
Step1: First, we try it on count matrix as the matrix is already avail.
NMF on count matrix
Step2: There are various choi... | Python Code:
import my_util as my_util
import cluster_skill_helpers as cluster_skill_helpers
from cluster_skill_helpers import *
import random as rd
HOME_DIR = 'd:/larc_projects/job_analytics/'
SKILL_DAT = HOME_DIR + 'data/clean/skill_cluster/'
SKILL_RES = HOME_DIR + 'results/' + 'skill_cluster/new/'
Explanation: Skil... |
3,080 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Face verification using Siamese Networks
Goals
train a network for face similarity using siamese networks
work data augmentation, generators and hard negative mining
use the model on your pi... | Python Code:
import tensorflow as tf
# If you have a GPU, execute the following lines to restrict the amount of VRAM used:
gpus = tf.config.experimental.list_physical_devices('GPU')
if len(gpus) > 1:
print("Using GPU {}".format(gpus[0]))
tf.config.experimental.set_visible_devices(gpus[0], 'GPU')
else:
print... |
3,081 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Assignment
Step1: Problem 3
Write a Python program that solves $Ax = b$ using LU decomposition. Use the functions <i>lu_factor</i> and <i>lu_solve</i> from <i>scipy.linalg</i> package.
$$ A... | Python Code:
# Initial import statements
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.pyplot import *
from numpy import *
from numpy.linalg import *
Explanation: Assignment: 05 LU decomposition etc.
Introduction to Numerical Problem Solving, Spring 2017
19.2.2017, Joonas Forsbe... |
3,082 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
RoadRunner transit model example I - basics
Author
Step1: Import the model
Step2: Example 1
Step3: Next, we initialise and set up a RoadRunnerModel choosing to use the four-parameter nonl... | Python Code:
%pylab inline
rc('figure', figsize=(13,5))
def plot_lc(time, flux, c=None, ylim=(0.9865, 1.0025), ax=None):
if ax is None:
fig, ax = subplots()
else:
fig, ax = None, ax
ax.plot(time, flux, c=c)
ax.autoscale(axis='x', tight=True)
setp(ax, xlabel='Time [d]', ylabel='Flux',... |
3,083 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Author
Step1: Exploratory analysis
First let's check out what the data look like and see if we can identify some patterns.
Step2: From a cursory look at the data we can see that there are ... | Python Code:
from itertools import chain
import pandas as pd
import re
from bob_emploi.data_analysis.lib import cleaned_data
jobs = cleaned_data.rome_jobs('../../../data')
Explanation: Author: Paul Duan
Skip the run test because the ROME version has to be updated to make it work in the exported repository. TODO: Update... |
3,084 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This is an example of using Python and R together within a Jupyter notebook. First, let's generate some data within python.
Step1: Now, we pass those two variables into R and perform linear... | Python Code:
import numpy
%load_ext rpy2.ipython
x=numpy.random.randn(100)
beta=3
y=beta*x+numpy.random.randn(100)
Explanation: This is an example of using Python and R together within a Jupyter notebook. First, let's generate some data within python.
End of explanation
%%R -i x,y -o beta_est
result=lm(y~x)
beta_est=re... |
3,085 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Machine Learning Model
Business Problem
Startup XYZ is in the business of giving personal loans, structured as non-recourse loans. The defaults on their loans are much higher than their comp... | Python Code:
#Load the libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Default Variables
%matplotlib inline
plt.rcParams['figure.figsize'] = (8,6)
plt.style.use('ggplot')
pd.set_option('display.float_format', lambda x: '%.2f' % x)
#Load the training dataset
df = pd.read_csv("../data/hi... |
3,086 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Multi-Task Learning Example
This is a simple example to show how to use mxnet for multi-task learning.
The network is jointly going to learn whether a number is odd or even and to actually r... | Python Code:
import logging
import random
import time
import matplotlib.pyplot as plt
import mxnet as mx
from mxnet import gluon, nd, autograd
import numpy as np
Explanation: Multi-Task Learning Example
This is a simple example to show how to use mxnet for multi-task learning.
The network is jointly going to learn whet... |
3,087 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
이 자체로 훌륭한 테스트 코드라고 말하는 것은 어렵다.
주피터 노트북용 테스트 코드였다.
python에서는 테스트 코드를 작성할 수 있는 unittest 모듈을 제공한다.
Step1: 개발 프로세스를 살펴보면
TDD => 테스트 주도 개발 ( Test Driven Development )
왜 중요할까요?
테스트 > 코드 => "테스트 코... | Python Code:
# 우선 형태만 보면
# class TestDoubleFunction(unittest.TestCase):
# def test_5_should_return_10(self):
# self.assertEqual(double(5), 10) # 이거랑 동일 assert double(5) == 10
# 주피터노트북에서는 이러한 형태로 테스트 못한다. 그래서 일단 pass
# 우선 hello.py라는 txt파일을 만든다. 안에 내용은
# def hello(name):
# print("hello, {name}".format... |
3,088 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
内容索引
该小结主要介绍了NumPy数组的基本操作。
子目1中,介绍创建和索引数组,数据类型,dtype类,自定义异构数据类型。
子目2中,介绍数组的索引和切片,主要是对[]运算符的操作。
子目3中,介绍如何改变数组的维度,分别介绍了ravel函数、flatten函数、transpose函数、resize函数、reshape函数的用法。
Step1: ndarray是一个多维... | Python Code:
%pylab inline
Explanation: 内容索引
该小结主要介绍了NumPy数组的基本操作。
子目1中,介绍创建和索引数组,数据类型,dtype类,自定义异构数据类型。
子目2中,介绍数组的索引和切片,主要是对[]运算符的操作。
子目3中,介绍如何改变数组的维度,分别介绍了ravel函数、flatten函数、transpose函数、resize函数、reshape函数的用法。
End of explanation
a = arange(5)
a.dtype
a
a.shape
Explanation: ndarray是一个多维数组对象,该对象由实际的数据、描述这些数据的元数据组成,大部分数组操... |
3,089 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
GLM
Step1: Local Functions
Step2: Generate Data
This dummy dataset is created to emulate some data created as part of a study into quantified self, and the real data is more complicated th... | Python Code:
## Interactive magics
%matplotlib inline
import sys
import warnings
warnings.filterwarnings('ignore')
import re
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import patsy as pt
from scipy import optimize
# pymc3 libraries
import pymc3 as pm
import theano as th... |
3,090 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1>SKLearn predictor - Regressor</h1>
<hr style="border
Step1: <span>
Build a processor.
</span>
<br>
<span>
This is required by the regressor in order to parse the input raw data.<br>
A A... | Python Code:
import sys
#sys.path.insert(0, 'I:/git/att/src/python/')
sys.path.insert(0, 'i:/dev/workspaces/python/att-workspace/att/src/python/')
Explanation: <h1>SKLearn predictor - Regressor</h1>
<hr style="border: 1px solid #000;">
<span>
<h2>ATT hit predictor.</h2>
</span>
<br>
<span>
This notebook shows how the h... |
3,091 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: 1. Get zip code from wikipedia
Step6: 2. Convert zip code to coordinates
Step7: 3. Sanity check
Step8: 4. Get bussiness type and # of establishments per year from US census
Check U... | Python Code:
GET SF ZIP CODES from http://www.city-data.com/zipmaps/San-Francisco-California.html
import itertools
sf_zip_codes = [94102, 94103, 94104, 94105, 94107, 94108, 94109, 94110, 94111, 94112, 94114, 94115, 94116, 94117, 94118, 94121, 94122, 94123, 94124, 94127, 94129, 94131, 94132, 94133, 94134, 94158]
Ex... |
3,092 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Set up working directory
Step1: README
This part of pipeline search for the SSU rRNA gene fragments, classify them, and extract reads aligned specific region. It is also heavy lifting part ... | Python Code:
cd /usr/local/notebooks
mkdir -p ./workdir
#check seqfile files to process in data directory (make sure you still remember the data directory)
!ls ./data/test/data
Explanation: Set up working directory
End of explanation
Seqfile='./data/test/data/2d.fa'
Explanation: README
This part of pipeline search for ... |
3,093 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2022 The TensorFlow Authors.
Step1: Assess privacy risks of an Image classification model with Secret Sharer Attack
<table class="tfo-notebook-buttons" align="left">
<td>
<a... | Python Code:
#@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
# dist... |
3,094 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Hub Authors.
Licensed under the Apache License, Version 2.0 (the "License");
Step1: TF-Hub로 Kaggle 문제를 해결하는 방법
<table class="tfo-notebook-buttons" align="left"... | Python Code:
# Copyright 2018 The TensorFlow Hub Authors. All Rights Reserved.
#
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... |
3,095 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Developmental file for modifying the 1D advection solver to work for multiple wave equations
Step1: Prototype implementation of LF flux for multiple-u's | Python Code:
import os
import sys
sys.path.insert(0, os.path.abspath('../../'))
import numpy as np
from matplotlib import pyplot as plt
import arrayfire as af
from dg_maxwell import params
from dg_maxwell import lagrange
from dg_maxwell import wave_equation as w1d
from dg_maxwell import utils
af.set_backend('opencl')
a... |
3,096 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tabular data
Step1: Starting from reading this dataset, to answering questions about this data in a few lines of code
Step2: How does the survival rate of the passengers differ between sex... | Python Code:
df = pd.read_csv("data/titanic.csv")
df.head()
Explanation: Tabular data
End of explanation
df['Age'].hist()
Explanation: Starting from reading this dataset, to answering questions about this data in a few lines of code:
What is the age distribution of the passengers?
End of explanation
df.groupby('Sex')[[... |
3,097 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Riemann interactive
In this notebook, we show interactive solutions of two Riemann problems for shallow water equations and acoustics. The user can interactively modify the phase planes and ... | Python Code:
import mpld3
import numpy as np
from clawpack.riemann import riemann_interactive
Explanation: Riemann interactive
In this notebook, we show interactive solutions of two Riemann problems for shallow water equations and acoustics. The user can interactively modify the phase planes and x-t planes and see its ... |
3,098 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Since we announced our collaboration with the World Bank and more partners to create the Open Traffic platform, we’ve been busy. We’ve shared two technical previews of the OSMLR linear refer... | Python Code:
from __future__ import division
from matplotlib import pyplot as plt
from matplotlib import cm, colors, patheffects
import numpy as np
import os
import glob
import urllib
import json
import pandas as pd
from random import shuffle, choice
import pickle
import sys; sys.path.insert(0, os.path.abspath('..'));
... |
3,099 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Adding new passbands to PHOEBE
In this tutorial we will show you how to add your own passband to PHOEBE. Adding a custom passband involves
Step1: If you plan on computing model atmosphere i... | Python Code:
#!pip install -I "phoebe>=2.2,<2.3"
Explanation: Adding new passbands to PHOEBE
In this tutorial we will show you how to add your own passband to PHOEBE. Adding a custom passband involves:
downloading and setting up model atmosphere tables;
providing a passband transmission function;
defining and registeri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.