Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
9,600 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sound waves as equations
Author
Step1: Fast Fourier Transform
We use the Fast Fourier Transform algorithm from the numpy library.
Step2: Writing the Fast Fourier Transform in Latex
We outp... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import wave
import sys
# Only opens 16bit PCM WAV files.
# The format can be changed in Audacity.
spf = wave.open('test2.wav','r')
# Only opens Mono files
if spf.getnchannels() == 2:
print 'Just mono files'
sys.exit(0)
# Extracts... |
9,601 | 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('reviews.txt', 'r') as f:
reviews = f.read()
with open('labels.txt', 'r') as f:
labels = f.read()
reviews[:1000]
Explanation: Sentiment Analysis with an RNN
In this notebook, you'll implement a recurrent neural network that performs sentiment ana... |
9,602 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Biophysics. Examples of code using Bio.PDB
Requirements
biophyton
jupyter
nglview
Step1: 1.1 Loading structure from PDB file
Step2: 1.2 Get Headers
Step3: 1.3 Alternatively . Download fro... | Python Code:
# import libraries
from Bio.PDB import *
import nglview as nv
Explanation: Biophysics. Examples of code using Bio.PDB
Requirements
biophyton
jupyter
nglview
End of explanation
pdb_file = '1ubq.pdb'
pdb_parser = PDBParser()
st = pdb_parser.get_structure('1UBQ', '1ubq.pdb')
import nglview as nv
view = nv.sho... |
9,603 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Scientific programming with the SciPy stack
Pandas
Import libraries and check versions.
Step1: Read the data and get a row count. Data source
Step2: SymPy
SymPy is a Python library for sy... | Python Code:
import pandas as pd
import numpy as np
import sys
print('Python version ' + sys.version)
print('Pandas version ' + pd.__version__)
print('Numpy version ' + np.__version__)
Explanation: Scientific programming with the SciPy stack
Pandas
Import libraries and check versions.
End of explanation
file_path = r'd... |
9,604 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Lab 9 - Graphs & Networks
In this lab we will do the following
Step2: 1. Get API key
Get a LinkedIn API key at http
Step3: 2. Get Access Token
Next we are scraping our data using th... | Python Code:
!pip install oauth2
!pip install unidecode
%matplotlib inline
from collections import defaultdict
import json
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib import rcParams
import matplotlib.cm as cm
import matplotlib as mpl
#colorbrewer2 Dark2 qua... |
9,605 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data generation
Step1: Preparing data set sweep
First, we're going to define the data sets that we'll sweep over. The following cell does not need to be modified unless if you wish to chang... | Python Code:
from os.path import join, expandvars
from joblib import Parallel, delayed
from glob import glob
from os import system
from tax_credit.framework_functions import (parameter_sweep,
generate_per_method_biom_tables,
move_r... |
9,606 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Aerosol
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'ipsl', 'sandbox-1', 'aerosol')
Explanation: ES-DOC CMIP6 Model Properties - Aerosol
MIP Era: CMIP6
Institute: IPSL
Source ID: SANDBOX-1
Topic: Aerosol
Sub-Topics: Transport, Emissions... |
9,607 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Survival Analysis (1)
source
Step2: political leaders
start | Python Code:
import pandas as pd
import lifelines
import matplotlib.pylab as plt
%matplotlib inline
data = lifelines.datasets.load_dd()
Explanation: Survival Analysis (1)
source : lifelines documents (https://lifelines.readthedocs.io/)
Survival Analysis is useful for searching break of machine or User's churn rate...a... |
9,608 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Hub Authors.
Licensed under the Apache License, Version 2.0 (the "License");
Step1: <table class="tfo-notebook-buttons" align="left">
<td> <a target="_bl... | Python Code:
#@title Copyright 2020 The TensorFlow Hub Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unl... |
9,609 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Defining the model
First, we define the model as a probabilistic program inheriting from pyprob.Model. Models inherit from torch.nn.Module and can be potentially trained with gradient-based ... | Python Code:
class GaussianUnknownMean(Model):
def __init__(self):
super().__init__(name='Gaussian with unknown mean') # give the model a name
self.prior_mean = 1
self.prior_std = math.sqrt(5)
self.likelihood_std = math.sqrt(2)
def forward(self): # Needed to specifcy how the gene... |
9,610 | 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', 'niwa', 'sandbox-1', 'toplevel')
Explanation: ES-DOC CMIP6 Model Properties - Toplevel
MIP Era: CMIP6
Institute: NIWA
Source ID: SANDBOX-1
Sub-Topics: Radiative Forcings.
Properties: ... |
9,611 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step3: <a href="https
Step4: We've succesfully loaded our data, but there are still a couple preprocessing steps to go through first. Specifically, we're going to
Step5: Now that we have o... | Python Code:
Install Data Commons API
We need to install the Data Commons API, since they don't ship natively with
most python installations.
In Colab, we'll be installing the Data Commons python and pandas APIs
through pip.
!pip install datacommons --upgrade --quiet
!pip install datacommons_pandas --upgrade --quiet
I... |
9,612 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Station Plot
Make a station plot, complete with sky cover and weather symbols.
The station plot itself is pretty straightforward, but there is a bit of code to perform the
data-wrangling (ho... | Python Code:
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.pyplot as plt
from metpy.calc import reduce_point_density
from metpy.cbook import get_test_data
from metpy.io import metar
from metpy.plots import add_metpy_logo, current_weather, sky_cover, StationPlot
Explanation: Station Plo... |
9,613 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example for ERA5 weather data download
This example shows you how to download ERA5 weather data from the Climate Data Store (CDS) and store it locally. Furthermore, it shows how to convert t... | Python Code:
from feedinlib import era5
Explanation: Example for ERA5 weather data download
This example shows you how to download ERA5 weather data from the Climate Data Store (CDS) and store it locally. Furthermore, it shows how to convert the weather data to the format needed by the pvlib and windpowerlib.
In order ... |
9,614 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Datapath Example 3
This notebook gives an example of how to build relatively simple data paths.
It assumes that you understand the concepts presented in the example 2
notebook.
Exampe Data M... | Python Code:
# Import deriva modules
from deriva.core import ErmrestCatalog, get_credential
# Connect with the deriva catalog
protocol = 'https'
hostname = 'www.facebase.org'
catalog_number = 1
# If you need to authenticate, use Deriva Auth agent and get the credential
credential = get_credential(hostname)
catalog = Er... |
9,615 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Ocean
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', 'dwd', 'sandbox-1', 'ocean')
Explanation: ES-DOC CMIP6 Model Properties - Ocean
MIP Era: CMIP6
Institute: DWD
Source ID: SANDBOX-1
Topic: Ocean
Sub-Topics: Timestepping Framework, Adve... |
9,616 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
IonQ ProjectQ Backend Example
This notebook will walk you through a basic example of using IonQ hardware to run ProjectQ circuits.
Setup
The only requirement to run ProjectQ circuits on IonQ... | Python Code:
# NOTE: Optional! This ignores warnings emitted from ProjectQ imports.
import warnings
warnings.filterwarnings('ignore')
# Import ProjectQ and IonQBackend objects, the setup an engine
import projectq.setups.ionq
from projectq import MainEngine
from projectq.backends import IonQBackend
# REPLACE WITH YOUR A... |
9,617 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Station Plot
Make a station plot, complete with sky cover and weather symbols.
The station plot itself is pretty straightforward, but there is a bit of code to perform the
data-wrangling (ho... | Python Code:
import cartopy.crs as ccrs
import cartopy.feature as feat
import matplotlib.pyplot as plt
import numpy as np
from metpy.calc import get_wind_components
from metpy.cbook import get_test_data
from metpy.plots import StationPlot
from metpy.plots.wx_symbols import current_weather, sky_cover
from metpy.units im... |
9,618 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Comparison of HeadLineSinkString and LeakyLineDoubletString vs. image well
Step1: Consider a well pumping in a phreatic aquifer with $S_y=0.1$. The hydraulic conductivity of the aquifer is ... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from ttim import *
Explanation: Comparison of HeadLineSinkString and LeakyLineDoubletString vs. image well
End of explanation
ml1 = ModelMaq(kaq=10, z=[20, 0], Saq=[0.1], phreatictop=True, tmin=0.001, tmax=100)
w1 = Well(ml1, 0, 0, rw=0.... |
9,619 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TensorFlow Reproducibility
This notebook explains how to get fully reproducible code with TensorFlow.
<table align="left">
<td>
<a target="_blank" href="https
Step1: Warning
Step2: C... | Python Code:
from IPython.display import IFrame
IFrame(src="https://www.youtube.com/embed/Ys8ofBeR2kA", width=560, height=315, frameborder="0", allowfullscreen=True)
Explanation: TensorFlow Reproducibility
This notebook explains how to get fully reproducible code with TensorFlow.
<table align="left">
<td>
<a targ... |
9,620 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
FloPy
A quick demo of how to control the ASCII format of numeric arrays written by FloPy
load and run the Freyberg model
Step1: Each Util2d instance now has a .format attribute, which is an... | Python Code:
%matplotlib inline
import sys
import os
import platform
import numpy as np
import matplotlib.pyplot as plt
import flopy
#Set name of MODFLOW exe
# assumes executable is in users path statement
version = 'mf2005'
exe_name = 'mf2005'
if platform.system() == 'Windows':
exe_name = 'mf2005.exe'
mfexe = exe... |
9,621 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial 01 - Hello World em Aprendizagem de Máquina
Para começar o nosso estudo de aprendizagem de máquina vamos começar com um exemplo simples de aprendizagem. O objetivo aqui é entender o... | Python Code:
# Vamos transformar as informações textuais em números: (0) irregular, (1) Suave.
# Os labels também serão transformados em números: (0) Maçã e (1) Laranja
features = [[140, 1], [130, 1], [150, 0], [170, 0]]
labels = [0, 0, 1, 1]
Explanation: Tutorial 01 - Hello World em Aprendizagem de Máquina
Para começa... |
9,622 | 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: Restart the kernel
After you install the additional packages, you need to restart the notebook kernel so it can find the packages.
Step... | Python Code:
%%writefile requirements.txt
joblib~=1.0
numpy~=1.20
scikit-learn~=0.24
google-cloud-storage>=1.26.0,<2.0.0dev
# Required in Docker serving container
%pip install -U --user -r requirements.txt
# For local FastAPI development and running
%pip install -U --user "uvicorn[standard]>=0.12.0,<0.14.0" fastapi~=0.... |
9,623 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Inferential Statistics
Let's say you have collected the height of 1,000 people living in Hong Kong. The mean of their height would be descriptive statistics, but their mean height does not i... | Python Code:
# Calling the binom module from scipy stats package
from scipy.stats import binom
# Plotting Function
import matplotlib.pyplot as plt
%matplotlib inline
x = list(range(7))
n, p = 6, 0.5
rv = binom(n, p)
plt.vlines(x, 0, rv.pmf(x), colors='r', linestyles='-', lw=1, label='Probability')
plt.legend(loc='bes... |
9,624 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MNIST digit recognition using SVC and PCA with RBF in scikit-learn
> Using optimal parameters, fit to BOTH original and deskewed data
Step1: Where's the data?
Step2: How much of the data w... | Python Code:
from __future__ import division
import os, time, math
import cPickle as pickle
import matplotlib.pyplot as plt
import numpy as np
import scipy
import csv
from operator import itemgetter
from tabulate import tabulate
from print_imgs import print_imgs # my own function to print a grid of square images
from s... |
9,625 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I'm using tensorflow 2.10.0. | Problem:
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
network_layout = []
for i in range(3):
network_layout.append(8)
model = Sequential()
inputdim = 4
activation = 'relu'
outputdim = 2
opt='rmsprop'
epochs = 50
#Adding input layer and first hidden... |
9,626 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DAT210x - Programming with Python for DS
Module5- Lab8
Step1: A Convenience Function
This convenience method will take care of plotting your test observations, comparing them to the regress... | Python Code:
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
matplotlib.style.use('ggplot') # Look Pretty
Explanation: DAT210x - Programming with Python for DS
Module5- Lab8
End of explanation
def drawLine(model, X_test, y_test, title):
fig = plt.figure()
ax = fig.add_su... |
9,627 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Practical PyTorch
Step1: The returned GloVe object includes attributes
Step3: Finding closest vectors
Going from word → vector is easy enough, but to go from vector → word takes ... | Python Code:
import torch
import torchtext.vocab as vocab
glove = vocab.GloVe(name='6B', dim=100)
print('Loaded {} words'.format(len(glove.itos)))
Explanation: Practical PyTorch: Exploring Word Vectors with GloVe
When working with words, dealing with the huge but sparse domain of language can be challenging. Even for a... |
9,628 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2021 The TensorFlow Authors.
Step2: Inspecting Quantization Errors with Quantization Debugger
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href=... | 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... |
9,629 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generative Adversarial Nets
Training a generative adversarial network to sample from a Gaussian distribution. This is a toy problem, takes < 3 minutes to run on a modest 1.2GHz CPU.
Step1: ... | Python Code:
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
%matplotlib inline
Explanation: Generative Adversarial Nets
Training a generative adversarial network to sample from a Gaussian distribution. This is a toy problem, takes < 3 minutes to run on a modest 1... |
9,630 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generate a functional label from source estimates
Threshold source estimates and produce a functional label. The label
is typically the region of interest that contains high values.
Here we ... | Python Code:
# Author: Luke Bloy <luke.bloy@gmail.com>
# Alex Gramfort <alexandre.gramfort@inria.fr>
# License: BSD-3-Clause
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.minimum_norm import read_inverse_operator, apply_inverse
from mne.datasets import sample
print(__doc__)
data_path = ... |
9,631 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Monte Carlo Methods
Step1: Integration
If we have an ugly function, say
$$
\begin{equation}
f(x) = \sin^2 \left(\frac{1}{x (2-x)}\right),
\end{equation}
$$
then it can be very difficult ... | Python Code:
from IPython.core.display import HTML
css_file = 'https://raw.githubusercontent.com/ngcm/training-public/master/ipython_notebook_styles/ngcmstyle.css'
HTML(url=css_file)
Explanation: Monte Carlo Methods: Lab 1
Take a look at Chapter 10 of Newman's Computational Physics with Python where much of this materi... |
9,632 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: tf.data を使って NumPy データをロードする
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https
Step2: .npz ファイルからのロード
Ste... | 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... |
9,633 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
BCC Text Dataset
Here we will build a classification model for the following dataset.
https
Step1: Class Imbalance Check
Step2: Let's use the Google Developer Guide to figure out which ki... | Python Code:
import pandas as pd
import numpy as np
%matplotlib inline
from matplotlib import pyplot as plt
plt.style.use('ggplot')
bbc_df = pd.read_csv(r"https://storage.googleapis.com/dataset-uploader/bbc/bbc-text.csv")
bbc_df.head()
Explanation: BCC Text Dataset
Here we will build a classification model for the foll... |
9,634 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Spektren Berechnen
Date
Step1: Intervalle
Step2: Integration
Um die Trezbandsignalen auf die Intervalle zu integrieren sind die 2 folgende funktionen im functions definiert
Step3: Beispei... | Python Code:
%reset -f
%matplotlib notebook
%load_ext autoreload
%autoreload 1
%aimport functions
import numpy as np
import copy
import acoustics
from functions import *
import matplotlib.pyplot as plt
import matplotlib as mpl
import seaborn as sns
mpl.rcParams['lines.linewidth']=0.5
# uncomment next line to connect a ... |
9,635 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
keras_lesson1.ipynb -- CodeAlong of fastai/courses/dl1/keras_lesson1.ipynb
Wayne H Nixalo
Using TensorFlow backend
# pip install tensorflow-gpu keras
Introduction to our first task
Step1: D... | Python Code:
%reload_ext autoreload
%autoreload 2
%matplotlib inline
PATH = "data/dogscats/"
sz = 224
batch_size=64
import numpy as np
from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing import image
from keras.layers import Dropout, Flatten, Dense
from keras.models import Model, Sequentia... |
9,636 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep learning on video titles
In this notebook we do some data learning using the titles and the number of subscribers of the videos.
Step1: Database selection
We can choose on which databa... | Python Code:
import requests
import json
import pandas as pd
from math import *
import numpy as np
import tensorflow as tf
import time
import collections
import os
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
from IPython.display import display
... |
9,637 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data Download
This notebook download all FITS data.
List of files is in file ondrejov-labeled-spectra.csv.
These spectra has been classified with
Spectral View tool.
Step1: Read CSV with La... | Python Code:
%matplotlib inline
import urllib.request
import urllib.parse
import io
import os
import csv
import glob
from functools import partial
from itertools import count
import numpy as np
from astropy.io import fits
import matplotlib.pyplot as plt
LABELS_FILE = 'data/ondrejov-dataset.csv'
!head $LABELS_FILE
Expla... |
9,638 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CSV Data to MySQL for use in VISDOM
This notebook can be used to construct an 'account' table and a 'meter_data' table in mysql, based on the csv files with data extracted from the prop39sch... | Python Code:
csv_dir = "PGE_csv"
Explanation: CSV Data to MySQL for use in VISDOM
This notebook can be used to construct an 'account' table and a 'meter_data' table in mysql, based on the csv files with data extracted from the prop39schools xml files, and an 'intervention' table based on the PEPS_Data.xlsx file availab... |
9,639 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<hr style="height
Step1: Defining your placeholders
A placeholder is simply a variable that we will assign data to at a later date. It allows us to create our operations and build our compu... | Python Code:
# import statements
from __future__ import division
import tensorflow as tf
import numpy as np
import tarfile
import os
import matplotlib.pyplot as plt
import time
# Display plots inline
%matplotlib inline
# import email data
def csv_to_numpy_array(filePath, delimiter):
return np.genfromtxt(filePath, ... |
9,640 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1> Repeatable splitting </h1>
In this notebook, we will explore the impact of different ways of creating machine learning datasets.
<p>
Repeatability is important in machine learning. If y... | Python Code:
from google.cloud import bigquery
Explanation: <h1> Repeatable splitting </h1>
In this notebook, we will explore the impact of different ways of creating machine learning datasets.
<p>
Repeatability is important in machine learning. If you do the same thing now and 5 minutes from now and get different answ... |
9,641 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Demo of Brunel on Cars Data
The Data
We read the data into a pandas data frame. In this case we are grabbing some data that represents cars.
We read it in and call the brunel use method to e... | Python Code:
import pandas as pd
import ibmcognitive
cars = pd.read_csv("data/Cars.csv")
cars.head(6)
Explanation: Demo of Brunel on Cars Data
The Data
We read the data into a pandas data frame. In this case we are grabbing some data that represents cars.
We read it in and call the brunel use method to ensure the names... |
9,642 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
[BONUS] Problem 3
Step7: Model
We need to take the advatange of a CNN structure which (implicitly) understands image contents and styles. Rather than training a completely new model from sc... | Python Code:
# Import what we need
import os
import sys
import numpy as np
import scipy.io
import scipy.misc
import tensorflow as tf # Import TensorFlow after Scipy or Scipy will break
import matplotlib.pyplot as plt
from matplotlib.pyplot import imshow
from PIL import Image
%matplotlib inline
Explanation: [BONUS] Pro... |
9,643 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="Images/Splice_logo.jpeg" width="250" height="200" align="left" >
Using the Feature Store for feature discovery
Step1: In addition to the Feature Set built in the last notebook, th... | Python Code:
#Begin spark session
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
#Create pysplice context. Allows you to create a Spark dataframe using our Native Spark DataSource
from splicemachine.spark import PySpliceContext
splice = PySpliceContext(spark)
#Iniatialize our Feature ... |
9,644 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Paradigm entropy
This notebook shows some conditional entropy calculations from Ackerman & Malouf (in press). The Pite Saami data is taken from
Step1: Read in the paradigms from tab-delimi... | Python Code:
%precision 3
import numpy as np
import pandas as pd
pd.set_option('display.float_format',lambda x : '%.3f'%x)
import entropy
Explanation: Paradigm entropy
This notebook shows some conditional entropy calculations from Ackerman & Malouf (in press). The Pite Saami data is taken from:
Wilbur, Joshua (2014). ... |
9,645 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Summarize tidy tables
This script summarizes the water use and water suppy tidy tables generated by the CreateUsageTable and CreateSupplyTable scripts, respectively. Each table is then merge... | Python Code:
#Import libraries
import sys, os
import pandas as pd
import numpy as np
#Get file names; these files are created by the CreateUsageTable.py and CreateSupplyTable.py respectively
dataDir = '../../Data'
tidyuseFN = dataDir + os.sep + "UsageDataTidy.csv"
tidysupplyFN = dataDir + os.sep + "SupplyTableTidy.csv"... |
9,646 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Quiz
Step1: Quiz
Step7: Result
Step8: Quiz
Step9: Quiz
Step11: Quiz | Python Code:
import numpy as np
import pandas
import matplotlib.pyplot as plt
def entries_histogram(turnstile_weather):
'''
Task description is above.
'''
plt.figure()
turnstile_weather['ENTRIESn_hourly'].loc[turnstile_weather['rain'] == 1].hist() # your code here to plot a historgram for hourl... |
9,647 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TEXT
This notebook serves as supporting material for topics covered in Chapter 22 - Natural Language Processing from the book Artificial Intelligence
Step1: CONTENTS
Text Models
Viterbi Tex... | Python Code:
from text import *
from utils import open_data
from notebook import psource
Explanation: TEXT
This notebook serves as supporting material for topics covered in Chapter 22 - Natural Language Processing from the book Artificial Intelligence: A Modern Approach. This notebook uses implementations from text.py.... |
9,648 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
how you can incorporate a preprocessing layer into a classification network and train it using a dataset
| Python Code::
from tensorflow.keras.utils import image_dataset_from_directory
import tensorflow as tf
import matplotlib.pyplot as plt
PATH='.../Citrus/Leaves' # modify to your path
ds = image_dataset_from_directory(PATH,
validation_split=0.2, subset="training",
... |
9,649 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Your first neural network
In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementat... | Python Code:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
Explanation: Your first neural network
In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of t... |
9,650 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Preparation
SciKit
We are using the brand new 0.16.1
Data Preparation
trainLabels.csv is provided by Kaggle, mix_lbp.csv are the features extracted for this learning.
Utilities
Developed to ... | Python Code:
from SupervisedLearning import SKSupervisedLearning
from train_files import TrainFiles
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from sklearn.metrics import log_loss, confusion_matrix
from sklearn.calibration import CalibratedClassifierCV
from tr_utils import vote
impo... |
9,651 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Isentropic Analysis
The MetPy function mpcalc.isentropic_interpolation allows for isentropic analysis from model
analysis data in isobaric coordinates.
Step1: Getting the data
In this examp... | Python Code:
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.pyplot as plt
import numpy as np
import xarray as xr
import metpy.calc as mpcalc
from metpy.cbook import get_test_data
from metpy.plots import add_metpy_logo, add_timestamp
from metpy.units import units
Explanation: Isentropic ... |
9,652 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Analyze Satisfaction Survey Responses
An example demonstration of a typical analysis workflow in DSX leveraging Spark, Watson APIs, Pandas, and various visualization libraries.
<img src='htt... | Python Code:
from IPython.display import HTML
HTML('''<script>
code_show=true;
function code_toggle() {
if (code_show){
$('div.input').hide();
} else {
$('div.input').show();
}
code_show = !code_show
}
$( document ).ready(code_toggle);
</script>
<form action="javascript:code_toggle()"><input type="submit" value... |
9,653 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="images/hanford_variables.png">
1. Import the necessary packages to read in the data, plot, and create a linear regression model
Step1: 2. Read in the hanford.csv file
Step2: 3. C... | Python Code:
import pandas as pd
%matplotlib inline
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
import numpy as np
Explanation: <img src="images/hanford_variables.png">
1. Import the necessary packages to read in the data, plot, and create a linear regression model
End of explanati... |
9,654 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Continued
Step1: More Text Analysis
Step2: Let's analyze the frequency of words that show up in question texts that have __ans__ in the 75th or above percentile
Step3: Since it's an inten... | Python Code:
import pandas as pd
import json
json_data = open('../views/sample/input00.in') # Edit this to where you have put the input00.in file
data = []
for line in json_data:
data.append(json.loads(line))
data.remove(9000)
data.remove(1000)
df = pd.DataFrame(data)
cleaned_df=pd.DataFrame(data[0:9000])
data_df =... |
9,655 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="https
Step1: Étude d'une boucle
Très souvent, on désire faire une action pour chaque élément d'une liste. Par exemple, afficher les carrés des nombres de 1 à 10. Ceci peut être f... | Python Code:
# Exécutez cette cellule !
from IPython.core.display import HTML
styles = "<style>\n.travail {\n background-size: 30px;\n background-image: url('https://cdn.pixabay.com/photo/2018/01/04/16/53/building-3061124_960_720.png');\n background-position: left top;\n background-repeat: no-repeat;\n p... |
9,656 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Effect of cancelling a process zero
The following exercise is taken from Åström & Wittenmark (problem 5.3)
Consider the system with pulse-transfer function
$$ H(z) = \frac{z+0.7}{z^2 - 1.8z... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import control
import sympy as sy
Explanation: Effect of cancelling a process zero
The following exercise is taken from Åström & Wittenmark (problem 5.3)
Consider the system with pulse-transfer function
$$ H(z) = \frac{z+0.7}{z^2 - 1.8z + 0.81}.$$
Use pol... |
9,657 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Intro to Random Forests
About this course
Teaching approach
This course is being taught by Jeremy Howard, and was developed by Jeremy along with Rachel Thomas. Rachel has been dealing with a... | Python Code:
%load_ext autoreload
%autoreload 2
%matplotlib inline
from fastai.imports import *
from fastai.structured import *
from pandas_summary import DataFrameSummary
from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier
from IPython.display import display
from sklearn import metrics
PATH = "d... |
9,658 | Given the following text description, write Python code to implement the functionality described.
Description:
"Given an array representing a branch of a tree that has non-negative integer nodes
your task is to pluck one of the nodes and return it.
The plucked node should be the node with the smallest even ... | Python Code:
def pluck(arr):
if(len(arr) == 0): return []
evens = list(filter(lambda x: x%2 == 0, arr))
if(evens == []): return []
return [min(evens), arr.index(min(evens))] |
9,659 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Trace Analysis
This notebook performs some analysis on the trace files for the initial consensus experiments.
Step1: Trace Visualization
Step2: Experiment Analysis
Some details on the expe... | Python Code:
%matplotlib inline
import os
import re
import csv
import glob
import json
import numpy as np
import pandas as pd
import seaborn as sns
## Load Data
PROPRE = re.compile(r'^trace-(\d+)ms-(\d+)user.tsv$')
TRACES = os.path.join("..", "fixtures", "traces", "trace-*")
def load_trace_data(traces=TRACES, pattern=... |
9,660 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Restore the whole energysystem with results
Step1: Convert keys to strings and print all keys
Step2: Use the outputlib to collect all the flows into and out of the electricity bus
Collect ... | Python Code:
energysystem = solph.EnergySystem()
energysystem.restore(dpath=None, filename=None)
Explanation: Restore the whole energysystem with results
End of explanation
string_results = outputlib.views.convert_keys_to_strings(energysystem.results['main'])
print(string_results.keys())
Explanation: Convert keys to st... |
9,661 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Procedure
Step1: Step 1
Step2: Step 2
Step3: Step 3
Step4: Visualize | Python Code:
import numpy as np
A_det = np.matrix('10 0; -2 100') #A-matrix
B_det = np.matrix('1 10') #B-matrix
f = np.matrix('1000; 0') #Functional unit vector f
g_LCA = B_det * A_det.I * f
print("The deterministic result is:", g_LCA[0,0])
Explanation: Procedure: Global sensitivity analysis f... |
9,662 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step6: Text Classification Using a Convolutional Neural Network on MXNet
This tutorial is based off of Yoon Kim's paper on using convolutional neural networks for scentence sentiment classif... | Python Code:
import urllib2
import numpy as np
import re
import itertools
from collections import Counter
def clean_str(string):
Tokenization/string cleaning for all datasets except for SST.
Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py
string = re.sub(r"[... |
9,663 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Bias on Wikipedia
Todd Schultz
Due
Step1: Import data of politicians by country
Import the data of policitcians by country provided by Oliver Keyes and found at https
Step2: Import populat... | Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import requests
import json
import copy
%matplotlib notebook
Explanation: Bias on Wikipedia
Todd Schultz
Due: November 2, 2017
Bias is an increasing important topic with today's reliance on data and aglorithms. Here, bias in policitical... |
9,664 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
============================================
4D Neuroimaging/BTi phantom dataset tutorial
============================================
Here we read 4DBTi epochs data obtained with a spherica... | Python Code:
# Authors: Alex Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD (3-clause)
import os.path as op
import numpy as np
from mayavi import mlab
from mne.datasets import phantom_4dbti
import mne
Explanation: ============================================
4D Neuroimaging/BTi phantom dataset tutorial
=======... |
9,665 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Methods
Data obtained from the Citizens Police Data Project.
This data includes only the FOIA dataset from 2011 to present (i.e. the Bond and Moore datasets have been removed).
This was acc... | Python Code:
#Record arrays
allegations = read.open_csv_url('https://raw.githubusercontent.com/jamestwhedbee/DataProjects/master/CPDB/Allegations.csv',parse_datetimes=['IncidentDate','StartDate','EndDate'])
citizens = read.open_csv_url('https://raw.githubusercontent.com/jamestwhedbee/DataProjects/master/CPDB/Citizens.c... |
9,666 | 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', 'inm', 'inm-cm5-0', 'toplevel')
Explanation: ES-DOC CMIP6 Model Properties - Toplevel
MIP Era: CMIP6
Institute: INM
Source ID: INM-CM5-0
Sub-Topics: Radiative Forcings.
Properties: 85... |
9,667 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lambda Function and More
<font color='red'>Reference Documents</font>
<OL>
<LI> <A HREF="http
Step1: Lambda as macro
Step2: Map Function
map() is a function with two arguments
Step3: The ... | Python Code:
lambda argument_list: expression
# The argument list consists of a comma separated list of arguments and
# the expression is an arithmetic expression using these arguments.
f = lambda x, y : x + y
f(2,1)
Explanation: Lambda Function and More
<font color='red'>Reference Documents</font>
<OL>
<LI> <A HREF=... |
9,668 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Group sizes
Get all unique size labels from the database.
Step1: Sizes per distributor
Step2: Print joint table with first 60 sizes.
Step3: Calculate entropy
Step4: Create new collection... | Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
from scipy.stats import entropy
from tabulate import tabulate
from pymongo import MongoClient
import matplotlib.pyplot as plt
plt.style.use('seaborn')
plt.rcParams["figure.figsize"] = (20,8)
db = MongoClient()['stores']
TOTAL_NUMBER_OF_PRODUCTS = db... |
9,669 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step2: JoinNode, synchronize and itersource
JoinNode has the opposite effect of iterables. Where iterables split up the execution workflow into many different branches, a JoinNode merges the... | Python Code:
from nipype import JoinNode, Node, Workflow
from nipype.interfaces.utility import Function, IdentityInterface
def get_data_from_id(id):
Generate a random number based on id
import numpy as np
return id + np.random.rand()
def merge_and_scale_data(data2):
Scale the input list by 1000
impo... |
9,670 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step 3
Step1: Load feature data set
We have previously created the labeled feature data set in the Code\2_feature_engineering.ipynb Jupyter notebook. Since the Azure Blob storage account na... | Python Code:
# import the libraries
import os
import glob
import time
# for creating pipelines and model
from pyspark.ml.feature import StringIndexer, OneHotEncoder, VectorAssembler, VectorIndexer
from pyspark.ml import Pipeline, PipelineModel
from pyspark.ml.classification import RandomForestClassifier
from pyspark.ml... |
9,671 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Receptive Field Estimation and Prediction
This example reproduces figures from Lalor et al.'s mTRF toolbox in
MATLAB
Step1: sphinx_gallery_thumbnail_number = 3
Step2: Load the data from t... | Python Code:
# Authors: Chris Holdgraf <choldgraf@gmail.com>
# Eric Larson <larson.eric.d@gmail.com>
# Nicolas Barascud <nicolas.barascud@ens.fr>
#
# License: BSD-3-Clause
Explanation: Receptive Field Estimation and Prediction
This example reproduces figures from Lalor et al.'s mTRF toolbox in
MATLAB ... |
9,672 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Convolutional GANs
In this notebook, you'll build a GAN using convolutional layers in the generator and discriminator. This is called a Deep Convolutional GAN, or DCGAN for short. The D... | Python Code:
# import libraries
import matplotlib.pyplot as plt
import numpy as np
import pickle as pkl
%matplotlib inline
Explanation: Deep Convolutional GANs
In this notebook, you'll build a GAN using convolutional layers in the generator and discriminator. This is called a Deep Convolutional GAN, or DCGAN for short.... |
9,673 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Section 6.4.3
Theis wells introduction
Theis considered the transient flow due to a well with a constant extraction since $t=0$ placed in a uniform confined aquifer of infinite extent.
The s... | Python Code:
from scipy.special import exp1
import numpy as np
import matplotlib.pyplot as plt
Explanation: Section 6.4.3
Theis wells introduction
Theis considered the transient flow due to a well with a constant extraction since $t=0$ placed in a uniform confined aquifer of infinite extent.
The solution may be opbtain... |
9,674 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Feed-forward neural network
This is a simple tutorial on how to train a feed-forward neural network to predict protein subcellular localization.
Step1: Building the network
The first thing ... | Python Code:
# Import all the necessary modules
import os
os.environ["THEANO_FLAGS"] = "mode=FAST_RUN,optimizer=None,device=cpu,floatX=float32"
import sys
sys.path.insert(0,'..')
import numpy as np
import theano
import theano.tensor as T
import lasagne
from confusionmatrix import ConfusionMatrix
from utils import itera... |
9,675 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
VGGNet in Keras
In this notebook, we fit a model inspired by the "very deep" convolutional network VGGNet to classify flowers into the 17 categories of the Oxford Flowers data set. Derived f... | Python Code:
import numpy as np
np.random.seed(42)
Explanation: VGGNet in Keras
In this notebook, we fit a model inspired by the "very deep" convolutional network VGGNet to classify flowers into the 17 categories of the Oxford Flowers data set. Derived from these two earlier notebooks.
Set seed for reproducibility
End... |
9,676 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Build a DNN using the Keras Functional API
Learning objectives
Review how to read in CSV file data using tf.data.
Specify input, hidden, and output layers in the DNN architecture.
Review and... | Python Code:
# You can use any Python source file as a module by executing an import statement in some other Python source file
# The import statement combines two operations; it searches for the named module, then it binds the
# results of that search to a name in the local scope.
import os, json, math
# Import data p... |
9,677 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Project Euler
Step2: Now write a set of assert tests for your number_to_words function that verifies that it is working as expected.
Step4: Now define a count_letters(n) that return... | Python Code:
def number_to_words(n):
Given a number n between 1-1000 inclusive return a list of words for the number.
wrds = []
ones = {1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',
9:'nine',10:'ten', 11:'eleven',12:'twelve',13:'thirteen',14:'fourteen',
15... |
9,678 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<div align="center">
<h2> Méthodes quantitatives en neurosciences </h2>
</div>
<div align="center">
<b><i> Cours NSC-2006, année 2015</i></b><br>
<b>Laboratoire d'analyse de données multid... | Python Code:
%matplotlib inline
from pymatbridge import Matlab
mlab = Matlab()
mlab.start()
%load_ext pymatbridge
Explanation: <div align="center">
<h2> Méthodes quantitatives en neurosciences </h2>
</div>
<div align="center">
<b><i> Cours NSC-2006, année 2015</i></b><br>
<b>Laboratoire d'analyse de données multidime... |
9,679 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Word2Vec using MXNet Gluon API
The goal of this notebook is to show Word2Vec Skipgram implementation with Negative Sampling to train word vectors on the text8 dataset.
Please note that p... | Python Code:
import time
import numpy as np
import logging
import sys, random, time, math
import mxnet as mx
from mxnet import nd
from mxnet import gluon
from mxnet.gluon import Block, nn, autograd
import cPickle
from sklearn.preprocessing import normalize
Explanation: Word2Vec using MXNet Gluon API
The goal of this no... |
9,680 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Spatial Joins
A spatial join uses binary predicates
such as intersects and crosses to combine two GeoDataFrames based on the spatial relationship
between their geometries.
A common use cas... | Python Code:
import os
from shapely.geometry import Point
from geopandas import GeoDataFrame, read_file
from geopandas.tools import overlay
# NYC Boros
zippath = os.path.abspath('nybb_14aav.zip')
polydf = read_file('/nybb_14a_av/nybb.shp', vfs='zip://' + zippath)
# Generate some points
b = [int(x) for x in polydf.total... |
9,681 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Understanding Document Clustering
Clustering is one of the most important Unsupervised Machine Learning Techniques. These algorithms come in handy, especially in situations where labelled da... | Python Code:
import pandas as pd
df = pd.read_csv('tmdb_5000_movies.csv.gz',
compression='gzip')
df.info()
df.head()
df = df[['title', 'tagline', 'overview', 'genres', 'popularity']]
df.tagline.fillna('', inplace=True)
df['description'] = df['tagline'].map(str) + ' ' + df['overview']
df.dropna(inplace... |
9,682 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Arduino Joystick Shield Example
This example shows how to use the Sparkfun Joystick
on the board. The Joystick shield contains an analog joystick which is
connected to A0 and A1 analog cha... | Python Code:
from pynq.overlays.base import BaseOverlay
base = BaseOverlay("base.bit")
Explanation: Arduino Joystick Shield Example
This example shows how to use the Sparkfun Joystick
on the board. The Joystick shield contains an analog joystick which is
connected to A0 and A1 analog channels of the Arduino connector... |
9,683 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Detached Binary
Step1: As always, let's do imports and initialize a logger and a new bundle.
Step2: Adding Datasets
Now we'll create an empty mesh dataset at quarter-phase so we can compar... | Python Code:
#!pip install -I "phoebe>=2.4,<2.5"
Explanation: Detached Binary: Roche vs Rotstar
Setup
Let's first make sure we have the latest version of PHOEBE 2.4 installed (uncomment this line if running in an online notebook session such as colab).
End of explanation
import phoebe
from phoebe import u # units
impor... |
9,684 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
What country are most billionaires from? For the top ones, how many billionaires per billion people?
Step1: Who are the top 10 richest billionaires?
Step2: What's the average wealth of a b... | Python Code:
df['citizenship'].value_counts().head()
df.groupby('citizenship')['networthusbillion'].sum().sort_values(ascending=False)
us_pop = 318.9 #billion (2014)
us_bill = df[df['citizenship'] == 'United States']
print("There are", us_pop/len(us_bill), "billionaires per billion people in the United States.")
germ_... |
9,685 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This is a python / R implementation for spatial analysis of radar rainfall fields. All courtesy for the R code implementation goes to Marc Schleiss
Notes before running
Step1: Inside the R... | Python Code:
from rpy2.robjects.packages import importr
from rpy2.robjects import r
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: This is a python / R implementation for spatial analysis of radar rainfall fields. All courtesy for the R code implementation goes t... |
9,686 | 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... |
9,687 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Create Two Vectors
Step2: Calculate Dot Product (Method 1)
Step3: Calculate Dot Product (Method 2) | Python Code:
# Load library
import numpy as np
Explanation: Title: Calculate Dot Product Of Two Vectors
Slug: calculate_dot_product_of_two_vectors
Summary: How to calculate the dot product of two vectors in Python.
Date: 2017-09-02 12:00
Category: Machine Learning
Tags: Vectors Matrices Arrays
Authors: Chris Albo... |
9,688 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Prediction (out of sample)
Step1: Artificial data
Step2: Estimation
Step3: In-sample prediction
Step4: Create a new sample of explanatory variables Xnew, predict and plot
Step5: Plot co... | Python Code:
%matplotlib inline
from __future__ import print_function
import numpy as np
import statsmodels.api as sm
Explanation: Prediction (out of sample)
End of explanation
nsample = 50
sig = 0.25
x1 = np.linspace(0, 20, nsample)
X = np.column_stack((x1, np.sin(x1), (x1-5)**2))
X = sm.add_constant(X)
beta = [5., 0.... |
9,689 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The seminator() function can also perform complementation of automata. This works by converting the input into a semi-deterministic TBA, and then applying the NCSB construction, that produc... | Python Code:
f = spot.formula('G(a | (b U (Gc | Gd)))')
aut = f.translate(); aut
neg1 = seminator(aut, complement="spot"); neg1
neg2 = seminator(aut, complement="pldi"); neg2
nf = spot.formula_Not(f)
assert neg1.equivalent_to(nf)
assert neg2.equivalent_to(nf)
Explanation: The seminator() function can also perform compl... |
9,690 | 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 ... |
9,691 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Objects and Data Structures Assessment Test
Test your knowledge.
Answer the following questions
Write a brief description of all the following Object Types and Data Structures we've learne... | Python Code:
print 10*100/10+5.75-5.5
Explanation: Objects and Data Structures Assessment Test
Test your knowledge.
Answer the following questions
Write a brief description of all the following Object Types and Data Structures we've learned about:
Numbers:
Strings:
Lists:
Tuples:
Dictionaries:
Numbers
Write an equat... |
9,692 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Testing look-elsewhere effect by creating 2d chi-square random fields with a Gaussian Process
by Kyle Cranmer, Dec 7, 2015
The correction for 2d look-elsewhere effect presented in
Estimatin... | Python Code:
%pylab inline --no-import-all
Explanation: Testing look-elsewhere effect by creating 2d chi-square random fields with a Gaussian Process
by Kyle Cranmer, Dec 7, 2015
The correction for 2d look-elsewhere effect presented in
Estimating the significance of a signal in a multi-dimensional search by Ofer Vite... |
9,693 | Given the following text description, write Python code to implement the functionality described.
Description:
Write a function that returns true if the given number is the multiplication of 3 prime numbers
and false otherwise.
Knowing that (a) is less then 100.
Example:
is_multiply_prime(30) == True
... | Python Code:
def is_multiply_prime(a):
def is_prime(n):
for j in range(2,n):
if n%j == 0:
return False
return True
for i in range(2,101):
if not is_prime(i): continue
for j in range(2,101):
if not is_prime(j): continue
for ... |
9,694 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Matplotlib Exercise 3
Imports
Step2: Contour plots of 2d wavefunctions
The wavefunction of a 2d quantum well is
Step3: The contour, contourf, pcolor and pcolormesh functions of Matplotlib ... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
Explanation: Matplotlib Exercise 3
Imports
End of explanation
def well2d(x, y, nx, ny, L=1.0):
Compute the 2d quantum well wave function.
xcoord, ycoord = np.meshgrid(x,y)
xpor = np.sin((nx*np.pi*xcoord)/L)
ypor = np.sin(... |
9,695 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2016.12.09 - work log - prelim_month - no single names
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Table-of-Contents" da... | Python Code:
import datetime
print( "packages imported at " + str( datetime.datetime.now() ) )
%pwd
Explanation: 2016.12.09 - work log - prelim_month - no single names
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Table-of-Contents" data-toc-modified-i... |
9,696 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A simple (ie. no error checking or sensible engineering) notebook to extract the student answer data from an xml file.
I'm not 100% sure what we actually need for the moment, so I'm just go... | Python Code:
filename='semeval2013-task7/semeval2013-Task7-5way/beetle/train/Core/FaultFinding-BULB_C_VOLTAGE_EXPLAIN_WHY1.xml'
import pandas as pd
from xml.etree import ElementTree as ET
tree=ET.parse(filename)
Explanation: A simple (ie. no error checking or sensible engineering) notebook to extract the student answer... |
9,697 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
An example of GEANT4 in IPython
Version 0.1, released 18/11/2014, alpha
This is a rough example of what can be done within IPython notebook with the GEANT4 python environment. Currently this... | Python Code:
%pylab inline
from Geant4 import *
from IPython.display import Image
Explanation: An example of GEANT4 in IPython
Version 0.1, released 18/11/2014, alpha
This is a rough example of what can be done within IPython notebook with the GEANT4 python environment. Currently this "linac head" is made of just a vac... |
9,698 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
.. _tut_raw_objects
Step1: Continuous data is stored in objects of type
Step2: Information about the channels contained in the
Step3: You can also pass an index directly to the
Step4: ... | Python Code:
from __future__ import print_function
import mne
import os.path as op
from matplotlib import pyplot as plt
Explanation: .. _tut_raw_objects:
The :class:Raw <mne.io.Raw> data structure: continuous data
End of explanation
# Load an example dataset, the preload flag loads the data into memory now
data_p... |
9,699 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<span style="color
Step1: Simulate data under a specified model
We are interested in estimating the Ne and divergence time values on this tree.
Step2: True measurements that will inform ou... | Python Code:
# conda install ipyrad -c conda-forge -c bioconda
# conda install ipcoal -c conda-forge
# conda install bpp -c conda-forge -c eaton-lab
import ipyrad.analysis as ipa
import pandas as pd
import numpy as np
import toytree
import toyplot
import ipcoal
Explanation: <span style="color:gray">ipyrad-analysis too... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.