Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
5,600 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ALGEBRA & DEFINITIONS
Clifford algebra is $$Cl_{1,4}(\mathbb{R})$$
Flat space, no metric, just signature
All constants are equal to 1
Step1: Quaternions
http
Step2: Imaginary unit
Step3: ... | Python Code:
from sympy import *
variables = (t, x, y, z, w) = symbols('t x y z w', real=True)
print(variables)
metric=[1
,-1
,-1
,-1
,-1]
myBasis='gamma_t gamma_x gamma_y gamma_z gamma_w'
sp5d = Ga(myBasis, g=metric, coords=variables,norm=True)
(gamma_t, gamma_x, gamma_y, gamma_z, gamma... |
5,601 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This IPython Notebook illustrates the use of the openmc.mgxs module to calculate multi-group cross sections for a heterogeneous fuel pin cell geometry. In particular, this Notebook illustrat... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('seaborn-dark')
import openmoc
import openmc
import openmc.mgxs as mgxs
import openmc.data
from openmc.openmoc_compatible import get_openmoc_geometry
%matplotlib inline
Explanation: This IPython Notebook illustrates the use of the openmc.mgxs... |
5,602 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interaktív függvények és ábrák
Az alábbiakban vizsgáljunk meg egy egyszerű módszert arra, hogy hogyan tehetjük Python-függvényeinket interaktívvá!
Ehhez az ipywidgets csomag lesz segítségünk... | Python Code:
%pylab inline
from ipywidgets import * # az interaktivitásért felelős csomag
Explanation: Interaktív függvények és ábrák
Az alábbiakban vizsgáljunk meg egy egyszerű módszert arra, hogy hogyan tehetjük Python-függvényeinket interaktívvá!
Ehhez az ipywidgets csomag lesz segítségünkre!
End of explanation
t=l... |
5,603 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: In this notebook we explore different approaches to classification. First let's make a function to generate some data for classification.
Step2: Let's make some data and plot them (... | Python Code:
import numpy
%matplotlib inline
import matplotlib.pyplot as plt
import scipy.stats
import matplotlib
from matplotlib.colors import ListedColormap
import sklearn.neighbors
import sklearn.cross_validation
import sklearn.metrics
import sklearn.lda
import sklearn.svm
import sklearn.linear_model
from sklearn.mo... |
5,604 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Parsing
Goals
Step1: Parsing is hard...
<h2>
<i>"System Administrators spent $24.3\%$ of
their work-life parsing files."</i>
<br><br>
Independent analysis by The GASP* Society ;) <br>
<... | Python Code:
import re
import nose
# %timeit
Explanation: Parsing
Goals:
- Plan a parsing strategy
- Use basic regular expressions: match, search, sub
- Benchmarking a parser
- Running nosetests
- Write a simple parser
Modules:
End of explanation
from __future__ import print_function
# Before writing the parser, collec... |
5,605 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1 Layer Network
Here we will make a network that will recognize 8x8 images of numbers. This will involve a creating a function that genrates networks and a function that can train the networ... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from IPython.html.widgets import interact
from sklearn.datasets import load_digits
from IPython.display import Image, display
digits = load_digits()
print(digits.data.shape)
def show_examples(i):
plt.matshow(digits.images[i].reshape(... |
5,606 | 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... |
5,607 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1>Python and MySQL</h1>
<h2>First import the python module containing the API</h2>
Step1: <h2>Set up a connection and create a cursor object</h2>
Step3: <h2>Execute a query and get the r... | Python Code:
import pymysql
Explanation: <h1>Python and MySQL</h1>
<h2>First import the python module containing the API</h2>
End of explanation
db = pymysql.connect("localhost","root","None" ,database="schooldb")
cursor = db.cursor()
Explanation: <h2>Set up a connection and create a cursor object</h2>
End of explanati... |
5,608 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Thermal Expansion
1. Introduction
A given crystal should have a well defined average lattice constant at a given pressure and temperature. Here we use silicon as an example to show how to ca... | Python Code:
from pylab import *
from ase.lattice.cubic import Diamond
from thermo.gpumd.io import ase_atoms_to_gpumd
import pandas as pd
Explanation: Thermal Expansion
1. Introduction
A given crystal should have a well defined average lattice constant at a given pressure and temperature. Here we use silicon as an exam... |
5,609 | 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 ... |
5,610 | Given the following text description, write Python code to implement the functionality described.
Description:
Print all the pairs that contains the positive and negative values of an element
Function to print pairs of positive and negative values present in the array ; Store all the positive elements in the unordered_... | Python Code:
def printPairs(arr , n ) :
pairs = set()
pair_exists = False
for i in range(0 , n ) :
if arr[i ] > 0 :
pairs . add(arr[i ] )
for i in range(0 , n ) :
if arr[i ] < 0 :
if(- arr[i ] ) in pairs :
print("{ } , ▁ { } ". format(arr[i ] , - arr[i ] ) )
pair_exists = True
if p... |
5,611 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Analise e Tratamento Basico (Triagem) de dados
Analises por Hans. 2015
2012 (10sec)
2013 (10sec)
2014 (10sec ate 1Min seguinte)
2015 (1Min)
Step1: Ajustando o dominio temporal da serie de d... | Python Code:
import sys
import numpy as np
import pandas as pd
print(sys.version) # Versao do python - Opcional
print(np.__version__) # VErsao do modulo numpy - Opcional
import matplotlib
import matplotlib.pyplot as plt
%matplotlib inline
import datetime
import time
#?pd.date_range
#rng = pd.date_range('1/1/2011', peri... |
5,612 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A NYC Taxi data cleaning and model building pipeline to forecast the trip time from A2B in NYC
Step1: Use the bash =)
Step2: So parsing does not work, do it manually
Step3: Some statistic... | Python Code:
import os as os
import pandas as pd
import numpy as np
from scipy import stats, integrate
import matplotlib.pyplot as plt
import matplotlib as mpl
import seaborn as sns
from statsmodels.distributions.empirical_distribution import ECDF
import datetime as dt
plt.style.use('seaborn-whitegrid')
plt.rcParams['i... |
5,613 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
XGBoost
We use the XGBoost Python package to separate signal from background for rare radiative decays $b \rightarrow s (d) \gamma$. XGBoost is a scalable, distributed implementation of grad... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import xgboost as xgb
import time, os
Explanation: XGBoost
We use the XGBoost Python package to separate signal from background for rare radiative decays $b \rightarrow s (d) \gamma$. XGBoost is a scalable, distrib... |
5,614 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
List vs numpy array
Germain Salvato Vallverdu
Step1: Utilisation d'une fonction
Step2: Produit scalaire
Ou produit de matrices ou matrices-vecteurs ou opération sur des vecteurs (sommes, p... | Python Code:
import numpy as np
import math as m
Explanation: List vs numpy array
Germain Salvato Vallverdu
End of explanation
def np_func(x):
return (3 * x ** 2 + 2 * x - 1) * np.exp(- x / 2.3) * np.sin(2 * x)
def m_func(x):
return (3 * x ** 2 + 2 * x - 1) * m.exp(- x / 2.3) * m.sin(2 * x)
x = np.linspace(0, 1... |
5,615 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial Part 6
Step1: Let's start with some basic imports
Step2: We use propane( $CH_3 CH_2 CH_3 $ ) as a running example throughout this tutorial. Many of the featurization methods use c... | Python Code:
%tensorflow_version 1.x
!curl -Lo deepchem_installer.py https://raw.githubusercontent.com/deepchem/deepchem/master/scripts/colab_install.py
import deepchem_installer
%time deepchem_installer.install(version='2.3.0')
Explanation: Tutorial Part 6: Going Deeper On Molecular Featurizations
One of the most impo... |
5,616 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A Bayesian model of book sales and literary prestige
Historians often have to work with missing evidence.
Book sales figures, for instance, are notoriously patchy. If we're interested in co... | Python Code:
# BASIC IMPORTS BEFORE WE BEGIN
import matplotlib
from matplotlib import pyplot as plt
%matplotlib inline
import pandas as pd
import csv
import statsmodels.formula.api as smf
from scipy.stats import pearsonr
import numpy as np
import random
import scipy.stats as ss
from patsy import dmatrices
Explanation: ... |
5,617 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dynamic UNet
Unet model using PixelShuffle ICNR upsampling that can be built on top of any pretrained architecture
Step1: Export - | Python Code:
#|export
def _get_sz_change_idxs(sizes):
"Get the indexes of the layers where the size of the activation changes."
feature_szs = [size[-1] for size in sizes]
sz_chg_idxs = list(np.where(np.array(feature_szs[:-1]) != np.array(feature_szs[1:]))[0])
return sz_chg_idxs
#|hide
test_eq(_get_sz_c... |
5,618 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
California house price prediction
Load the data and explore it
Step1: Create a test set
Step2: Do stratified sampling
Assuming median_income is an important predictor, we need to categoriz... | Python Code:
import pandas as pd
housing = pd.read_csv(r"E:\GIS_Data\file_formats\CSV\housing.csv")
housing.head()
housing.info()
# find unique values in ocean proximity column
housing.ocean_proximity.value_counts()
#describe all numerical rows - basic stats
housing.describe()
%matplotlib inline
import matplotlib.pyplo... |
5,619 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
VTK tools
Pygslib use VTK
Step1: Functions in vtktools
Step2: Load a cube defined in an stl file and plot it
STL is a popular mesh format included an many non-commercial and commercial sof... | Python Code:
import pygslib
import numpy as np
Explanation: VTK tools
Pygslib use VTK:
as data format and data converting tool
to plot in 3D
as a library with some basic computational geometry functions, for example to know if a point is inside a surface
Some of the functions in VTK were obtained or modified from Adam... |
5,620 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook describes the setup of CLdb with a set of E. coli genomes.
Notes
It is assumed that you have CLdb in your PATH
Step1: The required files are in '../ecoli_raw/'
Step2: Checkin... | Python Code:
# path to raw files
## CHANGE THIS!
rawFileDir = "~/perl/projects/CLdb/data/Ecoli/"
# directory where the CLdb database will be created
## CHANGE THIS!
workDir = "~/t/CLdb_Ecoli/"
# viewing file links
import os
import zipfile
import csv
from IPython.display import FileLinks
# pretty viewing of tables
## ge... |
5,621 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Basic PowerShell Execution
Metadata
| Metadata | Value |
|
Step1: Download & Process Security Dataset
Step2: Analytic I
Within the classic PowerShell log, event ID 400 indicates... | Python Code:
from openhunt.mordorutils import *
spark = get_spark()
Explanation: Basic PowerShell Execution
Metadata
| Metadata | Value |
|:------------------|:---|
| collaborators | ['@Cyb3rWard0g', '@Cyb3rPandaH'] |
| creation date | 2019/04/10 |
| modification date | 2020/09/20 |
| playbook relate... |
5,622 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Image Compression using Autoencoders with BPSK
This code is provided as supplementary material of the lecture Machine Learning and Optimization in Communications (MLOC).<br>
This code illust... | Python Code:
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import numpy as np
from matplotlib import pyplot as plt
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print("We are using the following device for learning:",device)
Explanation: Image Compression using Autoencoders... |
5,623 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
author = "Peter J Usherwood"
Esta tutorial é um exemplo de um aplicação em Python padrão, sem pacotes não padrão. Porque de isto, este codigo não é o mais simples ou eficiente, mas é transpa... | Python Code:
from random import seed
from random import randrange
import random
from csv import reader
from math import sqrt
import copy
Explanation: author = "Peter J Usherwood"
Esta tutorial é um exemplo de um aplicação em Python padrão, sem pacotes não padrão. Porque de isto, este codigo não é o mais simples ou efic... |
5,624 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Avani Goyal, Nathaniel Dirks
Step1: Load the RECS dataset into the memory.
It is loaded in two different variables to use it for two different purposes.
1. datanames
Step2: Preliminary an... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import datetime as dt
from operator import itemgetter
import math
%matplotlib inline
Explanation: Avani Goyal, Nathaniel Dirks :
12752 :
Final Project
Due: 12/13/2015
End of explanation
f= open('recs2009_public.csv','r')
datanames = np.genfromtxt(f,delimit... |
5,625 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Adding Context to Word Frequency Counts
While the raw data from word frequency counts is compelling, it does little but describe quantitative features of the corpus. In order to determine if... | Python Code:
# This is where the modules are imported
import nltk
from os import listdir
from os.path import splitext
from os.path import basename
from tabulate import tabulate
# These functions iterate through the directory and create a list of filenames
def list_textfiles(directory):
"Return a list of filenames e... |
5,626 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Excercises Electric Machinery Fundamentals
Chapter 6
Animation
Step1: Look at a superposition of two sinusoidal signals
Step2: This product can be rewritten as a sum using trigonometric eq... | Python Code:
from sympy import init_session
init_session()
%matplotlib notebook
Explanation: Excercises Electric Machinery Fundamentals
Chapter 6
Animation: Determining the rotor-slip with a compass
End of explanation
f=sin(x)*sin(y)
f
Explanation: Look at a superposition of two sinusoidal signals:
End of explanation
... |
5,627 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Duhamel Integral
Problem Data
Step1: Natural Frequency, Damped Frequency
Step2: Computation
Preliminaries
We chose a time step and we compute a number of constants of the integration proce... | Python Code:
M = 600000
T = 0.6
z = 0.10
p0 = 400000
t0, t1, t2, t3 = 0.0, 1.0, 3.0, 6.0
Explanation: Duhamel Integral
Problem Data
End of explanation
wn = 2*np.pi/T
wd = wn*np.sqrt(1-z**2)
Explanation: Natural Frequency, Damped Frequency
End of explanation
dt = 0.05
edt = np.exp(-z*wn*dt)
fac = dt/(2*M*wd)
Explanation... |
5,628 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Optymalizacja i propagacja wsteczna (backprop)
Zaczniemy od prostego przykładu. Funkcji kwadratowej
Step1: Funkcja ta ma swoje minimum w punkcie $x = 0$. Jak widać na powyższym rysunku, gdy... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import seaborn
%matplotlib inline
x = np.linspace(-3, 3, 100)
plt.plot(x, x**2, label='f(x)') # optymalizowana funkcja
plt.plot(x, 2 * x, label='pochodna -- f\'(x)') # pochodna
plt.legend()
plt.show()
Explanation: Optymalizacja i propagacja wsteczna (bac... |
5,629 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to numerical simulations
Step1: Now we will define the physical constants of our system, which will also establish the unit system we have chosen. We'll use SI units here. Belo... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
Explanation: Introduction to numerical simulations: The 2 Body Problem
Many problems in statistical physics and astrophysics require solving problems consisting of many particles at once (sometimes on the order of thousands or more!) Thi... |
5,630 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
I'm looking into doing a delta_sigma emulator. This is testing if the cat side works. Then i'll make an emulator for it.
Step1: Load up a snapshot at a redshift near the center of this bin.... | Python Code:
from pearce.mocks import cat_dict
import numpy as np
from os import path
from astropy.io import fits
import matplotlib
#matplotlib.use('Agg')
from matplotlib import pyplot as plt
%matplotlib inline
import seaborn as sns
sns.set()
z_bins = np.array([0.15, 0.3, 0.45, 0.6, 0.75, 0.9])
zbin=1
a = 0.81120
z = 1... |
5,631 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TensorFlow图相关知识简介
参考
Step1: tensorflow/python/framework/ops.py
+ Tensor
Step2: Operator
Step3: 实际上,对变量的读是通过tf.identity算子得到:
python
c = tf.add(b, tf.identity(v))
Variable
Step4: graph.pbt... | Python Code:
a = tf.constant(1)
b = a * 2
b
b.op
b.consumers()
a.op
a.consumers()
Explanation: TensorFlow图相关知识简介
参考: https://www.tensorflow.org/programmers_guide/graphs
tf.Graph
op, tensor
variable
name_scope, variable_scop, collection
save and restore
0. tf.Graph
tf.Graph: GraphDef => *.pb文件
+ Graph structure: Operato... |
5,632 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Error Estimation for Survey Data
the issue we have is the following
Step1: Closed Form Approximation
of course we could have done this analytically using Normal approximation
Step2: Thats ... | Python Code:
N_people = 500
ratio_female = 0.30
proba = 0.40
Explanation: Error Estimation for Survey Data
the issue we have is the following: we are drawing indendent random numbers from a binary distribution of probability $p$ (think: the probability of a certain person liking the color blue) and we have two groups (... |
5,633 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lesson 2
Step1: This is called an "if / else" statement. It basically allows you to create a "fork" in the flow of your program based on a condition that you define. If the condition is Tru... | Python Code:
construction = False
print "Turn right onto Main Street"
print "Turn left onto Maple Ave"
if construction:
print "Continue straight on Maple Ave"
print "Turn right onto Cat Lane"
print "Turn left onto Fake Street"
else:
print "Cut through the empty lot to Fake Street"
print "Go straigh... |
5,634 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Spectra in (optical) Astronomy
Here we introduce a simple spectrum, the example taken from the optical, where it all started.
To quote Roger Wesson, the author of this particular spectrum
St... | Python Code:
%matplotlib inline
# python 2-3 compatibility
from __future__ import print_function
Explanation: Spectra in (optical) Astronomy
Here we introduce a simple spectrum, the example taken from the optical, where it all started.
To quote Roger Wesson, the author of this particular spectrum:
The sample spectrum w... |
5,635 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using the graph from figure 10.1 from the textbook (http
Step1: http
Step2: Let's play with some algorithms in class | Python Code:
#Example Small social newtork as a connection matrix
sc1 = ([(0, 1, 1, 0, 0, 0, 0),
(1, 0, 1, 1, 0, 0, 0),
(1, 1, 0, 0, 0, 0, 0),
(0, 1, 0, 0, 1, 1, 1),
(0, 0, 0, 1, 0, 1, 0),
(0, 0, 0, 1, 1, 0, 1),
(0, 0, 0, 1, 0, 1, 0)])
Explanation: Using the graph from f... |
5,636 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
First, some code. Scroll down.
Step1: Initialize some feature-locations
Step2: Issue
Step3: We're testing L2 in isolation, so these "A", "B", etc. patterns are L4 representations, i.e. "f... | Python Code:
import itertools
import random
from htmresearch.algorithms.column_pooler import ColumnPooler
INPUT_SIZE = 10000
def createFeatureLocationPool(size=10):
duplicateFound = False
for _ in xrange(5):
candidateFeatureLocations = [frozenset(random.sample(xrange(INPUT_SIZE), 40))
... |
5,637 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Basic Plotting with matplotlib
You can show matplotlib figures directly in the notebook by using the %matplotlib notebook and %matplotlib inline magic commands.
%matplotlib notebook provide... | Python Code:
%matplotlib notebook
import matplotlib as mpl
mpl.get_backend()
import matplotlib.pyplot as plt
plt.plot?
# because the default is the line style '-',
# nothing will be shown if we only pass in one point (3,2)
plt.plot(3, 2)
# we can pass in '.' to plt.plot to indicate that we want
# the point (3,2) to be... |
5,638 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
02 - Example - Handling Duplicates and Missing Values
This notebook presents how to eliminate duplicates and solve the missing values.
By
Step1: Load the dataset that will be used
Using t... | Python Code:
import pandas as pd
import numpy as np
% matplotlib inline
from matplotlib import pyplot as plt
Explanation: 02 - Example - Handling Duplicates and Missing Values
This notebook presents how to eliminate duplicates and solve the missing values.
By: Hugo Lopes
Learning Unit 08
Some inital imports:
End of ... |
5,639 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Callbacks
author
Step5: Using a callback
Let's first take a look at how to use the built-in callbacks. We'll start off with the History callback, which is already automatically created and ... | Python Code:
%matplotlib inline
import numpy
import matplotlib.pyplot as plt
import seaborn; seaborn.set_style('whitegrid')
from pomegranate import *
numpy.random.seed(0)
numpy.set_printoptions(suppress=True)
%load_ext watermark
%watermark -m -n -p numpy,scipy,pomegranate
Explanation: Callbacks
author: Jacob Schreiber ... |
5,640 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data discovery using FITS (FIeld Time Series) database - for sites
In this notebook we will look at discovering what data exists for a site in the FITS (FIeld Time Series) database. Again so... | Python Code:
import pandas as pd
import matplotlib.pyplot as plt
import datetime
import numpy as np
# Create list of all typeIDs available in the FITS database
all_type_URL = 'https://fits.geonet.org.nz/type'
all_types = pd.read_json(all_type_URL).iloc[:,0]
all_typeIDs= []
for row in all_types:
all_typeIDs.app... |
5,641 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
EEG forward operator with a template MRI
This tutorial explains how to compute the forward operator from EEG data
using the standard template MRI subject fsaverage.
.. caution
Step1: Load t... | Python Code:
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Joan Massich <mailsik@gmail.com>
# Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD-3-Clause
import os.path as op
import numpy as np
import mne
from mne.datasets import eegbci
from mne.datasets import fetch_fsaverage
# Do... |
5,642 | 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... |
5,643 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Machine Learning Engineer Nanodegree
Unsupervised Learning
Project 3
Step1: Data Exploration
In this section, you will begin exploring the data through visualizations and code to understand... | Python Code:
# Import libraries necessary for this project
import numpy as np
import pandas as pd
import renders as rs
from IPython.display import display # Allows the use of display() for DataFrames
# Show matplotlib plots inline (nicely formatted in the notebook)
%matplotlib inline
# Load the wholesale customers data... |
5,644 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Box Plots
The following illustrates some options for the boxplot in statsmodels. These include violin_plot and bean_plot.
Step1: Bean Plots
The following example is taken from the docstring... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm
Explanation: Box Plots
The following illustrates some options for the boxplot in statsmodels. These include violin_plot and bean_plot.
End of explanation
data = sm.datasets.anes96.load_pandas()
party_ID = np.... |
5,645 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
State space modeling
Step2: To take advantage of the existing infrastructure, including Kalman filtering and maximum likelihood estimation, we create a new class which extends from dismalpy... | Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
from scipy.stats import norm
import dismalpy as dp
import matplotlib.pyplot as plt
Explanation: State space modeling: Local Linear Trends
This notebook describes how to extend the state space classes to create and estimate a custom model. Here we de... |
5,646 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
LDA Model
Introduces Gensim's LDA model and demonstrates its use on the NIPS corpus.
Step1: The purpose of this tutorial is to demonstrate how to train and tune an LDA model.
In this tutori... | Python Code:
import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
Explanation: LDA Model
Introduces Gensim's LDA model and demonstrates its use on the NIPS corpus.
End of explanation
import io
import os.path
import re
import tarfile
import smart_open
def extract_doc... |
5,647 | 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', 'ncc', 'noresm2-mm', 'aerosol')
Explanation: ES-DOC CMIP6 Model Properties - Aerosol
MIP Era: CMIP6
Institute: NCC
Source ID: NORESM2-MM
Topic: Aerosol
Sub-Topics: Transport, Emissions... |
5,648 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
KubeFlow Pipelines
Step1: Enter your gateway and the auth token
Use this extension on chrome to get token
Update values for the ingress gateway and auth session
Step2: Set the Log bucket... | Python Code:
! pip uninstall -y kfp
! pip install kfp
import kfp
import json
import os
from kfp.onprem import use_k8s_secret
from kfp import components
from kfp.components import load_component_from_file, load_component_from_url
from kfp import dsl
from kfp import compiler
import numpy as np
import logging
kfp.__versio... |
5,649 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The Cirq Developers
Step1: Ion Device Class
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step3: Defining an IonDevice
To defin... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# dist... |
5,650 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example 10
Step1: Create some dictionarys with parameters for cell
Step2: Create an helper function to instantiate a cell object given a set of parameters
Step3: Instantiate a LFPy.Cell o... | Python Code:
import LFPy
import MEAutility as mu
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
Explanation: Example 10: Extracellular stimulation of neurons
This is an example of LFPy running in an Jupyter notebook. To run through this example code and produce output, press... |
5,651 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fast Bayesian estimation of SARIMAX models
Introduction
This notebook will show how to use fast Bayesian methods to estimate SARIMAX (Seasonal AutoRegressive Integrated Moving Average with e... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pymc3 as pm
import statsmodels.api as sm
import theano
import theano.tensor as tt
from pandas.plotting import register_matplotlib_converters
from pandas_datareader.data import DataReader
plt.style.use("seaborn"... |
5,652 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Conditional Entropy
Step1: Problem 1b
Create a function, phase_plot, that takes x, y, and $P$ as inputs to create a phase-folded light curve (i.e., plot the data at their respective phase v... | Python Code:
def gen_periodic_data(x, period=1, amplitude=1, phase=0, noise=0):
'''Generate periodic data given the function inputs
y = A*cos(x/p - phase) + noise
Parameters
----------
x : array-like
input values to evaluate the array
period : float (default=1)
per... |
5,653 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
RNN from scratch using TensorFlow
<img src="http
Step1: First, we make some training data. To keep things simple, we'll only pick numbers between 0 and $2^6$, so that the sum of the two num... | Python Code:
import numpy as np
import pandas as pd
import tensorflow as tf
%pylab inline
pylab.style.use('ggplot')
Explanation: RNN from scratch using TensorFlow
<img src="http://d3kbpzbmcynnmx.cloudfront.net/wp-content/uploads/2015/09/rnn.jpg">
In this example, we'll build a simple RNN using TensorFlow and we'll trai... |
5,654 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Finding data with python-fmrest
This is a short example on finding records with python-fmrest.
Step1: Login
Step2: Specify find queries and retrieve foundset and record
We want to find rec... | Python Code:
import fmrest
Explanation: Finding data with python-fmrest
This is a short example on finding records with python-fmrest.
End of explanation
fms = fmrest.Server('https://10.211.55.15',
user='admin',
password='admin',
database='Contacts',
... |
5,655 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plotting Glider data with Python tools
In this notebook we demonstrate how to obtain and plot glider data using iris and cartopy. We will explore data from the Rutgers University RU29 Challe... | Python Code:
# See https://github.com/Unidata/netcdf-c/issues/1299 for the explanation of `#fillmismatch`.
url = (
"https://data.ioos.us/thredds/dodsC/deployments/rutgers/"
"ru29-20150623T1046/ru29-20150623T1046.nc3.nc#fillmismatch"
)
import iris
iris.FUTURE.netcdf_promote = True
glider = iris.load(url)
print(g... |
5,656 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Re-creating Capillary Hysteresis in Neutrally Wettable Fibrous Media
Step1: Now we set some key variables for the simulation, $\theta$ is the contact angle in each phase and without contact... | Python Code:
import pickle
import numpy as np
import openpnm as op
from pathlib import Path
import matplotlib.pyplot as plt
from openpnm.models import physics as pm
%matplotlib inline
ws = op.Workspace()
ws.settings["loglevel"] = 50
ws.clear()
np.random.seed(10)
path = Path('../../fixtures/hysteresis_paper_network.pnm'... |
5,657 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python for Bioinformatics
This Jupyter notebook is intented to be used alongside the book Python for Bioinformatics
Chapter 19
Step1: Listing 19.1
Step2: Listing 19.2 | Python Code:
!curl https://raw.githubusercontent.com/Serulab/Py4Bio/master/samples/samples.tar.bz2 -o samples.tar.bz2
!mkdir samples
!tar xvfj samples.tar.bz2 -C samples
Explanation: Python for Bioinformatics
This Jupyter notebook is intented to be used alongside the book Python for Bioinformatics
Chapter 19: Filtering... |
5,658 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Graphes - correction
Correction des exercices sur les graphes avec matplotlib.
Pour avoir des graphiques inclus dans le notebook, il faut ajouter cette ligne et l'exécuter en premier.
Step1:... | Python Code:
%matplotlib inline
Explanation: Graphes - correction
Correction des exercices sur les graphes avec matplotlib.
Pour avoir des graphiques inclus dans le notebook, il faut ajouter cette ligne et l'exécuter en premier.
End of explanation
from jyquickhelper import add_notebook_menu
add_notebook_menu()
Explanat... |
5,659 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Conditional non-linear systems of equations
Sometimes when performing modelling work in physical sciences we use different sets of equations to describe our system depending on conditions. S... | Python Code:
from __future__ import (absolute_import, division, print_function)
from functools import reduce
from operator import mul
import sympy as sp
import numpy as np
import matplotlib.pyplot as plt
from pyneqsys.symbolic import SymbolicSys, linear_exprs
sp.init_printing()
Explanation: Conditional non-linear syste... |
5,660 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
03-exploratory-analysis for final project
I am working on the Kaggle Grupo Bimbo competition dataset for this project.
Link to Grupo Bimbo Kaggle competition
Step1: Part 1. Identify the Pr... | Python Code:
import numpy as np
import pandas as pd
from sklearn import cross_validation
from sklearn import metrics
from sklearn import linear_model
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="whitegrid", font_scale=1)
%matplotlib inline
Explanation: 03-exploratory-analysis for final project
I... |
5,661 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
load clean descriptions into memory
| Python Code::
def load_clean_descriptions(filename, dataset):
# load document
doc = load_doc(filename)
descriptions = dict()
for line in doc.split('\n'):
# split line by white space
tokens = line.split()
# split id from description
image_id, image_desc = tokens[0], tokens[1:]
# skip images not in the set
... |
5,662 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a name="top"></a>
<div style="width
Step1: <a name="download"></a>
Downloading NARR Output
Lets investigate what specific NARR output is available to work with from NCEI.
https
Step2: Nex... | Python Code:
from datetime import datetime
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import numpy as np
from scipy.ndimage import gaussian_filter
from siphon.catalog import TDSCatalog
from siphon.ncss import NCSS
import matplotlib.pyplot as plt
import metpy.calc as mpcalc
import metpy.constants as m... |
5,663 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Hub Authors.
Licensed under the Apache License, Version 2.0 (the "License");
Step1: Universal Sentence Encoder
<table class="tfo-notebook-buttons" align="left"... | Python Code:
# Copyright 2018 The TensorFlow Hub Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... |
5,664 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1 STYLE="background
Step1: <h2 STYLE="background
Step2: <h4 style="padding
Step3: <h2 STYLE="background
Step4: <h4 style="padding
Step5: <h4 style="border-bottom
Step6: <h4 style="pa... | Python Code:
import numpy as np # 数値計算を行うライブラリ
import scipy as sp # 科学計算ライブラリ
from scipy import stats # 統計計算ライブラリ
Explanation: <h1 STYLE="background: #c2edff;padding: 0.5em;">Step 2. 統計的検定</h1>
<ol>
<li><a href="#1">カイ2乗検定</a>
<li><a href="#2">t検定</a>
<li><a href="#3">分散分析</a>
</ol>
<h4 style="border-bottom: solid 1px ... |
5,665 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Detect subframe preamble by majority voting amongst the possible offsets.
Step1: Most subframes do not have valid parity, as shown below. We use a weaker heuristic, where only parity of TLM... | Python Code:
preamble = np.array([1,0,0,0,1,0,1,1], dtype = 'uint8')
preamble_detect = np.where(np.abs(np.correlate(2*bits.astype('int')-1, 2*preamble.astype('int')-1)) == 8)[0]
preamble_offset = np.argmax(np.histogram(preamble_detect % subframe_size, bins = np.arange(0,subframe_size))[0])
subframes = bits[preamble_off... |
5,666 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Socks, Skeets, and Space Invaders
This notebook contains code from my blog, Probably Overthinking It
Copyright 2016 Allen Downey
MIT License
Step1: Socks
The sock drawer problem
Posed by Yu... | Python Code:
from __future__ import print_function, division
%matplotlib inline
import warnings
warnings.filterwarnings("ignore")
from thinkbayes2 import Pmf, Hist, Beta
import thinkbayes2
import thinkplot
Explanation: Socks, Skeets, and Space Invaders
This notebook contains code from my blog, Probably Overthinking It
... |
5,667 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Learning in Python
Get the code
Step1: So building and training Neural Networks in Python in simple!
But it is also powerful!
Neural Style Transfer
Step2: Let's load some data
Step6: ... | Python Code:
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
batch_size = 128
nb_classes = 10
nb_epoch = 15
# input image dimensions
img_rows, img_cols = 28, 28
# number of convolutional filters to use
nb_... |
5,668 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 14 – Recurrent Neural Networks
This notebook contains all the sample code and solutions to the exercises in chapter 14.
Setup
First, let's make sure this notebook works well in both ... | Python Code:
# To support both python 2 and python 3
from __future__ import division, print_function, unicode_literals
# Common imports
import numpy as np
import os
# to make this notebook's output stable across runs
def reset_graph(seed=42):
tf.reset_default_graph()
tf.set_random_seed(seed)
np.random.seed(... |
5,669 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Scripts
Calculate Mutual Info
The script "calculate_mutual_info.py" takes as an input a file containing various time-series replicas
Step1: then the argument parser is defined
Step2: Argum... | Python Code:
import ts
import matplotlib.pyplot as plt
import numpy as np
from argparse import ArgumentParser
Explanation: Scripts
Calculate Mutual Info
The script "calculate_mutual_info.py" takes as an input a file containing various time-series replicas: each column will be interpreted as different replica and each r... |
5,670 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TwoPortOnePath, EnhancedResponse, and FakeFlip
Intro
This example demonstrates a macgyver-ish shortcut you can take if you are measuring a device that is reciprocal and symmetric on a s... | Python Code:
from IPython.display import *
Image('three_receiver_cal/pics/macgyver.jpg', width='50%')
Explanation: TwoPortOnePath, EnhancedResponse, and FakeFlip
Intro
This example demonstrates a macgyver-ish shortcut you can take if you are measuring a device that is reciprocal and symmetric on a switch-less thre... |
5,671 | 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:
%matplotlib inline
import pickle as pkl
import matplotlib.pyplot as plt
import numpy as np
from scipy.io import loadmat
import tensorflow as tf
!mkdir data
Explanation: Deep Convolutional GANs
In this notebook, you'll build a GAN using convolutional layers in the generator and discriminator. This is called... |
5,672 | Given the following text description, write Python code to implement the functionality described.
Description:
Last digit in a power of 2
Python3 program to find last digit in a power of 2. ; Corner case ; Find the shift in current cycle and return value accordingly ; Driver code
| Python Code:
def lastDigit2PowerN(n ) :
if n == 0 :
return 1
elif n % 4 == 1 :
return 2
elif n % 4 == 2 :
return 4
elif n % 4 == 3 :
return 8
else :
for n in range(20 ) :
print(lastDigit2PowerN(n ) , end = "▁ ")
|
5,673 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Seem to need to do one run before the profiling
Every time the first run looks different than the rest, so we run one and throw it out.
Step1: Memory profile without sigma clipping
Step2: ... | Python Code:
_, _ = run_memory_profile(num_files, sampling_interval, size=image_size,
memory_limit=memory_limit, combine_method='average')
Explanation: Seem to need to do one run before the profiling
Every time the first run looks different than the rest, so we run one and throw it out.
End o... |
5,674 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
JSON examples and exercise
get familiar with packages for dealing with JSON
study examples with JSON strings and files
work on exercise to be completed and submitted
reference
Step1: impo... | Python Code:
import pandas as pd
Explanation: JSON examples and exercise
get familiar with packages for dealing with JSON
study examples with JSON strings and files
work on exercise to be completed and submitted
reference: http://pandas-docs.github.io/pandas-docs-travis/io.html#json
data source: http://jsonstudio.com... |
5,675 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dynamic Testing
We want to measure the dynamical characteristics of a SDOF building system,
i.e., its mass, its damping coefficient and its elastic stiffness.
To this purpose, we demonstrate... | Python Code:
from scipy import matrix, sqrt, pi, cos, sin, set_printoptions
p0 = 2224.0 # converted from kN to Newton
rho1 = 183E-6 ; rho2 = 368E-6 # converted from μm to m
w1 = 16.0 ; w2 = 25.0
th1 = 15.0 ; th2 = 55.0
d2r = pi/180.
cos1 = cos(d2r*th1) ; cos2 = cos(d2r*th2)
sin1 = sin(d2r*th1) ; sin2 = sin(d2r*th2)
# t... |
5,676 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A nonlinear perspective on climate change
<p class="gap2"></p>
The following lab will have you explore the concepts developed in Palmer (1999}
1. Exploring the Lorenz System
By now you are w... | Python Code:
%matplotlib inline
import numpy as np
from scipy import integrate
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.colors import cnames
from matplotlib import animation
import seaborn as sns
import butter_lowpass_filter as blf
Explanation: A nonlinear perspective... |
5,677 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Train A Smartcab to Drive
Christopher Phillippi
This project forks Udacity's Machine Learning Nanodegree Smartcab project with my solution, modifying/adding smartcab/agent.py and smartcab/no... | Python Code:
import numpy as np
import pandas as pd
import seaborn as sns
import pylab
%matplotlib inline
def expected_trials(total_states):
n_drawn = np.arange(1, total_states)
return pd.Series(
total_states * np.cumsum(1. / n_drawn[::-1]),
n_drawn
)
expected_trials(96).plot(
title='Ex... |
5,678 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
HydroTrend, Ganges Basin, Q0 Climate Scenario
Created By
Step1: Import the pymt package. Create a new instance. With each new run, it is wise to rename the instance
Step2: Note that the fo... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
Explanation: HydroTrend, Ganges Basin, Q0 Climate Scenario
Created By: Abby Eckland and Irina Overeem, March 2020
About this notebook
This notebook replicates and improves upon simulations originally run by Frances Dunn and Stephen Darby, reported in Darby... |
5,679 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interact Exercise 4
Imports
Step2: Line with Gaussian noise
Write a function named random_line that creates x and y data for a line with y direction random noise that has a normal distribut... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from IPython.html.widgets import interact, interactive, fixed
from IPython.display import display
Explanation: Interact Exercise 4
Imports
End of explanation
def random_line(m, b, sigma, size=10):
Create a line y = m*x + b + N(0,sigm... |
5,680 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Translation of Numeric Phrases with Seq2Seq
In the following we will try to build a translation model from french phrases describing numbers to the corresponding numeric representation (base... | Python Code:
from french_numbers import to_french_phrase
for x in [21, 80, 81, 300, 213, 1100, 1201, 301000, 80080]:
print(str(x).rjust(6), to_french_phrase(x))
Explanation: Translation of Numeric Phrases with Seq2Seq
In the following we will try to build a translation model from french phrases describing numbers t... |
5,681 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
First the data is loaded into Pandas data frames
Step1: Next select a subset of our train_data to use for training the model
Step2: Now train the SVM classifier and get validation accuracy... | Python Code:
import numpy as np
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
# Read the input datasets
train_data = pd.read_csv('../input/train.csv')
test_data = pd.read_csv('../input/test.csv')
# Fill missing numeric values with median for that column
train_data['Age'].fillna(train_data['Age'... |
5,682 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2021 Google LLC
Licensed under the Apache License, Version 2.0 (the "License")
Step1: Compile a model for the Edge TPU
This notebook offers a convenient way to compile a TensorFlo... | Python Code:
# 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
# distribute... |
5,683 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Gaussian Processes in Shogun
By Heiko Strathmann - <a href="mailto
Step1: Some Formal Background (Skip if you just want code examples)
This notebook is about Bayesian regression models with... | Python Code:
%matplotlib inline
# import all shogun classes
from shogun import *
import random
import numpy as np
import matplotlib.pyplot as plt
import os
SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data')
from math import exp
Explanation: Gaussian Processes in Shogun
By Heiko Strathmann - <a href="mailto:h... |
5,684 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Practical PyTorch
Step1: The Grid World, Agent and Environment
First we'll build the training environment, which is a simple square grid world with various rewards and a goal. If you're jus... | Python Code:
import numpy as np
from itertools import count
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.autograd as autograd
from torch.autograd import Variable
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import matplotlib.... |
5,685 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Representations and metrics
Question 1
<img src="images/Screen Shot 2016-07-02 at 9.34.11 AM.png">
Screenshot taken from Coursera
<!--TEASER_END-->
Answer
- https
Step1: Question 2
<img src... | Python Code:
def calculate_weight(feature):
weight = (1/(max(feature) - min(feature))) ** 2
return weight
price = calculate_weight(np.array([500000, 350000, 600000, 400000], dtype=float))
room = calculate_weight(np.array([3, 2, 4, 2], dtype=float))
lot = calculate_weight(np.array([1840, 1600, 2000, 1900], dt... |
5,686 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Build a recommender system with retail data on Vertex AI using PySpark
Table of contents
Overview
Dataset
Objective
Costs
Create a Dataproc cluster with component gateway enabled and Jupyter... | Python Code:
PROJECT_ID = ""
# Get your Google Cloud project ID from gcloud
if not os.getenv("IS_TESTING"):
shell_output=!gcloud config list --format 'value(core.project)' 2>/dev/null
PROJECT_ID = shell_output[0]
print("Project ID: ", PROJECT_ID)
Explanation: Build a recommender system with retail data on V... |
5,687 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
.. _tut_viz_epochs
Step1: This tutorial focuses on visualization of epoched data. All of the functions
introduced here are basically high level matplotlib functions with built in
intelligen... | Python Code:
import os.path as op
import mne
data_path = op.join(mne.datasets.sample.data_path(), 'MEG', 'sample')
raw = mne.io.read_raw_fif(op.join(data_path, 'sample_audvis_raw.fif'))
events = mne.read_events(op.join(data_path, 'sample_audvis_raw-eve.fif'))
picks = mne.pick_types(raw.info, meg='grad')
epochs = mne.Ep... |
5,688 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Nodes and Edges
Step1: Basic Network Statistics
Let's first understand how many students and friendships are represented in the network.
Step2: Exercise
Can you write a single line of code... | Python Code:
G = cf.load_seventh_grader_network()
Explanation: Nodes and Edges: How do we represent relationships between individuals using NetworkX?
As mentioned earlier, networks, also known as graphs, are comprised of individual entities and their representatives. The technical term for these are nodes and edges, an... |
5,689 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exploring the Lorenz System of Differential Equations
In this Notebook we explore the Lorenz system of differential equations
Step2: Computing the trajectories and plotting the result
We de... | Python Code:
%matplotlib inline
from IPython.html.widgets import interact, interactive
from IPython.display import clear_output, display, HTML
import numpy as np
from scipy import integrate
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.colors import cnames
from matplotlib ... |
5,690 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Import the functions (assumes that QTLight_functions.py is in your current working directory or in your python path)
Step1: Fetch relevant files from stacks populations run
Step2: create 1... | Python Code:
import QTLight_functions as QTL
Explanation: Import the functions (assumes that QTLight_functions.py is in your current working directory or in your python path)
End of explanation
%%bash
ln -s test-data/batch_1.vcf.gz .
ln -s test-data/populationmap .
mkdir matrix
Explanation: Fetch relevant files from st... |
5,691 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Visualize VGG16 Filters
Visualization of the filters of VGG16, via gradient ascent in input space.
Step1: Create a function to extract and display the generated input
Step2: Build the VGG1... | Python Code:
from __future__ import print_function
from scipy.misc import imsave
import numpy as np
import time
from keras.applications import vgg16
from keras import backend as K
# dimensions of the generated pictures for each filter.
img_width = 128
img_height = 128
# the name of the layer we want to visualize
# (see... |
5,692 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SLTimer Example Analysis of TDC2 Data
This notebook shows you how to find the estimation of a lens time delay from TDC2 light curve data using the PyCS code. For a detailed tutorial through ... | Python Code:
from __future__ import print_function
import os, urllib, numpy as np
%matplotlib inline
import sys
sys.path.append('../python')
import desc.sltimer
%load_ext autoreload
%autoreload 2
Explanation: SLTimer Example Analysis of TDC2 Data
This notebook shows you how to find the estimation of a lens time delay f... |
5,693 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exercises
Rules
Step1: 2) (From jakevdp)
Step2: 3) Write a function called sum_digits that returns the sum of the digits of an integer argument; that is, sum_digits(123) should return 6. ... | Python Code:
#The following line will only work if you create the make_sentence.py in the current directory
import make_sentence.py
Explanation: Exercises
Rules:
Every variable/function/class name should be meaningful
Variable/function names should be lowercase, class names uppercase
Write a documentation string (even ... |
5,694 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Computing source space SNR
This example shows how to compute and plot source space SNR as in [1]_.
Step1: EEG
Next we do the same for EEG and plot the result on the cortex | Python Code:
# Author: Padma Sundaram <tottochan@gmail.com>
# Kaisu Lankinen <klankinen@mgh.harvard.edu>
#
# License: BSD (3-clause)
import mne
from mne.datasets import sample
from mne.minimum_norm import make_inverse_operator, apply_inverse
import numpy as np
import matplotlib.pyplot as plt
print(__doc__)
data... |
5,695 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
seaborn.violinplot
Violinplots summarize numeric data over a set of categories. They are essentially a box plot with a kernel density estimate (KDE) overlaid along the range of the box and r... | Python Code:
%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
plt.rcParams['figure.figsize'] = (20.0, 10.0)
plt.rcParams['font.family'] = "serif"
df = pd.read_csv('../../../datasets/movie_metadata.csv')
df.head()
Explanation: seaborn.violinplot
Violinplots ... |
5,696 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dimensionality Reduction with Eigenvector / Eigenvalues and Correlation Matrix (PCA)
inspired by http
Step1: First we need the correlation matrix
Step2: Eigenvalues
Step3: Eigenvector as ... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
from numpy import linalg as LA
from sklearn import datasets
iris = datasets.load_iris()
Explanation: Dimensionality Reduction with Eigenvector / Eigenvalues and Correlation Matrix (PCA)
inspired ... |
5,697 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Titanic Project
For this project, I want to investigate the unfortunate tragedy of the sinking of the Titanic. The movie "Titanic"- which I watched when I was still a child left a strong... | Python Code:
#load the libraries that I might need to use
%matplotlib inline
import pandas as pd
import numpy as np
import csv
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
#read the csv file into a pandas dataframe
titanic_original = pd.DataFrame.from_csv('titanic-data.csv', index_col=None)... |
5,698 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Extinction (ebv, Av, & Rv)
Setup
Let's first make sure we have the latest version of PHOEBE 2.4 installed. (You can comment out this line if you don't use pip for your installation or don't ... | Python Code:
#!pip install -I "phoebe>=2.4,<2.5"
Explanation: Extinction (ebv, Av, & Rv)
Setup
Let's first make sure we have the latest version of PHOEBE 2.4 installed. (You can comment out this line if you don't use pip for your installation or don't want to update to the latest release).
End of explanation
import pho... |
5,699 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Grid Generation with Interactive Widgets
This notebook demostrates how to use the interative widgets.
See a version of it in action
Step1: Main Tutorial
Step2: Loading and plotting the bo... | Python Code:
from IPython.display import Audio,Image, YouTubeVideo
YouTubeVideo('S5SG9km2f_A', height=450, width=900)
Explanation: Grid Generation with Interactive Widgets
This notebook demostrates how to use the interative widgets.
See a version of it in action:
End of explanation
%matplotlib inline
import warnings
w... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.