Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
1,600 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sequence classification with LSTM
Step1: We will treat the MNIST image $\in \mathcal{R}^{28 \times 28}$ as $28$ sequences of a vector $\mathbf{x} \in \mathcal{R}^{28}$.
Our simple RNN consi... | Python Code:
import tensorflow as tf
import tensorflow.examples.tutorials.mnist.input_data as input_data
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
print ("Packages imported")
mnist = input_data.read_data_sets("data/", one_hot=True)
trainimgs, trainlabels, testimgs, testlabels \
= mnist.tra... |
1,601 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Logistic Regression
Step1: We need to define the sigmoid function $S(t)
Step2: As we are using NumPy to compute $\exp(t)$, we can feed this function with a numpy array to compute the sigm... | Python Code:
import numpy as np
Explanation: Logistic Regression
End of explanation
def sigmoid(t):
return 1.0 / (1.0 + np.exp(-t))
Explanation: We need to define the sigmoid function $S(t) := \large \frac{1}{1 + \exp(-t)}$.
End of explanation
sigmoid(np.array([-1.0, 0.0, 1.0]))
Explanation: As we are using NumPy t... |
1,602 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Solving problems by Searching
This notebook serves as supporting material for topics covered in Chapter 3 - Solving Problems by Searching and Chapter 4 - Beyond Classical Search from the boo... | Python Code:
from search import *
Explanation: Solving problems by Searching
This notebook serves as supporting material for topics covered in Chapter 3 - Solving Problems by Searching and Chapter 4 - Beyond Classical Search from the book Artificial Intelligence: A Modern Approach. This notebook uses implementations fr... |
1,603 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2.1 - 2.2 Migration
Step1: By default, ld_func is set to 'interp'. This will interpolate the limb-darkening directly, without requiring a specific law/function.
Note, however, that the bol... | Python Code:
import phoebe
b = phoebe.default_binary()
b.add_dataset('lc', dataset='lc01')
print(b.filter(qualifier='ld*', dataset='lc01'))
Explanation: 2.1 - 2.2 Migration: ld_coeffs_source
PHOEBE 2.2 introduces the capability to interpolate limb-darkening coefficients for a given ld_func (i.e. linear, quadratic, etc)... |
1,604 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Classify text with BERT
Learning Objectives
Learn how to load a pre-trained BERT model from TensorFlow Hub
Learn how to build your own model by combining with a classifier
Learn how to train... | Python Code:
# A dependency of the preprocessing for BERT inputs
!pip install -q --user tensorflow-text
Explanation: Classify text with BERT
Learning Objectives
Learn how to load a pre-trained BERT model from TensorFlow Hub
Learn how to build your own model by combining with a classifier
Learn how to train a your BERT ... |
1,605 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
LAB 3c
Step1: Verify tables exist
Run the following cells to verify that we have previously created the dataset and data tables. If not, go back to lab 1b_prepare_data_babyweight to create ... | Python Code:
%%bash
sudo pip freeze | grep google-cloud-bigquery==1.6.1 || \
sudo pip install google-cloud-bigquery==1.6.1
Explanation: LAB 3c: BigQuery ML Model Deep Neural Network.
Learning Objectives
Create and evaluate DNN model with BigQuery ML
Create and evaluate DNN model with feature engineering with ML.TRANSF... |
1,606 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DEMO - Dowload Satellite-Temperature, use it to force model
This demo requires that you download, from Brightspace, the following files and place them in your working directory
Step1: The O... | Python Code:
import model_Mussel_IbarraEtal2014 as MusselModel
days, dt, par, InitCond = MusselModel.load_defaults()
output = MusselModel.run_model(days,dt,InitCond,par)
MusselModel.plot_model(output)
Explanation: DEMO - Dowload Satellite-Temperature, use it to force model
This demo requires that you download, from Bri... |
1,607 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Nathan Yee
Computation Bayesian Statistics
Report01
License
Step1: Twin brothers and bayes theorem
Suppose we are asked the question
Step2: So, we can conclude that Elvis had a 14.8% chanc... | Python Code:
from thinkbayes2 import Pmf, Suite
import thinkplot
import math
% matplotlib inline
Explanation: Nathan Yee
Computation Bayesian Statistics
Report01
License: Attribution 4.0 International (CC BY 4.0)
End of explanation
# calculate number of male-male dizygotic twins using the percentage of dizygotic and pe... |
1,608 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<p>
<img src="http
Step1: A generalization using accumulation
Step2: According to A162741, we can generalize the pattern above
Step3: Unfolding a recurrence with generic coefficients
Step... | Python Code:
%run "recurrences.py"
%run "sums.py"
%run "start_session.py"
from itertools import accumulate
def accumulating(acc, current): return Eq(acc.lhs + current.lhs, acc.rhs + current.rhs)
Explanation: <p>
<img src="http://www.cerm.unifi.it/chianti/images/logo%20unifi_positivo.jpg"
alt="UniFI logo" style... |
1,609 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Make Template + Supernova
Test insertion of SNe in desisim.templates.GALAXY.
For now it will fail because metadata needed by the GALAXY is missing.
Step1: Generate BGS Galaxy
Just generate ... | Python Code:
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from desisim.templates import BGS
mpl.rc('font', size=14)
Explanation: Make Template + Supernova
Test insertion of SNe in desisim.templates.GALAXY.
For now it will fail because metadata needed by the GALAXY is missing.
End of expla... |
1,610 | Given the following text description, write Python code to implement the functionality described.
Description:
Detect cycle in Directed Graph using Topological Sort
Python3 program to implement the above approach ; Stack to store the visited vertices in the Topological Sort ; Store Topological Order ; Adjacency list to... | Python Code:
t = 0
n = 0
m = 0
a = 0
s =[]
tsort =[]
adj =[[ ] for i in range(100001 ) ]
visited =[False for i in range(100001 ) ]
def dfs(u ) :
visited[u ] = 1
for it in adj[u ] :
if(visited[it ] == 0 ) :
dfs(it )
s . append(u )
def check_cycle() :
pos = dict()
ind = 0
while... |
1,611 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
NbConvert
Command line usage
NbConvert is both a library and command line tool that allows you to convert notebooks to other formats. It ships with many common formats
Step1: Html is the (... | Python Code:
%%bash
ipython nbconvert 'Index.ipynb'
Explanation: NbConvert
Command line usage
NbConvert is both a library and command line tool that allows you to convert notebooks to other formats. It ships with many common formats: html, latex, markdown, python, rst, and slides
NbConvert relys on the Jinja templat... |
1,612 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fizz Buzz with Tensor Flow.
This notebook to explain the code from Fizz Buzz in Tensor Flow blog post written by Joel Grus
You should read his post first it is super funny!
His code try to... | Python Code:
import numpy as np
import tensorflow as tf
Explanation: Fizz Buzz with Tensor Flow.
This notebook to explain the code from Fizz Buzz in Tensor Flow blog post written by Joel Grus
You should read his post first it is super funny!
His code try to play the Fizz Buzz game by using machine learning.
This not... |
1,613 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Learn how to perform regression
We're going to train a neural network that knows how to perform inference in robust linear regression models.
The network will have as input
Step2: First ste... | Python Code:
import numpy as np
import torch
from torch.autograd import Variable
import sys, inspect
sys.path.insert(0, '..')
%matplotlib inline
import pymc
import matplotlib.pyplot as plt
from learn_smc_proposals import cde
from learn_smc_proposals.utils import systematic_resample
import seaborn as sns
sns.set_context... |
1,614 | 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... |
1,615 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Feature learning and write output
Step1: Classification
Step2: Sort results by accuracy of all features ('All' - Column 2)
Step3: Confusion matrix
According to results above, best classif... | Python Code:
print "mapping..."
data_list, pcadata_list, ldadata_list, nmfdata_list, ssnmfdata_list, classlabs, audiolabs = mapper.map_and_average_frames(min_variance=0.99)
mapper.write_output(data_list, pcadata_list, ldadata_list, nmfdata_list, ssnmfdata_list, classlabs, audiolabs)
Explanation: Feature learning and wr... |
1,616 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Stochastic depth
Dropout proved to be a working tool that improves the stability of a neural network. Essentially, dropout shuts down some neurons of a specific layer. Gao Huang, Yu Sun, Zhu... | Python Code:
import sys
import matplotlib.pyplot as plt
from tqdm import tqdm_notebook as tqn
%matplotlib inline
sys.path.append('../../..')
sys.path.append('../../utils')
import utils
from resnet_with_stochastic_depth import StochasticResNet
from batchflow import B,V,F
from batchflow.opensets import MNIST
from batchfl... |
1,617 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interferencia por haces múltiples. Filtros interferenciales.
El siguiente notebook explica la irradiancia obtenida en transmisión y reflexión cuando un haz incide en una lámina delgada plano... | Python Code:
from IPython.core.display import Image
Image("http://upload.wikimedia.org/wikipedia/commons/thumb/8/89/Multiple_beam_interference.png/580px-Multiple_beam_interference.png")
Explanation: Interferencia por haces múltiples. Filtros interferenciales.
El siguiente notebook explica la irradiancia obtenida en tra... |
1,618 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CPU Acceleration of Mandelbrot Generation
In this example we use numba to accelerate the generation of the Mandelbrot set.
The numba package allows us to compile python bytecode directly to ... | Python Code:
import numpy as np
import bokeh.plotting as bk
bk.output_notebook()
from numba import jit
from timeit import default_timer as timer
from IPython.html.widgets import interact, interact_manual, fixed, FloatText
Explanation: CPU Acceleration of Mandelbrot Generation
In this example we use numba to accelerate ... |
1,619 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Image Augmentation
Image Augmentation augments datasets (especially small datasets) to train model. The way to do image augmentation is to transform images by different ways. In this noteboo... | Python Code:
from zoo.common.nncontext import init_nncontext
from zoo.feature.image import *
import cv2
import numpy as np
from IPython.display import Image, display
sc = init_nncontext("Image Augmentation Example")
Explanation: Image Augmentation
Image Augmentation augments datasets (especially small datasets) to trai... |
1,620 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Land
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify do... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'niwa', 'sandbox-1', 'land')
Explanation: ES-DOC CMIP6 Model Properties - Land
MIP Era: CMIP6
Institute: NIWA
Source ID: SANDBOX-1
Topic: Land
Sub-Topics: Soil, Snow, Vegetation, Energ... |
1,621 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using critical sections
A critical section is a region of code that should not run in parallel. For example, the increment of a variable is not considered an atomic operation, so, it should ... | Python Code:
# Two threads that have a critical section executed in parallel without mutual exclusion.
# This code does not work!
import threading
import time
counter = 10
def task_1():
global counter
for i in range(10**6):
counter += 1
def task_2():
global counter
for i in range(10**6+... |
1,622 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Visualizing a Gensim model
To illustrate how to use pyLDAvis's gensim helper funtions we will create a model from the 20 Newsgroup corpus. Minimal preprocessing is done and so the model is n... | Python Code:
%%bash
mkdir -p data
pushd data
if [ -d "20news-bydate-train" ]
then
echo "The data has already been downloaded..."
else
wget http://qwone.com/%7Ejason/20Newsgroups/20news-bydate.tar.gz
tar xfv 20news-bydate.tar.gz
rm 20news-bydate.tar.gz
fi
echo "Lets take a look at the groups..."
ls 20news-bydate... |
1,623 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Key Requirements for the iRF scikit-learn implementation
The following is a documentation of the main requirements for the iRF implementation
Pseudocode iRF implementation
Inputs
Step1: Ste... | Python Code:
# Setup
%matplotlib inline
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.cross_validation import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import confusion_matrix
from sklearn.datasets import load_iris
from sklearn import... |
1,624 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src=images/continuum_analytics_b&w.png align="left" width="15%" style="margin-right
Step1: <hr/>
But as data grows and systems become more complex, moving data and querying data become... | Python Code:
import pandas as pd
df = pd.read_csv('data/iris.csv')
df.head()
df.groupby(df.Species).PetalLength.mean() # Average petal length per species
Explanation: <img src=images/continuum_analytics_b&w.png align="left" width="15%" style="margin-right:15%">
<h1 align='center'>Introduction to Blaze</h1>
In this tut... |
1,625 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Nonparametric estimatio of Doppler function
Step1: Doppler function
$$r\left(x\right)=\sqrt{x\left(1-x\right)}\sin\left(\frac{1.2\pi}{x+.05}\right),\quad x\in\left[0,1\right]$$
Step2: Deri... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import scipy.stats as ss
import sympy as sp
sns.set_context('notebook')
%matplotlib inline
Explanation: Nonparametric estimatio of Doppler function
End of explanation
x = np.linspace(.01, .99, num=1e3)
doppler = lambda x : np.sqrt(x *... |
1,626 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This demo shows how to use the Group Bayesian Representational Similarity Analysis (GBRSA) method in brainiak with a simulated dataset.
Note that although the name has "group", it is also su... | Python Code:
%matplotlib inline
import scipy.stats
import scipy.spatial.distance as spdist
import numpy as np
from brainiak.reprsimil.brsa import GBRSA
import brainiak.utils.utils as utils
import matplotlib.pyplot as plt
import matplotlib as mpl
import logging
np.random.seed(10)
import copy
Explanation: This demo shows... |
1,627 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Visualization 1
Step1: Scatter plots
Learn how to use Matplotlib's plt.scatter function to make a 2d scatter plot.
Generate random data using np.random.randn.
Style the markers (color, size... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
Explanation: Visualization 1: Matplotlib Basics Exercises
End of explanation
plt.scatter(np.random.randn(100), np.random.randn(100), c='g', s=50, marker='+', alpha=0.7)
plt.xlabel('Random x values')
plt.ylabel('Random y values')
plt.titl... |
1,628 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Speci... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'csiro-bom', 'sandbox-2', 'atmoschem')
Explanation: ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era: CMIP6
Institute: CSIRO-BOM
Source ID: SANDBOX-2
Topic: Atmoschem
Sub-Topics: Tran... |
1,629 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Spark Machine Learning Pipeline
This coursework is about implementing and applying Spark Machine Learning Pipelines, and evaluating them with respect to preprocessing, parametrisation, and s... | Python Code:
# import dependencies for creating a data frame
from pyspark.sql import SparkSession
from pyspark.sql import Row
from pyspark.sql.types import *
import csv
# Create SparkSession
spark = SparkSession.builder.getOrCreate()
# create RDD from csv files
trainRDD = spark.read.csv("hdfs://saltdean/data/data/san... |
1,630 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Access Ensembl BioMart using biomart module
We use rpy2 and R magics in IPython Notebook to utilize the powerful biomaRt package in R.
Usage
Step1: Tutorial
What marts are available?
Curren... | Python Code:
import pandas as pd
%load_ext rpy2.ipython
%%R
library(biomaRt)
%load_ext version_information
%version_information pandas, rpy2
Explanation: Access Ensembl BioMart using biomart module
We use rpy2 and R magics in IPython Notebook to utilize the powerful biomaRt package in R.
Usage:
Run Setup
Select a mart ... |
1,631 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
누적 분포 함수와 확률 밀도 함수
누적 분포 함수(cumulative distribution function)와 확률 밀도 함수(probabiligy density function)는 확률 변수의 분포 즉, 확률 분포를 수학적으로 정의하기 위한 수식이다.
확률 분포의 묘사
확률의 정의에서 확률은 사건(event)이라는 표본의 집합에 대해 ... | Python Code:
%%tikz
\filldraw [fill=white] (0,0) circle [radius=1cm];
\foreach \angle in {60,30,...,-270} {
\draw[line width=1pt] (\angle:0.9cm) -- (\angle:1cm);
}
\draw (0,0) -- (90:0.8cm);
Explanation: 누적 분포 함수와 확률 밀도 함수
누적 분포 함수(cumulative distribution function)와 확률 밀도 함수(probabiligy density function)는 확률 변수의 분포 즉... |
1,632 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Contextual Bandits (incomplete)
Step1: Query by Committee
Step2: Stochastic Gradient Descent
Step3: Random selection of data points at each iteration.
Step4: SVM with Random Sampling
Ste... | Python Code:
import numpy as np
import pandas as pd
import pickle
import seaborn as sns
from pandas import DataFrame, Index
from sklearn import metrics
from sklearn.linear_model import SGDClassifier
from sklearn.svm import SVC
from sklearn.kernel_approximation import RBFSampler, Nystroem
from sklearn.linear_model impor... |
1,633 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: Keras を使ったマルチワーカートレーニング
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https
Step2: TensorFlow をインポートする前に、環境... | 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... |
1,634 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Scheduler for quantum gates and instructions
Author
Step1: Gate schedule
Let's first define a quantum circuit
Step2: This is a rather boring circuit, but it is useful as a demonstration fo... | Python Code:
# imports
import qutip
from qutip_qip.circuit import QubitCircuit
from qutip_qip.compiler import Scheduler
from qutip_qip.compiler import Instruction
from qutip_qip.device import LinearSpinChain
Explanation: Scheduler for quantum gates and instructions
Author: Boxi Li (etamin1201@gmail.com)
The finite cohe... |
1,635 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Index - Back
Step1: Building a Custom Widget - Hello World
The widget framework is built on top of the Comm framework (short for communication). The Comm framework is a framework that allo... | Python Code:
from __future__ import print_function
Explanation: Index - Back
End of explanation
import ipywidgets as widgets
from traitlets import Unicode, validate
class HelloWidget(widgets.DOMWidget):
_view_name = Unicode('HelloView').tag(sync=True)
_view_module = Unicode('hello').tag(sync=True)
Explanation: ... |
1,636 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simulate binaural hearing when the stimulus is rotated around a ring of speakers.
Step1: First, some code to render a mouse's head and a ring of speakers
Step2: Virtual sources
Virtual sou... | Python Code:
#%%
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.collections import PatchCollection
Explanation: Simulate binaural hearing when the stimulus is rotated around a ring of speakers.
End of explanation
# MEASURE SOURCE ANGLE RELATIVE TO NOSE. POSITIVE... |
1,637 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have the tensors: | Problem:
import numpy as np
import pandas as pd
import torch
ids, x = load_data()
ids = torch.argmax(ids, 1, True)
idx = ids.repeat(1, 2).view(70, 1, 2)
result = torch.gather(x, 1, idx)
result = result.squeeze(1) |
1,638 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Spatial Weights
Spatial weights are mathematical structures used to represent spatial relationships. They characterize the relationship of each observation to every other observation using s... | Python Code:
import pysal as ps
import numpy as np
Explanation: Spatial Weights
Spatial weights are mathematical structures used to represent spatial relationships. They characterize the relationship of each observation to every other observation using some concept of proximity or closeness that depends on the weight t... |
1,639 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Poincare Map
This example shows how to calculate a simple Poincare Map with REBOUND. A Poincare Map (or sometimes calles Poincare Section) can be helpful to understand dynamical systems.
Ste... | Python Code:
import rebound
import numpy as np
Explanation: Poincare Map
This example shows how to calculate a simple Poincare Map with REBOUND. A Poincare Map (or sometimes calles Poincare Section) can be helpful to understand dynamical systems.
End of explanation
sim = rebound.Simulation()
sim.add(m=1.)
sim.add(m=1e-... |
1,640 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Authors.
Licensed under the Apache License, Version 2.0 (the "License").
Neural Machine Translation with Attention
<table class="tfo-notebook-buttons" align="le... | Python Code:
from __future__ import absolute_import, division, print_function
# Import TensorFlow >= 1.9 and enable eager execution
import tensorflow as tf
tf.enable_eager_execution()
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import unicodedata
import re
import numpy as np
imp... |
1,641 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introductory Notebook to mpnum
mpnum implements matrix product arrays (MPA), which are efficient parameterizations of certain multi-partite arrays. Special cases of the MPA structure, which ... | Python Code:
import numpy as np
import numpy.linalg as la
import mpnum as mp
Explanation: Introductory Notebook to mpnum
mpnum implements matrix product arrays (MPA), which are efficient parameterizations of certain multi-partite arrays. Special cases of the MPA structure, which are omnipresent in many-body quantum phy... |
1,642 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<span style="color
Step1: Fetch info for a published data set by its accession ID
You can find the study ID or individual sample IDs from published papers or by searching the NCBI or relate... | Python Code:
# conda install ipyrad -c bioconda
# conda install sratools -c bioconda
import ipyrad.analysis as ipa
Explanation: <span style="color:gray">ipyrad-analysis toolkit:</span> sratools
For reproducibility purposes, it is nice to be able to download the raw data for your analysis from an online repository like... |
1,643 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Integer representations
Integers are typically represented in memory as a base-2 bit pattern, and in python the built-in function bin can be used to inspect that
Step1: If the number of bit... | Python Code:
bin(19)
Explanation: Integer representations
Integers are typically represented in memory as a base-2 bit pattern, and in python the built-in function bin can be used to inspect that:
End of explanation
2 ** 200
Explanation: If the number of bits used is fixed, the range of integers that can be represented... |
1,644 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
plt.figure()
plt.pcolormesh(delz, cmap='RdBu', vmin=0, vmax=5)
plt.show()
It seems like this should work too...<br>
...but no. How do we look at maps of gradients?
Step1: Make up a uniform ... | Python Code:
xdelz = mg.link_vector_to_raster(delz, flip_vertically=True)[:,5]
print np.shape(xdelz),xdelz
# Make up a uniform vector field of wind direction U = (u,v) (at nodes or links?)
# Calculate wind stress (function of U and delz)
# Calculate flux vector Q = (qx,qy)
# Calculate flux divergence
for i in range(25)... |
1,645 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exact solution used in MES runs
We would like to MES the operation
$$
\partial_\rho\partial_\rho f
$$
Using cylindrical geometry.
This could of course be done with
$$
\partial_\rho^2 f
$$
b... | Python Code:
%matplotlib notebook
from sympy import init_printing
from sympy import S
from sympy import sin, cos, tanh, exp, pi, sqrt
from boutdata.mms import x, y, z, t
from boutdata.mms import DDX
import os, sys
# If we add to sys.path, then it must be an absolute path
common_dir = os.path.abspath('./../../../../comm... |
1,646 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
python libs for all vis things
Step1: matplotlib
interactive vis notes
Step2: + seaborn
Step3: ipywidgets
helpful tutorial here
with matplotlib
Step4: with seaborn! | Python Code:
%pylab inline
Explanation: python libs for all vis things
End of explanation
t = arange(0.0, 1.0, 0.01)
y1 = sin(2*pi*t)
y2 = sin(2*2*pi*t)
import pandas as pd
df = pd.DataFrame({'t': t, 'y1': y1, 'y2': y2})
df.head(10)
fig = figure(1, figsize = (10,10))
ax1 = fig.add_subplot(211)
ax1.plot(t, y1)
ax1.grid(... |
1,647 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Reusable Embeddings
Learning Objectives
1. Learn how to use a pre-trained TF Hub text modules to generate sentence vectors
1. Learn how to incorporate a pre-trained TF-Hub module into a Kera... | Python Code:
import os
import pandas as pd
from google.cloud import bigquery
Explanation: Reusable Embeddings
Learning Objectives
1. Learn how to use a pre-trained TF Hub text modules to generate sentence vectors
1. Learn how to incorporate a pre-trained TF-Hub module into a Keras model
1. Learn how to deploy and use a... |
1,648 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simulation of between-subjects regressor effects on HDDM parameters
This notebook is slightly modified from the .py posted by Michael, see here for the discussion.
The goal of this script is... | Python Code:
import hddm
from numpy import mean, std
import numpy as np
from pandas import Series
import pandas as pd
import os as os
import matplotlib.pyplot as plt
# os.chdir('/storage/home/mnh5174')
Explanation: Simulation of between-subjects regressor effects on HDDM parameters
This notebook is slightly mo... |
1,649 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Strings and Control Flow
Step1: Strings
Strings are just arrays of characters
Step2: Arithmetic with Strings
Step3: You can compare strings
Step4: Python supports Unicode characters
You ... | Python Code:
import numpy as np
from astropy.table import QTable
from astropy import units as u
Explanation: Strings and Control Flow
End of explanation
s = 'spam'
s,len(s),s[0],s[0:2]
s[::-1]
Explanation: Strings
Strings are just arrays of characters
End of explanation
e = "eggs"
s + e
s + " " + e
4 * (s + " ") + e
pr... |
1,650 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Solution Excercise 9 Team Hadochi
Jorn van der Ent
Michiel Voermans
23 January 2017
Load Modules and check for presence of ESRI Shapefile drive
Step1: Set working directory to 'data'
Step2:... | Python Code:
from osgeo import ogr
from osgeo import osr
import os
driverName = "ESRI Shapefile"
drv = ogr.GetDriverByName( driverName )
if drv is None:
print "%s driver not available.\n" % driverName
else:
print "%s driver IS available.\n" % driverName
Explanation: Solution Excercise 9 Team Hadochi
Jorn van d... |
1,651 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Bienvenid@s a Jupyter
Los cuadernos de Jupyter son una herramienta interactiva que te permite preparar documentos con código ejecutable, ecuaciones, texto, imágenes, videos, entre otros, que... | Python Code:
# Lo primero que ejecutarás será 'Hola Jupyter'
print('Hola a Todos')
Explanation: Bienvenid@s a Jupyter
Los cuadernos de Jupyter son una herramienta interactiva que te permite preparar documentos con código ejecutable, ecuaciones, texto, imágenes, videos, entre otros, que te ayuda a enriquecer o explicar ... |
1,652 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Decison Trees
First we'll load some fake data on past hires I made up. Note how we use pandas to convert a csv file into a DataFrame
Step1: scikit-learn needs everything to be numerical for... | Python Code:
import numpy as np
import pandas as pd
from sklearn import tree
input_file = "e:/sundog-consult/udemy/datascience/PastHires.csv"
df = pd.read_csv(input_file, header = 0)
df.head()
Explanation: Decison Trees
First we'll load some fake data on past hires I made up. Note how we use pandas to convert a csv fil... |
1,653 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href='http
Step1: Import matplotlib.pyplot as plt and set %matplotlib inline if you are using the jupyter notebook. What command do you use if you aren't using the jupyter notebook?
Step... | Python Code:
import numpy as np
x = np.arange(0,100)
y = x*2
z = x**2
Explanation: <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a>
Matplotlib Exercises - Solutions
Welcome to the exercises for reviewing matplotlib! Take your time with these, Matplotlib can be tricky to understand at fir... |
1,654 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
函数
Step1: 可接受任意数量参数的函数
为了能让一个函数接受任意数量的位置参数,可以使用一个*参数
为了接受任意数量的关键字参数,使用一个以 **开头的参数
这个和Packing和unpacking的用法是相同的,关键字参数一般是可以表示成字典的unpacking的
*arg1, **arg2就可以表示所有的参数形式
一个*参数只能出现在函数定义中最后一个位置参数后面,... | Python Code:
%matplotlib inline
# 多行结果输出支持
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
Explanation: 函数
End of explanation
# 可变参数 packing and unpacking
def avg(first, *rest):
return (first + sum(rest)) / (1 + len(rest))
# Sample use
avg(1, 2) # 1.5
avg(1... |
1,655 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<table align="left">
<td>
<a href="https
Step1: PIP Install Packages and dependencies
Step2: 1. Project Configuration
Step3: 2. Get training data
In this step, we are going to
Step4... | Python Code:
import sys
# If you are running this notebook in Colab, run this cell and follow the
# instructions to authenticate your GCP account. This provides access to your
# Cloud Storage bucket and lets you submit training jobs and prediction
# requests.
if 'google.colab' in sys.modules:
from google.colab import... |
1,656 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step5: Training data was collected in the Self-Driving Car simulator on Mac OS using a Playstation 3 console controller.
Recording Measurement class
To simplify accessing each measurement fr... | Python Code:
class RecordingMeasurement:
A representation of a vehicle's state at a point in time while driving
around a track during recording.
Features available are:
left_camera_view - An image taken by the LEFT camera.
center_camera_view - An image taken by the CENTER c... |
1,657 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: Word embeddings
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: Download the IMDb Dataset
Y... | 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... |
1,658 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Nuclear Data
In this notebook, we will go through the salient features of the openmc.data package in the Python API. This package enables inspection, analysis, and conversion of nuclear data... | Python Code:
%matplotlib inline
import os
from pprint import pprint
import shutil
import subprocess
import urllib.request
import h5py
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm
from matplotlib.patches import Rectangle
import openmc.data
Explanation: Nuclear Data
In this notebook, we will go... |
1,659 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Open Traffic Reporter
Map-Matching Optimization
The Open Traffic Reporter map-matching service is based on the Hidden Markov Model (HMM) design of Newton and Krumm (2009). Skipping over 99% ... | Python Code:
from __future__ import division
from matplotlib import pyplot as plt
import numpy as np
import os
import urllib
import json
import pandas as pd
from random import shuffle, choice
import pickle
import sys; sys.path.insert(0, os.path.abspath('..'));
import validator.validator as val
%matplotlib inline
mapzen... |
1,660 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plotting brightness temperatures in a Lambert Conformal Conic map projection
In this notebook we're going to continue working with http
Step1: the glob function finds a file using a wildcar... | Python Code:
from __future__ import print_function
import os,site
import glob
import h5py
from IPython.display import Image
import numpy as np
from matplotlib import pyplot as plt
#
# add the lib folder to the path assuming it is on the same
# level as the notebooks folder
#
libdir=os.path.abspath('../lib')
site.addsit... |
1,661 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Porting Tensorflow tutorial "Deep MNIST for Experts" to polygoggles
based on https
Step1: What TensorFlow actually did in that single line was to add new operations to the computation graph... | Python Code:
import math
import os
import tensorflow as tf
import datasets
import make_polygon_pngs
use_MNIST_instead_of_our_data = False
if use_MNIST_instead_of_our_data:
width = 28
height = 28
num_training_steps = 20000
batch_size = 50
else:
width = 70 # at 150, takes forever, 0 training accuracy ... |
1,662 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Load Boston Housing Dataset
Step2: Standardize Features
Step3: Fit Ridge Regression
The hyperparameter, $\alpha$, lets us control how much we penalize the coefficients, with ... | Python Code:
# Load library
from sklearn.linear_model import Lasso
from sklearn.datasets import load_boston
from sklearn.preprocessing import StandardScaler
Explanation: Title: Lasso Regression
Slug: lasso_regression
Summary: How to conduct lasso regression in scikit-learn for machine learning in Python.
Date: 20... |
1,663 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Showing a Test Sample
Step1: Finding a Valid Image Size
Not all the images have the same size dimensions so the first thing we'll have to do will be to rescale them. That's because the mode... | Python Code:
num_test_images = len(test_image_names)
idx = random.randint(0, num_test_images)
sample_file, sample_name = test_image_names[idx], test_image_names[idx].split('_')[:-1]
path_file = os.path.join(test_root_path, sample_file)
sample_image = imread(path_file)
print("Id: {}, Image Label: {}, Shape: {}".format(i... |
1,664 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Comparing Encoder-Decoders Analysis
Model Architecture
Step1: Perplexity on Each Dataset
Step2: Loss vs. Epoch
Step3: Perplexity vs. Epoch
Step4: Generations
Step5: BLEU Analysis
Step6:... | Python Code:
report_files = ["/Users/bking/IdeaProjects/LanguageModelRNN/experiment_results/encdec_noing10_200_512_04dra/encdec_noing10_200_512_04dra.json", "/Users/bking/IdeaProjects/LanguageModelRNN/experiment_results/encdec_noing10_200_512_04drb/encdec_noing10_200_512_04drb.json", "/Users/bking/IdeaProjects/Language... |
1,665 | 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', 'test-institute-3', 'sandbox-3', 'toplevel')
Explanation: ES-DOC CMIP6 Model Properties - Toplevel
MIP Era: CMIP6
Institute: TEST-INSTITUTE-3
Source ID: SANDBOX-3
Sub-Topics: Radiative... |
1,666 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Convenience methods for optimisation
This example demonstrates how to use the convenience methods fmin and curve_fit for optimisation.
These methods allow you to perform simple minimisation ... | Python Code:
import pints
# Define a quadratic function f(x)
def f(x):
return 1 + (x[0] - 3) ** 2 + (x[1] + 5) ** 2
# Choose a starting point for the search
x0 = [1, 1]
# Find the arguments for which it is minimised
xopt, fopt = pints.fmin(f, x0, method=pints.XNES)
print(xopt)
print(fopt)
Explanation: Convenience m... |
1,667 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lesson 14 访问网络初步和 requests 包
v1.0.0 2016.11 by David.Yi
v1.1 2020.5 2020.6 edit by David Yi
本次内容要点
requests 包介绍
访问网页
调用接口
思考一下:写个同步数据的软件需要注意哪些方面
requests 包
requests 包是 python 目前最好用的网站内容访问包,设... | Python Code:
# 获得一个网站的信息
import requests
r = requests.get('http://www.huifu.com')
print(r.content)
print(r.headers)
Explanation: Lesson 14 访问网络初步和 requests 包
v1.0.0 2016.11 by David.Yi
v1.1 2020.5 2020.6 edit by David Yi
本次内容要点
requests 包介绍
访问网页
调用接口
思考一下:写个同步数据的软件需要注意哪些方面
requests 包
requests 包是 python 目前最好用的网站内容访问包,设计... |
1,668 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1> Working with Data in Pandas </h1>
Patrick Phelps - Manger of Data Science @ Yelp
Frances Haugen - Product Manager @ Pinterest
<h3> Introduction </h3>
All numbers used in this exercise a... | Python Code:
%load_ext autoreload
%autoreload 2
%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import json
pd.set_option('display.mpl_style', 'default')
plt.rcParams['figure.figsize'] = (12.0, 8.0)
Explanation: <h1> Working with Data in Pandas </h1>
Patrick Phelps - Manger of ... |
1,669 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href='http
Step1: Get the Data
We'll work with the Ecommerce Customers csv file from the company. It has Customer info, suchas Email, Address, and their color Avatar. Then it also has nu... | Python Code:
import pandas as pd
import numpy, matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
Explanation: <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a>
Linear Regression - Project Exercise
Congratulations! You just got some contract work with an Ecommerce company b... |
1,670 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1. Combine the two lists
Step1: Solution
Step2: 2. Create all products of the two lists
Step3: Solution
Step4: Using product() from itertools with list()
Step5: 3. Sort the list
Do not ... | Python Code:
l0 = [0, 1, 2, 3, 4, 5]
l1 = ['a', 'b', 'c', 'd', 'e', 'f']
Explanation: 1. Combine the two lists
End of explanation
list(zip(l0, l1))
Explanation: Solution:
Use zip() with list()
End of explanation
l0 = [0, 1, 2]
l1 = ['a', 'b', 'c']
Explanation: 2. Create all products of the two lists
End of explanation
... |
1,671 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Calculating-Seasonal-Averages-from-Timeseries-of-Monthly-Means-" data-toc-mo... | Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
import xarray as xr
from netCDF4 import num2date
import matplotlib.pyplot as plt
print("numpy version : ", np.__version__)
print("pandas version : ", pd.__version__)
print("xarray version : ", xr.__version__)
Explanation: <h1>Table of Contents<spa... |
1,672 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Analýza volatilních pohybů v Pythonu a Pandas 2
Jde o příklad, jak hledat vztah konkrétní podmínky na výsledek. V následujícím článku popisuji, jaký má vliv volatilní úsečka, popsaná v předc... | Python Code:
import sys
import pandas as pd
import pandas_datareader as pdr
import pandas_datareader.data as web
import matplotlib
import seaborn as sns
import datetime
print('Python', sys.version)
print('Pandas', pd.__version__)
print('Pandas-datareader', pdr.__version__)
print('Matplotlib', matplotlib.__version__)
pr... |
1,673 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Preprocessing and Pipelines
Step1: Cross-validated pipelines including scaling, we need to estimate mean and standard deviation separately for each fold.
To do that, we build a pipeline.
St... | 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, digits.target)
Explanation: Preprocessing and Pipelines
End of explanation
from sklearn.pipeline import Pipeline
from sklear... |
1,674 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Visual Overview of Plotting Functions
We've talked a lot about laying things out, etc, but we haven't talked about actually plotting data yet. Matplotlib has a number of different plotting f... | Python Code:
np.random.seed(1)
x = np.arange(5)
y = np.random.randn(5)
fig, axes = plt.subplots(ncols=2, figsize=plt.figaspect(1./2))
vert_bars = axes[0].bar(x, y, color='lightblue', align='center')
horiz_bars = axes[1].barh(x, y, color='lightblue', align='center')
# I'll also introduce axhline & axvline to draw a line... |
1,675 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Model My Watershed (MMW) API Demo
Step1: MMW production API endpoint base url.
Step2: The job is not completed instantly and the results are not returned directly by the API request that i... | Python Code:
import json
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
def requests_retry_session(
retries=3,
backoff_factor=0.3,
status_forcelist=(500, 502, 504),
session=None,
):
session = session or requests.Session()
retry = ... |
1,676 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
An Introduction to Matplotlib
Tenzing HY Joshi
Step1: Where's the plot to this story?
By default, with pyplot the interactive Mode is turned off. That means that the state of our Figure is... | Python Code:
import matplotlib as mpl
mpl
# I normally prototype my code in an editor + ipy terminal.
# In those cases I import pyplot and numpy via
import matplotlib.pyplot as plt
import numpy as np
# In Jupy notebooks we've got magic functions and pylab gives you pyplot as plt and numpy as np
# %pylab
# Additionally... |
1,677 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Active Subspaces Example Function
Step1: First we draw M samples randomly from the input space.
Step2: Now we normalize the sampled values of the input parameters. The uniform inputs are l... | Python Code:
import active_subspaces as ac
import numpy as np
%matplotlib inline
# The borehole_functions.py file contains two functions: the borehole function (borehole(xx))
# and its gradient (borehole_grad(xx)). Each takes an Mx8 matrix (M is the number of data
# points) with rows being normalized inputs; borehole r... |
1,678 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
EEG processing and Event Related Potentials (ERPs)
For a generic introduction to the computation of ERP and ERF
see tut_epoching_and_averaging. Here we cover the specifics
of EEG, namely
Ste... | Python Code:
import mne
from mne.datasets import sample
Explanation: EEG processing and Event Related Potentials (ERPs)
For a generic introduction to the computation of ERP and ERF
see tut_epoching_and_averaging. Here we cover the specifics
of EEG, namely:
- setting the reference
- using standard montages :func:`mne.ch... |
1,679 | 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-... |
1,680 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
"Brute force" optimization with Scipy
Official documentation
Step1: Define the objective function
Step2: Minimize using the "Brute force" algorithm
Uses the "brute force" method, i.e. comp... | Python Code:
%matplotlib inline
import matplotlib
matplotlib.rcParams['figure.figsize'] = (8, 8)
# Setup PyAI
import sys
sys.path.insert(0, '/Users/jdecock/git/pub/jdhp/pyai')
import numpy as np
from scipy import optimize
# Plot functions
from pyai.optimize.utils import plot_contour_2d_solution_space
from pyai.optimize... |
1,681 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 1
Step1: Can you describe what this code did?
Can you adapt the code in this box yourself and make it print your own name?
Apart from printing words to your screen, you can also use... | Python Code:
print("Mike")
Explanation: Chapter 1: Variables
-- A Python Course for the Humanities by Folgert Karsdorp and Maarten van Gompel, with modifications by Mike Kestemont and Lars Wieneke
First steps
Everyone can learn how to program and the best way to learn it is by doing it. This tutorial on the Python prog... |
1,682 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Land
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify do... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'mri', 'sandbox-3', 'land')
Explanation: ES-DOC CMIP6 Model Properties - Land
MIP Era: CMIP6
Institute: MRI
Source ID: SANDBOX-3
Topic: Land
Sub-Topics: Soil, Snow, Vegetation, Energy ... |
1,683 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CNN transfer learning - Keras+TensorFlow
This is for CNN models transferred from pretrained model, using Keras based on TensorFlow. First, some preparation work.
Step1: Read the MNIST data.... | Python Code:
from keras.layers import Conv2D, MaxPooling2D, Input, Dense, Flatten, Activation, add, Lambda
from keras.layers.normalization import BatchNormalization
from keras.layers.pooling import GlobalAveragePooling2D
from keras.optimizers import RMSprop
from keras.backend import tf as ktf
from keras.models import M... |
1,684 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Advanced Functions Test
For this test, you should use the built-in functions to be able to write the requested functions in one line.
Problem 1
Use map to create a function which finds the l... | Python Code:
def word_lengths(phrase):
pass
word_lengths('How long are the words in this phrase')
Explanation: Advanced Functions Test
For this test, you should use the built-in functions to be able to write the requested functions in one line.
Problem 1
Use map to create a function which finds the length of e... |
1,685 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
#There are 4149 elements, and PE has a significant amount of missing values
Step1: The two wells have all PE missed
Step2: The PE of all wells have no strong variance; For now, fillin the ... | Python Code:
well_PE_Miss = train.loc[train["PE"].isnull(),"Well Name"].unique()
well_PE_Miss
train.loc[train["Well Name"] == well_PE_Miss[0]].count()
train.loc[train["Well Name"] == well_PE_Miss[1]].count()
Explanation: #There are 4149 elements, and PE has a significant amount of missing values
End of explanation
(tra... |
1,686 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a>
<img align=left src="files/images/pyspark-page1.svg" width=500 height=250 />
</a>
DataFrame API
GitHub
related blog post
<a>
<img align=left src="files/images/pyspark-page2.svg" width=50... | Python Code:
import IPython
print("pyspark version:" + str(sc.version))
print("Ipython version:" + str(IPython.__version__))
Explanation: <a>
<img align=left src="files/images/pyspark-page1.svg" width=500 height=250 />
</a>
DataFrame API
GitHub
related blog post
<a>
<img align=left src="files/images/pyspark-page2.svg" ... |
1,687 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Illustration of w-imaging
Step1: Generate baseline coordinates for an observation with the VLA over 6 hours, with a visibility recorded every 10 minutes. The phase center is fixed at a decl... | Python Code:
%matplotlib inline
import sys
sys.path.append('../..')
from matplotlib import pylab
pylab.rcParams['figure.figsize'] = 12, 10
import functools
import numpy
import scipy
import scipy.special
from crocodile.clean import *
from crocodile.synthesis import *
from crocodile.simulate import *
from util.visualize ... |
1,688 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Figure 5
Step1: Out-of-country performance
In this experiment, we compare the performance of models trained in-country with models trained out-of-country.
The parameters needed to produce t... | Python Code:
from fig_utils import *
import matplotlib.pyplot as plt
import time
%matplotlib inline
Explanation: Figure 5: Cross-border model generalization
This notebook generates individual panels of Figure 5 in "Combining satellite imagery and machine learning to predict poverty".
End of explanation
# Parameters
cou... |
1,689 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
3.1
Step1: Read the data
Data are in the child.iq directory of the ARM_Data download-- you might have
to change the path I use below to reflect the path on your computer.
Step2: First regr... | Python Code:
from __future__ import print_function, division
%matplotlib inline
import matplotlib
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# use matplotlib style sheet
plt.style.use('ggplot')
# import statsmodels for R-style regression
import statsmodels.formula.api as smf
Explanation: 3.1... |
1,690 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
probability density function - derivative of a CDF. Evaluating for x gives a probability density or "the probability per unit of x. In order to get a probability mass, you have to integrat... | Python Code:
%matplotlib inline
import thinkstats2
import thinkplot
import pandas as pd
import numpy as np
import math, random
mean, var = 163, 52.8
std = math.sqrt(var)
pdf = thinkstats2.NormalPdf(mean, std)
print "Density:",pdf.Density(mean + std)
thinkplot.Pdf(pdf, label='normal')
thinkplot.Show()
#by default, makes... |
1,691 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Qualitative Examples of Machine Learning Applications
Classification
Step1: We need a two-dimensional, [n_samples, n_features] representation. We can accomplish this by treating each pixel ... | Python Code:
from sklearn.datasets import load_digits
digits = load_digits()
digits.images.shape
idx = 14
digits.target[idx], digits.images[idx]
import matplotlib.pyplot as plt
fig, axes = plt.subplots(10, 10, figsize=(8, 8),
subplot_kw={'xticks':[], 'yticks':[]},
grid... |
1,692 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: CSV exercises
Step3: More about PandasSQL package
Step4: API excercise
We can access data on files or database but what about the data that sits in websites.
We need to crawl the we... | Python Code:
import pandas as pd
def add_full_name(path_to_csv, path_to_new_csv):
#Assume you will be reading in a csv file with the same columns that the
#Lahman baseball data set has -- most importantly, there are columns
#called 'nameFirst' and 'nameLast'.
#1) Write a function that reads a csv
#l... |
1,693 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
There are two ways to load a DiVinE model
Step1: The spot.ltsmin.load function compiles the model using the ltlmin interface and load it. This should work with DiVinE models if divine --LT... | Python Code:
!rm -f test1.dve
%%file test1.dve
int a = 0, b = 0;
process P {
state x;
init x;
trans
x -> x { guard a < 3 && b < 3; effect a = a + 1; },
x -> x { guard a < 3 && b < 3; effect b = b + 1; };
}
process Q {
state wait, work;
init wait;
trans
wait -> work { guard b > 1; },
work -> wait ... |
1,694 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Atividade de Regressão Linear
Código-fonte disponível em
Step2: Questões
1. Rode o mesmo programa nos dados contendo anos de escolaridade (primeira coluna) versus salário (segunda co... | Python Code:
%matplotlib notebook
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#Federal University of Campina Grande (UFCG)
#Author: Ítalo de Pontes Oliveira
#Adapted from: Siraj Raval
#Available at: https://github.com/llSourcell/linear_regression_live
#The optimal values of m and b can be actually calculated with way... |
1,695 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Background
I wrote this notebook as a simple training exercise to better understand feedforward neural networks. The naming conventions in this code match with Andrew Ng's free online course... | Python Code:
# NumPy is the fundamental package for scientific computing with Python.
import numpy as np
Explanation: Background
I wrote this notebook as a simple training exercise to better understand feedforward neural networks. The naming conventions in this code match with Andrew Ng's free online course in Machine ... |
1,696 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Primera parte
Step1: Se mostrará una aplicación de la SVD a la compresión de imágenes y reducción de ruido.
Step2: Pregunta
Step3: Hacer una función que me resuelva un sistema de ecuacion... | Python Code:
# Segunda parte: Aplicaciones en Python
Explanation: Primera parte: Concimiento básico de Algebra Lineal
Pregunta 1:¿Por qué una matriz equivale a una transformación lineal entre espacios vectoriales?
Porque na matriz realiza las operaciones básicas de suma, resta y multiplicación sobre los vectores canoni... |
1,697 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sound as 1D-Signal
Step1: Sound as 2D-Signal
Step2: Prepare a data
Step3: Nearest Neighbors genre classification
Step4: Convolution Nural Nets
http
Step5: Find Simular Tracks
<img src="... | Python Code:
plt.figure(figsize=(20,4))
pylab.plot(np.arange(len(y)) * 1.0 /sr, y, 'k')
pylab.xlim([0, 10])
pylab.show()
Explanation: Sound as 1D-Signal
End of explanation
S = librosa.feature.melspectrogram(y, sr=sr, n_mels=128)
log_S = librosa.logamplitude(S, ref_power=np.max)
plt.figure(figsize=(20,4))
librosa.displa... |
1,698 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
I recommend installing Anaconda for ease
Step1: All credit for the data, and our many thanks, go to the principal investigators who collected this data
and made it available
Step2: What s... | Python Code:
#import the packages we will use
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
#use simplest tool available
import statsmodels.formula.api as smf
import statsmodels.stats.multicomp as multi
import statsmodels.api as sm
import scipy.stats
from sklearn.cross_val... |
1,699 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Taller evaluable sobre la extracción, transformación y visualización de datos usando IPython
Juan David Velásquez Henao
jdvelasq@unal.edu.co
Universidad Nacional de Colombia, Sede Medellín
... | Python Code:
import pandas as pd
x=pd.DataFrame() #Mejor hasta ahora
for m in range(1995,2018):
if m < 2016:
o='.xlsx'
else:
o='.xls'
if m < 2000:
sK=3
else:
sK=2
n='Precio_Bolsa_Nacional_($kwh)_' + str(m) + o
y=pd.read_excel(n, skiprows=sK, parse_cols=24)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.