Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
4,300 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Levy Stable models of Stochastic Volatility
This tutorial demonstrates inference using the Levy Stable distribution through a motivating example of a non-Gaussian stochastic volatilty model.... | Python Code:
import math
import os
import torch
import pyro
import pyro.distributions as dist
from matplotlib import pyplot
from torch.distributions import constraints
from pyro import poutine
from pyro.contrib.examples.finance import load_snp500
from pyro.infer import EnergyDistance, Predictive, SVI, Trace_ELBO
from p... |
4,301 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1> Getting started with TensorFlow </h1>
In this notebook, you play around with the TensorFlow Python API.
Step1: <h2> Adding two tensors </h2>
First, let's try doing this using numpy, th... | Python Code:
import tensorflow as tf
import numpy as np
print(tf.__version__)
Explanation: <h1> Getting started with TensorFlow </h1>
In this notebook, you play around with the TensorFlow Python API.
End of explanation
a = np.array([5, 3, 8])
b = np.array([3, -1, 2])
c = np.add(a, b)
print(c)
Explanation: <h2> Adding t... |
4,302 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Automating the Analysis HIV Immunogen Antigenic Characteristics
(Alt Title
Step1: (1) Demo Script | Python Code:
#This is the MSD .txt output file I'll be working with:
data = open('data.txt')
data.read()
Explanation: Automating the Analysis HIV Immunogen Antigenic Characteristics
(Alt Title: I'm getting lazy)
Michael Chambers
What I Do: A lotta quality control for HIV Immunogens
Objective: Automate the data analysis... |
4,303 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Iowa State Liquor Sale Projection
The goal for this task was to provide a projection of liquor sales in the state of Iowa based on a dataset of sales of liquor from distributors to individua... | Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import StandardScaler
import statsmodels.api as sm
from sklearn.cross_validation import train_test_split
from sklearn.linear_model import LogisticRegression, LinearRegression
from sklearn... |
4,304 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Working on new API
The clustergrammer_widget class is now being loaded into the Network class. The class and widget instance are saved in th Network instance, net. This allows us to load dat... | Python Code:
import numpy as np
import pandas as pd
from clustergrammer_widget import *
net = Network(clustergrammer_widget)
Explanation: Working on new API
The clustergrammer_widget class is now being loaded into the Network class. The class and widget instance are saved in th Network instance, net. This allows us to ... |
4,305 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Byte 4
Step1: Custom functions and global variables
Step2: Dataset
Step3: Next, read the two documents describing the dataset (data/ACS2015_PUMS_README.pdf and data/PUMSDataDict15.txt) an... | Python Code:
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import pickle
import os
from IPython.display import Image
from IPython.display import display
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
... |
4,306 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Learning curve
Table of contents
Data preprocessing
Fitting random forest
Feature importance
Step1: Data preprocessing
Load simulation dataframe and apply specified quality cuts
Extract des... | Python Code:
import sys
sys.path.append('/home/jbourbeau/cr-composition')
print('Added to PYTHONPATH')
import argparse
from collections import defaultdict
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import seaborn.apionly as sns
from sklearn.metric... |
4,307 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="../static/images/joinnode.png" width="240">
JoinNode
JoinNode have the opposite effect of a MapNode or iterables. Where they split up the execution workflow into many different br... | Python Code:
from nipype import Node, JoinNode, Workflow
# Specify fake input node A
a = Node(interface=A(), name="a")
# Iterate over fake node B's input 'in_file?
b = Node(interface=B(), name="b")
b.iterables = ('in_file', [file1, file2])
# Pass results on to fake node C
c = Node(interface=C(), name="c")
# Join forked... |
4,308 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Proton Titration of a Rigid Body in Explicit Salt Solution
This will simulate proton equilibria in a rigid body composed of particles in a spherical simulation container. We use a continuum ... | Python Code:
from __future__ import division, unicode_literals, print_function
import matplotlib as mpl
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np, pandas as pd
import os.path, os, sys, json, filecmp, copy
plt.rcParams.update({'font.size': 16, 'figure.figsize': [8.0, 6.0]})
try:
workdir
e... |
4,309 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Flow rate waveform transformation
Arjan Geers
An artery's flow rate waveform (FRW) can be characterized in many ways. Three common descriptors are the heart rate (HR), pulsatility index (PI)... | Python Code:
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from ipywidgets import interact, IntSlider, FloatSlider
%matplotlib inline
Explanation: Flow rate waveform transformation
Arjan Geers
An artery's flow rate waveform (FRW) can be characterized in many ways. Three common descrip... |
4,310 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1 align="center">TensorFlow Neural Network Lab</h1>
<img src="image/notmnist.png">
In this lab, you'll use all the tools you learned from Introduction to TensorFlow to label images of Engl... | Python Code:
import hashlib
import os
import pickle
from urllib.request import urlretrieve
import numpy as np
from PIL import Image
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelBinarizer
from sklearn.utils import resample
from tqdm import tqdm
from zipfile import ZipFile
p... |
4,311 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plot Kmeans clusters stored in a GeoTiff
This is a notebook plots the GeoTiffs created out of kmeans. Such GeoTiffs contains the Kmeans cluster IDs.
Dependencies
Step1: Spark Context
Step2:... | Python Code:
import sys
sys.path.append("/usr/lib/spark/python")
sys.path.append("/usr/lib/spark/python/lib/py4j-0.10.4-src.zip")
sys.path.append("/usr/lib/python3/dist-packages")
import os
os.environ["HADOOP_CONF_DIR"] = "/etc/hadoop/conf"
import os
os.environ["PYSPARK_PYTHON"] = "python3"
os.environ["PYSPARK_DRIVER_P... |
4,312 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A Sinous Violin
The aim of this short notebook is to show how to use NumPy and SciPy to play with spectral audio signal analysis (and synthesis).
Lots of prior knowledge is assumed, and her... | Python Code:
%matplotlib inline
from IPython.display import Audio
import librosa
import matplotlib.pyplot as plt
import numpy as np
import scipy as sp
plt.rcParams['figure.figsize'] = 8, 4
plt.style.use('ggplot')
Explanation: A Sinous Violin
The aim of this short notebook is to show how to use NumPy and SciPy to play w... |
4,313 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Named Topologies
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step1: TiltedSquareLattice
This is a grid lattice rotated 45-degrees.
This topol... | Python Code:
try:
import cirq
except ImportError:
print("installing cirq...")
!pip install --quiet cirq --pre
print("installed cirq.")
import cirq
from typing import Iterable, List, Optional, Sequence
import matplotlib.pyplot as plt
import numpy as np
import networkx as nx
Explanation: Named Topolo... |
4,314 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
AutoML SDK
Step1: Install the Google cloud-storage library as well.
Step2: Restart the Kernel
Once you've installed the AutoML SDK and Google cloud-storage, you need to restart the noteboo... | Python Code:
! pip3 install -U google-cloud-automl --user
Explanation: AutoML SDK: AutoML video object tracking model
Installation
Install the latest (preview) version of AutoML SDK.
End of explanation
! pip3 install google-cloud-storage
Explanation: Install the Google cloud-storage library as well.
End of explanation
... |
4,315 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Prepare Tidy CVC Datasets (with SWMM model hydrology)
Setup the basic working environment
Step1: Load External Data (this takes a while)
Step2: Load CVC Database
Step3: Hydrologic Relatio... | Python Code:
%matplotlib inline
import os
import sys
import datetime
import warnings
import csv
import numpy as np
import matplotlib.pyplot as plt
import pandas
import seaborn
seaborn.set(style='ticks', context='paper')
import wqio
import pybmpdb
import pynsqd
import pycvc
min_precip = 1.9999
big_storm_date = datetime.... |
4,316 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Create an example dataframe
Step2: Grab rows based on column values | Python Code:
# Import modules
import pandas as pd
# Set ipython's max row display
pd.set_option('display.max_row', 1000)
# Set iPython's max column width to 50
pd.set_option('display.max_columns', 50)
Explanation: Title: Select Rows When Columns Contain Certain Values
Slug: pandas_select_rows_when_column_has_certain_va... |
4,317 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SPADE Tutorial
Step1: Generate correlated data
SPADE is a method to detect repeated spatio-temporal activity patterns in parallel spike train data that occur in excess to chance expectation... | Python Code:
import numpy as np
import quantities as pq
import neo
import elephant
import viziphant
np.random.seed(4542)
Explanation: SPADE Tutorial
End of explanation
spiketrains = elephant.spike_train_generation.compound_poisson_process(
rate=5*pq.Hz, A=[0]+[0.98]+[0]*8+[0.02], t_stop=10*pq.s)
len(spiketrains)
Exp... |
4,318 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Estimating Work Tour Scheduling
This notebook illustrates how to re-estimate the mandatory tour scheduling component for ActivitySim. This process
includes running ActivitySim in estimatio... | Python Code:
import os
import larch # !conda install larch -c conda-forge # for estimation
import pandas as pd
Explanation: Estimating Work Tour Scheduling
This notebook illustrates how to re-estimate the mandatory tour scheduling component for ActivitySim. This process
includes running ActivitySim in estimation mod... |
4,319 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Runtime Analysis
using Finding the nth Fibonacci numbers as a computational object to think with
Step1: Fibonacci
Excerpt from Algorithms by S. Dasgupta, C.H. Papadimitriou, and U.V. Vazira... | Python Code:
%pylab inline
# Import libraries
from __future__ import absolute_import, division, print_function
import math
from time import time
import matplotlib.pyplot as pyplt
Explanation: Runtime Analysis
using Finding the nth Fibonacci numbers as a computational object to think with
End of explanation
from IPython... |
4,320 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Indic NLP Library
The goal of the Indic NLP Library is to build Python based libraries for common text processing and Natural Language Processing in Indian languages. Indian languages share ... | Python Code:
# The path to the local git repo for Indic NLP library
INDIC_NLP_LIB_HOME="e:\indic_nlp_library"
# The path to the local git repo for Indic NLP Resources
INDIC_NLP_RESOURCES="e:\indic_nlp_resources"
Explanation: Indic NLP Library
The goal of the Indic NLP Library is to build Python based libraries for comm... |
4,321 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Número de datos obtenidos y perdidos
Importamos las librerías necesarias
Step1: Importamos las librerías creadas para trabajar
Step2: Generamos los datasets de todos los días
Notas
Step3: ... | Python Code:
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Número de datos obtenidos y perdidos
Importamos las librerías necesarias
End of explanation
import ext_datos as ext
import procesar as pro
import time_plot as tplt
Explanation: Importamos las librerías creadas para trabajar... |
4,322 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SysKey Registry Keys Access
Metadata
| Metadata | Value |
|
Step1: Download & Process Security Dataset
Step2: Analytic I
Look for handle requests and access operations to specif... | Python Code:
from openhunt.mordorutils import *
spark = get_spark()
Explanation: SysKey Registry Keys Access
Metadata
| Metadata | Value |
|:------------------|:---|
| collaborators | ['@Cyb3rWard0g', '@Cyb3rPandaH'] |
| creation date | 2019/06/25 |
| modification date | 2020/09/20 |
| playbook relat... |
4,323 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Compute induced power in the source space with dSPM
Returns STC files ie source estimates of induced power
for different bands in the source space. The inverse method
is linear based on dSPM... | Python Code:
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD-3-Clause
import matplotlib.pyplot as plt
import mne
from mne import io
from mne.datasets import sample
from mne.minimum_norm import read_inverse_operator, source_band_induced_power
print(__doc__)
Explanation: Compute induced power... |
4,324 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Import required modules
Step1: Set image and catalogue filenames
Step2: Load in images, noise maps, header info and WCS information
Step3: Load in catalogue you want to fit (and make any ... | Python Code:
from astropy.io import ascii, fits
import pylab as plt
%matplotlib inline
from astropy import wcs
import numpy as np
import xidplus
from xidplus import moc_routines
import pickle
Explanation: Import required modules
End of explanation
#Folder containing maps
pswfits='/Users/pdh21/astrodata/COSMOS/P4/COSMOS... |
4,325 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Testing Algorithm Performance in Off-Policy Setting
Step1: Assessing Learning Algorithms
In theory, it is possible to solve for the value function sought by the learning algorithms directly... | Python Code:
%load_ext autoreload
%autoreload 2
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import algos
import features
import parametric
import policy
import chicken
from agents import OffPolicyAgent, OnPolicyAgent
from rlbench import *
Explanation: Testing Algorithm Performance in Off-Polic... |
4,326 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
That looks like the best way to represent the data if we want to calculate the $R^2$ distance on a per-symbol basis. I could add it to the single val function.
Step1: Now, let's implement t... | Python Code:
def run_single_val(x, y, ahead_days, estimator):
multiindex = x.index.nlevels > 1
x_y = pd.concat([x, y], axis=1)
x_y_sorted = x_y.sort_index()
if multiindex:
x_y_train = x_y_sorted.loc[:fe.add_market_days(x_y_sorted.index.levels[0][-1], -ahead_days)]
x_y_val = x_y_sort... |
4,327 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MNIST ML Pros tutorial
This notebook is based on the tutorial found here
This tutorial is very similar to the beginners tutorial except for some incremental improvements added to the end to ... | Python Code:
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/data/MNIST/",one_hot=True)
sess = tf.InteractiveSession()
Explanation: MNIST ML Pros tutorial
This notebook is based on the tutorial found here
This tutorial is very similar to the beginne... |
4,328 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Consume native Keras model served by TF-Serving
This notebook shows client code needed to consume a native Keras model served by Tensorflow serving. The Tensorflow serving model needs to be ... | Python Code:
from __future__ import division, print_function
from google.protobuf import json_format
from grpc.beta import implementations
from sklearn.preprocessing import OneHotEncoder
from tensorflow_serving.apis import predict_pb2
from tensorflow_serving.apis import prediction_service_pb2
from sklearn.metrics impor... |
4,329 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep learning
Driven by practicality as we are for the purpose of this course, we will dwelve directly into an example of using DL. We will gradually learn more things as we do things.
Most ... | Python Code:
import tensorflow as tf
from tensorflow.keras.datasets import mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
print(train_images.shape)
print(train_labels.shape)
# reshape (flatten) and scale images
train_images = train_images.reshape((60000, 28 * 28))
train_images = trai... |
4,330 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Minería de Texto
La minería de texto es el proceso de obtener información de alta calidad a partir del texto.
¿Qué clase de información?
-Palabras Clave
Step1: Segundo paso, obtener el con... | Python Code:
def testFacebookPageFeedData(page_id, access_token):
# construct the URL string
base = "https://graph.facebook.com/v2.10"
node = "/" + page_id + "/feed" # changed
parameters = "/?fields=message,created_time,reactions.type(LOVE).limit(0).summary(total_count).as(reactions_love),reactions... |
4,331 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
------------- User's settings -------------
Step1: ------------- (semi)-Automatic -------------
Step2: Configure GPU/CPU devices
Step3: Load data
Step4: Stack single-channel images (maxi... | Python Code:
# Location of digested data
input_directory = '/digested/'
# Desired location to save temporary PNG outputs:
png_directory = '/digested_png/'
# Location of saved trained model
model_directory = '/model_directory/'
# Desired location for outputs
output_directory = '/output_directory_transferred/'
# Define n... |
4,332 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Custom Image Augmentations with BaseImageAugmentationLayer
Author
Step1: First, let's implement some helper functions to visualize intermediate results
Step2: BaseImageAugmentationLayer In... | Python Code:
import tensorflow as tf
from tensorflow import keras
import keras_cv
from tensorflow.keras import layers
from keras_cv import utils
from keras_cv.layers import BaseImageAugmentationLayer
import matplotlib.pyplot as plt
tf.autograph.set_verbosity(0)
Explanation: Custom Image Augmentations with BaseImageAugm... |
4,333 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Secondary structure prediction
Proteins have four levels of structure
Step1: Training GOR III
We can now create our GOR3 instance and train it with the extracted training data
Step2: Predi... | Python Code:
datasetPath = joinpath("resources", "dataset")
with open(joinpath(datasetPath, "CATH_info.txt")) as infoFile:
with open(joinpath(datasetPath, "CATH_info-PARSED.txt"), 'w') as outFile:
dsspPath = joinpath(datasetPath, "dssp", "")
for line in infoFile.readlines():
d = DSSP(dsspPath + line[0:4] + ".ds... |
4,334 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the Licens... | Python Code:
!git clone https://github.com/google-research/google-research.git
# install tensorflow_model_optimization
!pip install tensorflow_model_optimization
import sys
import os
import tarfile
import urllib
import zipfile
sys.path.append('./google-research')
Explanation: Copyright 2019 Google LLC
Licensed under th... |
4,335 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
M-Estimators for Robust Linear Modeling
Step1: An M-estimator minimizes the function
$$Q(e_i, \rho) = \sum_i~\rho \left (\frac{e_i}{s}\right )$$
where $\rho$ is a symmetric function of the... | Python Code:
%matplotlib inline
from __future__ import print_function
from statsmodels.compat import lmap
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
import statsmodels.api as sm
Explanation: M-Estimators for Robust Linear Modeling
End of explanation
norms = sm.robust.norms
def plot_weigh... |
4,336 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Intrusive Galerkin
When talking about polynomial chaos expansions, there are typically two
categories methods that are used
Step1: Here the parameters are positional defined as $\alpha$ and... | Python Code:
from problem_formulation import joint
joint
Explanation: Intrusive Galerkin
When talking about polynomial chaos expansions, there are typically two
categories methods that are used: non-intrusive and intrusive methods. The
distinction between the two categories lies in how one tries to solve the
problem at... |
4,337 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example of online analysis using OnACID
Complete pipeline for online processing using CaImAn Online (OnACID).
The demo demonstates the analysis of a sequence of files using the CaImAn online... | Python Code:
try:
if __IPYTHON__:
# this is used for debugging purposes only. allows to reload classes when changed
get_ipython().magic('load_ext autoreload')
get_ipython().magic('autoreload 2')
except NameError:
pass
import logging
import numpy as np
logging.basicConfig(format=
... |
4,338 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Reading Excel files
This notebook demonstrates how to read and manipulate data from
Excel using Pandas
Step1: Get IRS data on businesses
The IRS website has some aggregated statistics on bu... | Python Code:
# The library for handling tabular data is called 'pandas'
# Everyone shortens this to 'pd' for convenience.
import pandas as pd
Explanation: Reading Excel files
This notebook demonstrates how to read and manipulate data from
Excel using Pandas:
Input / Output
summaries
plotting
First, import the Pandas li... |
4,339 | 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', 'cas', 'fgoals-g3', 'toplevel')
Explanation: ES-DOC CMIP6 Model Properties - Toplevel
MIP Era: CMIP6
Institute: CAS
Source ID: FGOALS-G3
Sub-Topics: Radiative Forcings.
Properties: 85... |
4,340 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Convolutional Networks
So far we have worked with deep fully-connected networks, using them to explore different optimization strategies and network architectures. Fully-connected net... | Python Code:
# As usual, a bit of setup
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
from cs231n.classifiers.cnn import *
from cs231n.data_utils import get_CIFAR10_data
from cs231n.gradient_check import eval_numerical_gradient_array, eval_numerical_gradient
from cs231n.layers... |
4,341 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Machine Learning
Machine Learning is a set of algorithms to enable computers to make and improve predictions or behaviors based on some data. This ability is not explicitly programmed. It in... | Python Code:
from IPython.core.display import Image, display
display(Image(filename='Reg1.png'))
display(Image(filename='Reg2.png'))
from IPython.core.display import Image, display
display(Image(filename='Cluster0.png'))
display(Image(filename='Cluster1.png'))
Explanation: Machine Learning
Machine Learning is a set of ... |
4,342 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a id='top'> </a>
Author
Step1: Cosmic-ray composition spectrum analysis
Table of contents
Define analysis free parameters
Data preprocessing
Fitting random forest
Fraction correctly identi... | Python Code:
%load_ext watermark
%watermark -u -d -v -p numpy,matplotlib,scipy,pandas,sklearn,mlxtend
Explanation: <a id='top'> </a>
Author: James Bourbeau
End of explanation
%matplotlib inline
from __future__ import division, print_function
from collections import defaultdict
import itertools
import numpy as np
from s... |
4,343 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Adding Custom Operator Steps in Integration Schemes
In addition to forces that modify particle accelerations every timestep, we can use REBOUNDx to add operations that happen before and/or a... | Python Code:
import rebound
import reboundx
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
def makesim():
sim = rebound.Simulation()
sim.G = 4*np.pi**2
sim.add(m=1.)
sim.add(m=1.e-4, a=1.)
sim.add(m=1.e-4, a=1.5)
sim.move_to_com()
return sim
Explanation: Adding Custom ... |
4,344 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Numpy Exercise 4
Imports
Step1: Complete graph Laplacian
In discrete mathematics a Graph is a set of vertices or nodes that are connected to each other by edges or lines. If those edges don... | Python Code:
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
Explanation: Numpy Exercise 4
Imports
End of explanation
import networkx as nx
K_5=nx.complete_graph(5)
nx.draw(K_5)
Explanation: Complete graph Laplacian
In discrete mathematics a Graph is a set of vertices or node... |
4,345 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Convolutional Weights and Bias
Weight Shape
Step1: Bias Shape
Step2: Convolutional Layers
Step3: Activation Shape
Step4: Activation2 Shape
Step5: Fully Connected Layer
The output of a C... | Python Code:
# 3 x 3 filter shape
filter1 = [
[.1, .1, .2],
[.1, .1, .2],
[.2, .2, .2],
]
# Each filter only has one input channel (grey scale)
# 3 x 3 x 1
channel_filters1 = [filter1]
# We want to output 2 channels which requires another set of 3 x 3 x 1
filter2 = [
[.9, .5, .9],
[.5, .3, .5],
... |
4,346 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Coal production in mines 2013
by
Step1: Cleaned Data
We cleaned this data in the notebook stored in
Step2: Predict the Production of coal mines
Step3: Random Forest Regressor | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from sklearn.cross_validation import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import explained_variance_score, r2_score, mean_squared_error
sns.set... |
4,347 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TLE matching for Lucky-7 among the TLEs for 2019-038 launch using on-board GPS data.
Step2: SpaceTrack latest TLEs for objects 44387 - 44419 retrieved on 2019-07-25.
Step3: Load Lucky-7 GP... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from skyfield.sgp4lib import EarthSatellite
from skyfield.constants import AU_KM, DAY_S
from skyfield.functions import length_of
import skyfield.api
import tabulate
from IPython.display import HTML, display
import datetime
import astropy... |
4,348 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Verify producing the sames results.
Step1: General timing
Step2: API testing, making the same method calls and verifying results. Intentionally doing the full matrix in the (very unexpecte... | Python Code:
import numpy.testing as npt
ids, otu_ids, otu_data, t = get_random_samples(10, tree, True)
fu_mat = make_and_run_pw_distances(unifrac, otu_data, otu_ids=otu_ids, tree=t)
u_mat = pw_distances(unweighted_unifrac, otu_data, otu_ids=otu_ids, tree=t)
fwu_mat = make_and_run_pw_distances(w_unifrac, otu_data, otu_... |
4,349 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to PyMC3
Probabilistic programming (PP) allows flexible specification of Bayesian statistical models in code. PyMC3 is a new, open-source PP framework with an intuitive and read... | Python Code:
%load ../data/melanoma_data.py
%matplotlib inline
import seaborn as sns; sns.set_context('notebook')
from pymc3 import Normal, Model, DensityDist, sample, log, exp
with Model() as melanoma_survival:
# Convert censoring indicators to indicators for failure event
failure = (censored==0).astype(int)
... |
4,350 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dual Momentum Sector Rotation (DMSR)
'Relative momentum looks at price strength with respect to other assets.
Absolute momentum uses an asset’s own past performance to infer future
performan... | Python Code:
import datetime
import matplotlib.pyplot as plt
import pandas as pd
import pinkfish as pf
import strategy
# Format price data.
pd.options.display.float_format = '{:0.2f}'.format
%matplotlib inline
# Set size of inline plots.
'''note: rcParams can't be in same cell as import matplotlib
or %matplotlib inl... |
4,351 | 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', 'ipsl', 'sandbox-2', 'ocean')
Explanation: ES-DOC CMIP6 Model Properties - Ocean
MIP Era: CMIP6
Institute: IPSL
Source ID: SANDBOX-2
Topic: Ocean
Sub-Topics: Timestepping Framework, Ad... |
4,352 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 Google Inc.
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 Licen... | Python Code:
%%bash
pip3 install git+https://github.com/GoogleCloudPlatform/healthcare.git#subdirectory=imaging/ml/toolkit
pip3 install dicomweb-client
pip3 install pydicom
Explanation: Copyright 2018 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in complia... |
4,353 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Learning
Assignment 2
Previously in 1_notmnist.ipynb, we created a pickle with formatted datasets for training, development and testing on the notMNIST dataset.
The goal of this assignm... | Python Code:
# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
from __future__ import print_function
import numpy as np
import tensorflow as tf
from six.moves import cPickle as pickle
from six.moves import range
Explanation: Deep Learning
Assignment 2
Previousl... |
4,354 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: Simple audio recognition
Step2: Import the mini Speech Commands dataset
To save time with data loading, you will be working with a smaller ver... | 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... |
4,355 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Linear Regression
Step1: Following the steps prescribed by Jake Vanderplas in his awesome text Python Data Science Handbook. He has kindly provided all his codes on github as well.
Step 1. ... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
X = np.random.rand(100)
y = X + 0.1 * np.random.randn(100)
plt.scatter(X, y);
plt.show()
Explanation: Linear Regression
End of explanation
from sklearn.linear_model import LinearRegression
Explanation: Following the steps prescribed b... |
4,356 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
(quickstart)=
Quickstart
Step1: The easiest way to get started with using emcee is to use it for a project. To get you started, here’s an annotated, fully-functional example that demonstrat... | Python Code:
%config InlineBackend.figure_format = "retina"
from matplotlib import rcParams
rcParams["savefig.dpi"] = 100
rcParams["figure.dpi"] = 100
rcParams["font.size"] = 20
Explanation: (quickstart)=
Quickstart
End of explanation
import numpy as np
Explanation: The easiest way to get started with using emcee is to... |
4,357 | Given the following text description, write Python code to implement the functionality described.
Description:
A simple program which should return the value of x if n is
a prime number and should return the value of y otherwise.
Examples:
for x_or_y(7, 34, 12) == 34
for x_or_y(15, 8, 5) == 5
| Python Code:
def x_or_y(n, x, y):
if n == 1:
return y
for i in range(2, n):
if n % i == 0:
return y
break
else:
return x |
4,358 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Landice
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'ipsl', 'sandbox-2', 'landice')
Explanation: ES-DOC CMIP6 Model Properties - Landice
MIP Era: CMIP6
Institute: IPSL
Source ID: SANDBOX-2
Topic: Landice
Sub-Topics: Glaciers, Ice.
Prop... |
4,359 | 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-3', 'toplevel')
Explanation: ES-DOC CMIP6 Model Properties - Toplevel
MIP Era: CMIP6
Institute: NIWA
Source ID: SANDBOX-3
Sub-Topics: Radiative Forcings.
Properties: ... |
4,360 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data Analysis in High Energy Physics
Step1: Two-tailed $p$-value
As for the two-tailed Gaussian,
$\displaystyle p(x) = P(\left|X\right| \geq x) = 1-\text{erf}\left(\frac{x}{\sqrt{2}\sigma}\... | Python Code:
import math
import numpy as np
from scipy import special as special
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
from prettytable import PrettyTable
Explanation: Data Analysis in High Energy Physics: Exercise 1.5 $p$-values
Find the number of standard deviations corresp... |
4,361 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exercises
Q 1
When talking about floating point, we discussed machine epsilon, $\epsilon$—this is the smallest number that when added to 1 is still different from 1.
We'll compute $\ep... | Python Code:
import random
random_number = random.randint(0,9)
Explanation: Exercises
Q 1
When talking about floating point, we discussed machine epsilon, $\epsilon$—this is the smallest number that when added to 1 is still different from 1.
We'll compute $\epsilon$ here:
Pick an initial guess for $\epsilon$ of e... |
4,362 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
Blocking is typically done to reduce the number of tuple pairs considered for matching. There are several blocking methods proposed. The py_entitymatching package supports a sub... | Python Code:
%load_ext autotime
# Import py_entitymatching package
import py_entitymatching as em
import os
import pandas as pd
Explanation: Introduction
Blocking is typically done to reduce the number of tuple pairs considered for matching. There are several blocking methods proposed. The py_entitymatching package sup... |
4,363 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
22/10
Entrada y salida de datos
Funciones (parámetros por default, nombrados), módulos (distintas formas de importarlos)
CLASE DE LABORATORIO
Vencimiento TP1
Enunciado del TP 2
Funciones
Un... | Python Code:
def sumar(x, y): # Defino la función sumar
return x + y
x = 4
z = 5
print sumar(x, z) # Invoco a la función sumar con los parámetros x y z
print sumar(1, 2) # Invoco a la función sumar con los parámetros 1 y 2
Explanation: 22/10
Entrada y salida de datos
Funciones (parámetros por default, nombrados)... |
4,364 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Procesos ETVL usando IPython -- 9 -- Taller
Notas de clase sobre la extracción, transformación, visualización y carga de datos usando IPython
Juan David Velásquez Henao
jdvelasq@unal.edu.co... | Python Code:
import pandas as pd
import statistics as st
import numpy as np
Explanation: Procesos ETVL usando IPython -- 9 -- Taller
Notas de clase sobre la extracción, transformación, visualización y carga de datos usando IPython
Juan David Velásquez Henao
jdvelasq@unal.edu.co
Universidad Nacional de Colombia, Sede M... |
4,365 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Des dates qui font des nombres premiers (suite) ?
Ce petit notebook Jupyter, écrit en Python, a pour but de résoudre la question suivante
Step1: Elle marche très bien, et est très rapide !... | Python Code:
from sympy import isprime
Explanation: Des dates qui font des nombres premiers (suite) ?
Ce petit notebook Jupyter, écrit en Python, a pour but de résoudre la question suivante :
"Pour un jour fixé, en utilisant le jour le mois et les deux chiffres de l'année comme briques de base, et les opérations arithm... |
4,366 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Selecting Columns Programmatically Using Column Expressions Tutorial
MLDB provides a complete implementation of the SQL SELECT statement. Most of the functions you are accustomed to using ar... | Python Code:
from pymldb import Connection
mldb = Connection()
Explanation: Selecting Columns Programmatically Using Column Expressions Tutorial
MLDB provides a complete implementation of the SQL SELECT statement. Most of the functions you are accustomed to using are available in your queries.
MLDB is different from t... |
4,367 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Classes and Object Oriented Programming
We have looked at functions which take input and return output (or do things to the input). However, sometimes it is useful to think about objects fir... | Python Code:
p_normal = (12, -14, 0, 2)
Explanation: Classes and Object Oriented Programming
We have looked at functions which take input and return output (or do things to the input). However, sometimes it is useful to think about objects first rather than the actions applied to them.
Think about a polynomial, such as... |
4,368 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This script is for retrieving images based on sketch query
Step1: caffe
First, we need to import caffe. You'll need to have caffe installed, as well as python interface for caffe.
Step2: N... | Python Code:
import numpy as np
from pylab import *
%matplotlib inline
import os
import sys
Explanation: This script is for retrieving images based on sketch query
End of explanation
#TODO: specify your caffe root folder here
caffe_root = "X:\caffe_siggraph/caffe-windows-master"
sys.path.insert(0, caffe_root+'/python')... |
4,369 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Recon Cartographer
A script to transform a photo of a region sticker discovered through a recon action into a grayscale template that is convenient for printing. Different arrangements of su... | Python Code:
%matplotlib inline
import io
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas
import seaborn as sns
import skimage
import skimage.color
import skimage.data
import skimage.feature
import skimage.filters
import skimage.future
import skimage.io
import skimage.morphology
import skimag... |
4,370 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Comparing initial sampling methods on integer space
Holger Nahrstaedt 2020 Sigurd Carlsen October 2019
.. currentmodule
Step1: Random sampling
Step2: Sobol'
Step3: Classic latin hypercube... | Python Code:
print(__doc__)
import numpy as np
np.random.seed(1234)
import matplotlib.pyplot as plt
from skopt.space import Space
from skopt.sampler import Sobol
from skopt.sampler import Lhs
from skopt.sampler import Halton
from skopt.sampler import Hammersly
from skopt.sampler import Grid
from scipy.spatial.distance ... |
4,371 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A Period - Magnitude Relation in Cepheid Stars
Cepheids are stars whose brightness oscillates with a stable period that appears to be strongly correlated with their luminosity (or absolute m... | Python Code:
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = (15.0, 8.0)
Explanation: A Period - Magnitude Relation in Cepheid Stars
Cepheids are stars whose brightness oscillates with a stable period that appears to be strong... |
4,372 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data Collection
Step1: Ordinal Genres
Below, we make the genres ordinal to fit in the random forest classifiers. We add a new column to our dataframe to do so, write a function to populate ... | Python Code:
import pandas as pd
from os import path
from sklearn.ensemble import RandomForestClassifier
import numpy as np
from sklearn.ensemble import ExtraTreesClassifier
import sklearn
# Edit path if need be (shouldn't need to b/c we all have the same folder structure)
CSV_PATH_1 = '../Videos/all_data'
CSV_PATH_2 =... |
4,373 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Question 1
Step1: 1.1
b. Find the average of a list of numbers using a for loop
Step2: 1.1
c. Write a program that prints string in reverse. Print character by character
Input
Step3: 1.2
... | Python Code:
maxNumber = 0
numberList = [15,4,26,1,9,21,3,6,13]
for each in numberList:
if each>maxNumber:
maxNumber = each
print("The largest number in the list is {0}".format(maxNumber))
Explanation: Question 1:
For basic operation using list, tuple and dictionaries
1.1
a. Finds the largest of a list of n... |
4,374 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook is to aid in the development of a complete market simulator.
Step1: Let's first create a quantization function
Step2: Let's create an Indicator and extract some values
Step3:... | Python Code:
# Basic imports
import os
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import datetime as dt
import scipy.optimize as spo
import sys
from time import time
from sklearn.metrics import r2_score, median_absolute_error
%matplotlib inline
%pylab inline
pylab.rcParams['figure.figsize'] ... |
4,375 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step2: Week9
Step5: 数据集
在训练我们的GAN网络之前, 先介绍一下本次实验可训练GAN的数据集,我们提供了两个数据集来供大家进行尝试数据集.
- MNIST手写体3类数据集,这里为了加快我们的训练速度,我们提供了一个简化版本的只包含数字0,2的2类MNIST数据集,每类各1000张.图片为28*28的单通道灰度图(我们将其resize到32*32),对于... | Python Code:
import torch
torch.cuda.set_device(2)
import torch
import numpy as np
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
%matplotlib inline
class Generator(nn.Module):
def __init__(self, image_size=32, latent_... |
4,376 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Gaussian Mixture Models and Expectation Maximisation in Shogun
By Heiko Strathmann - heiko.strathmann@gmail.com - http
Step2: Set up the model in Shogun
Step3: Sampling from mixture... | Python Code:
%pylab inline
%matplotlib inline
import os
SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data')
# import all Shogun classes
from shogun import *
from matplotlib.patches import Ellipse
# a tool for visualisation
def get_gaussian_ellipse_artist(mean, cov, nstd=1.96, color="red", linewidth=3):
... |
4,377 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
AutoML SDK
Step1: Install the Google cloud-storage library as well.
Step2: Restart the Kernel
Once you've installed the AutoML SDK and Google cloud-storage, you need to restart the noteboo... | Python Code:
! pip3 install -U google-cloud-automl --user
Explanation: AutoML SDK: AutoML image classification model
Installation
Install the latest (preview) version of AutoML SDK.
End of explanation
! pip3 install google-cloud-storage
Explanation: Install the Google cloud-storage library as well.
End of explanation
i... |
4,378 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Hack for Heat #7
Step1: I removed entires earlier than 2011 because there are data quality issues (substantially fewer cases)
Step2: Heat complaints by borough
Step3: There were about a m... | Python Code:
connection = psycopg2.connect('dbname = threeoneone user=threeoneoneadmin password=threeoneoneadmin')
cursor = connection.cursor()
cursor.execute('''SELECT DISTINCT complainttype FROM service;''')
complainttypes = cursor.fetchall()
cursor.execute('''SELECT createddate, borough, complainttype FROM service;'... |
4,379 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MNIST Digit Recognition - CNN
Step1: Prepare Data
Step2: Define Network
Step3: Train Network
Step4: Visualize with Tensorboard
We have also requested the total_loss and total_accuracy sc... | Python Code:
from __future__ import division, print_function
from sklearn.preprocessing import OneHotEncoder
from sklearn.metrics import accuracy_score, confusion_matrix
import numpy as np
import matplotlib.pyplot as plt
import os
import tensorflow as tf
%matplotlib inline
DATA_DIR = "../../data"
TRAIN_FILE = os.path.j... |
4,380 | 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="#Load-signal" data-toc-modified-id="Load-signal-1"><span class="toc-item-num"... | Python Code:
# Add MOSQITO to the Python path
import sys
sys.path.append('..')
# Import numpy
import numpy as np
# Import plot function
import matplotlib.pyplot as plt
# Import multiple spectrum computation tool
from scipy.signal import stft
# Import mosqito functions
from mosqito.utils import load
from mosqito.sq_metr... |
4,381 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: TV Script Generation
In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Ne... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
data_dir = './data/simpsons/moes_tavern_lines.txt'
text = helper.load_data(data_dir)
# Ignore notice, since we don't use it for analysing the data
text = text[81:]
Explanation: TV Script Generation
In this project, you'll generate your own Simpsons TV script... |
4,382 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Discovery of prime integrals with dCGP
Lets first import dcgpy and pyaudi and set up things as to use dCGP on gduals defined over vectorized floats
Step1: We consider a set of differential ... | Python Code:
from dcgpy import expression_gdual_vdouble as expression
from dcgpy import kernel_set_gdual_vdouble as kernel_set
from pyaudi import gdual_vdouble as gdual
from matplotlib import pyplot as plt
import numpy as np
from numpy import sin, cos
from random import randint, random
np.seterr(all='ignore') # avoids ... |
4,383 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Machine Learning
Author
Step1: Ok, let's get the data, then and have a look at some examples. It seems that there is a lot of variation for some numbers there. Can you make ... | Python Code:
# pythons scientific computing package and a random number generator
import numpy as np
import random
from keras.datasets import mnist
# machine learning classifiers and metrics
from sklearn.naive_bayes import MultinomialNB
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accurac... |
4,384 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Linear Regression
This is the first assignment from Andrew Ng's Machine Learning class. In this notebook we perform linear regression with one variable and with multiple variables.
Importin... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Linear Regression
This is the first assignment from Andrew Ng's Machine Learning class. In this notebook we perform linear regression with one variable and with multiple variables.
Importing Libraries
End of explanation
exe... |
4,385 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Decoding (MVPA)
Step1: Transformation classes
Scaler
The
Step2: PSDEstimator
The
Step3: Source power comodulation (SPoC)
Source Power Comodulation (
Step4: Decoding over time
This stra... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
import mne
from mne.datasets import sample
from mne.decoding import (SlidingEstimator, GeneralizingEstimator, Sc... |
4,386 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Computing π by simulation
<img src="../img/cannon-circle.png" width="500">
Consider a cannon firing random shots on a square field enclosing a circle. If the radius of the circle is 1, then ... | Python Code:
import random
def rnd(n):
return [random.uniform(-1, 1) for _ in range(n)]
SHOTS = 5000
x = rnd(SHOTS)
y = rnd(SHOTS)
Explanation: Computing π by simulation
<img src="../img/cannon-circle.png" width="500">
Consider a cannon firing random shots on a square field enclosing a circle. If the radius of the ... |
4,387 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Iris Data Set
This problem sheet relates to the Iris data set and uses jupyter, numpy and pyplot. Problems are labelled 1 to 10.
1. Get and load the Iris data.
Step1: 2. Write a note about... | Python Code:
import numpy as np
# Adapted from https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.genfromtxt.html
filename = 'data.csv'
sLen, sWid, pLen, pWid = np.genfromtxt('data.csv', delimiter=',', usecols=(0,1,2,3), unpack=True, dtype=float)
spec = np.genfromtxt('data.csv', delimiter=',', usecols=(4... |
4,388 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
pypdb demos
This is a set of basic examples of the usage and outputs of the various individual functions included in. There are generally three types of functions.
Preamble
Step1: Search fu... | Python Code:
%pylab inline
from IPython.display import HTML
# Import from local directory
# import sys
# sys.path.insert(0, '../pypdb')
# from pypdb import *
# Import from installed package
from pypdb import *
%load_ext autoreload
%autoreload 2
Explanation: pypdb demos
This is a set of basic examples of the usage and o... |
4,389 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Représentation graphique des orbitales atomiques
Germain Salvato-Vallverdu germain.vallverdu@univ-pau.fr
Parties Radiales
Parties angulaires
Orbitales atomiques
Un site avec de nombreuses vi... | Python Code:
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
%matplotlib inline
Explanation: Représentation graphique des orbitales atomiques
Germain Salvato-Vallverdu germain.vallverdu@univ-pau.fr
Parties Radiales
Parties angulaires
Orbitales atomiques
Un site avec de nombreuses visualisati... |
4,390 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Machine Learning in Cyber Security
Learn to spot an attacker through monitoring TCP logs.
Dataset
Step1: Transform Data
Dataset values are all of type "object" => convert to numeric types.
... | Python Code:
from array import array
import matplotlib.pyplot as plt
import pandas as pd
import sklearn
from sklearn.datasets import fetch_kddcup99
from sklearn.model_selection import train_test_split, KFold, cross_val_score
from sklearn import preprocessing
from sklearn.linear_model import LogisticRegression
from skle... |
4,391 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
We start by importing NumPy which you should be familiar with from the previous tutorial. The next library introduced is called MatPlotLib which is the roughly the Python equivalent of Matla... | Python Code:
fig, ax = pl.subplots(2,2, figsize=(8,6))
fig
ax
ax[0,0]
Explanation: We start by importing NumPy which you should be familiar with from the previous tutorial. The next library introduced is called MatPlotLib which is the roughly the Python equivalent of Matlab's plotting functionality. Think of it as a Ma... |
4,392 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Visualising modes
In this example, we use a simple approach to search for the modes of a split ring resonator, and visualise the corresponding current and charge distribution. These modes ex... | Python Code:
# the numpy library contains useful mathematical functions
import numpy as np
# import useful python libraries
import os.path as osp
# import the openmodes packages
import openmodes
# setup 2D plotting
%matplotlib inline
from openmodes.ipython import matplotlib_defaults
matplotlib_defaults()
import matplo... |
4,393 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The brythonmagic extension has been tested on
Step1: brythonmagic installation
Just type the following
Step2: And load the brython js lib in the notebook
Step3: Warning
In order to load j... | Python Code:
import IPython
IPython.version_info
Explanation: The brythonmagic extension has been tested on:
End of explanation
%install_ext https://raw.github.com/kikocorreoso/brythonmagic/master/brythonmagic.py
%load_ext brythonmagic
Explanation: brythonmagic installation
Just type the following:
End of explanation
f... |
4,394 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
(NVM)=
1.3 Normas vectoriales y matriciales
```{admonition} Notas para contenedor de docker
Step1: Norma $2$
Step2: Norma $1$
Step3: Norma $\infty$
Step4: ```{admonition} Observación
Ste... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
Explanation: (NVM)=
1.3 Normas vectoriales y matriciales
```{admonition} Notas para contenedor de docker:
Comando de docker para ejecución de la nota de forma local:
nota: cambiar <ruta a mi directorio> por la ruta de directorio que se desea mapear a... |
4,395 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Queries
Marvin Queries are a tool designed to remotely query the MaNGA dataset in global and local galaxy properties, and retrieve only the results you want. Let's learn the basics of how t... | Python Code:
# Python 2/3 compatibility
from __future__ import print_function, division, absolute_import
# import matplolib just in case
import matplotlib.pyplot as plt
# this line tells the notebook to plot matplotlib static plots in the notebook itself
%matplotlib inline
# this line does the same thing but makes the ... |
4,396 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
BigQuery Anonymize Dataset
Copies tables and view from one dataset to another and anynonamizes all rows. Used to create sample datasets for dashboards.
License
Copyright 2020 Google LLC,
Li... | Python Code:
!pip install git+https://github.com/google/starthinker
Explanation: BigQuery Anonymize Dataset
Copies tables and view from one dataset to another and anynonamizes all rows. Used to create sample datasets for dashboards.
License
Copyright 2020 Google LLC,
Licensed under the Apache License, Version 2.0 (the... |
4,397 | 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 SDK, you need to restart the notebook kernel so it can find the packages. You can restart kern... | Python Code:
import os
# The Google Cloud Notebook product has specific requirements
IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version")
# Google Cloud Notebook requires dependencies to be installed with '--user'
USER_FLAG = ""
if IS_GOOGLE_CLOUD_NOTEBOOK:
USER_FLAG = "--user"
! pip ... |
4,398 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Formulas
Step1: Import convention
You can import explicitly from statsmodels.formula.api
Step2: Alternatively, you can just use the formula namespace of the main statsmodels.api.
Step3: O... | Python Code:
from __future__ import print_function
import numpy as np
import statsmodels.api as sm
Explanation: Formulas: Fitting models using R-style formulas
Since version 0.5.0, statsmodels allows users to fit statistical models using R-style formulas. Internally, statsmodels uses the patsy package to convert formul... |
4,399 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using the library(odd number of qubits)
This code tutorial shows how to estimate a 1-RDM and perform variational optimization
Step1: Generate the input files, set up quantum resources, and ... | Python Code:
# Import library functions and define a helper function
import numpy as np
import cirq
from openfermioncirq.experiments.hfvqe.gradient_hf import rhf_func_generator
from openfermioncirq.experiments.hfvqe.opdm_functionals import OpdmFunctional
from openfermioncirq.experiments.hfvqe.analysis import (compute_o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.