Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
3,800 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SARIMAX
Step1: Model Selection
As in Durbin and Koopman, we force a number of the values to be missing.
Step2: Then we can consider model selection using the Akaike information criteria (A... | Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
from scipy.stats import norm
import statsmodels.api as sm
import matplotlib.pyplot as plt
import requests
from io import BytesIO
from zipfile import ZipFile
# Download the dataset
dk = requests.get('http://www.ssfpack.com/files/DK-data.zip').content... |
3,801 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Landice
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'bcc', 'sandbox-3', 'landice')
Explanation: ES-DOC CMIP6 Model Properties - Landice
MIP Era: CMIP6
Institute: BCC
Source ID: SANDBOX-3
Topic: Landice
Sub-Topics: Glaciers, Ice.
Proper... |
3,802 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Manipulating FileFunction Spectra
This tutorial demonstrates some of the methods that can be used to manipulate FileFunction sources in fermipy. For this example we'll use the draco analysi... | Python Code:
import os
if os.path.isfile('../data/draco.tar.gz'):
!tar xzf ../data/draco.tar.gz
else:
!curl -OL https://raw.githubusercontent.com/fermiPy/fermipy-extras/master/data/draco.tar.gz
!tar xzf draco.tar.gz
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from fermipy.gtanalysi... |
3,803 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ex3
Step1: To create a VectorFitting instance, a Network containing the frequency responses of the N-port is passed. In this example a copy of Agilent_E5071B.s4p from the skrf/tests folder ... | Python Code:
import skrf
import numpy as np
import matplotlib.pyplot as mplt
Explanation: Ex3: Fitting spiky responses
The Vector Fitting feature is demonstrated using a 4-port example network copied from the scikit-rf tests folder. This network is a bit tricky to fit because of its many resonances in the individual re... |
3,804 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Goal
Step1: Load some data
I'm going to work with the data from the combined data sets. The analysis for this data set is in analysis\Cf072115_to_Cf072215b.
The one limitation here is that ... | Python Code:
import os
import sys
import matplotlib.pyplot as plt
import numpy as np
import imageio
import pandas as pd
import seaborn as sns
sns.set(style='ticks')
sys.path.append('../scripts/')
import bicorr as bicorr
import bicorr_e as bicorr_e
import bicorr_plot as bicorr_plot
import bicorr_sums as bicorr_sums
impo... |
3,805 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Basic Text Classification with Naive Bayes
In the mini-project, you'll learn the basics of text analysis using a subset of movie reviews from the rotten tomatoes database. You'll also use a ... | Python Code:
%matplotlib inline
import numpy as np
import scipy as sp
import matplotlib as mpl
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from six.moves import range
import seaborn as sns
# Setup Pandas
pd.set_option('display.width', 500)
pd.set_option('display.... |
3,806 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A Pragmatic Introduction to Perceptual Vector Quantization (part 1)
Luc Trudeau
Context
This guide explains Perceptual Vector Quantization by presenting it in a practical context. By pratica... | Python Code:
%matplotlib inline
import numpy as np
from scipy.ndimage import imread
import matplotlib.pyplot as plt
def showImage(im):
plt.imshow(im, cmap = plt.get_cmap('gray'), vmin = 0, vmax = 255)
plt.title("This image has %d shades of gray." % len(np.unique(im)))
im = imread("images/tiger.png")
im = im[:,... |
3,807 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Astronomical python packages
In this lecture we will introduce the astropy library and the
affiliated package astroquery.
The official documents of these packages are available at
Step1: To... | Python Code:
from astropy.utils.data import download_file
from astropy.io import fits
image_file = download_file('http://data.astropy.org/tutorials/FITS-images/HorseHead.fits',
cache=True)
Explanation: Astronomical python packages
In this lecture we will introduce the astropy library and the
... |
3,808 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Bidirectional A$^*$ Search
Step1: The function search takes three arguments to solve a search problem
Step2: Given a state and a parent dictionary Parent, the function path_to returns a pa... | Python Code:
import sys
sys.path.append('..')
from Set import Set
Explanation: Bidirectional A$^*$ Search
End of explanation
def search(start, goal, next_states, heuristic):
estimate = heuristic(start, goal)
ParentA = { start: start }
ParentB = { goal : goal }
DistanceA = { start: 0 }
Distance... |
3,809 | 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', 'ncc', 'noresm2-mm', 'atmos')
Explanation: ES-DOC CMIP6 Model Properties - Atmos
MIP Era: CMIP6
Institute: NCC
Source ID: NORESM2-MM
Topic: Atmos
Sub-Topics: Dynamical Core, Radiation,... |
3,810 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Splitting dataset and writing TF Records
This notebook shows you how to split a dataset into training, validation, testing and write those images into TensorFlow Record files.
Step1: Writin... | Python Code:
import pandas as pd
df = pd.read_csv('gs://practical-ml-vision-book/flowers_5_jpeg/flower_photos/all_data.csv', names=['image','label'])
df.head()
import numpy as np
np.random.seed(10)
rnd = np.random.rand(len(df))
train = df[ rnd < 0.8 ]
valid = df[ (rnd >= 0.8) & (rnd < 0.9) ]
test = df[ rnd >= 0.9 ]
p... |
3,811 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Recurrent neural networks
Import various modules that we need for this notebook (now using Keras 1.0.0)
Step1: Load the MNIST dataset, flatten the images, convert the class labels, and scal... | Python Code:
%pylab inline
import copy
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import sys
import os
import xml.etree.ElementTree as ET
from keras.datasets import imdb, reuters
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.... |
3,812 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
02 - Reverse Time Migration
This notebook is the second in a series of tutorial highlighting various aspects of seismic inversion based on Devito operators. In this second example we aim to ... | Python Code:
import numpy as np
%matplotlib inline
from devito import configuration
configuration['log-level'] = 'WARNING'
Explanation: 02 - Reverse Time Migration
This notebook is the second in a series of tutorial highlighting various aspects of seismic inversion based on Devito operators. In this second example we a... |
3,813 | 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 tabular classification model for online prediction with... |
3,814 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pandas
Step1: get_dummies converts a categorical variable into indicator variables, i.e. 1 or 0.
Step2: Join this new data frame with the original, row for row
Step3: We can accomplish so... | Python Code:
df = pandas.read_csv('data/red_wine.csv', delimiter=';', parse_dates='time')
df.head()
df['quality'].unique()
Explanation: Pandas: Combining Datasets
Pandas documentation: Merging
Pandas allows us to combine two sets of data using merge, join, and concat.
End of explanation
quality_dummies = pandas.get_dum... |
3,815 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Facies classification using Convolutional Neural Networks
Team StoDIG - Statoil Deep-learning Interest Group
David Wade, John Thurmond & Eskil Kulseth Dahl
In this python notebook we propos... | Python Code:
%%sh
pip install pandas
pip install scikit-learn
pip install keras
pip install sklearn
from __future__ import print_function
import time
import numpy as np
%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.colors as colors
from mpl_toolkits.axes_grid1 import make_axes... |
3,816 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 3 - Training process and learning rate
In this chapter we will clean up our code and create a logistic classifier class that works much like many modern deep learning libraries do. W... | Python Code:
# Numpy handles matrix multiplication, see http://www.numpy.org/
import numpy as np
# PyPlot is a matlab like plotting framework, see https://matplotlib.org/api/pyplot_api.html
import matplotlib.pyplot as plt
# This line makes it easier to plot PyPlot graphs in Jupyter Notebooks
%matplotlib inline
import s... |
3,817 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example with real audio recordings
The iterations are dropped in contrast to the offline version. To use past observations the correlation matrix and the correlation vector are calculated re... | Python Code:
channels = 8
sampling_rate = 16000
delay = 3
alpha=0.99
taps = 10
frequency_bins = stft_options['size'] // 2 + 1
Explanation: Example with real audio recordings
The iterations are dropped in contrast to the offline version. To use past observations the correlation matrix and the correlation vector are calc... |
3,818 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
벡터 공간
벡터의 기하학적 의미
길이가 $K$인 벡터(vector) $a$는 $K$차원의 공간에서 원점과 벡터 $a$의 값으로 표시되는 점을 연결한 화살표(arrow)로 간주할 수 있다.
$$ a = \begin{bmatrix}1 \ 2 \end{bmatrix} $$
Step1: 벡터의 길이
벡터 $a$ 의 길이를 놈(norm) $\|... | Python Code:
a = [1, 2]
plt.annotate('', xy=a, xytext=(0,0), arrowprops=dict(facecolor='black'))
plt.plot(0, 0, 'ro', ms=10)
plt.plot(a[0], a[1], 'ro', ms=10)
plt.text(0.35, 1.15, "$a$", fontdict={"size": 18})
plt.xticks(np.arange(-2, 4))
plt.yticks(np.arange(-1, 4))
plt.xlim(-2.4, 3.4)
plt.ylim(-1.2, 3.2)
plt.show()
E... |
3,819 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1 align="center">TensorFlow Neural Network Lab</h1>
<img src="image/notmnist.png">
In this lab, you'll use all the tools you learned from Introduction to TensorFlow to label images of Engl... | Python Code:
!which python
Explanation: <h1 align="center">TensorFlow Neural Network Lab</h1>
<img src="image/notmnist.png">
In this lab, you'll use all the tools you learned from Introduction to TensorFlow to label images of English letters! The data you are using, <a href="http://yaroslavvb.blogspot.com/2011/09/notmn... |
3,820 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
iPython Cookbook - Monte Carlo Pricing II - Call (Lognormal)
Pricing a call option with Monte Carlo (Normal model)
Step1: Those are our option and market parameters
Step2: We now define ou... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
Explanation: iPython Cookbook - Monte Carlo Pricing II - Call (Lognormal)
Pricing a call option with Monte Carlo (Normal model)
End of explanation
strike = 100
mat = 1
forward = 100
vol = 0.3
Explanation: Those are our option and market parame... |
3,821 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Wind and Sea Level Pressure Interpolation
Interpolate sea level pressure, as well as wind component data,
to make a consistent looking analysis, featuring contours of pressure and wind barbs... | Python Code:
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from matplotlib.colors import BoundaryNorm
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from metpy.calc import wind_components
from metpy.cbook import get_test_data
from metpy.interpolate import interpolate_to_grid, rem... |
3,822 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Minimax Algorithm with Memoization
This notebook implements the minimax algorithm with memoization
and thereby implements a program that can play various deterministic, zero-sum, turn-t... | Python Code:
def maxValue(State):
if finished(State):
return utility(State)
return max([ minValue(ns) for ns in next_states(State, gPlayers[0]) ])
Explanation: The Minimax Algorithm with Memoization
This notebook implements the minimax algorithm with memoization
and thereby implements a program that ca... |
3,823 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CartesianCoords and PolarCoords are classes that were designed to be used in-house for the conversion between Cartesian and Polar coordinates. You just need to initialise the object with som... | Python Code:
cc = pmt.CartesianCoords(5,5)
print("2D\n")
print("x-coordinate: {}".format(cc.x))
print("y-coordinate: {}".format(cc.y))
print("radial: {}".format(cc.r))
print("azimuth: {}".format(cc.a))
cc3D = pmt.CartesianCoords(1,2,3)
print("\n3D\n")
print("x-coordinate: {}".format(cc3D.x))
print("y-coordin... |
3,824 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
BERT Experiments with passage
In this notebook we repeat the experiments from the first BERT notebook, but this time we also feed the passage to the model. This results in the following diff... | Python Code:
import torch
from pytorch_transformers.tokenization_bert import BertTokenizer
from pytorch_transformers.modeling_bert import BertForSequenceClassification
BERT_MODEL = 'bert-base-uncased'
tokenizer = BertTokenizer.from_pretrained(BERT_MODEL)
Explanation: BERT Experiments with passage
In this notebook we re... |
3,825 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simple 2D Plots using Matplotlib
Week 4 onwards (Term 2)
Import dependencies
Step1: Load the dataset from the csv file
Step2: Process the data
We will output the data in the form of a nump... | Python Code:
import numpy as np
%run 'preprocessor.ipynb' #our own preprocessor functions
Explanation: Simple 2D Plots using Matplotlib
Week 4 onwards (Term 2)
Import dependencies
End of explanation
with open('/Users/timothy/Desktop/Files/data_new/merged.csv', 'r') as f:
reader = csv.reader(f)
data = list(r... |
3,826 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Regressions
Author
Step1: Underfitting | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import math
x = np.linspace(0,4*math.pi,100)
y = map(math.sin,x)
plt.plot(x,y)
plt.plot(x,y,'o')
plt.show()
Explanation: Regressions
Author: Yang Long
Email: longyang_123@yeah.net
Linear Regression
Logistic Regression
Softmax Regression... |
3,827 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step2: We compare three implementations of the same Algorithm
Step5: Multiprocessing implementation
Step8: ipyparallel implementation
First start ipython cluster in terminal
<center> $ipcl... | Python Code:
from random import uniform
from time import time
def sample_circle(n):
throw n darts in [0, 1] * [0, 1] square, return the number
of darts inside unit circle.
Parameter
---------
n: number of darts to throw.
Return
------
m: number of darts inside unit... |
3,828 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Grid algorithm for a logitnormal-binomial hierarchical model
Bayesian Inference with PyMC
Copyright 2021 Allen B. Downey
License
Step2: Heart Attack Data
This example is based on Cha... | Python Code:
# If we're running on Colab, install libraries
import sys
IN_COLAB = 'google.colab' in sys.modules
if IN_COLAB:
!pip install pymc3
!pip install arviz
!pip install empiricaldist
# PyMC generates a FutureWarning we don't need to deal with yet
import warnings
warnings.filterwarnings("ignore", cate... |
3,829 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Propensity to Buy
Company XYZ is into creating productivity apps on cloud. Their apps are quite popular across the industry spectrum - large enterprises, small and medium companies and start... | Python Code:
#code here
Explanation: Propensity to Buy
Company XYZ is into creating productivity apps on cloud. Their apps are quite popular across the industry spectrum - large enterprises, small and medium companies and startups - all of them use their apps.
A big challenge that their sales team need to know is to kn... |
3,830 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1 align="center"></h1>
<h1 align="center">Problem 1 - Building an HBM</h1>
<h2 align="center">Hierarchical Bayesian Modeling of a Truncated Gaussian Population with PyStan and PyJAGS</h2>
... | Python Code:
import numpy as np
import scipy.stats as stats
import pandas as pd
import matplotlib.pyplot as plt
import pyjags
import pystan
import pickle
import triangle_linear
from IPython.display import display, Math, Latex
from __future__ import division, print_function
from pandas.tools.plotting import *
from matpl... |
3,831 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
What is the quickest way to convert the non-diagonal elements of a square symmetrical numpy ndarray to 0? I don't wanna use LOOPS! | Problem:
import numpy as np
a = np.array([[1,0,2,3],[0,5,3,4],[2,3,2,10],[3,4, 10, 7]])
result = np.einsum('ii->i', a)
save = result.copy()
a[...] = 0
result[...] = save |
3,832 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fungal ITS QIIME analysis tutorial
In this tutorial we illustrate steps for analyzing fungal ITS amplicon data using the QIIME/UNITE reference OTUs (alpha version 12_11) to compare the compo... | Python Code:
!(wget ftp://ftp.microbio.me/qiime/tutorial_files/its-soils-tutorial.tgz || curl -O ftp://ftp.microbio.me/qiime/tutorial_files/its-soils-tutorial.tgz)
!(wget ftp://ftp.microbio.me/qiime/tutorial_files/its_12_11_otus.tgz || curl -O ftp://ftp.microbio.me/qiime/tutorial_files/its_12_11_otus.tgz)
Explanation:... |
3,833 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Softmax exercise
Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet) with your assignment submission. For more details see ... | Python Code:
# Run some setup code
import numpy as np
import matplotlib.pyplot as plt
# This is a bit of magic to make matplotlib figures appear inline in the notebook
# rather than in a new window.
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpola... |
3,834 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Reading multiple files with xarray
From the documentation
Step1: Note that the default chunking will have each file in a separate chunk. You can't change this with the chunk option (i.e. th... | Python Code:
import xarray
ds = xarray.open_mfdataset(allfiles) #chunks={'lev': 1, 'time': 1956})
Explanation: Reading multiple files with xarray
From the documentation: xarray uses Dask, which divides arrays into many small pieces, called chunks, each of which is presumed to be small enough to fit into memory.
Unlik... |
3,835 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Toplevel
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specif... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'bnu', 'sandbox-2', 'toplevel')
Explanation: ES-DOC CMIP6 Model Properties - Toplevel
MIP Era: CMIP6
Institute: BNU
Source ID: SANDBOX-2
Sub-Topics: Radiative Forcings.
Properties: 85... |
3,836 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Assignment 2
Step1: Let's look at what a random episode looks like.
Step2: In the episode above, the agent falls into a hole after two timesteps. Also note the stochasticity--on the first ... | Python Code:
from frozen_lake import FrozenLakeEnv
env = FrozenLakeEnv()
print(env.__doc__)
Explanation: Assignment 2: Markov Decision Processes
Homework Instructions
All your answers should be written in this notebook. You shouldn't need to write or modify any other files.
Look for four instances of "YOUR CODE HERE"-... |
3,837 | 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, notebook style sheet by L.A. Barba, N.C. Clementi
Step1: 2D SH finite diffe... | 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, noteb... |
3,838 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Language Translation
In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset o... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
import problem_unittests as tests
source_path = 'data/small_vocab_en'
target_path = 'data/small_vocab_fr'
source_text = helper.load_data(source_path)
target_text = helper.load_data(target_path)
Explanation: Language Translation
In this project, you’re going ... |
3,839 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Inferring species trees with tetrad
When you install ipyrad a number of analysis tools are installed as well. This includes the program tetrad, which applies the theory of phylogenetic invar... | Python Code:
## conda install ipyrad -c ipyrad
## conda install toytree -c eaton-lab
import ipyrad.analysis as ipa
import ipyparallel as ipp
import toytree
Explanation: Inferring species trees with tetrad
When you install ipyrad a number of analysis tools are installed as well. This includes the program tetrad, which a... |
3,840 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Welcome to the Development Version of BASS
This notebook is inteded for very advanced users, as there is almost no interactivity features. However, this notebook is all about speed. If you k... | Python Code:
from bass import *
Explanation: Welcome to the Development Version of BASS
This notebook is inteded for very advanced users, as there is almost no interactivity features. However, this notebook is all about speed. If you know exactly what you are doing, then this is the notebook for you.
BASS: Biomedical A... |
3,841 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Support Vector Machines
Step1: Kernel SVMs
Predictions in a kernel-SVM are made using the formular
$$
\hat{y} = \alpha_0 + \alpha_1 y_1 k(\mathbf{x^{(1)}}, \mathbf{x}) + ... + \alpha_n y_n ... | Python Code:
from sklearn.datasets import load_digits
from sklearn.cross_validation import train_test_split
digits = load_digits()
X_train, X_test, y_train, y_test = train_test_split(digits.data / 16., digits.target % 2, random_state=2)
from sklearn.svm import LinearSVC, SVC
linear_svc = LinearSVC(loss="hinge").fit(X_t... |
3,842 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="images/csdms_logo.jpg">
Flexural Subsidence
Link to this notebook
Step1: Import the Subside class, and instantiate it. In Python, a model with a BMI will have no arguments for its... | Python Code:
from __future__ import print_function
%matplotlib inline
import matplotlib.pyplot as plt
Explanation: <img src="images/csdms_logo.jpg">
Flexural Subsidence
Link to this notebook: https://github.com/csdms/pymt/blob/master/docs/demos/subside.ipynb
Install command: $ conda install notebook pymt_sedflux
This e... |
3,843 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="../../../images/qiskit-heading.gif" alt="Note
Step1: Theoretical background
In addition to the GHZ states, the generalized W states, as proposed by Dür, Vidal and Cirac, in 2000, ... | Python Code:
# useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import time
from pprint import pprint
# importing Qiskit
from qiskit import Aer, IBMQ
from qiskit.backends.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execut... |
3,844 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Table of Contents
<p><div class="lev1 toc-item"><a href="#In-Built-Functions" data-toc-modified-id="In-Built-Functions-1"><span class="toc-item-num">1 </span>In-Built Functions</a... | Python Code:
# Some functions already covered
nums = [num**2 for num in range(1,11)]
print(nums) #print is a function, atleast Python 3.x onwards
# In Python 2.x - Not a function, it's a statement.
# Will give an error in Python 3.x
print nums
len(nums)
max(nums)
min(nums)
sum(nums)
nums.reverse()
nums
# Reverse a str... |
3,845 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lists
<img src="../images/python-logo.png">
Lists are sequences that hold heterogenous data types that are separated by commas between two square brackets. Lists have zero-based indexing, wh... | Python Code:
# import thr random numbers module. More on modules in a future notebook
import random
Explanation: Lists
<img src="../images/python-logo.png">
Lists are sequences that hold heterogenous data types that are separated by commas between two square brackets. Lists have zero-based indexing, which means that th... |
3,846 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
BPSK Demodulation in Nonlinear Channels with Deep Neural Networks
This code is provided as supplementary material of the lecture Machine Learning and Optimization in Communications (MLOC).<b... | Python Code:
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import matplotlib.pyplot as plt
from ipywidgets import interactive
import ipywidgets as widgets
%matplotlib inline
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print("We are using the following device for learning... |
3,847 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Jeopardy Questions
Jeopardy is a popular TV show in the US where participants answer questions to win money. It's been running for a few decades, and is a major force in popular culture.
Let... | Python Code:
import pandas as pd
# Read the dataset into a Pandas DataFrame
jeopardy = pd.read_csv('../data/jeopardy.csv')
# Print out the first 5 rows
jeopardy.head(5)
# Print out the columns
jeopardy.columns
# Remove the spaces from column names
col_names = jeopardy.columns
col_names = [s.strip() for s in col_names]
... |
3,848 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CSAL4243
Step1: <br>
Task 1
Step4: Linear Regression with Gradient Descent code
Step5: Run Gradient Descent on training data
Step6: Plot trained line on data
Step7: <br>
Task 2
Step8: ... | Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
import seaborn as sns
from sklearn import linear_model
import matplotlib.pyplot as plt
import matplotlib as mpl
# read house_train.csv data in pandas dataframe df_train using pandas read_csv function
df_train = pd.read_csv('datasets/house_price/trai... |
3,849 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
NATURAL LANGUAGE PROCESSING APPLICATIONS
In this notebook we will take a look at some indicative applications of natural language processing. We will cover content from nlp.py and text.py, f... | Python Code:
from utils import open_data
from text import *
flatland = open_data("EN-text/flatland.txt").read()
wordseq = words(flatland)
P_flatland = NgramCharModel(2, wordseq)
faust = open_data("GE-text/faust.txt").read()
wordseq = words(faust)
P_faust = NgramCharModel(2, wordseq)
Explanation: NATURAL LANGUAGE PROCES... |
3,850 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
載入 Word2Vec Embeddings
Step1: 資料前處理
Step2: 設計 Graph
Step3: Build Category2Vec
參考論文
Step4: 測試 Category Vec
Step5: 開始轉換成向量
Step6: Load TagVectors
Step7: 進行隨機抽樣驗證 | Python Code:
class PixWord2Vec:
# vocabulary indexing
index2word = None
word2indx = None
# embeddings vector
embeddings = None
# Normailized embeddings vector
final_embeddings = None
# hidden layer's weight and bias
softmax_weights = None
softmax_biases = None
... |
3,851 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Load up the DECALS info tables
Step1: Alright, now lets just pick a few specific bricks that are both in SDSS and have fairly deep g and r data
Step2: And the joint distribution?
Step3: L... | Python Code:
bricks = Table.read('decals_dr3/survey-bricks.fits.gz')
bricksdr3 = Table.read('decals_dr3/survey-bricks-dr3.fits.gz')
fn_in_sdss = 'decals_dr3/in_sdss.npy'
try:
bricksdr3['in_sdss'] = np.load(fn_in_sdss)
except:
bricksdr3['in_sdss'] = ['unknown']*len(bricksdr3)
bricksdr3
goodbricks = (bricksdr3['i... |
3,852 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example of reproducing HHT analysis results in Su et al. 2015
Su et al. 2015
Step1: Running EEMD of the QPO signal and checking the orthogonality of the IMF components
Step2: Reproducing F... | Python Code:
from astropy.io import ascii
data = ascii.read('./XTE_J1550_564_30191011500A_2_13kev_001s_0_2505s.txt')
time = data['col1']
rate = data['col2']
dt = time[1] - time[0]
Explanation: Example of reproducing HHT analysis results in Su et al. 2015
Su et al. 2015: "Characterizing Intermittency of 4-Hz Quasi-perio... |
3,853 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pandas querying and metadata with Epochs objects
Demonstrating pandas-style string querying with Epochs metadata.
For related uses of
Step1: We can use this metadata attribute to select su... | Python Code:
# Authors: Chris Holdgraf <choldgraf@gmail.com>
# Jona Sassenhagen <jona.sassenhagen@gmail.com>
# Eric Larson <larson.eric.d@gmail.com>
# License: BSD (3-clause)
import mne
import numpy as np
import matplotlib.pyplot as plt
# Load the data from the internet
path = mne.datasets.kiloword.da... |
3,854 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow IO Authors.
Step1: TensorFlow IO에서 PostgreSQL 데이터베이스 읽기
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https
Step2: PostgreS... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# dist... |
3,855 | 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 ... |
3,856 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Choropleth from the Brazil's northeast
<hr>
<div style="text-align
Step1: Data
Step2: We found some misinformation about the na me of the municipalities regarding to IBGE information and t... | Python Code:
#System libraries
import os
import sys
#Basic libraries for data analysis
import numpy as np
from numpy import random
import pandas as pd
#Choropleth necessary libraries
##GeoJson data
import json
##Necessary to create shapes in folium
from shapely.geometry import Polygon
from shapely.geometry import Point... |
3,857 | 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... |
3,858 | 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', 'csir-csiro', 'sandbox-1', 'ocnbgchem')
Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem
MIP Era: CMIP6
Institute: CSIR-CSIRO
Source ID: SANDBOX-1
Topic: Ocnbgchem
Sub-Topics: Tr... |
3,859 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
EventVestor
Step1: Let's go over the columns
Step2: We've done much of the data processing for you. Fields like timestamp and sid are standardized across all our Store Datasets, so the dat... | Python Code:
# import the dataset
# from quantopian.interactive.data.eventvestor import dividends as dataset
# or if you want to import the free dataset, use:
from quantopian.interactive.data.eventvestor import dividends_free as dataset
# import data operations
from odo import odo
# import other libraries we will use
... |
3,860 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
리스트 조건제시법(List Comprehension)
주요 내용
주어진 리스트를 이용하여 특정 성질을 만족하는 새로운 리스트를 생성하고자 할 때
리스트 조건제시법을 활용하면 매우 효율적인 코딩을 할 수 있다.
리스트 조건제시법은 집합을 정의할 때 사용하는 조건제시법과 매우 유사하다.
예를 들어,0부터 1억 사이에 있는 홀수들을 원소로 ... | Python Code:
odd_20 = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
Explanation: 리스트 조건제시법(List Comprehension)
주요 내용
주어진 리스트를 이용하여 특정 성질을 만족하는 새로운 리스트를 생성하고자 할 때
리스트 조건제시법을 활용하면 매우 효율적인 코딩을 할 수 있다.
리스트 조건제시법은 집합을 정의할 때 사용하는 조건제시법과 매우 유사하다.
예를 들어,0부터 1억 사이에 있는 홀수들을 원소로 갖는 집합을 정의하려면
두 가지 방법을 활용할 수 있다.
원소나열법
{1, 3, 5, 7, 9, 11,... |
3,861 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Executed
Step1: Load software and filenames definitions
Step2: Data folder
Step3: List of data files
Step4: Data load
Initial loading of the data
Step5: Laser alternation selection
At t... | Python Code:
ph_sel_name = "None"
data_id = "17d"
# data_id = "7d"
Explanation: Executed: Mon Mar 27 11:36:36 2017
Duration: 9 seconds.
usALEX-5samples - Template
This notebook is executed through 8-spots paper analysis.
For a direct execution, uncomment the cell below.
End of explanation
from fretbursts import *
init_... |
3,862 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Вопросы по прошлому занятию
* Почему файлы лучше всего открывать через with?
* Зачем нужен Git?
* Как переместить файл из папки "/some/folder" в папку "/another/dir"?
* Зачем нужен subproces... | Python Code:
from collections import Counter
def checkio(arr):
counts = Counter(arr)
return [
w for w in arr if counts[w] > 1
]
Explanation: Вопросы по прошлому занятию
* Почему файлы лучше всего открывать через with?
* Зачем нужен Git?
* Как переместить файл из папки "/some/folder" в папку "/anothe... |
3,863 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TensorFlow Tutorial #01
Simple Linear Model
by Magnus Erik Hvass Pedersen
/ GitHub / Videos on YouTube
Introduction
This tutorial demonstrates the basic workflow of using TensorFlow with a s... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
from sklearn.metrics import confusion_matrix
Explanation: TensorFlow Tutorial #01
Simple Linear Model
by Magnus Erik Hvass Pedersen
/ GitHub / Videos on YouTube
Introduction
This tutorial demonstrates the basic wo... |
3,864 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Linear Magnetic Inversion
Objective
Step1: Now that we have all our spatial components, we can create our linear system. For a single location and single component of the data, the system w... | Python Code:
from SimPEG import Mesh
from SimPEG.Utils import mkvc, surface2ind_topo
from SimPEG import Maps
from SimPEG import Regularization
from SimPEG import DataMisfit
from SimPEG import Optimization
from SimPEG import InvProblem
from SimPEG import Directives
from SimPEG import Inversion
from SimPEG import PF
impo... |
3,865 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step15: Table of Contents
<p><div class="lev1"><a href="#Bayesian-Networks-Essays"><span class="toc-item-num">1 </span>Bayesian Networks Essays</a></div><div class="lev2"><a href=... | Python Code:
from IPython.display import HTML, display
from nxpd import draw
from functools import wraps
from itertools import permutations
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
import re
%matplotlib inline
Σ = sum
def auto_display(f):
@wraps(f)
def _f(self, *args, **kwargs):
... |
3,866 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Db2 OData Tutorial
This tutorial will explain some of the features that are available in the IBM Data Server Gateway for OData Version 1.0.0. IBM Data Server Gateway for OData enables you to... | Python Code:
%run db2odata.ipynb
Explanation: Db2 OData Tutorial
This tutorial will explain some of the features that are available in the IBM Data Server Gateway for OData Version 1.0.0. IBM Data Server Gateway for OData enables you to quickly create OData RESTful services to query and update data in IBM Db2 LUW.
... |
3,867 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Download the list of occultation periods from the MOC at Berkeley.
Note that the occultation periods typically only are stored at Berkeley for the future and not for the past. So this is onl... | Python Code:
fname = io.download_occultation_times(outdir='../data/')
print(fname)
Explanation: Download the list of occultation periods from the MOC at Berkeley.
Note that the occultation periods typically only are stored at Berkeley for the future and not for the past. So this is only really useful for observation pl... |
3,868 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example 1
Step1: Import the Servo class. It is needed for creating the Servo objects
Step2: Import the IPython 3 interact function. It is needed for creating the Interactive slider that mo... | Python Code:
from serial import Serial
Explanation: Example 1: Moving one servo connected to the zum bt-328 board
Introduction
This example shows how to move one servo using the interactive IPython 3.0 widgets from Jupyter (known before as ipython notebooks). This notebook is only a "hello world" example, but it opens ... |
3,869 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2021 The TensorFlow Authors.
Step1: <table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step3: Preparing data and model
The EMNIST data pr... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# dist... |
3,870 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Home Assignment No. 3
Step1: <br>
Bayesian Models. GLM
Task 1 (1 pt.)
Consider a univariate Gaussian distribution $\mathcal{N}(x; \mu, \tau^{-1})$.
Let's define Gaussian-Gamma prior for par... | Python Code:
import numpy as np
import pandas as pd
import torch
%matplotlib inline
import matplotlib.pyplot as plt
Explanation: Home Assignment No. 3: Part 1
In this part of the homework you are to solve several problems related to machine learning algorithms.
* For every separate problem you can get only 0 points or ... |
3,871 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
train_iris.py コードの補足説明
はじめに
train_iris.py をそのまま動かす際には scikitlearn が必要となるので、
shell
pip install scikit-learn
conda install scikit-learn
のどちらかを実行してほしい。
Step1: cupy フラグのたて方
CUDA が使えるならば、データセットを... | Python Code:
from chainer import cuda
import numpy as np
from sklearn import datasets
from sklearn.model_selection import train_test_split
import pandas as pd
Explanation: train_iris.py コードの補足説明
はじめに
train_iris.py をそのまま動かす際には scikitlearn が必要となるので、
shell
pip install scikit-learn
conda install scikit-learn
のどちらかを実行してほしい。... |
3,872 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
107
Step1: The swissmetro dataset used in this example is conveniently bundled with Larch,
accessible using the data_warehouse module. We'll load this file using
the pandas read_csv comma... | Python Code:
import larch
import pandas as pd
from larch.roles import P,X
Explanation: 107: Latent Class Models
In this example, we will replicate the latent class example model
from Biogeme.
End of explanation
from larch import data_warehouse
raw = pd.read_csv(larch.data_warehouse.example_file('swissmetro.csv.gz'))
Ex... |
3,873 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
データの取得方法
ここではQuandl.comからのデータを受け取っています。今回入手した日経平均株価は、
時間、開始値、最高値、最低値、終値のデータを入手していますが、古いデータは終値しかないようですので、終値を用います。
*** TODO いつからデータを入手することが最も効果的かを考える。(処理時間と制度に影響が出るため)
Step1: 抜けデータが目立ったため、週単位... | Python Code:
import quandl
data = quandl.get('NIKKEI/INDEX')
data[:5]
data_normal = (((data['Close Price']).to_frame())[-10000:-1])['Close Price']
data_normal[-10:-1] # 最新のデータ10件を表示
Explanation: データの取得方法
ここではQuandl.comからのデータを受け取っています。今回入手した日経平均株価は、
時間、開始値、最高値、最低値、終値のデータを入手していますが、古いデータは終値しかないようですので、終値を用います。
*** TODO いつか... |
3,874 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This is used to profile https
Step1: With View options set to
Step2: | Python Code:
!pip install pyprof2calltree
!brew install qcachegrind
%%writefile test_41.py
from galgebra.ga import Ga
GA = Ga('e*1|2|3')
a = GA.mv('a', 'vector')
b = GA.mv('b', 'vector')
c = GA.mv('c', 'vector')
def cross(x, y):
return (x ^ y).dual()
xx = cross(a, cross(b, c))
!python -m cProfile -o test_41.cprof t... |
3,875 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Numpy, sebagai salah satu library yang saling penting di pemrograman yang menggunakan matematika dan angka, memberikan kemudahan dalam melakukan operasi aljabar matriks. Bila deklarasi array... | Python Code:
import numpy as np
Explanation: Numpy, sebagai salah satu library yang saling penting di pemrograman yang menggunakan matematika dan angka, memberikan kemudahan dalam melakukan operasi aljabar matriks. Bila deklarasi array a = [[1,0],[0,1]] memberikan array 2D biasa, maka dengan Numpy, a = np.array([[1,0],... |
3,876 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Importing our wordlists
Here we import all of our wordlists and add them to an array which me can merge at the end.
This wordlists should not be filtered at this point. However they should ... | Python Code:
wordlists = []
Explanation: Importing our wordlists
Here we import all of our wordlists and add them to an array which me can merge at the end.
This wordlists should not be filtered at this point. However they should all contain the same columns to make merging easier for later.
End of explanation
!head -... |
3,877 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Outline
Collect some tweets
Annotate the tweets
Calculate the accuracy
Step1: Collect some data
Step2: Annotate the data
Start by tokenizing
Step3: Now tag the tokens with parts-of-speec... | Python Code:
from pprint import pprint
Explanation: Outline
Collect some tweets
Annotate the tweets
Calculate the accuracy
End of explanation
# we'll use data from a job that collected tweets about parenting
tweet_bodies = [body for body in open('tweet_bodies.txt')]
# sanity checks
pprint(len(tweet_bodies))
# sanity c... |
3,878 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
I'm looking into doing a delta_sigma emulator. This is testing if the cat side works. Then i'll make an emulator for it.
Step1: Load up a snapshot at a redshift near the center of this bin.... | Python Code:
from pearce.mocks import cat_dict
import numpy as np
from os import path
from astropy.io import fits
import matplotlib
#matplotlib.use('Agg')
from matplotlib import pyplot as plt
%matplotlib inline
import seaborn as sns
sns.set()
z_bins = np.array([0.15, 0.3, 0.45, 0.6, 0.75, 0.9])
zbin=1
a = 0.81120
z = 1... |
3,879 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial 03
Step1: Accordingly, to use the ring road scenario for this tutorial, we specify its (string) names as follows
Step2: Another difference between SUMO and RLlib experiments is th... | Python Code:
import flow.scenarios as scenarios
print(scenarios.__all__)
Explanation: Tutorial 03: Running RLlib Experiments
This tutorial walks you through the process of running traffic simulations in Flow with trainable RLlib-powered agents. Autonomous agents will learn to maximize a certain reward over the rollouts... |
3,880 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Saving and Reloading Simulations
Here we show how to save a binary field with all the parameters for particles and the simulation's REBOUNDx effects. We begin with a one planet system subjec... | Python Code:
import rebound
import numpy as np
sim = rebound.Simulation()
sim.add(m=1., hash="star") # Sun
sim.add(m=1.66013e-07,a=0.387098,e=0.205630, hash="planet") # Mercury-like
sim.move_to_com() # Moves to the center of momentum frame
ps = sim.particles
print("t = {0}, pomega = {1}".format(sim.t, sim.particles[1].... |
3,881 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python Function Quick Reference
Table of contents
<a href="#1.-Declaring-Functions">Declaring Functions</a>
<a href="#2.-Return-Values">Return Values</a>
<a href="#3.-Parameters">Parameters<... | Python Code:
def print_text():
print('this is text')
# call the function
print_text()
Explanation: Python Function Quick Reference
Table of contents
<a href="#1.-Declaring-Functions">Declaring Functions</a>
<a href="#2.-Return-Values">Return Values</a>
<a href="#3.-Parameters">Parameters</a>
<a href="#4.-DocStrings... |
3,882 | 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 ... |
3,883 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Notebook is a revised version of notebook from Amy Wu and Shen Zhimo
E2E ML on GCP
Step1: Restart the kernel
After you install the additional packages, you need to restart the notebook kern... | Python Code:
import os
# The Vertex AI Workbench Notebook product has specific requirements
IS_WORKBENCH_NOTEBOOK = os.getenv("DL_ANACONDA_HOME")
IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists(
"/opt/deeplearning/metadata/env_version"
)
# Vertex AI Notebook requires dependencies to be installed with '--user'
U... |
3,884 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<center> Using DEAP to do multiobjective optimization with NSGA2</center>
<center>Yannis Merlet, sept 2018</center>
1st release of this notebook, still in progress though. If you have any su... | Python Code:
import random
import datetime
import multiprocessing
import numpy as np
from deap import base
from deap import creator
from deap import tools
### If your evaluation function is external...
# import YourEvaluationFunction as evaluation
Explanation: <center> Using DEAP to do multiobjective optimization with ... |
3,885 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
follow-trend
1. S&P 500 index closes above its 200 day moving average
2. The stock closes above its upper band, buy
1. S&P 500 index closes below its 200 day moving average
2. The st... | Python Code:
import datetime
import matplotlib.pyplot as plt
import pandas as pd
import pinkfish as pf
import strategy
# Format price data
pd.options.display.float_format = '{:0.2f}'.format
%matplotlib inline
# Set size of inline plots
'''note: rcParams can't be in same cell as import matplotlib
or %matplotlib inlin... |
3,886 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Spectrometer accuracy assesment using validation tarps
Background
In this lesson we will be examing the accuracy of the Neon Imaging Spectrometer (NIS) against targets with known reflectance... | Python Code:
import h5py
import csv
import numpy as np
import os
import gdal
import matplotlib.pyplot as plt
import sys
from math import floor
import time
import warnings
warnings.filterwarnings('ignore')
%matplotlib inline
Explanation: Spectrometer accuracy assesment using validation tarps
Background
In this lesson we... |
3,887 | 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', 'cmcc', 'cmcc-cm2-hr4', 'atmos')
Explanation: ES-DOC CMIP6 Model Properties - Atmos
MIP Era: CMIP6
Institute: CMCC
Source ID: CMCC-CM2-HR4
Topic: Atmos
Sub-Topics: Dynamical Core, Radi... |
3,888 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
APScheduler and PyMongo
The following is a simple example using APScheduler and PyMongo to pull down the price of bitcoin every minute using the <a href="http
Step1: First we created a func... | Python Code:
from pymongo import MongoClient
client = MongoClient()
bitcoin = client.test_database.bitcoin
import urllib2
import requests
response = requests.get("http://api.coindesk.com/v1/bpi/currentprice.json")
bitcoin_response = response.json()
print bitcoin_response['bpi']['EUR']['rate_float']
Explanation: APSched... |
3,889 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Enter State Farm
Step1: Setup batches
Step2: Rather than using batches, we could just import all the data into an array to save some processing time. (In most examples I'm using the batche... | Python Code:
from __future__ import division, print_function
%matplotlib inline
#path = "data/state/"
path = "data/state/sample/"
from importlib import reload # Python 3
import utils; reload(utils)
from utils import *
from IPython.display import FileLink
batch_size=64
Explanation: Enter State Farm
End of explanation
b... |
3,890 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Neutron Diffusion Equation Criticality Eigenvalue Calculation
Description
Step1: Material Properties
Step2: Slab Geometry Width and Discretization
Step3: Generation of Leakage and Absorpt... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
Explanation: Neutron Diffusion Equation Criticality Eigenvalue Calculation
Description: Solves neutron diffusion equation (NDE) in slab geometry. Finds width of critical slab using one-speed diffusion theory with zero flux boundary condi... |
3,891 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I'm looking for a fast solution to MATLAB's accumarray in numpy. The accumarray accumulates the elements of an array which belong to the same index. An example: | Problem:
import numpy as np
a = np.arange(1,11)
accmap = np.array([0,1,0,0,0,1,1,2,2,1])
result = np.bincount(accmap, weights = a) |
3,892 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Problems on Arrays and Strings
P1. Is Unique
Step1: P2. Check Permutation
Step2: P3. URLify
Step3: P4. Palindrome Permutation
Step4: P5. One Away
Step5: P6. String Compression
Step6: P... | Python Code:
# With Hashmap.
# Time Complexity: O(n)
def if_unique(string):
chr_dict = {}
for char in string:
if char not in chr_dict:
chr_dict[char] = 1
else:
return False
return True
# Without additional memory.
# Time Complexity: O(n^2)
def if_unique_m(string)... |
3,893 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Latent Function Inference with Pyro + GPyTorch (Low-Level Interface)
Overview
In this example, we will give an overview of the low-level Pyro-GPyTorch integration.
The low-level interface ma... | Python Code:
import math
import torch
import pyro
import tqdm
import gpytorch
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline
Explanation: Latent Function Inference with Pyro + GPyTorch (Low-Level Interface)
Overview
In this example, we will give an overview of the low-level Pyro-GPyTorch int... |
3,894 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<p><font size="6"><b>Jupyter notebook INTRODUCTION </b></font></p>
Introduction to GIS scripting
May, 2017
© 2017, Stijn Van Hoey (stijnvanho... | Python Code:
from IPython.display import Image
Image(url='http://python.org/images/python-logo.gif')
Explanation: <p><font size="6"><b>Jupyter notebook INTRODUCTION </b></font></p>
Introduction to GIS scripting
May, 2017
© 2017, Stijn Van Hoey (stijnvanhoey@... |
3,895 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Backpropagation in Multilayer Neural Networks
Goals
Step1: Preprocessing
Normalization
Train / test split
Step2: Numpy Implementation
a) Logistic Regression
In this section we will impleme... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import load_digits
digits = load_digits()
sample_index = 45
plt.figure(figsize=(3, 3))
plt.imshow(digits.images[sample_index], cmap=plt.cm.gray_r,
interpolation='nearest')
plt.title("image label: %d" % di... |
3,896 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Kalman Filter
Kalman filters are linear models for state estimation of dynamic systems [1]. They have been the <i>de facto</i> standard in many robotics and tracking/prediction applications... | Python Code:
import os
import math
import torch
import pyro
import pyro.distributions as dist
from pyro.infer.autoguide import AutoDelta
from pyro.optim import Adam
from pyro.infer import SVI, Trace_ELBO, config_enumerate
from pyro.contrib.tracking.extended_kalman_filter import EKFState
from pyro.contrib.tracking.distr... |
3,897 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Instanciando Componente de Publicação de Mensagens no MQTT
Step1: Componente para simulação de um sensor
bash
IoT_sensor(<name/id>, <grandeza física >, <unidade de medida>... | Python Code:
publisher = IoT_mqtt_publisher("localhost", 1883)
Explanation: Instanciando Componente de Publicação de Mensagens no MQTT
End of explanation
sensor_1 = IoT_sensor("1", "temperature", "°C", 20, 26, 2)
sensor_2 = IoT_sensor("2", "umidade", "%", 50, 60, 3)
sensor_3 = IoT_sensor("3", "temperature", "°C", ... |
3,898 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 13
Modeling and Simulation in Python
Copyright 2021 Allen Downey
License
Step4: Code from previous chapters
make_system, plot_results, and calc_total_infected are unchanged.
Step5: ... | Python Code:
# install Pint if necessary
try:
import pint
except ImportError:
!pip install pint
# download modsim.py if necessary
from os.path import exists
filename = 'modsim.py'
if not exists(filename):
from urllib.request import urlretrieve
url = 'https://raw.githubusercontent.com/AllenDowney/ModSim/... |
3,899 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
利用神经网络的 Kera 预测学生录取情况
在该 notebook 中,我们基于以下三条数据预测了加州大学洛杉矶分校的研究生录取情况:
GRE 分数(测试)即 GRE Scores (Test)
GPA 分数(成绩)即 GPA Scores (Grades)
评级(1-4)即 Class rank (1-4)
数据集来源:http
Step1: <div>
<table bo... | Python Code:
# Importing pandas and numpy
import pandas as pd
import numpy as np
# Reading the csv file into a pandas DataFrame
data = pd.read_csv('student_data.csv')
# Printing out the first 10 rows of our data
data[:10]
Explanation: 利用神经网络的 Kera 预测学生录取情况
在该 notebook 中,我们基于以下三条数据预测了加州大学洛杉矶分校的研究生录取情况:
GRE 分数(测试)即 GRE S... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.