Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
15,700 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
What's new in the Forecastwrapper
Solar Irradiance on a tilted plane
Wind on an oriented building face
No more "include this", "include that". Everything is included. (I implemented these fl... | Python Code:
import os
import sys
import inspect
import pandas as pd
import charts
Explanation: What's new in the Forecastwrapper
Solar Irradiance on a tilted plane
Wind on an oriented building face
No more "include this", "include that". Everything is included. (I implemented these flags to speed to speed up some thin... |
15,701 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ABC inference of upper limit on star-formation timescale from lack of CCSN
The ABC sampling assuming K stars that go CCSN in tccsn years
Step1: The PDF for 1, 2, and 5 CCSN
Step2: And the ... | Python Code:
def sftime_ABC(n=100,K=1,tccsn=4.,tmax=20.):
out= []
for ii in range(n):
while True:
# Sample from prior
tsf= numpy.random.uniform()*tmax
# Sample K massive-star formation times
stars= numpy.random.uniform(size=K)*tsf
# Only accept... |
15,702 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Content under Creative Commons Attribution license CC-BY 4.0, code under BSD 3-Clause License © 2018 by D. Koehn, heterogeneous models are from this Jupyter notebook by Heiner Igel (@heiner... | Python Code:
# Execute this cell to load the notebook's style sheet, then ignore it
from IPython.core.display import HTML
css_file = '../style/custom.css'
HTML(open(css_file, "r").read())
Explanation: Content under Creative Commons Attribution license CC-BY 4.0, code under BSD 3-Clause License © 2018 by D. Koehn, hete... |
15,703 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Let's start with the original regular expression and
string to search from Travis'
regex problem.
Step3: The regex had two bugs.
- Two [[ near the end of the pattern string.
- The si... | Python Code:
pattern = re.compile(r
(?P<any>any4?) # "any"
# association
| # or
(?P<object_eq>object ([\w-]+) eq (\d+)) # object
... |
15,704 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
First we import some datasets of interest
Step1: Now we separate the winners from the losers and organize our dataset
Step2: Now we match the detailed results to the merge dataset above
St... | Python Code:
#the seed information
df_seeds = pd.read_csv('../input/WNCAATourneySeeds_SampleTourney2018.csv')
#tour information
df_tour = pd.read_csv('../input/WRegularSeasonCompactResults_PrelimData2018.csv')
Explanation: First we import some datasets of interest
End of explanation
df_seeds['seed_int'] = df_seeds['See... |
15,705 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Model13
Step2: Feature functions(private)
Step3: Feature function(public)
Step4: Utility functions
Step5: GMM
Classifying questions
features
Step7: B. Modeling
Select model
Step8... | Python Code:
import gzip
import pickle
from os import path
from collections import defaultdict
from numpy import sign
Load buzz data as a dictionary.
You can give parameter for data so that you will get what you need only.
def load_buzz(root='../data', data=['train', 'test', 'questions'], format='pklz'):
buzz_data ... |
15,706 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Recreate Figure 5
The purpose of this notebook is to combine all the digital gene expression data for the retina cells, downloaded from the Gene Expression Omnibus using the accession number... | Python Code:
import altair
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
# Set the plotting style as for a "paper" (smaller labels)
# and using a white background with a grid ("whitegrid")
sns.set(context='paper', style='whitegrid')
%matplotlib inline
Explanation: Recreat... |
15,707 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The targeting algorithm of CRPropa
Here we will introduce you to the targeting algorithm in CRPropa, which emits particles from their sources using a von-Mises-Fisher distribution instead of... | Python Code:
import numpy as np
from crpropa import *
# Create a random magnetic-field setup
randomSeed = 42
turbSpectrum = SimpleTurbulenceSpectrum(0.2*nG, 200*kpc, 2*Mpc, 5./3.)
gridprops = GridProperties(Vector3d(0), 256, 100*kpc)
BField = SimpleGridTurbulence(turbSpectrum, gridprops, randomSeed)
# Cosmic-ray propag... |
15,708 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Organizing your code with functions
<img src="images/pestle.png" width="75" align="right">Years ago I learned to make Thai red curry paste from scratch, including roasting then grinding seed... | Python Code:
def pi():
return 3.14159
Explanation: Organizing your code with functions
<img src="images/pestle.png" width="75" align="right">Years ago I learned to make Thai red curry paste from scratch, including roasting then grinding seeds and pounding stuff in a giant mortar and pestle. It takes forever and so ... |
15,709 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
model 02
Load train, test, questions data from pklz
First of all, we need to read those three data set.
Step1: Make training set
For training model, we might need to make feature and lable ... | Python Code:
import gzip
import cPickle as pickle
with gzip.open("../data/train.pklz", "rb") as train_file:
train_set = pickle.load(train_file)
with gzip.open("../data/test.pklz", "rb") as test_file:
test_set = pickle.load(test_file)
with gzip.open("../data/questions.pklz", "rb") as questions_file:
question... |
15,710 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Atmos
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify d... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'noaa-gfdl', 'gfdl-cm4', 'atmos')
Explanation: ES-DOC CMIP6 Model Properties - Atmos
MIP Era: CMIP6
Institute: NOAA-GFDL
Source ID: GFDL-CM4
Topic: Atmos
Sub-Topics: Dynamical Core, Ra... |
15,711 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
0. Introduction
The following notebook is going to demonstrate the usage of prediction-wrapper, a set of utility classes that makes it much easier to run sklearn machine learning experiments... | Python Code:
import pandas as pd
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
from binary_classifier_wrappers import KfoldBinaryClassifierWrapper
from metric_wrappers import RSquare, AUC, RMSE
Explanation: 0. Intro... |
15,712 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
With this notebook you can subselect TeV sources for the stacked analysis of the catalog and rank TeV sources for the IGMF analysis
Imports
Step1: Loading the FHES catalog
Step2: Performin... | Python Code:
import os
import sys
from collections import OrderedDict
import yaml
import numpy as np
from astropy.io import fits
from astropy.table import Table, Column, join, hstack, vstack
from haloanalysis.utils import create_mask, load_source_rows
from haloanalysis.sed import HaloSED
from haloanalysis.model import ... |
15,713 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Regression in Python
This is a very quick run-through of some basic statistical concepts, adapted from Lab 4 in Harvard's CS109 course. Please feel free to try the original lab if you're fee... | Python Code:
# special IPython command to prepare the notebook for matplotlib and other libraries
%pylab inline
import numpy as np
import pandas as pd
import scipy.stats as stats
import matplotlib.pyplot as plt
import sklearn
import seaborn as sns
# special matplotlib argument for improved plots
from matplotlib import... |
15,714 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MultiPolygons
The MultiPolygons glyphs is modeled closely on the GeoJSON spec for Polygon and MultiPolygon. The data that are used to construct MultiPolygons are nested 3 deep. In the top le... | Python Code:
from bokeh.plotting import figure, output_notebook, show
output_notebook()
p = figure(plot_width=300, plot_height=300, tools='hover,tap,wheel_zoom,pan,reset,help')
p.multi_polygons(xs=[[[[1, 2, 2, 1, 1]]]],
ys=[[[[3, 3, 4, 4, 3]]]])
show(p)
Explanation: MultiPolygons
The MultiPolygons glyp... |
15,715 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Begin by defining the output parsing function for usage
Define overnight output file location and parse into dictionary
Step1: Define a function that lets us pull out the optimal fit for a ... | Python Code:
OVERNIGHT_FILE = '/home/buck06191/Desktop/optimisation_edit.json'
with open(OVERNIGHT_FILE) as f:
optim_data = json.load(f)
# Check length of each dict section before converting to pandas DF
import copy
x = copy.copy(optim_data)
{k:len(x[k]) for k in x.keys()}
overnight_df = pd.DataFrame(optim_data)
Ex... |
15,716 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Ocnbgchem
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', 'dwd', 'sandbox-1', 'ocnbgchem')
Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem
MIP Era: CMIP6
Institute: DWD
Source ID: SANDBOX-1
Topic: Ocnbgchem
Sub-Topics: Tracers.
Proper... |
15,717 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Self-Driving Car Engineer Nanodegree
Deep Learning
Project
Step1: Step 1
Step2: Visualizing Dataset
Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended... | Python Code:
# Load pickled data
import pickle
# Loading the relevant files:
# Training Data: train.p
# Validating Data: valid.p
# Testing Data: test.p
training_file = "train.p"
validation_file= "valid.p"
testing_file = "test.p"
with open(training_file, mode='rb') as f:
train = pickle.load(f)
with open(validation_f... |
15,718 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CI/CD for TFX pipelines
Learning Objectives
Develop a CI/CD workflow with Cloud Build to build and deploy TFX pipeline code.
Integrate with Github to automatically trigger pipeline deploymen... | Python Code:
REGION = "us-central1"
PROJECT_ID = !(gcloud config get-value core/project)
PROJECT_ID = PROJECT_ID[0]
ARTIFACT_STORE = f"gs://{PROJECT_ID}"
Explanation: CI/CD for TFX pipelines
Learning Objectives
Develop a CI/CD workflow with Cloud Build to build and deploy TFX pipeline code.
Integrate with Github to aut... |
15,719 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Authors.
Step1: カスタム訓練:ウォークスルー
<table class="tfo-notebook-buttons" align="left">
<td> <a target="_blank" href="https
Step2: 次に、Colab メニューから Runtime >... | 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... |
15,720 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
AI Explanations
Step1: Run the following cell to create your Cloud Storage bucket if it does not already exist.
Step2: Timestamp
If you are in a live tutorial session, you might be using a... | Python Code:
import os
PROJECT_ID = "" # TODO: your PROJECT_ID here.
os.environ["PROJECT_ID"] = PROJECT_ID
BUCKET_NAME = "" # TODO: your BUCKET_NAME here.
REGION = "us-central1"
os.environ['BUCKET_NAME'] = BUCKET_NAME
os.environ['REGION'] = REGION
Explanation: AI Explanations: Explaining a tabular data model
Overview
... |
15,721 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1 align="center">Oncolist Server API Examples</h1>
<h3 align="center">Author
Step1: <font color='blue'> Notice
Step2: After you verified the project information, you can execute the pipe... | Python Code:
import os
import sys
sys.path.append(os.getcwd().replace("notebooks", "cfncluster"))
## S3 input and output address.
s3_input_files_address = "s3://path/to/input folder"
s3_output_files_address = "s3://path/to/output folder"
## CFNCluster name
your_cluster_name = "cluster_name"
## The private key pair for ... |
15,722 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A Review of EuroSciPy2015
0. IPython Notebooks
1. Tutorial 1
Step1: Create a local host for the notebook in the directory of interest by running the command
Step2: Images, data files, etc.... | Python Code:
pip install ipython-notebook
Explanation: A Review of EuroSciPy2015
0. IPython Notebooks
1. Tutorial 1: An Introduction to Python (Joris Vankerschaver)
2. Tutorial 2: Never get in a data battle without Numpy arrays (Valerio Maggio)
3. numexpr
4. Interesting talks
0. Jupyter aka IPython Notebook
Interactive... |
15,723 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step7: Building Custom Plugins
The 3ML instrument/data philosophy focuses on the abstraction of the data to likelihood interface. Rather than placing square pegs in round holes by enforcing ... | Python Code:
class PluginPrototype(object):
__metaclass__ = abc.ABCMeta
def __init__(self, name, nuisance_parameters):
assert is_valid_variable_name(name), "The name %s cannot be used as a name. You need to use a valid " \
"python identifier: no spaces, canno... |
15,724 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<b>Exercise</b>
Step1: The grammar that should be used to parse this program is given in the file
Examples/simple.g. It is very similar to the grammar that we have developed previously for... | Python Code:
cat Examples/sum-for.sl
Explanation: <b>Exercise</b>: Extending a Shift-Reduce Parser
In this exercise your task is to extend the shift-reduce parser
that has been discussed in the lecture so that it returns an abstract syntax tree. You should test it with the program sum-for.sl that is given the director... |
15,725 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<div class="alert alert-success">
Este notebook de ipython depende del modulo `vis_int`, el cual es ilustrado en el notebook de [Visualización e Interacción](vis_int.ipybn).
</div>
Step1: T... | Python Code:
from vis_int import *
import vis_int
print(dir(vis_int))
Explanation: <div class="alert alert-success">
Este notebook de ipython depende del modulo `vis_int`, el cual es ilustrado en el notebook de [Visualización e Interacción](vis_int.ipybn).
</div>
End of explanation
def biseccion(funcion, a, b, tol_x = ... |
15,726 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step2: Imports
Step3: tf.data.Dataset
Step4: Let's have a look at the data
Step5: Keras model
If you are not sure what cross-entropy, dropout, softmax or batch-normalizati... | Python Code:
BATCH_SIZE = 128
EPOCHS = 10
training_images_file = 'gs://mnist-public/train-images-idx3-ubyte'
training_labels_file = 'gs://mnist-public/train-labels-idx1-ubyte'
validation_images_file = 'gs://mnist-public/t10k-images-idx3-ubyte'
validation_labels_file = 'gs://mnist-public/t10k-labels-idx1-ubyte'
Expl... |
15,727 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Feature
Step1: Config
Automatically discover the paths to various data folders and compose the project structure.
Step2: Identifier for storing these features on disk and referring to them... | Python Code:
from pygoose import *
import hashlib
Explanation: Feature: PageRank on Question Co-Occurrence Graph
This is a "magic" (leaky) feature that exploits the patterns in question co-occurrence graph (based on the kernel by @zfturbo).
Imports
This utility package imports numpy, pandas, matplotlib and a helper kg ... |
15,728 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
12d - AgriPV
Step1: General Parameters and Variables
Step2: <a id='step1'></a>
1. Loop to Raytrace and sample irradiance at where Three would be located
Step3: <a id='step2'></a>
2. Calcu... | Python Code:
import bifacial_radiance
import os
from pathlib import Path
import numpy as np
import pandas as pd
testfolder = str(Path().resolve().parent.parent / 'bifacial_radiance' / 'TEMP' / 'Tutorial_18')
if not os.path.exists(testfolder):
os.makedirs(testfolder)
resultsfolder = os.path.join(testfolder, 'r... |
15,729 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Querying the GitHub API for repositories and organizations
By Stuart Geiger and Jamie Whitacre, made at a SciPy 2016 sprint. See the rendered, interactive, embedable map here.
Step1: With t... | Python Code:
!pip install pygithub
!pip install geopy
!pip install ipywidgets
from github import Github
#this is my private login credentials, stored in ghlogin.py
import ghlogin
g = Github(login_or_token=ghlogin.gh_user, password=ghlogin.gh_passwd)
Explanation: Querying the GitHub API for repositories and organization... |
15,730 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Hyperparamètres, LassoRandomForestRregressor et grid_search (correction)
Le notebook explore l'optimisation des hyper paramaètres du modèle LassoRandomForestRegressor, et fait varier le nomb... | Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
%matplotlib inline
Explanation: Hyperparamètres, LassoRandomForestRregressor et grid_search (correction)
Le notebook explore l'optimisation des hyper paramaètres du modèle LassoRandomForestRegressor, et fait varier le nombre d'arbre et le para... |
15,731 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Let's admit it, bayesian modeling on time series is slow. In pymc3, it typically implies using theano scan operation. Here, we will show how to profile one step of the kalman filter, as well... | Python Code:
import numpy as np
import theano
import theano.tensor as tt
import kalman
Explanation: Let's admit it, bayesian modeling on time series is slow. In pymc3, it typically implies using theano scan operation. Here, we will show how to profile one step of the kalman filter, as well as the scan... |
15,732 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Excercise - Working With CSV
Using the CSV module
A CSV file is often used exchange format for spreadsheets and databases.
Each line is called a record and each field within a record is sepe... | Python Code:
import csv
Explanation: Excercise - Working With CSV
Using the CSV module
A CSV file is often used exchange format for spreadsheets and databases.
Each line is called a record and each field within a record is seperated by a delimiter such as comma, tab etc.
We use the module "CSV" which is not included in... |
15,733 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ordinary Differential Equations Exercise 1
Imports
Step2: Lorenz system
The Lorenz system is one of the earliest studied examples of a system of differential equations that exhibits chaotic... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import odeint
from IPython.html.widgets import interact, fixed
from IPython.html.widgets import interact, interactive, fixed
Explanation: Ordinary Differential Equations Exercise 1
Imports
End of explanation
def lore... |
15,734 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: MyHDL Function (module)
An introductory MyHDL tutorial presents a small example towards the begining of the post. A MyHDL anatomy graphic (see below) is used to describe the parts of... | Python Code:
def shifty(clock, reset, load, load_value, output_bit, initial_value=0):
Ports:
load: input, load strobe, load the `load_value`
load_value: input, the value to be loaded
output_bit: output, The most significant
initial_value: internal shift registers initial value (val... |
15,735 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1D Wasserstein barycenter comparison between exact LP and entropic regularization
This example illustrates the computation of regularized Wasserstein Barycenter
as proposed in [3] and exact ... | Python Code:
# Author: Remi Flamary <remi.flamary@unice.fr>
#
# License: MIT License
import numpy as np
import matplotlib.pylab as pl
import ot
# necessary for 3d plot even if not used
from mpl_toolkits.mplot3d import Axes3D # noqa
from matplotlib.collections import PolyCollection # noqa
#import ot.lp.cvx as cvx
Expl... |
15,736 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Train Network for feature extraction
Feed MFCC values for each song to and encoder-decoder network.
Step1: Read data
Pad items with max length of 150
X.shape = (N, 150, 20)
Step2: Train
Re... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn
seaborn.set()
import cPickle
import numpy as np
from keras import backend as K
from keras.models import Sequential, model_from_yaml
from keras.layers.recurrent import LSTM
from keras.layers.core import Activation, Dense, Dropout, RepeatVecto... |
15,737 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Alpsko smučanje
Obdelava podatkov
Step1: Najprej sem spletne strani FIS pobrala podatke o smučarjih in njihovih id številkah na spletišču FIS. Id-je sem potrebovala za sestavljanje url nasl... | Python Code:
%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
import numpy as py
#import scipy
# Make the graphs a bit prettier, and bigger
#pd.set_option('display.mpl_style', 'default')
#plt.rcParams['figure.figsize'] = (15, 5)
# This is necessary to show lots of columns in pandas 0.12.
# Not ne... |
15,738 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Anna KaRNNa
In this notebook, we'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book... | Python Code:
import time
from collections import namedtuple
import numpy as np
import tensorflow as tf
Explanation: Anna KaRNNa
In this notebook, we'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book.
This network... |
15,739 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lab 8 - Simple Harmonic Oscillator states
Problems from Chapter 12
Step1: Define the standard operators
Step2: Problem 12.1
Step3: Problem 12.2
Step4: Problem 12.3 (use n=2 as a test-cas... | Python Code:
from numpy import sqrt
from qutip import *
Explanation: Lab 8 - Simple Harmonic Oscillator states
Problems from Chapter 12
End of explanation
N = 10 # pick a size for our state-space
a = destroy(N)
n = a.dag()*a
Explanation: Define the standard operators
End of explanation
a*a.dag() - a.dag()*a
Explanatio... |
15,740 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Training Ensemble on MNIST Dataset
On the function points branch of nengo
On the vision branch of nengo_extras
Step1: Load the MNIST training and testing images
Step2: Create array of imag... | Python Code:
import matplotlib.pyplot as plt
%matplotlib inline
import nengo
import numpy as np
import scipy.ndimage
from scipy.ndimage.interpolation import rotate
import matplotlib.animation as animation
from matplotlib import pylab
from PIL import Image
import nengo.spa as spa
import cPickle
import random
from nengo_... |
15,741 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
KubeFlow Pipelines
Step1: import the necessary packages
Step2: Enter your gateway and the auth token
Use this extension on chrome to get token
Update values for the ingress gateway and au... | Python Code:
! pip uninstall -y kfp
! pip install --no-cache-dir kfp
Explanation: KubeFlow Pipelines : Pytorch Cifar10 Image classification
This notebook shows PyTorch CIFAR10 end-to-end classification example using Kubeflow Pipelines.
An example notebook that demonstrates how to:
Get different tasks needed for the ... |
15,742 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
AVA dataset explorer
This study aims to explore and select a chunk of the AVA dataset to be used in preliminary tests of a aesthetic classifier.
Step1: First of all the dataset must be load... | Python Code:
import pandas as pd
import numpy as np
import seaborn
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: AVA dataset explorer
This study aims to explore and select a chunk of the AVA dataset to be used in preliminary tests of a aesthetic classifier.
End of explanation
ava_header = ["row_number... |
15,743 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: Keras 모델 저장 및 로드
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https
Step2: 전체 모델 저장 및 로딩
전체 모델을 단일 아티팩트로 저... | 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... |
15,744 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Remote Data
Yahoo
St. Louis Fed (FRED)
Google
documentation
Step1: Yahoo finance
Step2: FRED
source
Step3: Google | Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import datetime
from pandas_datareader import data, wb
Explanation: Remote Data
Yahoo
St. Louis Fed (FRED)
Google
documentation: http://pandas.pydata.org/pandas-docs/stable/remote_data.html
Installation Requirement
pa... |
15,745 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python Training - Lesson 5 - Python idioms and Pythonic code
Python guidelines - how to code?
Style and readbility of code - PEP8
PEP8 is a set of common sense practices and rules on how to ... | Python Code:
# Example of what that means:
# Some dictionary which we obtained, have no control of.
dictionary = {"a":1, "b":2, "c":3}
# List of keys we always check.
some_keys = ["a", "b", "c", "d"]
# Old-style way - Look before you leap (LBYL)
for k in some_keys:
if k not in dictionary:
print("Expected to... |
15,746 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Compute EBTEL Results
Run the single- and two-fluid EBTEL models for a variety of inputs. This will be the basis for the rest of our analysis.
First, import any needed modules.
Step1: Setup... | Python Code:
import sys
import os
import subprocess
import pickle
import numpy as np
sys.path.append(os.path.join(os.environ['EXP_DIR'],'ebtelPlusPlus/rsp_toolkit/python'))
from xml_io import InputHandler,OutputHandler
Explanation: Compute EBTEL Results
Run the single- and two-fluid EBTEL models for a variety of inputs... |
15,747 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Revisão de Álgebra Linear
Step1: Matrizes
$$ A = \begin{bmatrix} 123, & 343, & 100\
33, & 0, & -50 \end{bmatrix} $$
Step2: $$ A = \begin{bmatrix} 123, & 343, &... | Python Code:
import numpy as np
from numpy.random import randn
Explanation: Revisão de Álgebra Linear
End of explanation
A = np.array([[123, 343, 100],
[ 33, 0, -50]])
print (A )
print (A.shape )
print (A.shape[0] )
print (A.shape[1] )
B = np.array([[5, 3, 2, 1, 4],
[0, 2, 1, 3, 8]])
print... |
15,748 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interface caching
This section details the interface-caching mechanism, exposed in the nipype.caching module.
Interface caching
Step1: Note that the caching directory is a subdirectory call... | Python Code:
from nipype.caching import Memory
mem = Memory(base_dir='.')
Explanation: Interface caching
This section details the interface-caching mechanism, exposed in the nipype.caching module.
Interface caching: why and how
Pipelines (also called workflows) specify processing by an execution graph. This is useful b... |
15,749 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Training a neural network on MNIST with Keras
This simple example demonstrates how to plug TensorFlow Datasets (TFDS) into a Keras model.
Copyright 2020 The TensorFlow Datasets Authors, Lice... | Python Code:
import tensorflow as tf
import tensorflow_datasets as tfds
Explanation: Training a neural network on MNIST with Keras
This simple example demonstrates how to plug TensorFlow Datasets (TFDS) into a Keras model.
Copyright 2020 The TensorFlow Datasets Authors, Licensed under the Apache License, Version 2.0
<t... |
15,750 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interpolation Exercise 1
Step1: 2D trajectory interpolation
The file trajectory.npz contains 3 Numpy arrays that describe a 2d trajectory of a particle as a function of time
Step2: Use the... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from scipy.interpolate import interp1d
Explanation: Interpolation Exercise 1
End of explanation
data=np.load('trajectory.npz')
t=data['t']
x=data['x']
y=data['y']
assert isinstance(x, np.ndarray) and len(x)==40
asse... |
15,751 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
EfficientNetV2 with tf-hub
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step1: 3.Inference with ImageNet 1k/2k checkpoints
3.1 ImageNet1k checkpo... | Python Code:
import itertools
import os
import matplotlib.pylab as plt
import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
print('TF version:', tf.__version__)
print('Hub version:', hub.__version__)
print('Phsical devices:', tf.config.list_physical_devices())
def get_hub_url_and_isize(model_name, ck... |
15,752 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook covers using metrics to analyze the 'accuracy' of prophet models. In this notebook, we will extend the previous example (http
Step1: Read in the data
Read the data in from the... | Python Code:
import pandas as pd
import numpy as np
from fbprophet import Prophet
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error
%matplotlib inline
plt.rcParams['figure.figsize']=(20,10)
plt.style.use('ggplot')
Explanation: This notebook covers using metr... |
15,753 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<div class="jumbotron text-left"><b>
This tutorial describes how to perform a mixed optimization using the SMT toolbox. The idea is to use a Bayesian Optimization (EGO method) to solve an un... | Python Code:
%matplotlib inline
from math import exp
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors
from mpl_toolkits.mplot3d import Axes3D
from scipy.stats import norm
from scipy.optimize import minimize
import scipy
import six
from smt.applications import EGO
from smt.surrogate_mod... |
15,754 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Work with Philadelphia crime rate data
The dataset has information about the house prices in Philadelphia, additionally, has information about the crime rates in various neighborhoods. So we... | Python Code:
crime_rate_data = graphlab.SFrame.read_csv('Philadelphia_Crime_Rate_noNA.csv')
crime_rate_data
graphlab.canvas.set_target('ipynb')
crime_rate_data.show(view='Scatter Plot', x = "CrimeRate", y = "HousePrice")
Explanation: Work with Philadelphia crime rate data
The dataset has information about the house pr... |
15,755 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
exportByFeat(img, fc, prop, folder, name, scale, dataType, **kwargs)
Step1: FeatureCollection
Step2: Image
Step3: Execute | Python Code:
import ee
ee.Initialize()
from geetools import batch
Explanation: exportByFeat(img, fc, prop, folder, name, scale, dataType, **kwargs):
Export an image clipped by features (Polygons). You can use the same arguments as the original function ee.batch.export.image.toDrive
Parameters
img: image to clip
fc: fea... |
15,756 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Load Iris Flower Dataset
Step2: Standardize Features
Step3: Conduct Meanshift Clustering
MeanShift has two important parameters we should be aware of. First, bandwidth sets r... | Python Code:
# Load libraries
from sklearn import datasets
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import MeanShift
Explanation: Title: Meanshift Clustering
Slug: meanshift_clustering
Summary: How to conduct meanshift clustering in scikit-learn.
Date: 2017-09-22 12:00
Category: Machine Lea... |
15,757 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Create geological model and drillhole from sections
This is to extract points from geological model defined in sections (dxf files) We also generate drillhole data. The section must be difin... | Python Code:
# import modules
import pygslib
import ezdxf
import pandas as pd
import numpy as np
Explanation: Create geological model and drillhole from sections
This is to extract points from geological model defined in sections (dxf files) We also generate drillhole data. The section must be difined as dxf section wi... |
15,758 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Miniconda Installation
Install Miniconda from their Website.
All required python packages will be downloaded using the conda package and environment management system.
When Miniconda is inst... | Python Code:
conda update --all
Explanation: Miniconda Installation
Install Miniconda from their Website.
All required python packages will be downloaded using the conda package and environment management system.
When Miniconda is installed on your system, open up your shell with the command <kbd>WINDOWS</kbd> + <kbd>R... |
15,759 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
How the Climate in Melbourne has Changed Over a Century
A strong and longer than usual heat wave has hit the southern states of Australia so we thought to look into the weather data for Mel... | Python Code:
%matplotlib inline
import numpy as np
from dh_py_access import package_api
import dh_py_access.lib.datahub as datahub
import xarray as xr
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from po_data_process import make_comparison_plot, make_plot, make_anomalies_plot
import warnings... |
15,760 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Quantum Electrodynamics with Geometric Algebra (WIP)
Theory overview
Quantum Electrodynamics (QED) describes electrons, positrons (anti-electrons) and photons in a 4-dimensional spacetime wi... | Python Code:
sta = GeometricAlgebra([1, -1, -1, -1])
for basis in sta.basis_mvs:
sta.print(basis)
Explanation: Quantum Electrodynamics with Geometric Algebra (WIP)
Theory overview
Quantum Electrodynamics (QED) describes electrons, positrons (anti-electrons) and photons in a 4-dimensional spacetime with fields defin... |
15,761 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python Gateway Tutorial
The UnetStack Python gateway API is available via unet-contrib, or from PyPi.
Import unetpy
If you haven't installed unetpy, you need to do that first
Step1: Open a ... | Python Code:
from unetpy import *
Explanation: Python Gateway Tutorial
The UnetStack Python gateway API is available via unet-contrib, or from PyPi.
Import unetpy
If you haven't installed unetpy, you need to do that first: pip install unetpy
End of explanation
sock = UnetSocket('localhost', 1100)
modem = sock.getGatewa... |
15,762 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Convolutional Autoencoder
Sticking with the MNIST dataset, let's improve our autoencoder's performance using convolutional layers. Again, loading modules and the data.
Step1: Network Archit... | Python Code:
%matplotlib inline
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', validation_size=0)
img = mnist.train.images[2]
plt.imshow(img.reshape((28, 28)), cmap='Greys_r')
Explanati... |
15,763 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sample Data from some function
Step1: A Gaussian process is a collection of random variables, any finite number of which have a joint Gaussian distribution. Below we outline a GP given some... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from numpy import linalg
from sklearn import gaussian_process
from functools import partial
# Define the function which you wish to estimate, adding noise
def func(x):
return x*np.sin(x)
def noise(x):
return np.random.randn(len(x... |
15,764 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
In this tutorial, you'll learn how to create interactive maps with the folium package. Along the way, you'll apply your new skills to visualize Boston crime data.
Step1: Your ... | Python Code:
#$HIDE_INPUT$
import pandas as pd
import geopandas as gpd
import math
import folium
from folium import Choropleth, Circle, Marker
from folium.plugins import HeatMap, MarkerCluster
Explanation: Introduction
In this tutorial, you'll learn how to create interactive maps with the folium package. Along the way... |
15,765 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Measurement class basics
Objects of the measurement class are used to save all the information for one single measurement (in contrast to an object of the sample class that is used for multi... | Python Code:
## start qkit and import the necessary classes; here we assume a already configured qkit environment
import qkit
qkit.start()
from qkit.measure.measurement_class import Measurement
Explanation: Measurement class basics
Objects of the measurement class are used to save all the information for one single me... |
15,766 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Source of the materials
Step1: This code will print out a summary of the alignment
Step2: You’ll notice in the above output the sequences have been truncated. We
could instead write our ow... | Python Code:
from Bio import AlignIO
alignment = AlignIO.read("data/PF05371_seed.sth", "stockholm")
Explanation: Source of the materials: Biopython cookbook (adapted)
<font color='red'>Status: Draft</font>
Multiple Sequence Alignment objects {#chapter:Bio.AlignIO}
This chapter is about Multiple Sequence Alignments, by ... |
15,767 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Usage examples
Step1: The io module manages where data is stored and
This is my database root path, where all downloaded images are automatically stored.
Check if this is automatically set... | Python Code:
from pyciss import io
Explanation: Usage examples
End of explanation
io.config
io.get_db_root()
Explanation: The io module manages where data is stored and
This is my database root path, where all downloaded images are automatically stored.
Check if this is automatically set for you at a reasonable locati... |
15,768 | Given the following text description, write Python code to implement the functionality described.
Description:
Greatest odd factor of an even number
Python3 program for the above approach ; Function to print greatest odd factor ; Initialize i with 1 ; Iterate till i <= pow_2 ; find the pow ( 2 , i ) ; If factor is odd ... | Python Code:
import math
def greatestOddFactor(n ) :
pow_2 = int(math . log(n , 2 ) )
i = 1
while i <= pow_2 :
fac_2 =(2 ** i )
if(n % fac_2 == 0 ) :
if(( n // fac_2 ) % 2 == 1 ) :
print(n // fac_2 )
break
i += 1
N = 8642
greatestOddFactor(N )
|
15,769 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Bar data
Step1: Historical data
To get the earliest date of available bar data the "head timestamp" can be requested
Step2: To request hourly data of the last 60 trading days
Step3: Conve... | Python Code:
from ib_insync import *
util.startLoop()
ib = IB()
ib.connect('127.0.0.1', 7497, clientId=14)
Explanation: Bar data
End of explanation
contract = Stock('TSLA', 'SMART', 'USD')
ib.reqHeadTimeStamp(contract, whatToShow='TRADES', useRTH=True)
Explanation: Historical data
To get the earliest date of available ... |
15,770 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
To understand how Pandas works with time series, we need to understand the datetime module of Python. The main object types of this module are below
date - stores year, month, day using Greg... | Python Code:
from datetime import datetime
now = datetime.now()
now
(now.year, now.month, now.day, now.hour, now.minute)
Explanation: To understand how Pandas works with time series, we need to understand the datetime module of Python. The main object types of this module are below
date - stores year, month, day using ... |
15,771 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Excercises Electric Machinery Fundamentals
Chapter 9
Problem 9-9
Step1: Description
How many pulses per second must be supplied to the control unit of the motor in Problem 9-8 to achieve
a ... | Python Code:
%pylab notebook
Explanation: Excercises Electric Machinery Fundamentals
Chapter 9
Problem 9-9
End of explanation
p = 12
n_m = 600 # [r/min]
Explanation: Description
How many pulses per second must be supplied to the control unit of the motor in Problem 9-8 to achieve
a rotational speed of 600 r/min?
En... |
15,772 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step7: Arbres binaires
Le but de ce TP est d'implanter les fonctions usuelles telles que la génération exhaustive (fabriquer tous les éléments de l'ensemble), rank et unrank sur l'ensemble d... | Python Code:
class BinaryTree():
def __init__(self, children = None):
A binary tree is either a leaf or a node with two subtrees.
INPUT:
- children, either None (for a leaf), or a list of size excatly 2
of either two binary trees or 2 obje... |
15,773 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Contents and Objective
Describing several commands and methods that will be used throughout the simulations
<b>Note
Step1: Tuples
Similar to lists but "immutable", i.e., entries can be appe... | Python Code:
# defining lists
sport_list = [ 'cycling', 'football', 'fitness' ]
first_prime_numbers = [ 2, 3, 5, 7, 11, 13, 17, 19 ]
# getting contents
sport = sport_list[ 2 ]
third_prime = first_prime_numbers[ 2 ]
# printing
print( 'All sports:', sport_list )
print( 'Sport to be done:', sport )
print( '\nFirst primes:... |
15,774 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Elementary Web Scraping
Joshua G. Mausolf
Preliminary Steps
Step2: Elementary Web Scraping Using NLTK and Beautiful Soup
*Suppose we want to write a utility function that takes a URL as its... | Python Code:
#Import NLTK and Texts
import nltk
from nltk import *
from nltk.book import *
from nltk.corpus import stopwords
#Import Web Scraping Modules
from urllib import request
from bs4 import BeautifulSoup
#Command All Matplotlib Graphs to Appear in Inline in Notebook
%matplotlib inline
Explanation: Elementary Web... |
15,775 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sentiment Analysis with an RNN
In this notebook, you'll implement a recurrent neural network that performs sentiment analysis. Using an RNN rather than a feedfoward network is more accurate ... | Python Code:
import numpy as np
import tensorflow as tf
with open('../sentiment_network/reviews.txt', 'r') as f:
reviews = f.read()
with open('../sentiment_network/labels.txt', 'r') as f:
labels = f.read()
reviews[:2000]
Explanation: Sentiment Analysis with an RNN
In this notebook, you'll implement a recurrent ... |
15,776 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step6: Copyright 2019 Google LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the... | Python Code:
DIM = 100 # Number of bits in the bit strings (i.e. the "models").
NOISE_STDEV = 0.01 # Standard deviation of the simulated training noise.
EARLY_SIGNAL_NOISE = 0.005 # Standard deviation of the noise added to earlier
# observations.
REDUCTION_FACTOR = 100.0 # The factor by ... |
15,777 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plotly Alpha Shapes as Mesh3d instances
Starting with a finite set of 3D points, Plotly can generate a Mesh3d object, that depending on a key value can be the convex hull of that set, its ... | Python Code:
from IPython.display import IFrame
IFrame('https://plot.ly/~empet/13475/', width=800, height=350)
Explanation: Plotly Alpha Shapes as Mesh3d instances
Starting with a finite set of 3D points, Plotly can generate a Mesh3d object, that depending on a key value can be the convex hull of that set, its Delau... |
15,778 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dataset
Download the dataset and save it to a directory at per your convience. IMDB comments
Step1: Run the following lines when you run this notebook first time on your system.
Step2: Now... | Python Code:
import pandas as pd # Used for dataframe functions
import json # parse json string
import nltk # Natural language toolkit for TDIDF etc.
from bs4 import BeautifulSoup # Parse html string .. to extract text
import re # Regex parser
import numpy as np # Linear algebbra
from sklearn import * # machine learn... |
15,779 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Authors.
Licensed under the Apache License, Version 2.0 (the "License").
Neural Machine Translation with Attention
<table class="tfo-notebook-buttons" align="le... | Python Code:
from __future__ import absolute_import, division, print_function
# Import TensorFlow >= 1.9 and enable eager execution
import tensorflow as tf
tf.enable_eager_execution()
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import unicodedata
import re
import numpy as np
imp... |
15,780 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Homework 10 Key
CHE 116
Step1: 1. Conceptual Questions
Describe the general process for parametric hypothesis tests.
Why would you choose a non-parametric hypothesis test over a parametric ... | Python Code:
import scipy.stats as ss
import numpy as np
Explanation: Homework 10 Key
CHE 116: Numerical Methods and Statistics
4/3/2019
End of explanation
import scipy.stats as ss
ss.t.cdf(-2, 4) * 2
Explanation: 1. Conceptual Questions
Describe the general process for parametric hypothesis tests.
Why would you choose... |
15,781 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
pyphysio tutorial
1. Signals
The class Signal together with the class Algorithm are the two main classes in pyphysio.
In this first tutorial we will see how the class Signal can be used to f... | Python Code:
# import packages
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: pyphysio tutorial
1. Signals
The class Signal together with the class Algorithm are the two main classes in pyphysio.
In this first tutorial we will see how the class Signal can be used to facilitate the ma... |
15,782 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: KL and non overlapping distributions
non overlapping distributions (visual)
explain ratio will be infinity - integral
move the distributions closer and they will not h... | Python Code:
import jax
import random
import numpy as np
import jax.numpy as jnp
import seaborn as sns
import matplotlib.pyplot as plt
import scipy
!pip install -qq dm-haiku
!pip install -qq optax
try:
import haiku as hk
except ModuleNotFoundError:
%pip install -qq haiku
import haiku as hk
try:
import o... |
15,783 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A Walk through PyStyl
Experiments in stylometry typically kick off with creating a corpus, or the collection of texts which we would like to compare. In pystyl, we use the Corpus class to re... | Python Code:
%load_ext autoreload
%autoreload 1
%matplotlib inline
from pystyl.corpus import Corpus
corpus = Corpus(language='en')
Explanation: A Walk through PyStyl
Experiments in stylometry typically kick off with creating a corpus, or the collection of texts which we would like to compare. In pystyl, we use the Cor... |
15,784 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Let's Grow your Own Inner Core!
Choose a model in the list
Step1: Define the geodynamical model
Un-comment one of the model
Step2: Change the values of the parameters to get the model you ... | Python Code:
%matplotlib inline
# import statements
import numpy as np
import matplotlib.pyplot as plt #for figures
from mpl_toolkits.basemap import Basemap #to render maps
import math
import json #to write dict with parameters
from GrowYourIC import positions, geodyn, geodyn_trg, geodyn_static, plot_data, data
plt.rcP... |
15,785 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: 使用 Tensorflow Lattice 实现道德形状约束
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https
Step2: 导入所需的软件包:
Step3: ... | 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... |
15,786 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Continuous training pipeline with Kubeflow Pipeline and AI Platform
Learning Objectives
Step6: The pipeline uses a mix of custom and pre-build components.
Pre-build components. The pipeline... | Python Code:
!grep 'BASE_IMAGE =' -A 5 pipeline/covertype_training_pipeline.py
Explanation: Continuous training pipeline with Kubeflow Pipeline and AI Platform
Learning Objectives:
1. Learn how to use Kubeflow Pipeline(KFP) pre-build components (BiqQuery, AI Platform training and predictions)
1. Learn how to use KFP li... |
15,787 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Kernel Density Estimation
Kernel density estimation is the process of estimating an unknown probability density function using a kernel function $K(u)$. While a histogram counts the number o... | Python Code:
%matplotlib inline
import numpy as np
from scipy import stats
import statsmodels.api as sm
import matplotlib.pyplot as plt
from statsmodels.distributions.mixture_rvs import mixture_rvs
Explanation: Kernel Density Estimation
Kernel density estimation is the process of estimating an unknown probability densi... |
15,788 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Categorical Ordinary Least-Squares
Unit 12, Lecture 3
Numerical Methods and Statistics
Prof. Andrew White, April 19 2018
Goals
Step1: Regression with discrete domains
Let's say we have a po... | Python Code:
%matplotlib inline
import random
import numpy as np
import matplotlib.pyplot as plt
from math import sqrt, pi, erf
import seaborn
seaborn.set_context("talk")
#seaborn.set_style("white")
import scipy.stats
Explanation: Categorical Ordinary Least-Squares
Unit 12, Lecture 3
Numerical Methods and Statistics
Pr... |
15,789 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Image Classification
In this project, you'll classify images from the CIFAR-10 dataset. The dataset consists of airplanes, dogs, cats, and other objects. You'll preprocess the images... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
from urllib.request import urlretrieve
from os.path import isfile, isdir
from tqdm import tqdm
import problem_unittests as tests
import tarfile
cifar10_dataset_folder_path = 'cifar-10-batches-py'
# Use Floyd's cifar-10 dataset if present
floyd_cifa... |
15,790 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Nested rejection sampling
This example demonstrates how to use nested rejection sampling [1] to sample from the posterior distribution for a logistic model fitted to model-simulated data.
Ne... | Python Code:
import pints
import pints.toy as toy
import numpy as np
import matplotlib.pyplot as plt
# Load a forward model
model = toy.LogisticModel()
# Create some toy data
r = 0.015
k = 500
real_parameters = [r, k]
times = np.linspace(0, 1000, 100)
signal_values = model.simulate(real_parameters, times)
# Add indepen... |
15,791 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
零和ゲームのナッシュ均衡
quantecon.game_theory と scipy.optimize.linprog で求めてみる
Step1: じゃんけん・ゲームを例に計算してみる.
あとあと便利なので,NumPy array としてプレイヤー0の利得行列を定義しておく
Step2: quantecon.game_theory でナッシュ均衡を求める
Step3: プ... | Python Code:
import numpy as np
from scipy.optimize import linprog
import quantecon.game_theory as gt
Explanation: 零和ゲームのナッシュ均衡
quantecon.game_theory と scipy.optimize.linprog で求めてみる
End of explanation
U = np.array(
[[0, -1, 1],
[1, 0, -1],
[-1, 1, 0]]
)
Explanation: じゃんけん・ゲームを例に計算してみる.
あとあと便利なので,NumPy arr... |
15,792 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Encoder-Decoder Analysis
Model Architecture
Step1: Perplexity on Each Dataset
Step2: Loss vs. Epoch
Step3: Perplexity vs. Epoch
Step4: Generations
Step5: BLEU Analysis
Step6: N-pairs B... | Python Code:
report_file = '/Users/bking/IdeaProjects/LanguageModelRNN/reports/encdec_noing_250_512_025dr.json'
log_file = '/Users/bking/IdeaProjects/LanguageModelRNN/logs/encdec_noing_250_512_025dr_logs.json'
import json
import matplotlib.pyplot as plt
with open(report_file) as f:
report = json.loads(f.read())
wit... |
15,793 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Path Management
Goal
Normalize paths on different platform
Create, copy and remove folders
Handle errors
Modules
Step1: See also
Step2: Multiplatform Path Management
The os.path module see... | Python Code:
import os
import os.path
import shutil
import errno
import glob
import sys
Explanation: Path Management
Goal
Normalize paths on different platform
Create, copy and remove folders
Handle errors
Modules
End of explanation
# Be python3 ready
from __future__ import unicode_literals, print_function
Explanation:... |
15,794 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lab
Step1: Create Cloud Storage bucket for storing Vertex Pipeline artifacts
Step2: Create BigQuery dataset
Step3: Exploratory Data Analysis in BigQuery
Step4: Create BigQuery dataset fo... | Python Code:
# Add installed depedencies to Python PATH variable.
PATH=%env PATH
%env PATH={PATH}:/home/jupyter/.local/bin
PROJECT_ID = !(gcloud config get-value core/project)
PROJECT_ID = PROJECT_ID[0]
REGION = 'us-central1'
BQ_DATASET_NAME = 'chicago_taxi'
BQ_TABLE_NAME = 'chicago_taxi_tips_raw'
BQ_LOCATION = 'US'
!e... |
15,795 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Custom Estimators
In this notebook we'll write an Custom Estimator (using a model function we specifiy). On the way, we'll use tf.layers to write our model. In the next notebook, we'll use t... | Python Code:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import numpy as np
import tensorflow as tf
Explanation: Custom Estimators
In this notebook we'll write an Custom Estimator (using a model function we specifiy). On the way, we'll use tf.... |
15,796 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Gender Pay Gap Inequality in the U.S. and Potential Insights
A Research Project at NYU's Stern School of Buinsess — May 2016
Written by Jerry "Joa" Allen (joa218@nyu.edu)
Abstract
Althoug... | Python Code:
import sys # system module
import pandas as pd # data package
import matplotlib.pyplot as plt # graphics module
import datetime as dt # date and time module
import numpy as np # foundation for Pandas
import seaborn... |
15,797 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Re-referencing the EEG signal
This example shows how to load raw data and apply some EEG referencing schemes.
Step1: We will now apply different EEG referencing schemes and plot the resulti... | Python Code:
# Authors: Marijn van Vliet <w.m.vanvliet@gmail.com>
# Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#
# License: BSD (3-clause)
import mne
from mne.datasets import sample
from matplotlib import pyplot as plt
print(__doc__)
# Setup for reading the raw data
data_path = sample.data_pa... |
15,798 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In an jupyter notebook if your bokeh tooltips extend beyond the extent of your plot, the css from the jupyter notebook can interfere with the display leaving something like this (note this i... | Python Code:
Image(url="https://raw.githubusercontent.com/birdsarah/bokeh-miscellany/master/cut-off-tooltip.png", width=400, height=400)
Explanation: In an jupyter notebook if your bokeh tooltips extend beyond the extent of your plot, the css from the jupyter notebook can interfere with the display leaving something li... |
15,799 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Hausaufgaben
1) Geben Sie alle Unicode-Zeichen zwischen 34 und 250 aus und geben Sie alle aus, die keine Buchstaben oder Zahlen sind
Step1: oder
Step2: Wir können die Funktion auch direkt ... | Python Code:
#1a) alle unicode Z. zwischen 34 u 250 ausgeben
a = [chr(c) for c in range(34,250)]
print(a[:50])
Explanation: Hausaufgaben
1) Geben Sie alle Unicode-Zeichen zwischen 34 und 250 aus und geben Sie alle aus, die keine Buchstaben oder Zahlen sind
End of explanation
a = list(map(chr, range(34, 250)))
print(a[:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.