Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
9,700 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Critical Radii
Step1: As always, let's do imports and initialize a logger and a new Bundle.
Step2: Detached Systems
Detached systems are the default case for default_binary. The requiv_ma... | Python Code:
#!pip install -I "phoebe>=2.4,<2.5"
Explanation: Critical Radii: Detached Systems
Setup
Let's first make sure we have the latest version of PHOEBE 2.4 installed (uncomment this line if running in an online notebook session such as colab).
End of explanation
import phoebe
from phoebe import u # units
import... |
9,701 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Clustering with K-means
In the unsupervised setting, one of the most straightforward tasks we can perform is to find groups of data instances which are similar between each other. We call su... | Python Code:
import pandas as pd
import numpy as np
df = pd.read_csv('NAm2.txt', sep=" ")
print(df.head())
print(df.shape)
# List of populations/tribes
tribes = df.Pop.unique()
country = df.Country.unique()
print(tribes)
print(country)
# The features that we need for clustering starts from the 9th one
# Subset of the ... |
9,702 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Training a machine learning model with scikit-learn
From the video series
Step1: scikit-learn 4-step modeling pattern
Step 1
Step2: Step 2
Step3: Name of the object does not matter
Can sp... | Python Code:
# import load_iris function from datasets module
from sklearn.datasets import load_iris
# save "bunch" object containing iris dataset and its attributes
iris = load_iris()
# store feature matrix in "X"
X = iris.data
# store response vector in "y"
y = iris.target
# print the shapes of X and y
print X.shape
... |
9,703 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
통계적 사고 (2판) 연습문제 (thinkstats2.com, think-stat.xwmooc.org)<br>
Allen Downey / 이광춘(xwMOOC)
Step1: <tt>birthord</tt>에 대한 빈도수를 출력하고 codebook 게시된 결과값과 비교하시오.
Step2: <tt>prglngth</tt>에 대한 빈도수를 출... | Python Code:
import nsfg
df = nsfg.ReadFemPreg()
df
Explanation: 통계적 사고 (2판) 연습문제 (thinkstats2.com, think-stat.xwmooc.org)<br>
Allen Downey / 이광춘(xwMOOC)
End of explanation
df.birthord.value_counts().sort_index()
Explanation: <tt>birthord</tt>에 대한 빈도수를 출력하고 codebook 게시된 결과값과 비교하시오.
End of explanation
df.prglngth.value_... |
9,704 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Examples of @map_e, @fmap_e and map_element
This notebook had examples of map from IoTPy/IoTPy/agent_types/op.py
You can create an agent that maps an input stream to an output stream using m... | Python Code:
import os
import sys
sys.path.append("../")
from IoTPy.core.stream import Stream, run
from IoTPy.agent_types.op import map_element
from IoTPy.helper_functions.recent_values import recent_values
Explanation: Examples of @map_e, @fmap_e and map_element
This notebook had examples of map from IoTPy/IoTPy/agent... |
9,705 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<header class="w3-container w3-teal">
<img src="images/utfsm.png" alt="" align="left"/>
<img src="images/inf.png" alt="" align="right"/>
</header>
<br/><br/><br/><br/><br/>
IWI131
Programaci... | Python Code:
print len("\n")
a1 = 'casa\narbol\npatio'
print a1
print len(a1)
a2 = '''casa
arbol
patio'''
print a2
print len(a2)
print a1==a2
b = 'a\nb\nc'
print b
print len(b)
Explanation: <header class="w3-container w3-teal">
<img src="images/utfsm.png" alt="" align="left"/>
<img src="images/inf.png" alt="" align="ri... |
9,706 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Learning
This notebook serves as supporting material for topics covered in Chapter 18 - Learning from Examples , Chapter 19 - Knowledge in Learning, Chapter 20 - Learning Probabilistic Model... | Python Code:
from learning import *
Explanation: Learning
This notebook serves as supporting material for topics covered in Chapter 18 - Learning from Examples , Chapter 19 - Knowledge in Learning, Chapter 20 - Learning Probabilistic Models from the book Artificial Intelligence: A Modern Approach. This notebook uses im... |
9,707 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
INS-GPS Integration
This notebook shows an idealized example of loose INS-GPS integration.
Creating a trajectory and generating inertial readings
First we need to generate a trajectory. To k... | Python Code:
from pyins import sim
from pyins.coord import perturb_ll
def generate_trajectory(n_points, min_step, max_step, angle_spread, random_state=0):
rng = np.random.RandomState(random_state)
xy = [np.zeros(2)]
angle = rng.uniform(2 * np.pi)
heading = [90 - angle]
angle_spread = np.deg2rad... |
9,708 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tufte
A Jupyter notebook with examples of how to use tufte.
Introduction
Currently, there are four supported plot types
Step1: tufte plots can take inputs of several types
Step2: You'll no... | Python Code:
%matplotlib inline
import string
import random
from collections import defaultdict
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import tufte
Explanation: Tufte
A Jupyter notebook with examples of how to use tufte.
Introduction
Currently, there are four sup... |
9,709 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step2: Image_Augmentation
The following function takes the 8bit grayscale images that we are using and performs a series of affine transformations to the images. There are vertical and horiz... | Python Code:
# Function for rotating the image files.
def Image_Rotate(img, angle):
Rotates a given image the requested angle. Returns the rotated image.
rows,cols = img.shape
M = cv2.getRotationMatrix2D((cols/2,rows/2), angle, 1)
return(cv2.warpAffine(img,M,(cols,rows)))
# Function for augmen... |
9,710 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: BERT Question Answer with TensorFlow Lite Model Maker
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="htt... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# dist... |
9,711 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fractional optimization
This notebook shows how to solve a simple concave fractional problem, in which the objective is to maximize the ratio of a nonnegative concave function and a positive... | Python Code:
!pip install --upgrade cvxpy
import cvxpy as cp
import numpy as np
import matplotlib.pyplot as plt
Explanation: Fractional optimization
This notebook shows how to solve a simple concave fractional problem, in which the objective is to maximize the ratio of a nonnegative concave function and a positive
conv... |
9,712 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Comparing MC and LHS methods for sampling from a uniform distribution
This note compares the moments of the emperical uniform distribution sampled using Latin Hypercube sampling with Multi-D... | Python Code:
import numpy as np
import lhsmdu
import matplotlib.pyplot as plt
def simpleaxis(axes, every=False):
if not isinstance(axes, (list, np.ndarray)):
axes = [axes]
for ax in axes:
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
if every:
... |
9,713 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Изразът 0 <= seconds <= 59 e булев и има стойност True или False.
Step1: Т. е. горната функция е еквивалентна на
Step2: когато 0 <= seconds <= 59 е True, и на
Step3: когато 0 ... | Python Code:
seconds = 30
0 <= seconds <= 59
seconds = -1
0 <= seconds <= 59
Explanation: Изразът 0 <= seconds <= 59 e булев и има стойност True или False.
End of explanation
def valid_seconds(seconds):
if True:
return True
else:
return False
Explanation: Т. е. горната функция е еквивалент... |
9,714 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="http
Step1: Note
Step2: Include the input file that contains all input parameters needed for all components. This file can either be a Python dictionary or a text file that can be... | Python Code:
from __future__ import print_function
%matplotlib inline
import time
import numpy as np
from landlab.io import read_esri_ascii
from landlab import RasterModelGrid as rmg
from landlab import load_params
from Ecohyd_functions_DEM import (
Initialize_,
Empty_arrays,
Create_PET_lookup,
Save_,
... |
9,715 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TensorFlow Tutorial #02
Convolutional Neural Network
by Magnus Erik Hvass Pedersen
/ GitHub / Videos on YouTube
Introduction
The previous tutorial showed that a simple linear model had about... | Python Code:
from IPython.display import Image
Image('images/02_network_flowchart.png')
Explanation: TensorFlow Tutorial #02
Convolutional Neural Network
by Magnus Erik Hvass Pedersen
/ GitHub / Videos on YouTube
Introduction
The previous tutorial showed that a simple linear model had about 91% classification accuracy ... |
9,716 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
First, I made a mistake naming the data set! It's 2015 data, not 2014 data. But yes, still use 311-2014.csv. You can rename it.
Importing and preparing your data
Import your data, but only t... | Python Code:
#df = pd.read_csv('311-2010-2016.csv')
# We select a list of columns for a better efficiency
columns_list = ['Unique Key', 'Created Date', 'Closed Date', 'Agency', 'Agency Name',
'Complaint Type', 'Descriptor', 'Borough']
df = pd.read_csv('311-2015.csv', nrows=200000, usecols= columns_list)
df['Crea... |
9,717 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Monte Carlo Methods
Step1: Point to note
Step2: Efficiency
Note that the sum over all particles scales as $n^2$ where $n$ is the number of particles. As the number of steps the algorithm w... | Python Code:
from IPython.core.display import HTML
css_file = 'https://raw.githubusercontent.com/ngcm/training-public/master/ipython_notebook_styles/ngcmstyle.css'
HTML(url=css_file)
Explanation: Monte Carlo Methods: Lab 2
End of explanation
p_JZG_T2 = [0.1776, 0.329, 0.489, 0.7, 1.071, 1.75, 3.028, 5.285, 9.12]
Explan... |
9,718 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
层次聚类 Lab
在此 notebook 中,我们将使用 sklearn 对鸢尾花数据集执行层次聚类。该数据集包含 4 个维度/属性和 150 个样本。每个样本都标记为某种鸢尾花品种(共三种)。
在此练习中,我们将忽略标签和基于属性的聚类,并将不同层次聚类技巧的结果与实际标签进行比较,看看在这种情形下哪种技巧的效果最好。然后,我们将可视化生成的聚类层次。
1. 导入鸢尾花数据集... | Python Code:
from sklearn import datasets
iris = datasets.load_iris()
Explanation: 层次聚类 Lab
在此 notebook 中,我们将使用 sklearn 对鸢尾花数据集执行层次聚类。该数据集包含 4 个维度/属性和 150 个样本。每个样本都标记为某种鸢尾花品种(共三种)。
在此练习中,我们将忽略标签和基于属性的聚类,并将不同层次聚类技巧的结果与实际标签进行比较,看看在这种情形下哪种技巧的效果最好。然后,我们将可视化生成的聚类层次。
1. 导入鸢尾花数据集
End of explanation
iris.data[:10]
iris.target
... |
9,719 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Decision Trees
An introductory example of decision trees using data from this interactive visualization. This is an over-simplified example that doesn't use normalization as a pre-processing... | Python Code:
# Load packages
import pandas as pd
from sklearn import tree
from __future__ import division
from sklearn.cross_validation import train_test_split
from sklearn.neighbors import KNeighborsClassifier
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
# Read data
df = pd.read_csv('./data/ho... |
9,720 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
imports
Step1: importing datasets
Step2: pretty cleaned datasets ( Majority numbers, so dont forget to use gplearn (Genetic Programming Module) plus different feats on basis of +,-,*,/
Ste... | Python Code:
%load_ext autoreload
%autoreload 2
%matplotlib inline
import time
import xgboost as xgb
import lightgbm as lgb
# import category_encoders as cat_ed
# import gc, mlcrate, glob
# from gplearn.genetic import SymbolicTransformer, SymbolicRegressor
from fastai.imports import *
from fastai.structured import *
fr... |
9,721 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tuning query parameters for the MSMARCO Document dataset
The following shows a principled, data-driven approach to tuning parameters of a basic query, such as field boosts, using the MSMARCO... | Python Code:
%load_ext autoreload
%autoreload 2
import importlib
import os
import sys
from elasticsearch import Elasticsearch
from skopt.plots import plot_objective
# project library
sys.path.insert(0, os.path.abspath('..'))
import qopt
importlib.reload(qopt)
from qopt.notebooks import evaluate_mrr100_dev, optimize_que... |
9,722 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Reverse engineering a dynamic web page
Initialization
Import modules needed below. It is assumed a downloader.py module is in the working directory.
Step1: First attempt
Step2: Clearly not... | Python Code:
import os, json
import lxml.html
import cssselect
import pprint
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtWebKit import *
# go to working dir, where a module downloader.py should exist
os.chdir(r'C:\Users\ps\Desktop\python\work\web scraping')
from downloader import Downloader ... |
9,723 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1> Feature Engineering </h1>
In this notebook, you will learn how to incorporate feature engineering into your pipeline.
<ul>
<li> Working with feature columns </li>
<li> Adding feature cr... | Python Code:
%%bash
sudo pip install httplib2==0.12.0 apache-beam[gcp]==2.16.0
Explanation: <h1> Feature Engineering </h1>
In this notebook, you will learn how to incorporate feature engineering into your pipeline.
<ul>
<li> Working with feature columns </li>
<li> Adding feature crosses in TensorFlow </li>
<li> Reading... |
9,724 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Land
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify do... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'bcc', 'bcc-esm1', 'land')
Explanation: ES-DOC CMIP6 Model Properties - Land
MIP Era: CMIP6
Institute: BCC
Source ID: BCC-ESM1
Topic: Land
Sub-Topics: Soil, Snow, Vegetation, Energy Ba... |
9,725 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Boundary Layer Solver
This notebook will develop a numerical method for solving the boundary layer momentum integral equation using Pohlhausen velocity profiles.
Momentum integral equation
I... | Python Code:
import numpy
def pohlF(eta): return 2*eta-2*eta**3+eta**4
def pohlG(eta): return eta/6*(1-eta)**3
from matplotlib import pyplot
%matplotlib inline
def pohlPlot(lam):
pyplot.xlabel(r'$u/u_e$', fontsize=16)
pyplot.axis([-0.1,1.1,0,1])
pyplot.ylabel(r'$y/\delta$', fontsize=16)
eta = numpy.lins... |
9,726 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Analyzing the NYC Subway Dataset
Questions
Overview
This project consists of two parts. In Part 1 of the project, you should have completed the questions in Problem Sets 2, 3, and 4 in the I... | Python Code:
import pandas as pd
import pandasql as pdsql
import datetime as dt
import numpy as np
import scipy as sc
import scipy.stats
import statsmodels.api as sm
from sklearn.linear_model import SGDRegressor
from ggplot import *
%matplotlib inline
Explanation: Analyzing the NYC Subway Dataset
Questions
Overview
Thi... |
9,727 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
title
Step1: In order to call one of the functions belonging to a particular module, you can use the . syntax. For example, numpy has a mean() function which will compute the arithmetic mea... | Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_context("poster")
sns.set(style="ticks",font="Arial",font_scale=2)
Explanation: title: "Data Cleaning in Python"
subtitle: "CU Psych Scientific Computing Workshop"
weight: 1201
tags: ["core", "python"]
Goal... |
9,728 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Compute
Now that we have datasets added to our Bundle, our next step is to run the forward model and compute a synthetic model for each of these datasets.
Setup
Let's first make sure we have... | Python Code:
!pip install -I "phoebe>=2.0,<2.1"
Explanation: Compute
Now that we have datasets added to our Bundle, our next step is to run the forward model and compute a synthetic model for each of these datasets.
Setup
Let's first make sure we have the latest version of PHOEBE 2.0 installed. (You can comment out thi... |
9,729 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Draw sample MNIST images from dataset
Demonstrates how to sample and plot MNIST digits using tf.keras API.
Using tf.keras.datasets, loading the MNIST data is just 1-line of code. After loadi... | Python Code:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.keras.datasets import mnist
import matplotlib.pyplot as plt
# load dataset
(x_train, y_train), (x_test, y_test) = mnist.load_data()
Explanation: Draw sample MNIST ... |
9,730 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
QuTiP Example
Step1: Plotting Support
Step2: Jaynes-Cummings model, with the cavity as a non-Markovian bath
As a simple example, we consider the Jaynes-Cummings mode, and the non-Markovian... | Python Code:
import numpy as np
import qutip as qt
from qutip.ipynbtools import version_table
import qutip.nonmarkov.transfertensor as ttm
Explanation: QuTiP Example: The Transfer Tensor Method for Non-Markovian Open Quantum Systems
Arne L. Grimsmo <br>
Université de Sherbrooke <br>
arne.grimsmo@gmail.com
$\newcommand{... |
9,731 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Profiling and Optimizing
By C Hummels (Caltech)
Step1: It can be hard to guess which code is going to operate faster just by looking at it because the interactions between software and comp... | Python Code:
import random
import numpy as np
from matplotlib import pyplot as plt
Explanation: Profiling and Optimizing
By C Hummels (Caltech)
End of explanation
string_list = ['the ', 'quick ', 'brown ', 'fox ', 'jumped ', 'over ', 'the ', 'lazy ', 'dog']
%%timeit
output = ""
# complete
%%timeit
# complete
%%timeit
o... |
9,732 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Build your own NER Tagger
Named Entity Recognition (NER) , also known as entity chunking/extraction , is a popular technique used in information extraction to identify and segment the named ... | Python Code:
import pandas as pd
df = pd.read_csv('ner_dataset.csv.gz', compression='gzip', encoding='ISO-8859-1')
df.info()
df.T
df = df.fillna(method='ffill')
df.info()
df.T
df['Sentence #'].nunique(), df.Word.nunique(), df.POS.nunique(), df.Tag.nunique()
Explanation: Build your own NER Tagger
Named Entity Recognitio... |
9,733 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Land
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify do... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'hammoz-consortium', 'sandbox-2', 'land')
Explanation: ES-DOC CMIP6 Model Properties - Land
MIP Era: CMIP6
Institute: HAMMOZ-CONSORTIUM
Source ID: SANDBOX-2
Topic: Land
Sub-Topics: Soi... |
9,734 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Q6
In this question, we'll dive more deeply into some of the review questions from the last flipped session.
A
In one of the review questions, we discussed creating nested for-loops in order... | Python Code:
def my_pairs(x):
list_of_pairs = []
### BEGIN SOLUTION
### END SOLUTION
return list_of_pairs
try:
combinations
itertools.combinations
except:
assert True
else:
assert False
from itertools import combinations as c
i1 = [1, 2, 3]
a1 = set(list(c(i1, 2)))
assert ... |
9,735 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Piecewise Exact Integration
The Dynamical System
We want to study a damped SDOF system, so characterized
Step1: The excitation is given by a force such that the static displacement is 5 mm,... | Python Code:
T=1.0 # Natural period of the oscillator
w=2*pi # circular frequency of the oscillator
m=1000.0 # oscillator's mass, in kg
k=m*w*w # oscillator stifness, in N/m
z=0.05 # damping ratio over critical
c=2*z*m*w # dampin... |
9,736 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
(DGFLUJOREDES)=
4.2 Definiciones generales de flujo en redes
```{admonition} Notas para contenedor de docker
Step1: ```{admonition} Comentarios
Los siguientes nombres son utilizados para re... | Python Code:
import matplotlib.pyplot as plt
import networkx as nx
nodes_pos_ex_1 = [[0.09090909090909091, 0.4545454545454546],
[0.36363636363636365, 0.7272727272727273],
[0.36363636363636365, 0.18181818181818182],
[0.6363636363636364, 0.7272727272727273],
... |
9,737 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Auto MPG Data
Step1: 2D Binning
Default behavior for 2d binning is to bin the dimensions provided, then count the rows that fall into each bin. This is visualizing how the source data repre... | Python Code:
df.head()
Explanation: Auto MPG Data
End of explanation
hm = HeatMap(df, x=bins('mpg'), y=bins('displ'))
show(hm)
Explanation: 2D Binning
Default behavior for 2d binning is to bin the dimensions provided, then count the rows that fall into each bin. This is visualizing how the source data represents all po... |
9,738 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simple Maps in IPython
This notebook demonstrates the basics of mapping data in IPython. All you need is a simple dataset, containing coordinate values.
Step1: And now let's test if the Bas... | Python Code:
%pylab inline
from pylab import *
pylab.rcParams['figure.figsize'] = (8.0, 6.4)
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
Explanation: Simple Maps in IPython
This notebook demonstrates the basics of mapping data in IPython. All you need is a simple dataset,... |
9,739 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Security-Constrained Optimisation
In this example, the dispatch of generators is optimised using the security-constrained linear OPF, to guaranteed that no branches are overloaded by certain... | Python Code:
import pypsa, os
import numpy as np
network = pypsa.examples.scigrid_de(from_master=True)
Explanation: Security-Constrained Optimisation
In this example, the dispatch of generators is optimised using the security-constrained linear OPF, to guaranteed that no branches are overloaded by certain branch outage... |
9,740 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data
We have the CSV file output of a git blame result.
Step1: Main Contributors
The blame file incorporates every single line of code with the author that changed that line at last.
Step2:... | Python Code:
import pandas as pd
blame_log = pd.read_csv("../demos/dataset/linux_blame_log.csv")
blame_log.head()
blame_log.info()
Explanation: Data
We have the CSV file output of a git blame result.
End of explanation
top10 = blame_log.author.value_counts().head(10)
top10
%matplotlib inline
top10_authors.plot.pie();
E... |
9,741 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
.. _tut_stats_cluster_source_rANOVA
Step1: Set parameters
Step2: Read epochs for all channels, removing a bad one
Step3: Transform to source space
Step4: Transform to common cortical spa... | Python Code:
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# Eric Larson <larson.eric.d@gmail.com>
# Denis Engemannn <denis.engemann@gmail.com>
#
# License: BSD (3-clause)
import os.path as op
import numpy as np
from numpy.random import randn
import matplotlib.pyplot as plt
i... |
9,742 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Hub Authors.
Licensed under the Apache License, Version 2.0 (the "License");
Step1: 映画レビューを使ったテキスト分類
<table class="tfo-notebook-buttons" align="left">
<td><a... | Python Code:
# Copyright 2019 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... |
9,743 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using pymldb Tutorial
Interactions with MLDB occurs via a REST API. Interacting with a REST API over HTTP from a Notebook interface can be a little bit laborious if you're using a general-pu... | Python Code:
from pymldb import Connection
mldb = Connection("http://localhost")
Explanation: Using pymldb Tutorial
Interactions with MLDB occurs via a REST API. Interacting with a REST API over HTTP from a Notebook interface can be a little bit laborious if you're using a general-purpose Python library like requests d... |
9,744 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This challenge will get you familiar with the basic elements of Python by programming a simple card game. We will create a custom class to represent each player in the game, which will store... | Python Code:
import random
Explanation: This challenge will get you familiar with the basic elements of Python by programming a simple card game. We will create a custom class to represent each player in the game, which will store information about their current pot, as well as a series of methods defining how they pla... |
9,745 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tarea 2, parte 2
<hr>
Pregunta 1
Según <a href="https
Step1: <hr>
Pregunta 3
A simple vista, aproximadamente, se tiene
$T_T = 0.7$ d
$T_F = 0.4$ d
$\Delta F = 0.003$
Con esto, se calculan l... | Python Code:
import numpy as np
from scipy.signal import medfilt
import matplotlib.pyplot as plt
import kplr
%matplotlib inline
client = kplr.API()
koi = client.koi(1274.01)
lcs = koi.get_light_curves(short_cadence=True)
p = 704.2
time, flux, ferr, med = [], [], [], []
for lc in lcs:
with lc.open() as f:
# ... |
9,746 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Probability Authors.
Licensed under the Apache License, Version 2.0 (the "License");
Step1: Eight schools
<table class="tfo-notebook-buttons" align="left">
<... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" }
# 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... |
9,747 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Prediction using the bottom up method
This notebook details the process of prediction from which homework a notebook came after featurizing the notebook using the bottom up method. This is d... | Python Code:
import sys
home_directory = '/dfs/scratch2/fcipollone'
sys.path.append(home_directory)
import numpy as np
from nbminer.notebook_miner import NotebookMiner
hw_filenames = np.load('../homework_names_jplag_combined_per_student.npy')
hw_notebooks = [[NotebookMiner(filename) for filename in temp[:59]] for temp ... |
9,748 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
One Queue or Two
Modeling and Simulation in Python
Copyright 2021 Allen Downey
License
Step1: This notebook presents a case study from Modeling and Simulation in Python. It explores a ques... | Python Code:
# install Pint if necessary
try:
import pint
except ImportError:
!pip install pint
# download modsim.py if necessary
from os.path import exists
filename = 'modsim.py'
if not exists(filename):
from urllib.request import urlretrieve
url = 'https://raw.githubusercontent.com/AllenDowney/ModSim/... |
9,749 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Reading and writing raw files
In this example, we read a raw file. Plot a segment of MEG data
restricted to MEG channels. And save these data in a new
raw file.
Step1: Show MEG data | Python Code:
# Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD (3-clause)
import mne
from mne.datasets import sample
print(__doc__)
data_path = sample.data_path()
fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
raw = mne.io.read_raw_fif(fname)
# Set up pick list: MEG + STI 014 - bad ch... |
9,750 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
モデル化
Next >> 0_quickstart
Prev >> editing
シミュレーションを行う際に一番最初に行うのは モデル化 である.シミュレーションの結果は,どのようにモデル化を行ったかによって大きく影響される.当然ではあるが.
例えば,単振り子のシミュレーションにおいて,0_quickstartでは 摩擦 による運動の減衰を考えなかったが,これを考えてモデル化... | Python Code:
import numpy as np
from scipy.integrate import odeint
from math import sin
''' constants '''
m = 1 # mass of the pendulum [kg]
l = 1 # length of the pendulum [m]
g = 10 # Gravitational acceleration [m/s^2]
c = 0.3 # Damping constant [kg.m/(rad.s)]
''' time setting '''
t_end = 10 # simulation time [s]
t_fps... |
9,751 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
GA4GH IPython Example Notebook
This notebook provides an overview of how to call a the GA4GH reference server from an iPython notebook. Before running this notebook
Step1: Great! Now we ca... | Python Code:
baseURL = "http://localhost:8000"
client = ga4gh.client.HttpClient(baseURL)
Explanation: GA4GH IPython Example Notebook
This notebook provides an overview of how to call a the GA4GH reference server from an iPython notebook. Before running this notebook:
git clone https://github.com/ga4gh/server.git -b de... |
9,752 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Training a neural network on MNIST with Keras
This simple example demonstrates how to plug TensorFlow Datasets (TFDS) into a Keras model.
Copyright 2020 The TensorFlow Datasets Authors, Lice... | Python Code:
import tensorflow as tf
import tensorflow_datasets as tfds
Explanation: Training a neural network on MNIST with Keras
This simple example demonstrates how to plug TensorFlow Datasets (TFDS) into a Keras model.
Copyright 2020 The TensorFlow Datasets Authors, Licensed under the Apache License, Version 2.0
<t... |
9,753 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Correlating microstripline model to measurement
Target
The aim of this example is to correlate the microstripline model to the measurement over 4 frequency decades from 1MHz to 5GHz.
Plan
Tw... | Python Code:
%load_ext autoreload
%autoreload 2
import skrf as rf
import numpy as np
from numpy import real, log10, sum, absolute, pi, sqrt
import matplotlib.pyplot as plt
from scipy.optimize import minimize, differential_evolution
rf.stylely()
Explanation: Correlating microstripline model to measurement
Target
The aim... |
9,754 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ejercicios 2
1 Ejercicio
Escribir una función que reciba como parámetro una lista de elementos y devuelva el valor True si la lista posee elementos y False en caso contrario.
Step1: 2 Ejerc... | Python Code:
def tieneElementos(milista):
return len(milista) > 0
print(tieneElementos([]))
print(tieneElementos([1, 3, 96]))
Explanation: Ejercicios 2
1 Ejercicio
Escribir una función que reciba como parámetro una lista de elementos y devuelva el valor True si la lista posee elementos y False en caso contrario.
En... |
9,755 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1>WorkCamp # Maschinelles Lernen - ## Grundlagen - ###2018</h1>
<h2>Praktische Übung</h2>
<h3>Beispiel xx # Arbeiten mit Sensordaten ## Feature Selektion</h3>
Problemstellung
Step1: Probl... | Python Code:
# Laden der entsprechenden Module (kann etwas dauern !)
# Wir laden die Module offen, damit man einmal sieht, was da alles benötigt wird
# Allerdings aufpassen, dann werden die Module anderst angesprochen wie beim Standard
# zum Beispiel pyplot und nicht plt
from matplotlib import pyplot
pyplot.rcParams["f... |
9,756 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
RateChar
RateChar is a tool for performing generalised supply-demand analysis (GSDA) [2,3]. This entails the generation data needed to draw rate characteristic plots for all the variable spe... | Python Code:
mod = pysces.model('lin4_fb.psc')
rc = psctb.RateChar(mod)
Explanation: RateChar
RateChar is a tool for performing generalised supply-demand analysis (GSDA) [2,3]. This entails the generation data needed to draw rate characteristic plots for all the variable species of metabolic model through parameter sca... |
9,757 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Clustering
Clustering techniques are unsupervised learning algorithms that try to group unlabelled data into "clusters", using the (typically spatial) structure of the data itself.
The easie... | Python Code:
%matplotlib inline
import math, numpy as np, matplotlib.pyplot as plt, operator, torch
Explanation: Clustering
Clustering techniques are unsupervised learning algorithms that try to group unlabelled data into "clusters", using the (typically spatial) structure of the data itself.
The easiest way to demonst... |
9,758 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Calculate mean width and lenght from test images
Step1: Size mean dimension will be used for the resizing process. All the images will be scaled to (149, 149) since it's the average of the ... | Python Code:
import os, random
from scipy.misc import imread, imresize
width = 0
lenght = 0
num_test_images = len(test_image_names)
for i in range(num_test_images):
path_file = os.path.join(test_root_path, test_image_names[i])
image = imread(path_file)
width += image.shape[0]
lenght += image.shape[1]
wi... |
9,759 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Preferential Attachment
Outline
- Basic Simulation and Plot
Step1: Simulation
Step2: Experiment 1
- Alpha = 1,
- hypothesis
Step3: Experiment 2
- Alpha < 1,
- Hypothesis
Step4: Exper... | Python Code:
import networkx as netx
import numpy as np
import matplotlib.pyplot as plt
import warnings
import random
import itertools
def power_law_graph(G):
histo = netx.degree_histogram(G)
_ = plt.loglog(histo, 'b-', marker='o')
_ = plt.ylabel("k(x)")
_ = plt.xlabel("k")
plt.show()
def plot(T,sk... |
9,760 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tips for Selecting Columns in a DataFrame
Notebook to accompany this post.
Step1: Build a mapping list so we can see the index of all the columns
Step2: We can also build a dictionary
Step... | Python Code:
import pandas as pd
import numpy as np
df = pd.read_csv(
'https://data.cityofnewyork.us/api/views/vfnx-vebw/rows.csv?accessType=DOWNLOAD&bom=true&format=true'
)
Explanation: Tips for Selecting Columns in a DataFrame
Notebook to accompany this post.
End of explanation
col_mapping = [f"{c[0]}:{c[1]}" for... |
9,761 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
scikit-learn is a machine learning library for python, with a very easy to use API and great documentation.
Step1: Lets load up our trajectory. This is the trajectory that we generated in
t... | Python Code:
%matplotlib inline
from __future__ import print_function
import mdtraj as md
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
Explanation: scikit-learn is a machine learning library for python, with a very easy to use API and great documentation.
End of explanation
traj = md.load('ala2... |
9,762 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using MBA
cmin and cmax are coordinates of the bottom-left and the top-right corners of the bounding box containing scattered data. coo and val are arrays containing coordinates and values o... | Python Code:
cmin = [0.0, 0.0]
cmax = [1.0, 1.0]
coo = uniform(0, 1, (7,2))
val = uniform(0, 1, coo.shape[0])
Explanation: Using MBA
cmin and cmax are coordinates of the bottom-left and the top-right corners of the bounding box containing scattered data. coo and val are arrays containing coordinates and values of the... |
9,763 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Two Object Tracking
Summary of notebook
<b> Kalman filter
Step1: Target information
Step2: The Kalman Filter Model
Step3: Motion and measurement models
Step4: Priors
Step5: Linear Kalma... | Python Code:
%matplotlib inline
%load_ext autoreload
%autoreload 2
import numpy as np
from matplotlib import pylab as plt
from mpl_toolkits import mplot3d
from canonical_gaussian import CanonicalGaussian as CG
from gaussian_mixture import GaussianMixtureModel as GMM
from calc_traj import calc_traj
from range_doppler im... |
9,764 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Apply logistic regression to categorize whether a county had high mortality rate due to contamination
1. Import the necessary packages to read in the data, plot, and create a logistic regres... | Python Code:
import pandas as pd
%matplotlib inline
import numpy as np
from sklearn.linear_model import LogisticRegression
import statsmodels.formula.api as smf
Explanation: Apply logistic regression to categorize whether a county had high mortality rate due to contamination
1. Import the necessary packages to read in ... |
9,765 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Unit 1
Step1: your explanation here (delete this)
2. If the temperature of an oven is 450 degrees Fahrenheit, what is it in kelvins? | Python Code:
## your code here
## or
## type what you put in calculator (safer to convert cell to markdown)
Explanation: Unit 1: Programming Basics
Lesson 1: Introduction to Python - Pre-activity
Scientific Context: Unit Conversions
The International System of Units (SI) is the modern metric system of measurement. It ... |
9,766 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
If, Elif, Else Statements
Programming starts and ends at control flow. Decisions need to be made to carry out the functions you write. We make decisions use the if, elif, and else statement.... | Python Code:
you = "ready"
if you == "ready":
print("Vamanos!")
else:
print("What's wrong?")
Explanation: If, Elif, Else Statements
Programming starts and ends at control flow. Decisions need to be made to carry out the functions you write. We make decisions use the if, elif, and else statement. Like any other ... |
9,767 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="http
Step1: 1. Load a shapefile that represents the river network
First, we need to create a Landlab NetworkModelGrid to represent the river network. Each link on the grid represen... | Python Code:
import warnings
warnings.filterwarnings('ignore')
import os
import pathlib
import matplotlib.pyplot as plt
import numpy as np
from landlab.components import FlowDirectorSteepest, NetworkSedimentTransporter
from landlab.data_record import DataRecord
from landlab.grid.network import NetworkModelGrid
from lan... |
9,768 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1D Optimal Classifier Compared With a Simple Neural Network
This tutorial is part of the EFI Data Analytics for Physics workshop. It is meant for the beginner HEP undergraduate or graduate s... | Python Code:
# Import the print function that is compatible with Python 3
from __future__ import print_function
# Import numpy - the fundamental package for scientific computing with Python
import numpy as np
# Import plotting Python plotting from matplotlib
import matplotlib.pyplot as plt
Explanation: 1D Optimal Clas... |
9,769 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1D Wasserstein barycenter demo
This example illustrates the computation of regularized Wassersyein Barycenter
as proposed in [3].
[3] Benamou, J. D., Carlier, G., Cuturi, M., Nenna, L., & Pe... | Python Code:
# Author: Remi Flamary <remi.flamary@unice.fr>
#
# License: MIT License
import numpy as np
import matplotlib.pylab as pl
import ot
# necessary for 3d plot even if not used
from mpl_toolkits.mplot3d import Axes3D # noqa
from matplotlib.collections import PolyCollection
Explanation: 1D Wasserstein barycente... |
9,770 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simulating the 1945 Makran Tsunami using Thetis
The 1945 Makran Tsunami was a large tsunami which originated due to the 1945 Balochistan earthquake. The resulting tsunami is beielved to have... | Python Code:
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import scipy.interpolate # used for interpolation
import pyproj # used for coordinate transformations
import math
from thetis import *
Explanation: Simulating the 1945 Makran Tsunami using Thetis
The 1945 Makran Tsunami was a large tsun... |
9,771 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Aligning MRS voxels with the anatomy
Several steps in the analysis and interpertation of the MRS data require knowledge of the anatomical location of the volume from which MRS data was acqui... | Python Code:
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
%matplotlib inline
import os.path as op
import nibabel as nib
import MRS.data as mrd
import IPython.html.widgets as wdg
import IPython.display as display
mrs_nifti = nib.load(op.join(mrd.data_folder, '12_1_PROBE_MEGA_L_Occ.nii.gz'))
t1_ni... |
9,772 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<!--BOOK_INFORMATION-->
<a href="https
Step1: Then we can visualize Lena with the following command (don't forget to switch the BGR
ordering of the color channels to RGB)
Step2: The image ... | Python Code:
import cv2
import numpy as np
lena = cv2.imread('data/lena.jpg', cv2.IMREAD_COLOR)
import matplotlib.pyplot as plt
%matplotlib inline
plt.style.use('ggplot')
plt.rc('axes', **{'grid': False})
Explanation: <!--BOOK_INFORMATION-->
<a href="https://www.packtpub.com/big-data-and-business-intelligence/machine-l... |
9,773 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Notebook arguments
measurement_id (int)
Step1: Selecting a data file
Step2: Data load and Burst search
Load and process the data
Step3: Compute background and burst search
Step4: Perform... | Python Code:
import time
from pathlib import Path
import pandas as pd
from scipy.stats import linregress
from IPython.display import display
from fretbursts import *
sns = init_notebook(fs=14)
import lmfit; lmfit.__version__
import phconvert; phconvert.__version__
Explanation: Notebook arguments
measurement_id (int): S... |
9,774 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deriving coefficients for the implicit scheme
The ice sheet energy balance model uses an implicit scheme to solve the
heat equation for $N$ layers. It uses the Crank-Nicholson scheme to disc... | Python Code:
from sympy import *
init_printing()
tnew_x = Symbol('T^{i+1}_x')
tnew_xprev = Symbol('T^{i+1}_{x-1}')
tnew_xafter = Symbol('T^{i+1}_{x+1}')
told_x = Symbol('T^{i}_x')
told_xprev = Symbol('T^{i}_{x-1}')
told_xafter = Symbol('T^{i}_{x+1}')
u_x = Symbol('\kappa_x')
u_xprev = Symbol('\kappa_{x-1}')
u_xafter = ... |
9,775 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
YAML support is provided by PyYAML at http
Step2: The following cell provides an initial example of a note in our system.
A note is nothing more than a YAML document. The idea of notetakin... | Python Code:
import yaml
Explanation: YAML support is provided by PyYAML at http://pyyaml.org/. This notebook depends on it.
End of explanation
myFirstZettel=
title: First BIB Note for Castells
tags:
- Castells
- Network Society
- Charles Babbage is Awesome
- Charles Didn't do Everything
mentions:
- gkt
- d... |
9,776 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
QuickDraw Data
If machine learning is rocket science then data is your fuel! So before
doing anything we will have a close look at the data available and spend
some time bringing it into the... | Python Code:
data_path = '/content/gdrive/My Drive/amld_data'
# Alternatively, you can also store the data in a local directory. This method
# will also work when running the notebook in Jupyter instead of Colab.
# data_path = './amld_data
if data_path.startswith('/content/gdrive/'):
from google.colab import drive
... |
9,777 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data Bootcamp
Step1: Population by age
We have both "estimates" of the past (1950-2015) and "projections" of the future (out to 2100). Here we focus on the latter, specifically what the UN... | Python Code:
# import packages
import pandas as pd # data management
import matplotlib.pyplot as plt # graphics
import matplotlib as mpl # graphics parameters
import numpy as np # numerical calculations
# IPython command, puts plots in notebook
%matplotlib inl... |
9,778 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sinkhorn Divergence Hessians
Samples two point clouds, computes their sinkhorn_divergence
We show in this colab how OTT and JAX can be used to compute automatically the Hessian of the Sinkho... | Python Code:
import jax
import jax.numpy as jnp
import ott
from ott.tools import sinkhorn_divergence
from ott.geometry import pointcloud
import matplotlib.pyplot as plt
Explanation: Sinkhorn Divergence Hessians
Samples two point clouds, computes their sinkhorn_divergence
We show in this colab how OTT and JAX can be use... |
9,779 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<p><font size="6"><b>Visualization - Matplotlib</b></font></p>
© 2021, Joris Van den Bossche and Stijn Van Hoey. Licensed under CC BY 4.0 Creative Commons
Matplotlib
Matplotlib is a Python p... | Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
Explanation: <p><font size="6"><b>Visualization - Matplotlib</b></font></p>
© 2021, Joris Van den Bossche and Stijn Van Hoey. Licensed under CC BY 4.0 Creative Commons
Matplotlib
Matplotlib is a Python package used widely throughout the... |
9,780 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SemCor
SemCor is a WordNet annotated subset of the Brown corpus. WordNet has coarse features for nouns and verbs, called "supersenses". These are things like "NOUN.BODY", "VERB.MOTION". Supe... | Python Code:
import pandas as pd
from nltk.corpus import semcor
from nltk.corpus.reader.wordnet import Lemma
tagged_chunks = semcor.tagged_chunks(tag='both')
tagged_chunks = list(tagged_chunks) # takes ages
Explanation: SemCor
SemCor is a WordNet annotated subset of the Brown corpus. WordNet has coarse features for nou... |
9,781 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Predicting Student Admissions with Neural Networks in Keras
In this notebook, we predict student admissions to graduate school at UCLA based on three pieces of data
Step1: Plotting the data... | Python Code:
# Importing pandas and numpy
import pandas as pd
import numpy as np
# Reading the csv file into a pandas DataFrame
data = pd.read_csv('student_data.csv')
# Printing out the first 10 rows of our data
data[:10]
Explanation: Predicting Student Admissions with Neural Networks in Keras
In this notebook, we pred... |
9,782 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Extra 3.2 - Historical Provenance - Application 3
Step1: Labelling data
Since we are only interested in the instruction messages, we categorise the data entity into two sets
Step2: Balanci... | Python Code:
import pandas as pd
filepath = "rrg/ancestor-graphs.csv"
df = pd.read_csv(filepath, index_col=0)
df.head()
Explanation: Extra 3.2 - Historical Provenance - Application 3: RRG Chat Messages
Identifying instructions from chat messages in the Radiation Response Game.
In this notebook, we explore the performan... |
9,783 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
WASP-80b broadband analysis
3a. Gaussian process hyperparameter estimation I
Hannu Parviainen, Instituto de Astrofísica de Canarias<br>
This notebook works as an appendix to Parviainen et al... | Python Code:
%pylab inline
%run __init__.py
from exotk.utils.misc import fold
from src.extcore import *
Explanation: WASP-80b broadband analysis
3a. Gaussian process hyperparameter estimation I
Hannu Parviainen, Instituto de Astrofísica de Canarias<br>
This notebook works as an appendix to Parviainen et al., Ground bas... |
9,784 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
'rv' Datasets and Options
Setup
Let's first make sure we have the latest version of PHOEBE 2.3 installed (uncomment this line if running in an online notebook session such as colab).
Step1: ... | Python Code:
#!pip install -I "phoebe>=2.3,<2.4"
Explanation: 'rv' Datasets and Options
Setup
Let's first make sure we have the latest version of PHOEBE 2.3 installed (uncomment this line if running in an online notebook session such as colab).
End of explanation
import phoebe
from phoebe import u # units
logger = phoe... |
9,785 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Heat Transfer Conduction Calculations
This jupyter notebook walks through basic heat transfer calculations.
There are three basic types of heat transfer
Step1: 1. Conduction
Conduction is d... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
Explanation: Heat Transfer Conduction Calculations
This jupyter notebook walks through basic heat transfer calculations.
There are three basic types of heat transfer:
1. Conduction
1. Convection
1. Radiation
This tutorial covers conduction calculations
We ... |
9,786 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1> Create TensorFlow DNN model </h1>
This notebook illustrates
Step1: <h2> Create TensorFlow model using TensorFlow's Estimator API </h2>
<p>
First, write an input_fn to read the data.
St... | Python Code:
!sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst
# Ensure the right version of Tensorflow is installed.
!pip freeze | grep tensorflow==2.1
# change these to try this notebook out
BUCKET = 'cloud-training-demos-ml'
PROJECT = 'cloud-training-demos'
REGION = 'us-central1'
import os
os.enviro... |
9,787 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Test for Mohammed
This container was started with
sudo docker run -d -p 433
Step1: Here are the RadarSat-2 quadpol coherency matrix image directories as created from the Sentinel-1 Toolbox
... | Python Code:
%matplotlib inline
Explanation: Test for Mohammed
This container was started with
sudo docker run -d -p 433:8888 --name=sar -v /home/mort/imagery/mohammed/Data:/home/imagery mort/sardocker
End of explanation
ls /home/imagery
Explanation: Here are the RadarSat-2 quadpol coherency matrix image directories as... |
9,788 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Epoching and averaging (ERP/ERF)
Step1: In MNE, epochs refers to a collection of single trials or short segments
of time locked raw data. If you haven't already, you might want to check out... | Python Code:
import os.path as op
import numpy as np
import mne
Explanation: Epoching and averaging (ERP/ERF)
End of explanation
data_path = mne.datasets.sample.data_path()
fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(fname, add_eeg_ref=False)
raw.set_eeg_reference() #... |
9,789 | 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... |
9,790 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
k-Nearest Neighbor (kNN) exercise
Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet) with your assignment submission. For ... | Python Code:
# Run some setup code for this notebook.
import random
import numpy as np
from data_utils import load_CIFAR10
import matplotlib.pyplot as plt
# This is a bit of magic to make matplotlib figures appear inline in the notebook
# rather than in a new window.
%matplotlib inline
plt.rcParams['figure.figsize'] = ... |
9,791 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook works out the expected hillslope sediment flux, topography, and soil thickness for steady state on a 4x7 grid. This provides "ground truth" values for tests.
Let the hillslope ... | Python Code:
D = 0.01
Sc = 0.8
Hstar = 0.5
E = 0.0001
P0 = 0.0002
Explanation: This notebook works out the expected hillslope sediment flux, topography, and soil thickness for steady state on a 4x7 grid. This provides "ground truth" values for tests.
Let the hillslope erosion rate be $E$, the flux coefficient $D$, crit... |
9,792 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Multimodal multivariate Gaussian
We can create a multimodal multivariate gaussian using MultimodalGaussianLogPDF. By default, this has the distribution
$$ p(\boldsymbol{x}) \propto \mathcal{... | Python Code:
import pints
import pints.toy
import numpy as np
import matplotlib.pyplot as plt
# Create log pdf
log_pdf = pints.toy.MultimodalGaussianLogPDF()
# Contour plot of pdf
levels = np.linspace(-3,12,20)
num_points = 100
x = np.linspace(-5, 15, num_points)
y = np.linspace(-5, 15, num_points)
X, Y = np.meshgrid(x... |
9,793 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Construct data and experiments directorys from environment variables
Step1: Specify main run parameters
Step2: Load data and normalise inputs
Step3: Specify prior parameters (data depende... | Python Code:
data_dir = os.path.join(os.environ['DATA_DIR'], 'uci')
exp_dir = os.path.join(os.environ['EXP_DIR'], 'apm_mcmc')
Explanation: Construct data and experiments directorys from environment variables
End of explanation
data_set = 'pima'
method = 'apm(mi+mh)'
n_chain = 10
chain_offset = 0
seeds = np.random.rando... |
9,794 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
When analyzing data, I usually use the following three modules. I use pandas for data management, filtering, grouping, and processing. I use numpy for basic array math. I use toyplot for ren... | Python Code:
import pandas
import numpy
import toyplot
import toyplot.pdf
import toyplot.png
import toyplot.svg
print('Pandas version: ', pandas.__version__)
print('Numpy version: ', numpy.__version__)
print('Toyplot version: ', toyplot.__version__)
Explanation: When analyzing data, I usually use the following three... |
9,795 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: List Superfund sites
The individual sites are instances of SuperfundSite, and are listed in the corresponding Graph Browser page.
To programmatically list all Superfun... | Python Code:
!pip install datacommons_pandas datacommons --upgrade --quiet
# Import Data Commons libraries
import datacommons as dc
import datacommons_pandas as dcpd
Explanation: <a href="https://colab.research.google.com/github/datacommonsorg/api-python/blob/master/notebooks/Accessing_Superfund_data_from_Data_Commons.... |
9,796 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Gradio and HuggingFace
In this demo, we show how to build ready to deploy or use deep learning models.
Hugging Face hosts thousands of pre-trained models in Model Hub. They also built high-... | Python Code:
!pip install transformers
!pip install gradio
Explanation: Gradio and HuggingFace
In this demo, we show how to build ready to deploy or use deep learning models.
Hugging Face hosts thousands of pre-trained models in Model Hub. They also built high-level APIs so we can easily use and deploy pre-trained mod... |
9,797 | 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', 'mohc', 'hadgem3-gc31-hh', 'aerosol')
Explanation: ES-DOC CMIP6 Model Properties - Aerosol
MIP Era: CMIP6
Institute: MOHC
Source ID: HADGEM3-GC31-HH
Topic: Aerosol
Sub-Topics: Transpor... |
9,798 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright (c) 2018 Geosoft Inc.
https
Step1: Calculate the depth from the tilt-angle and tilt-derivative
The depth is the reciprocal of the horizontal gradient at the zero-contour of the ti... | Python Code:
import geosoft.gxpy.gx as gx
import geosoft.gxpy.utility as gxu
import geosoft.gxpy.grid as gxgrd
import geosoft.gxpy.grid_utility as gxgrdu
import geosoft.gxpy.map as gxmap
import geosoft.gxpy.view as gxview
import geosoft.gxpy.group as gxgrp
import numpy as np
from IPython.display import Image
gxc = gx.G... |
9,799 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ordinary Differential Equations Exercise 3
Imports
Step1: Damped, driven nonlinear pendulum
The equations of motion for a simple pendulum of mass $m$, length $l$ are
Step4: Write a functio... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from scipy.integrate import odeint
from IPython.html.widgets import interact, fixed
Explanation: Ordinary Differential Equations Exercise 3
Imports
End of explanation
g = 9.81 # m/s^2
l = 0.5 # length of pendul... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.