Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
5,700
Given the following text description, write Python code to implement the functionality described below step by step Description: Cahn-Hilliard Example This example demonstrates how to use PyMKS to solve the Cahn-Hilliard equation. The first section provides some background information about the Cahn-Hilliard equation ...
Python Code: %matplotlib inline %load_ext autoreload %autoreload 2 import numpy as np import matplotlib.pyplot as plt Explanation: Cahn-Hilliard Example This example demonstrates how to use PyMKS to solve the Cahn-Hilliard equation. The first section provides some background information about the Cahn-Hilliard equation...
5,701
Given the following text description, write Python code to implement the functionality described below step by step Description: Compute IonPopSolver Results Here, we'll run the IonPopSolver code using some of the EBTEL results in order to account for non-equilibrium ionization in our results. We'll use the multiproce...
Python Code: import os import pickle import multiprocessing import subprocess import xml.etree.ElementTree as ET import numpy as np Explanation: Compute IonPopSolver Results Here, we'll run the IonPopSolver code using some of the EBTEL results in order to account for non-equilibrium ionization in our results. We'll use...
5,702
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', 'noaa-gfdl', 'sandbox-3', 'seaice') Explanation: ES-DOC CMIP6 Model Properties - Seaice MIP Era: CMIP6 Institute: NOAA-GFDL Source ID: SANDBOX-3 Topic: Seaice Sub-Topics: Dynamics, The...
5,703
Given the following text description, write Python code to implement the functionality described below step by step Description: Let's scrape a practice table The latest Mountain Goats album is called Goths. (It's good!) I made a simple HTML table with the track listing -- let's scrape it into a CSV. Import the module...
Python Code: from bs4 import BeautifulSoup import csv Explanation: Let's scrape a practice table The latest Mountain Goats album is called Goths. (It's good!) I made a simple HTML table with the track listing -- let's scrape it into a CSV. Import the modules we'll need End of explanation # in a with block, open the HTM...
5,704
Given the following text description, write Python code to implement the functionality described below step by step Description: NLP training example In this example, we'll train an NLP model for sentiment analysis of tweets using spaCy. First we download spaCy language libraries. Step1: And import the boilerplate co...
Python Code: !python -m spacy download en_core_web_sm Explanation: NLP training example In this example, we'll train an NLP model for sentiment analysis of tweets using spaCy. First we download spaCy language libraries. End of explanation from __future__ import unicode_literals, print_function import boto3 import json ...
5,705
Given the following text description, write Python code to implement the functionality described below step by step Description: Probabilistic Bayesian Neural Networks Author Step1: Create training and evaluation datasets Here, we load the wine_quality dataset using tfds.load(), and we convert the target feature to f...
Python Code: import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers import tensorflow_datasets as tfds import tensorflow_probability as tfp Explanation: Probabilistic Bayesian Neural Networks Author: Khalid Salama<br> Date created: 2021/01/15<br> Last modified: 2021/...
5,706
Given the following text description, write Python code to implement the functionality described below step by step Description: Integration Exercise 1 Imports Step2: Trapezoidal rule The trapezoidal rule generates a numerical approximation to the 1d integral Step3: Now use scipy.integrate.quad to integrate the f an...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from scipy import integrate Explanation: Integration Exercise 1 Imports End of explanation def trapz(f, a, b, N): Integrate the function f(x) over the range [a,b] with N points. #I worked with James A # YOUR CODE HERE #ra...
5,707
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook describes how to use the provided tools to interface with the data. It goes over the process of installing the tools, retrieving the data, and opening the data within a noteboo...
Python Code: import numpy as np import matplotlib.pylab as plt %matplotlib notebook Explanation: This notebook describes how to use the provided tools to interface with the data. It goes over the process of installing the tools, retrieving the data, and opening the data within a notebook. <br> <br> Importing the tools ...
5,708
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1 align="center">Basic CFNCluster Setup</h1> <h3 align="center">Author Step1: 1. Install CFNCluster Notice Step2: 2. Upgrade CFNCluster Step3: 3. Configure CFNCluster To configure CFNCl...
Python Code: import os import sys sys.path.append(os.getcwd().replace("notebooks/awsCluster", "src/awsCluster")) ## Input the AWS account access keys aws_access_key_id = "/**aws_access_key_id**/" aws_secret_access_key = "/**aws_secret_access_key**/" ## CFNCluster name your_cluster_name = "cluster_name" ## The private ...
5,709
Given the following text description, write Python code to implement the functionality described below step by step Description: How to use implemented algorithms Overview The project has the following structure Step1: We will check if the library is imported correctly by computing a few parameters of empty graph. St...
Python Code: import sys, os # sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath('../src/')))) sys.path.append('../src/') import graph reload(graph) Explanation: How to use implemented algorithms Overview The project has the following structure: doc contains documentation of the project src contains all t...
5,710
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Aerosol 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', 'mohc', 'ukesm1-0-ll', 'aerosol') Explanation: ES-DOC CMIP6 Model Properties - Aerosol MIP Era: CMIP6 Institute: MOHC Source ID: UKESM1-0-LL Topic: Aerosol Sub-Topics: Transport, Emiss...
5,711
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: Weight clustering in Keras example <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: Train 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...
5,712
Given the following text description, write Python code to implement the functionality described below step by step Description: Regridding input data to higher resolution The initial resolution of the input file is used as the higher resolution that Badlands model can used. If one started with a given resolution and ...
Python Code: import sys print(sys.version) print(sys.executable) %matplotlib inline # Import badlands grid generation toolbox import pybadlands_companion.resizeInput as resize Explanation: Regridding input data to higher resolution The initial resolution of the input file is used as the higher resolution that Badlands ...
5,713
Given the following text description, write Python code to implement the functionality described below step by step Description: xrange vs range looping For long for loops with no need to track iteration use Step1: This will loop through 10 times, but the iteration variable won't be unused as it was never assigned. ...
Python Code: for _ in xrange(10): print "Do something" Explanation: xrange vs range looping For long for loops with no need to track iteration use: End of explanation for i in range(1,10): vars()['x'+str(i)] = i Explanation: This will loop through 10 times, but the iteration variable won't be unused as it was n...
5,714
Given the following text description, write Python code to implement the functionality described below step by step Description: Chopsticks! A few researchers set out to determine the optimal length of chopsticks for children and adults. They came up with a measure of how effective a pair of chopsticks performed, call...
Python Code: import pandas as pd # pandas is a software library for data manipulation and analysis # We commonly use shorter nicknames for certain packages. Pandas is often abbreviated to pd. # hit shift + enter to run this cell or block of code path = r'/Users/scott/googledrive/udacity/data_science/project_0/chopstick...
5,715
Given the following text description, write Python code to implement the functionality described below step by step Description: Python for Webscraping SOC 590 Step1: open US News Rankings for Sociology webpage view page source to see html Step3: create a function to extract page data from US News Step4: make empty...
Python Code: import os import urllib import webbrowser import pandas as pd from bs4 import BeautifulSoup Explanation: Python for Webscraping SOC 590: Big Data and Population Processes 17th October 2016 Tutorial 2: Webscraping with a function Outline Import modules Examine html structure of a webpage Use Beautiful Soup ...
5,716
Given the following text description, write Python code to implement the functionality described below step by step Description: Primeiramente, é necessária a leitura dos 3 arquivos, inserindo as informações em um vetor Step1: Depois, devemos retirar cada quebra de linha no final de cada linha, ou seja, os '\n'. Step...
Python Code: import codecs with codecs.open("imdb_labelled.txt", "r", "utf-8") as arquivo: vetor = [] for linha in arquivo: vetor.append(linha) with codecs.open("amazon_cells_labelled.txt", "r", "utf-8") as arquivo: for linha in arquivo: vetor.append(linha) with codecs.open("yelp_labelled....
5,717
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: How to batch convert sentence lengths to masks in PyTorch?
Problem: import numpy as np import pandas as pd import torch lens = load_data() max_len = max(lens) mask = torch.arange(max_len).expand(len(lens), max_len) > (max_len - lens.unsqueeze(1) - 1) mask = mask.type(torch.LongTensor)
5,718
Given the following text description, write Python code to implement the functionality described below step by step Description: ETL with PySpark SQL Step1: Importing and creating SparkSession Step2: Setting filesystem and files Load all CSV's files from HiggsTwitter dataset (http Step3: Convert CSV's dataframes to...
Python Code: import os import sys os.environ["SPARK_HOME"] = "/Users/projects/.pyenv/versions/3.7.10/envs/tatapower/lib/python3.7/site-packages/pyspark" # os.environ["HADOOP_HOME"] = "" # os.environ["PYSPARK_PYTHON"] = "/opt/cloudera/parcels/Anaconda/bin/python" # os.environ["JAVA_HOME"] = "/usr/java/jdk1.8.0_161/jre" ...
5,719
Given the following text description, write Python code to implement the functionality described below step by step Description: Setup command line client The following is code to get the client and set it up. Step1: Describes the tests needed to validate the PutFile functionality. The commands presented are just exa...
Python Code: %env CLIENT bitrepository-client-1.9-RC1 !wget -Nq "https://sbforge.org/download/attachments/25395346/${CLIENT}.zip" !unzip -quo ${CLIENT}.zip %alias bitmag ${CLIENT}/bin/bitmag.sh %l #Some imports we will need later import random import string Explanation: Setup command line client The following is code t...
5,720
Given the following text description, write Python code to implement the functionality described below step by step Description: Accompanying code examples of the book "Introduction to Artificial Neural Networks and Deep Learning Step1: Scientific Computing in NumPy This appendix offers a quick tour of the NumPy libr...
Python Code: %load_ext watermark %watermark -a 'Sebastian Raschka' -p numpy Explanation: Accompanying code examples of the book "Introduction to Artificial Neural Networks and Deep Learning: A Practical Guide with Applications in Python" by Sebastian Raschka. All code examples are released under the MIT license. If you...
5,721
Given the following text description, write Python code to implement the functionality described below step by step Description: Principal Component Analysis in Shogun By Abhijeet Kislay (GitHub ID Step1: Some Formal Background (Skip if you just want code examples) PCA is a useful statistical technique that has found...
Python Code: %pylab inline %matplotlib inline import os SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data') # import all shogun classes from shogun import * import shogun as sg Explanation: Principal Component Analysis in Shogun By Abhijeet Kislay (GitHub ID: <a href='https://github.com/kislayabhi'>kislayabhi...
5,722
Given the following text description, write Python code to implement the functionality described below step by step Description: Subprocess WindowsError 5 场景是这样的,有一个app目录,里面有一个主程序main.py, 主程序会调用app目录外的updater.py对app目录进行升级 Step1: updater.py代码 启动后会对app目录重命名为app_old Step2: build.py 代码 将main.py打包成exe并复制到main.py相同的目录 将u...
Python Code: # encoding: utf-8 import logging import os import subprocess import sys CUR_DIR = os.path.dirname(os.path.abspath(sys.argv[0])) logging.basicConfig(filename=os.path.join(CUR_DIR, "app.log"), filemode="w",level=logging.INFO, format='%(asctime)s [%(levelname)s]- %(mes...
5,723
Given the following text description, write Python code to implement the functionality described below step by step Description: Markov Chains author Step1: Markov chains have log probability, fit, summarize, and from summaries methods implemented. They do not have classification capabilities by themselves, but when ...
Python Code: %matplotlib inline import time import pandas import random import numpy import matplotlib.pyplot as plt import seaborn; seaborn.set_style('whitegrid') import itertools from pomegranate import * random.seed(0) numpy.random.seed(0) numpy.set_printoptions(suppress=True) %load_ext watermark %watermark -m -n -p...
5,724
Given the following text description, write Python code to implement the functionality described below step by step Description: TODO Step1: Create a master bias frame Step2: Create the master flat frame Step3: Process object frames Bias, flat corrections Step4: Now that those intermediate frames are written, we n...
Python Code: # Standard library from os.path import join import sys if '/Users/adrian/projects/longslit/' not in sys.path: sys.path.append('/Users/adrian/projects/longslit/') # Third-party from astropy.constants import c import numpy as np import matplotlib.pyplot as plt import astropy.units as u from astropy.io im...
5,725
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', 'uhh', 'sandbox-3', 'seaice') Explanation: ES-DOC CMIP6 Model Properties - Seaice MIP Era: CMIP6 Institute: UHH Source ID: SANDBOX-3 Topic: Seaice Sub-Topics: Dynamics, Thermodynamics,...
5,726
Given the following text description, write Python code to implement the functionality described below step by step Description: Parallelization Another nice thing about Python is, how easily you can parallelize your code. Here comes one example for multiprocessing. map An often used function in Python is map. It mapp...
Python Code: def f(x): return x**2 l = range(8) s = map(f, l) print 'input: ', l print 'output:', s Explanation: Parallelization Another nice thing about Python is, how easily you can parallelize your code. Here comes one example for multiprocessing. map An often used function in Python is map. It mapps a given fun...
5,727
Given the following text description, write Python code to implement the functionality described below step by step Description: Table of Contents Iterative vs fragment-based mapping Advantages of iterative mapping Advantages of fragment-based mapping Mapping Iterative mapping Fragment-based mapping Iterative vs fragm...
Python Code: from pytadbit.mapping.full_mapper import full_mapping Explanation: Table of Contents Iterative vs fragment-based mapping Advantages of iterative mapping Advantages of fragment-based mapping Mapping Iterative mapping Fragment-based mapping Iterative vs fragment-based mapping Iterative mapping first proposed...
5,728
Given the following text description, write Python code to implement the functionality described below step by step Description: <a name="top"></a> <div style="width Step1: <a href="#top">Top</a> <hr style="height Step2: We can also find the list of datasets within a time range Step3: Exercise Starting from http St...
Python Code: from datetime import datetime, timedelta from siphon.catalog import TDSCatalog date = datetime.utcnow() - timedelta(days=1) cat = TDSCatalog('http://thredds.ucar.edu/thredds/catalog/nexrad/level3/' f'N0Q/LRX/{date:%Y%m%d}/catalog.xml') Explanation: <a name="top"></a> <div style="width:1000...
5,729
Given the following text description, write Python code to implement the functionality described below step by step Description: Monte Carlo integration Monte Carlo is the simplest of all collocation methods. It consist of the following steps Step1: Then we generate samples from the three schemes Step2: From the thr...
Python Code: from problem_formulation import joint joint Explanation: Monte Carlo integration Monte Carlo is the simplest of all collocation methods. It consist of the following steps: Generate (pseudo-)random samples $Q_1, ..., Q_N$. Evaluate model solver $U_1=u(Q_1), ..., U_N=u(Q_N)$ for each sample. Use empirical me...
5,730
Given the following text description, write Python code to implement the functionality described below step by step Description: What questions would you have about this data? Step1: How would you encode categorical data such a carrier, day of week and origin airport as numerical features? Step2: Features Step3: Un...
Python Code: df.shape len(set(df.Origin)) df.FlightDate.min() df.FlightDate.max() df.DepTime.count() df.DepTime.dropna().describe() needed_columns = ['Year', 'Quarter', 'Month', 'DayofMonth', 'DayOfWeek', 'FlightDate', 'UniqueCarrier', 'Origin', 'OriginCityName', 'Dest', 'DestCityName', 'CRSDepTime', 'DepTi...
5,731
Given the following text description, write Python code to implement the functionality described below step by step Description: Demonstrate linear inverse model for the heat budget Horizontal heat transports are non-linear terms if one assume that both temperatures and velocities have to be optimized. In order to kee...
Python Code: import numpy as np Explanation: Demonstrate linear inverse model for the heat budget Horizontal heat transports are non-linear terms if one assume that both temperatures and velocities have to be optimized. In order to keep the model as simple as possible, we hypothesized that only velocities require optim...
5,732
Given the following text description, write Python code to implement the functionality described below step by step Description: Exploring QVEC I want to spend some time now looking closer at QVEC's output, namely the correlations and the alignment matrix. The second main point of the original paper is that the alignm...
Python Code: %matplotlib inline import os import csv from itertools import product import pandas as pd import numpy as np from scipy import stats import statsmodels.api as sm import matplotlib.pyplot as plt import seaborn as sns sns.set() data_path = '../../data' tmp_path = '../../tmp' Explanation: Exploring QVEC I wan...
5,733
Given the following text description, write Python code to implement the functionality described below step by step Description: Regressão Linear Este notebook mostra uma implementação básica de Regressão Linear e o uso da biblioteca MLlib do PySpark para a tarefa de regressão na base de dados Million Song Dataset do ...
Python Code: sc = SparkContext.getOrCreate() # carregar base de dados from test_helper import Test import os.path baseDir = os.path.join('Data') inputPath = os.path.join('millionsong.txt') fileName = os.path.join(baseDir, inputPath) numPartitions = 2 rawData = sc.textFile(fileName, numPartitions) # EXERCICIO numPoints ...
5,734
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: Does improved weight pruning outperforms regular SET
Python Code: %load_ext autoreload %autoreload 2 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 import * from nupic.research.framewo...
5,735
Given the following text description, write Python code to implement the functionality described below step by step Description: Generate Training sets Based on "Reproducible Experiments" notebook Step1: Initiate experiment with this input file Step2: Before we start to draw random realisations of the model, we shou...
Python Code: %matplotlib inline # here the usual imports. If any of the imports fails, # make sure that pynoddy is installed # properly, ideally with 'python setup.py develop' # or 'python setup.py install' import sys, os import matplotlib.pyplot as plt import numpy as np # adjust some settings for matplotlib from ma...
5,736
Given the following text description, write Python code to implement the functionality described below step by step Description: 9. Morphology — Lab exercises XFST / foma XFST provides two formalisms for creating FSA / FST for morphology and related fields Step1: 2. subprocess The subprocess module provides full acce...
Python Code: import os # Note that the actual output of `ls` is not printed! print('Exit code:', os.system('ls -a')) files = os.listdir('.') print('Should have printed:\n\n{}'.format('\n'.join(files if len(files) <= 3 else files[:3] + ['...']))) Explanation: 9. Morphology — Lab exercises XFST / foma XFST provides two f...
5,737
Given the following text description, write Python code to implement the functionality described below step by step Description: Handwritten Number Recognition with TFLearn and MNIST In this notebook, we'll be building a neural network that recognizes handwritten numbers 0-9. This kind of neural network is used in a ...
Python Code: # Import Numpy, TensorFlow, TFLearn, and MNIST data import numpy as np import tensorflow as tf import tflearn import tflearn.datasets.mnist as mnist Explanation: Handwritten Number Recognition with TFLearn and MNIST In this notebook, we'll be building a neural network that recognizes handwritten numbers 0-...
5,738
Given the following text description, write Python code to implement the functionality described below step by step Description: Project 22 Step1: Importing of the dataset Method definition for reading one of the available datasets Step2: Checking for missing data In the following lines, we check for missing values ...
Python Code: # General Imports for more than one file import pandas as pd import numpy as np # For reading the CSV from pandas import read_csv # Imports for the classification from sklearn.metrics import confusion_matrix from sklearn.metrics import f1_score from sklearn.model_selection import cross_validate from sklea...
5,739
Given the following text description, write Python code to implement the functionality described below step by step Description: Milestone 2 - this version has all the input completed, individually and each tested. 2-Dimensional Frame Analysis - Version 04 This program performs an elastic analysis of 2-dimensional str...
Python Code: from __future__ import print_function import salib as sl sl.import_notebooks() from Tables import Table from Nodes import Node from Members import Member from LoadSets import LoadSet, LoadCombination from NodeLoads import makeNodeLoad from MemberLoads import makeMemberLoad from collections import OrderedDi...
5,740
Given the following text description, write Python code to implement the functionality described below step by step Description: Video Codec Unit (VCU) Demo Example Step1: Run the Demo Step2: Video Step3: Audio Step4: Advanced options
Python Code: from IPython.display import HTML HTML('''<script> code_show=true; function code_toggle() { if (code_show){ $('div.input').hide(); } else { $('div.input').show(); } code_show = !code_show } $( document ).ready(code_toggle); </script> <form action="javascript:code_toggle()"><input type="submit" value...
5,741
Given the following text description, write Python code to implement the functionality described below step by step Description: Generative Adversarial Network In this notebook, we'll be building a generative adversarial network (GAN) trained on the MNIST dataset. From this, we'll be able to generate new handwritten d...
Python Code: %matplotlib inline import pickle as pkl 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') Explanation: Generative Adversarial Network In this notebook, we'll be building a gen...
5,742
Given the following text description, write Python code to implement the functionality described below step by step Description: Let's see what the column names that end in 'ID' are. Those are probably primary keys and foreign keys. Step1: First, let's set the index to what I think is the primary key
Python Code: for col in probe_spec.columns: if col.endswith('ID'): print col Explanation: Let's see what the column names that end in 'ID' are. Those are probably primary keys and foreign keys. End of explanation probe_spec.set_index('DesignID',inplace=True) probe_spec.head() design_type = pd.read_csv('NiPO...
5,743
Given the following text description, write Python code to implement the functionality described below step by step Description: Short intro to the SCT library of AutoGraph Work in progress, use with care and expect changes. The pyct module packages the source code transformation APIs used by AutoGraph. This tutorial ...
Python Code: !pip install tf-nightly Explanation: Short intro to the SCT library of AutoGraph Work in progress, use with care and expect changes. The pyct module packages the source code transformation APIs used by AutoGraph. This tutorial is just a preview - there is no PIP package yet, and the API has not been finali...
5,744
Given the following text description, write Python code to implement the functionality described below step by step Description: Numerical differential equations In the simplest methods for solving differential equations numerically, one goes back to the definition of the differential operator Step1: Now let us see i...
Python Code: dx = 0.3 x = np.arange(0, 10, dx) # returns [0, dx, 2dx, 3dx, 4dx, 5dx, ...] print(x) f1 = np.sin(x) f2 = x**2/100 f3 = np.log(1+x)-1 fs = [f1, f2, f3] for i in range(3): plt.plot(x, fs[i]) df1 = np.cos(x) df2 = x/50 df3 = 1/(1+x) dfs = [df1, df2, df3] Explanation: Numerical differential equations In the s...
5,745
Given the following text description, write Python code to implement the functionality described below step by step Description: Dynamic Pricing Game Notebook for testing your algorithms You can use this notebook to run your buyer/seller algorithms and compare them to the naive ones provided. In the below code, make a...
Python Code: import sys import os import matplotlib.pyplot as plt import numpy.random as rn import numpy as np %matplotlib inline # TODO: write the path to the root directory of the simulation game code below. # It should have a README.md file under it and 'simulation_game', 'simulation_algos', 'test directories' unde...
5,746
Given the following text description, write Python code to implement the functionality described below step by step Description: Built-in linear stability analysis Step1: To perform linear stability analysis, we simply call pyqg's built-in method stability_analysis Step2: The eigenvalues are stored in omg, and th...
Python Code: import numpy as np from numpy import pi import matplotlib.pyplot as plt %matplotlib inline import pyqg m = pyqg.LayeredModel(nx=256, nz = 2, U = [.01, -.01], V = [0., 0.], H = [1., 1.], L=2*pi,beta=1.5, rd=1./20., rek=0.05, f=1.,delta=1.) Explanation: Built-in linear stability...
5,747
Given the following text description, write Python code to implement the functionality described below step by step Description: The Hipster Effect Step2: This gives us a nice way to move from our preference $x_i$ to a probability of switching styles. Here $\beta$ is inversely related to noise. For large $\beta$, the...
Python Code: import numpy as np import holoviews as hv hv.notebook_extension(bokeh=True, width=90) %%output backend='matplotlib' %%opts NdOverlay [aspect=1.5 figure_size=200 legend_position='top_left'] x = np.linspace(-1, 1, 1000) curves = hv.NdOverlay(key_dimensions=['$\\beta$']) for beta in [0.1, 0.5, 1, 5]: curv...
5,748
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Aerosol 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', 'inm', 'inm-cm5-0', 'aerosol') Explanation: ES-DOC CMIP6 Model Properties - Aerosol MIP Era: CMIP6 Institute: INM Source ID: INM-CM5-0 Topic: Aerosol Sub-Topics: Transport, Emissions, ...
5,749
Given the following text description, write Python code to implement the functionality described below step by step Description: An Introduction to Bayesian Statistical Analysis Though many of you will have taken a statistics course or two during your undergraduate (or graduate education, most of those who have will l...
Python Code: from scipy.stats import binom # Binomial probability mass function yvals = range(10+1) plt.plot(yvals, binom.pmf(yvals, 10, 0.5), 'ro') # Binomial likelhood function pvals = np.linspace(0, 1) y = 4 plt.plot(pvals, binom.pmf(y, 10, pvals)); Explanation: An Introduction to Bayesian Statistical Analysis Thoug...
5,750
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2016 Google Inc. 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 obtai...
Python Code: %%javascript // From https://github.com/kmahelona/ipython_notebook_goodies $.getScript('https://kmahelona.github.io/ipython_notebook_goodies/ipython_notebook_toc.js') Explanation: Copyright 2016 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use...
5,751
Given the following text description, write Python code to implement the functionality described below step by step Description: Receptive Field Estimation and Prediction This example reproduces figures from Lalor et al's mTRF toolbox in matlab [1]_. We will show how the Step1: Load the data from the publication Fir...
Python Code: # Authors: Chris Holdgraf <choldgraf@gmail.com> # Eric Larson <larson.eric.d@gmail.com> # Nicolas Barascud <nicolas.barascud@ens.fr> # # License: BSD (3-clause) # sphinx_gallery_thumbnail_number = 3 import numpy as np import matplotlib.pyplot as plt from scipy.io import loadmat from os.pa...
5,752
Given the following text description, write Python code to implement the functionality described below step by step Description: Lab 2 Due 11 Step1: The code below produces the data frames used in the examples Step2: Pandas and Wrangling For the examples that follow, we will be using a toy data set containing inform...
Python Code: import pandas as pd import numpy as np # These lines load the tests. !pip install -U okpy from client.api.notebook import Notebook ok = Notebook('lab02.ok') Explanation: Lab 2 Due 11:59pm 01/27/2017 (Completion-based) In this lab you will see some examples of some commonly used data wrangling tools in Pyth...
5,753
Given the following text description, write Python code to implement the functionality described below step by step Description: Survival Analysis with Plotly Step1: Introduction Survival analysis is a set of statistical methods for analyzing the occurrence of event data over time. It is also used to determine the r...
Python Code: # You can also install packages from within IPython! # Install Python Packages !pip install lifelines !pip install rpy2 !pip install plotly !pip install pandas # Install R libraries %load_ext rpy2.ipython %R install.packages("devtools") %R install_github("ropensci/plotly") %R install.packages("IOsurv") %R ...
5,754
Given the following text description, write Python code to implement the functionality described below step by step Description: Trabajando de forma conjunta con Python y con R. Hoy vamos a ver como podemos juntar lo bueno de R, algunas de sus librerías, con Python usando rpy2. Pero, lo primero de todo, ¿qué es rpy2?...
Python Code: # Importamos pandas y numpy para manejar los datos que pasaremos a R import pandas as pd import numpy as np # Usamos rpy2 para interactuar con R import rpy2.robjects as ro # Activamos la conversión automática de tipos de rpy2 import rpy2.robjects.numpy2ri rpy2.robjects.numpy2ri.activate() import matplotlib...
5,755
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 4 The greatest theorem never told This chapter focuses on an idea that is always bouncing around our minds, but is rarely made explicit outside books devoted to statistics. In fact, ...
Python Code: %matplotlib inline import numpy as np from IPython.core.pylabtools import figsize import matplotlib.pyplot as plt figsize(12.5, 5) import pymc as pm sample_size = 100000 expected_value = lambda_ = 4.5 poi = pm.rpoisson N_samples = range(1, sample_size, 100) for k in range(3): samples = poi(lambda_, siz...
5,756
Given the following text description, write Python code to implement the functionality described below step by step Description: Read in the data.. Step1: The columns are the instances and rows the features so we need to transpose the dataset. Step2: Read in the labels... Step3: We are using the OAC labeling... Ste...
Python Code: data = pd.read_csv('/Users/Frankie/Documents/Dissertation/Data/pancreatic/24hProbeExpressionValues.csv') data[:5] Explanation: Read in the data.. End of explanation data = data.T Explanation: The columns are the instances and rows the features so we need to transpose the dataset. End of explanation label =...
5,757
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to NumPy Topics Basic Synatx creating vectors matrices special Step1: This code sets up Ipython Notebook environments (lines beginning with %), and loads several libraries and ...
Python Code: %matplotlib inline import math import numpy as np import matplotlib.pyplot as plt import seaborn as sbn ##from scipy import * Explanation: Introduction to NumPy Topics Basic Synatx creating vectors matrices special: ones, zeros, identity eye add, product, inverse Mechanics: indexing, slicing, concatenating...
5,758
Given the following text description, write Python code to implement the functionality described below step by step Description: Multiclass Classification Last modification Step1: In this example, the wine dataset contains 178 samples, 13 features, and 3 clases. Details of the dataset can be find here. Step2: This s...
Python Code: # Load the iris dataset and randomly permute it import numpy as np #import logging #logger = logging.getLogger() #logger.setLevel(logging.DEBUG) #logging.debug("test") from sklearn.datasets import load_iris from sklearn.ensemble import RandomForestClassifier from sklearn.svm import SVC from sklearn.model_s...
5,759
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Alternative Step2: Checking our results (inference)
Python Code: !pip install -q tf-nightly-gpu-2.0-preview import tensorflow as tf print(tf.__version__) (x_train, y_train), (x_test, y_test) = tf.keras.datasets.fashion_mnist.load_data() x_train.shape import numpy as np # add empty color dimension x_train = np.expand_dims(x_train, -1) x_test = np.expand_dims(x_test, -1) ...
5,760
Given the following text description, write Python code to implement the functionality described below step by step Description: Integration Exercise 2 Imports Step1: Indefinite integrals Here is a table of definite integrals. Many of these integrals has a number of parameters $a$, $b$, etc. Find five of these integr...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import seaborn as sns from scipy import integrate Explanation: Integration Exercise 2 Imports End of explanation def integrand(x, a): return 1.0/(x**2 + a**2) def integral_approx(a): # Use the args keyword argument to feed extra ...
5,761
Given the following text description, write Python code to implement the functionality described below step by step Description: Lesson 8 v1.1, 2020.4 2020.5 edit by David Yi 本课内容要点 函数介绍和用法 思考一下:剪刀石头布 函数用法 函数是组织好的、可重复使用的、用来实现单一或相关联功能的代码段。函数能提高应用的模块性,和代码的重复利用率。 python 提供了许多内建函数,比如 print(), max(); python 提供的大量内建函数,可以满足绝...
Python Code: # 计算圆的面积 # 不用函数的话,每次需要写一些重复的代码 r1 = 4 r2 = 6 r3 = 5.61 s1 = 3.14 * r1 * r1 s2 = 3.14 * r2 * r2 s3 = 3.14 * r3 * r3 print(s1) print(s2) print(s3) # 定义一个函数,用来计算圆面积 # 输入 半径,返回 圆面积 def func1(r): s = 3.14 * r * r return s print(func1(4)) print(func1(6)) print(func1(5.61)) # 先来看看 python 内置的获取最大值的函数 print...
5,762
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: A notebook to process experimental results of ex2_prob_params.py. p(reject) as problem parameters are varied. Step2: $$p(x)=\mathcal{N}(0, I) \ q(x)=\mathcal{N}(0, I)$$ Step3: $$p(x...
Python Code: %load_ext autoreload %autoreload 2 %matplotlib inline #%config InlineBackend.figure_format = 'svg' #%config InlineBackend.figure_format = 'pdf' import numpy as np import matplotlib import matplotlib.pyplot as plt import kgof.data as data import kgof.glo as glo import kgof.goftest as gof import kgof.kernel ...
5,763
Given the following text description, write Python code to implement the functionality described below step by step Description: Comparing Keras and Scikit models deployed on Cloud AI Platform with the What-if Tool In this notebook we'll use the UCI wine quality dataset to train both tf.keras and Scikit learn regressi...
Python Code: import sys python_version = sys.version_info[0] # If you're running on Colab, you'll need to install the What-if Tool package and authenticate def pip_install(module): if python_version == '2': !pip install {module} --quiet else: !pip3 install {module} --quiet try: import google...
5,764
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...
5,765
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Logistic Regression Step2: <hr /> Data setup for the 10 digit classes The data is the same that was used in the last post but this time I will use all of the 0-9 images. There are 42...
Python Code: import pandas as pd # data handeling import numpy as np # numerical computing from scipy.optimize import minimize # optimization code import matplotlib.pyplot as plt # plotting import seaborn as sns %matplotlib inline sns.set() import itertools # combinatorics functions for multinomial code # # Mai...
5,766
Given the following text description, write Python code to implement the functionality described below step by step Description: 3/10/17 Trying to get a critical infinite serpent simulation, e.g. $k_{\infty}$ = 1 U235 = .418% U238 = .8625% k = 1.07238 msr2g_enrU 2/10/17 Serpent run yielded k_eff of 1.03 msr2g_part_U_s...
Python Code: k_nom = 1.0545 k_f_1144 = 1.04149 fuel_reactivity = (k_f_1144 - k_nom) / k_nom / 400 print(fuel_reactivity) Explanation: 3/10/17 Trying to get a critical infinite serpent simulation, e.g. $k_{\infty}$ = 1 U235 = .418% U238 = .8625% k = 1.07238 msr2g_enrU 2/10/17 Serpent run yielded k_eff of 1.03 msr2g_part...
5,767
Given the following text description, write Python code to implement the functionality described below step by step Description: My note Step1: Test OpenCV Step2: Test TensorFlow Step3: Test Moviepy Step4: Troubleshooting ffmpeg NOTE Step6: Create a new video with moviepy by processing each frame to YUV color spa...
Python Code: import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np %matplotlib inline img = mpimg.imread('test.jpg') plt.imshow(img) Explanation: My note: 1. Install Anaconda 2. Setup the carnd-term1 environment as instructions in Starter Kit. 3. Run the test.ipynb in the carnd-term1 ker...
5,768
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: Create Dummy Variables with Pandas
Python Code:: import pandas as pd X = pd.get_dummies(X, columns=['neighbourhood_group','room_type'], drop_first=True)
5,769
Given the following text description, write Python code to implement the functionality described below step by step Description: <img src="images/logo.jpg" style="display Step1: <p style="text-align Step2: <p style="text-align Step3: <p style="text-align Step4: <p style="text-align Step5: <p style="text-align Ste...
Python Code: def silly_generator(): a = 1 yield a b = a + 1 yield b c = [1, 2, 3] yield c Explanation: <img src="images/logo.jpg" style="display: block; margin-left: auto; margin-right: auto;" alt="לוגו של מיזם לימוד הפייתון. נחש מצויר בצבעי צהוב וכחול, הנע בין האותיות של שם הקורס: לומדים פייתון...
5,770
Given the following text description, write Python code to implement the functionality described below step by step Description: 2/22/17 Step1: So it looks like there's excellent agreement between the theoretical calculation of the material buckling and the value output by serpent, so it seems reasonable to guess tha...
Python Code: bm2 = .00202183 height = 198.12 radius = var('radius') solns = solve(bm2 == (pi/height)^2 + (2.405/radius)^2, radius, solution_dict=True) [s[radius].n() for s in solns] radius = solns[1][radius].n() print(radius) nu = 2.43654 sigma_f = 1.3769e-3 sigma_a = 2.21110e-3 diff = 5.31788e-1 bm2_calc = (nu * sigma...
5,771
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook was prepared by Donne Martin. Source and license info is on GitHub. Kaggle Machine Learning Competition Step1: Explore the Data Read the data Step2: View the data types of ea...
Python Code: import pandas as pd import numpy as np import pylab as plt # Set the global default size of matplotlib figures plt.rc('figure', figsize=(10, 5)) # Size of matplotlib figures that contain subplots fizsize_with_subplots = (10, 10) # Size of matplotlib histogram bins bin_size = 10 Explanation: This notebook w...
5,772
Given the following text description, write Python code to implement the functionality described below step by step Description: PySAL Change Log Statistics Step1: with open('../packages.yml') as package_file Step2: Our last main release was 2019-01-30 Step3: get dates of tags with open('subtags', 'r') as tag_name ...
Python Code: from __future__ import print_function import os import json import re import sys import pandas import subprocess from subprocess import check_output #import yaml from datetime import datetime, timedelta from dateutil.parser import parse import pytz utc=pytz.UTC from datetime import datetime, timedelta from...
5,773
Given the following text description, write Python code to implement the functionality described below step by step Description: WHFast tutorial This tutorial is an introduction to the python interface of WHFast, a fast and unbiased symplectic Wisdom-Holman integrator. This integrator is well suited for integrations o...
Python Code: import rebound Explanation: WHFast tutorial This tutorial is an introduction to the python interface of WHFast, a fast and unbiased symplectic Wisdom-Holman integrator. This integrator is well suited for integrations of planetary systems in which the planets stay roughly on their orbits. If close encounter...
5,774
Given the following text description, write Python code to implement the functionality described below step by step Description: 1. Partial function application 2. Pattern matching Ciastocna aplikacia - Partially applied functions http Step1: Iny priklad Step2: Balicek functools ma na to funkciu, ktora definiciu tak...
Python Code: def add(a, b): return a + b def make_adder(a) : def adder(b) : return add(a, b) return adder add_two = make_adder(20) add_two(4) Explanation: 1. Partial function application 2. Pattern matching Ciastocna aplikacia - Partially applied functions http://blog.dhananjaynene.com/tags/function...
5,775
Given the following text description, write Python code to implement the functionality described below step by step Description: Big 3 statistics uslisted.txt Step1: Show types of companies Step2: Step 1. Include only publicly listed companies from the US Keep only larger shareholder percentage between direct and to...
Python Code: #Install libraries needed !pip install --upgrade pip !pip install pandas !pip install numpy #Import libraries needed import pandas as pd import numpy as np from collections import Counter Explanation: Big 3 statistics uslisted.txt: Downloaded from Orbis, file containing the following fields: 'Company name'...
5,776
Given the following text description, write Python code to implement the functionality described below step by step Description: Enron Scandal Step1: 1. Data Processing and Exploratory Data Analysis Load the Data Step2: Explore the Data Step3: Imbalanced target Step4: Transform the data Step5: Missing features St...
Python Code: import os import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import helper import keras helper.info_gpu() #sns.set_palette("Reds") helper.reproducible(seed=0) # setup reproducible results from run to run using Keras %matplotlib inline %load_ext autoreload %autorel...
5,777
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 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 a...
Python Code: import numpy as np import scipy.stats import seaborn as sns import matplotlib import matplotlib.pyplot as plt sns.set_context('paper', font_scale=2.0, rc={'lines.linewidth': 2.0}) sns.set_style('whitegrid') # We use INTEGRATION_LIMIT instead of infinity in integration limits INTEGRATION_LIMIT = 10. # Thres...
5,778
Given the following text description, write Python code to implement the functionality described below step by step Description: Anomaly Detection on MNIST This notebook shows how a Deep Learning Auto-Encoder model can be used to find outliers in a dataset. Consider the following three-layer neural network with one h...
Python Code: import numpy as np import theano import lasagne import matplotlib.pyplot as plt %matplotlib inline import gzip import pickle # Seed for reproducibility np.random.seed(42) # Download the MNIST digits dataset (actually, these are already downloaded locally) # !wget -N --directory-prefix=./data/MNIST/ http://...
5,779
Given the following text description, write Python code to implement the functionality described below step by step Description: Load airports of each country Step1: record schedules for 2 weeks, then augment count with weekly flight numbers. seasonal and seasonal charter will count as once per week for 3 months, so ...
Python Code: L=json.loads(file('../json/L.json','r').read()) M=json.loads(file('../json/M.json','r').read()) N=json.loads(file('../json/N.json','r').read()) import requests AP={} for c in M: if c not in AP:AP[c]={} for i in range(len(L[c])): AP[c][N[c][i]]=L[c][i] sch={} Explanation: Load airports of ea...
5,780
Given the following text description, write Python code to implement the functionality described below step by step Description: Win/Loss Betting Model Step2: Pymc Model Determining Binary Win Loss Step3: Plot the last period rating for some teams Step4: Plot some over time ratings
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline data = pd.read_csv('data.csv', index_col=0).reset_index(drop=True) teams = np.sort(np.unique(np.concatenate([data['Team 1 ID'], data['Team 2 ID']]))) periods = data.Date.unique() tmap = {v:k for ...
5,781
Given the following text description, write Python code to implement the functionality described below step by step Description: Implementing Maps as Arrays If the keys are natural numbers less than a given natural number n that is not too big, a map can be implemented via an array. The class ArrayMap shows how this ...
Python Code: class ArrayMap: def __init__(self, n): self.mArray = [None] * n def find(self, k): return self.mArray[k] def insert(self, k, v): self.mArray[k] = v def delete(self, k): self.mArray[k] = None def __repr__(self): result = ...
5,782
Given the following text description, write Python code to implement the functionality described below step by step Description: Assignment 4 Solution Step1: 4. The Database object you just created has a phases attribute that is a dictionary. Print this dictionary. The keys are the phase names and the values are Phas...
Python Code: from pycalphad import Database solder_dbf = Database('Ag-Bi-Cu-Pb-Sb-Sn-nist-solders.tdb') Explanation: Assignment 4 Solution: Introduction to pycalphad User questions and feedback can be directed to the pycalphad Google Group. Bugs can be reported to the GitHub repo. 1. Ensure pycalphad is installed. For ...
5,783
Given the following text description, write Python code to implement the functionality described below step by step Description: GeoViews is a Python library that makes it easy to explore and visualize geographical, meteorological, and oceanographic datasets, such as those used in weather, climate, and remote sensing ...
Python Code: import geoviews as gv import geoviews.feature as gf import xarray as xr from cartopy import crs gv.extension('bokeh', 'matplotlib') (gf.ocean + gf.land + gf.ocean * gf.land * gf.coastline * gf.borders).opts( 'Feature', projection=crs.Geostationary(), global_extent=True, height=325).cols(3) Explanation:...
5,784
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Fully-Connected Neural Nets In the previous homework you implemented a fully-connected two-layer neural network on CIFAR-10. The implementation was simple but not very modular since t...
Python Code: # As usual, a bit of setup import time import numpy as np import matplotlib.pyplot as plt from cs231n.classifiers.fc_net import * from cs231n.data_utils import get_CIFAR10_data from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array from cs231n.solver import Solver %matplot...
5,785
Given the following text description, write Python code to implement the functionality described below step by step Description: Introducing Pandas From the docs Step1: Introducing DataFrame From the docs Step2: The Jupyter Notebook automatically renders DataFrame as HTML! Note the first column; this is an Index, an...
Python Code: import pandas as pd pd.options.display.max_rows = 20 %matplotlib inline Explanation: Introducing Pandas From the docs: A Python package providing fast, flexible, and expressive data structures designed to make working with “relational” or “labeled” data both easy and intuitive. We also use matplotlib: A Py...
5,786
Given the following text description, write Python code to implement the functionality described below step by step Description: Deep Learning Assignment 4 Previously in 2_fullyconnected.ipynb and 3_regularization.ipynb, we trained fully connected networks to classify notMNIST characters. The goal of this assignment i...
Python Code: # These are all the modules we'll be using later. Make sure you can import them # before proceeding further. from __future__ import print_function import numpy as np import tensorflow as tf from six.moves import cPickle as pickle from six.moves import range pickle_file = '../notMNIST.pickle' with open(pick...
5,787
Given the following text description, write Python code to implement the functionality described below step by step Description: Vertex client library Step1: Install the latest GA version of google-cloud-storage library as well. Step2: Restart the kernel Once you've installed the Vertex client library and Google clo...
Python Code: import os import sys # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install -U google-cloud-aiplatform $USER_FLAG Explanation: Vertex client library: AutoML image classification model for online prediction <table...
5,788
Given the following text description, write Python code to implement the functionality described below step by step Description: Deploying NVIDIA Triton Inference Server in AI Platform Prediction Custom Container (REST API) In this notebook, we will walk through the process of deploying NVIDIA's Triton Inference Serve...
Python Code: PROJECT_ID='[Enter project name - REQUIRED]' REPOSITORY='caipcustom' REGION='us-central1' TRITON_VERSION='20.06' import os import random import requests import json MODEL_BUCKET='gs://{}-{}'.format(PROJECT_ID,random.randint(10000,99999)) ENDPOINT='https://{}-ml.googleapis.com/v1'.format(REGION) TRITON_IMAG...
5,789
Given the following text description, write Python code to implement the functionality described below step by step Description: Example of using two distance + thresholds in one ABC sampling run Step1: Distance measure compares mean + variance
Python Code: samples_size = 1000 mean = 2 sigma = 1 data = np.random.normal(mean, sigma, samples_size) f,ax = plt.subplots() sns.distplot(data) def create_new_sample(theta): mu,sigma = theta if sigma<=0: sigma=10 return np.random.normal(mu, sigma, samples_size) Explanation: Example of using two dist...
5,790
Given the following text description, write Python code to implement the functionality described below step by step Description: Exercise 5.18 Plots L vs T from a source file and fits polynomials of varying degrees to it Step1: Below are the polynomials being fit to the data Step2: Exercise 5.22 Computes the midpoin...
Python Code: p1.part_a() Explanation: Exercise 5.18 Plots L vs T from a source file and fits polynomials of varying degrees to it End of explanation p1.part_b() Explanation: Below are the polynomials being fit to the data End of explanation p2.midpointint(p2.function, 1, 3, 50)[0] p2.sum_vectorized(p2.function, 1, 3, 5...
5,791
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: Object Detection <table class="tfo-notebook-buttons" align="left"> <td> ...
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...
5,792
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: <a href="http Step3: Doc tests The following docstring section 'Examples' should help the user understand what is the component's purpose and how it works. It is an example (or examp...
Python Code: import numpy as np from landlab import Component, FieldError class KinwaveOverlandFlowModel(Component): Calculate water flow over topography. Landlab component that implements a two-dimensional kinematic wave model. You can put other information here... Anything you thi...
5,793
Given the following text description, write Python code to implement the functionality described below step by step Description: BBH class $ecc==0$ Step1: 5 realization results (93328, 13) (17287278, 13) (17380606, 14) Step2: Mergers Event Rate Step3: $\frac{1}{4\pi/3(30Mpc)^313.5Gyr}=\frac{1}{4\pi/32700013.5 {Gpc}...
Python Code: # ## load example data for testing # BBHex=pd.read_csv('../data/RES/1024/BBHex.dat',delim_whitespace=True,header=None, # names=['Galaxy','RA','Dec','Dist','VMag','Model','Age','T_eject','M1','M2','Seperation','Ecc','Period']) # BBHex.sample(2) # ## label example data for analysis # merge_li...
5,794
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step2: Parameters Step3: Colab-only auth for this notebook and the TPU Step4: TPU detection Step5: tf.data.Dataset Step6: Let's have a look at the data Step7: Estimator ...
Python Code: import os, re, math, json, shutil, pprint, datetime import PIL.Image, PIL.ImageFont, PIL.ImageDraw # "pip3 install Pillow" or "pip install Pillow" if needed import numpy as np import tensorflow as tf from matplotlib import pyplot as plt from tensorflow.python.platform import tf_logging print("Tensorflow v...
5,795
Given the following text description, write Python code to implement the functionality described below step by step Description: Lab 09a Step1: Next, let's load the data. The iris data set is included in scikit-learn's datasets submodule, so we can just load it directly like this Step2: Exploratory data analysis Let...
Python Code: %matplotlib inline import numpy as np import pandas as pd from matplotlib import pyplot as plt from sklearn import cluster from sklearn import datasets Explanation: Lab 09a: K-means clustering Introduction This lab focuses on $K$-means clustering using the Iris flower data set. At the end of the lab, you s...
5,796
Given the following text description, write Python code to implement the functionality described below step by step Description: $\hat R$ locker This notebook serves as a sandbox to understand the potential of the nested-$\hat R$ diagnostic. The underlying idea is to gather short chains into a long "super chains" and ...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" } # 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...
5,797
Given the following text description, write Python code to implement the functionality described below step by step Description: Identifying safe loans with decision trees The LendingClub is a peer-to-peer leading company that directly connects borrowers and potential lenders/investors. In this notebook, you will buil...
Python Code: import graphlab graphlab.canvas.set_target('ipynb') Explanation: Identifying safe loans with decision trees The LendingClub is a peer-to-peer leading company that directly connects borrowers and potential lenders/investors. In this notebook, you will build a classification model to predict whether or not a...
5,798
Given the following text description, write Python code to implement the functionality described below step by step Description: Markov switching autoregression models This notebook provides an example of the use of Markov switching models in Statsmodels to replicate a number of results presented in Kim and Nelson (19...
Python Code: %matplotlib inline import numpy as np import pandas as pd import statsmodels.api as sm import matplotlib.pyplot as plt import requests from io import BytesIO # NBER recessions from pandas_datareader.data import DataReader from datetime import datetime usrec = DataReader('USREC', 'fred', start=datetime(1947...
5,799
Given the following text description, write Python code to implement the functionality described below step by step Description: Problem Set 01 1. COUNTING VOWELS Assume s is a string of lower case characters. Write a program that counts up the number of vowels contained in the string s. Valid vowels are Step1: 2. CO...
Python Code: s= 'wordsmith' vowels = {'a','e','i','o','u'} count = 0 for char in s: if char in vowels: count+=1 print "Number of vowels: " + str(count) Explanation: Problem Set 01 1. COUNTING VOWELS Assume s is a string of lower case characters. Write a program that counts up the number of vowels contained ...