Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
6,600 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to data analytics with pandas
Quentin Caudron
<br />
<img src="images/pydata.png" width="200px" />
<br />@QuentinCaudron
Notebooks
Step1: Systems check
Do you have a working P... | Python Code:
%%HTML
<style>
.rendered_html {
font-size: 0.7em;
}
.CodeMirror-scroll {
font-size: 1.2em;
}
.rendered_html table, .rendered_html th, .rendered_html tr, .rendered_html td, .rendered_html h2, .rendered_html h4 {
font-size: 100%;
}
</style>
Explanation: Introduction to data analytics with pandas
Q... |
6,601 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href='http
Step1: We'll start off by trying to find out if the string "phone" is inside the text string. Now we could quickly do this with
Step2: But let's show the format for regular e... | Python Code:
text = "The agent's phone number is 408-555-1234. Call soon!"
Explanation: <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a>
Regular Expressions
Regular Expressions (sometimes called regex for short) allow a user to search for strings using almost any sort of rule they can co... |
6,602 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Link analysis
(Inspired by and borrowed heavily from
Step2: Co-authorship network
Summaries maps paper ids to paper summaries. Let us now create here mappings by different criteria.
... | Python Code:
import pickle, bz2
from collections import *
import numpy as np
import matplotlib.pyplot as plt
# show plots inline within the notebook
%matplotlib inline
# set plots' resolution
plt.rcParams['savefig.dpi'] = 100
from IPython.display import display, HTML
Ids_file = 'data/air__Ids.pkl.bz2'
Summaries_file = ... |
6,603 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Introduction" data-toc-modified-id="Introduction-1"><span class="toc-item-nu... | Python Code:
debug_flag = False
Explanation: <h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Introduction" data-toc-modified-id="Introduction-1"><span class="toc-item-num">1 </span>Introduction</a></span></li><li><span><a href="#Setup" data-to... |
6,604 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
What are the underlying biophysics that govern astrocyte behavior? To explore this question we have at our disposal a large dataset of observations. A key concept we must face i... | Python Code:
x1 = np.random.uniform(size=500)
x2 = np.random.uniform(size=500)
plt.scatter(x1,x2); plt.xlim(-0.25,1.25); plt.ylim(-0.25,1.25)
plt.grid(); plt.show()
Explanation: Introduction
What are the underlying biophysics that govern astrocyte behavior? To explore this question we have at our disposal a large datas... |
6,605 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CSX91
Step1: Q. What happens if there is no return?
2. Scope
In python functions have their own scope (namespace).
Python first looks at the function's namespace first before looking at the... | Python Code:
def foo():
return 1
foo()
Explanation: CSX91: Python Tutorial
1. Functions
Fucntions in Python are created using the keyword def
It can return values with return
Let's create a simple function:
End of explanation
aString = 'Global var'
def foo():
a = 'Local var'
print locals()
foo()
print globa... |
6,606 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
AnnVariables
This script runs repeated cross-validation as a search for suitable parameter values for
the ANN and the genetic algorithm.
It has been re-run for all data-sets. The output of ... | Python Code:
# import stuffs
%matplotlib inline
import numpy as np
import pandas as pd
from pyplotthemes import get_savefig, classictheme as plt
plt.latex = True
Explanation: AnnVariables
This script runs repeated cross-validation as a search for suitable parameter values for
the ANN and the genetic algorithm.
It has ... |
6,607 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Flowers retraining example
이미 학습된 잘 알려진 모델을 이용하여 꽃의 종류를 예측하는 예제입니다.
기존의 Minst 예제와는 거의 차이점이 없습니다. 단지 2가지만 다를 뿐입니다.
숫자이미지 대신에 꽃이미지이름으로 분류되어 있는 folder를 dataset으로 이용한다.
이미 잘 짜여진 Neural model과 사전... | Python Code:
!if [ ! -d "/tmp/flower_photos" ]; then curl http://download.tensorflow.org/example_images/flower_photos.tgz | tar xz -C /tmp ;rm /tmp/flower_photos/LICENSE.txt; fi
%matplotlib inline
Explanation: Flowers retraining example
이미 학습된 잘 알려진 모델을 이용하여 꽃의 종류를 예측하는 예제입니다.
기존의 Minst 예제와는 거의 차이점이 없습니다. 단지 2가지만 다를 뿐입... |
6,608 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
07 - Model Deployment
by Alejandro Correa Bahnsen & Iván Torroledo
version 1.2, Feb 2018
Part of the class Machine Learning for Risk Management
This notebook is licensed under a Creative Com... | Python Code:
import pandas as pd
import zipfile
with zipfile.ZipFile('../datasets/model_deployment/phishing.csv.zip', 'r') as z:
f = z.open('phishing.csv')
data = pd.read_csv(f, index_col=False)
data.head()
data.tail()
data.phishing.value_counts()
Explanation: 07 - Model Deployment
by Alejandro Correa Bahnsen &... |
6,609 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a id='top'></a>
Complex vibration modes
Complex vibration modes arise in experimental research and numerical simulations when non proportional damping is adopted. In such cases a state spac... | Python Code:
import sys
import numpy as np
import scipy as sp
import matplotlib as mpl
print('System: {}'.format(sys.version))
print('numpy version: {}'.format(np.__version__))
print('scipy version: {}'.format(sp.__version__))
print('matplotlib version: {}'.format(mpl.__version__))
Explanation: <a id='top'></a>
Complex... |
6,610 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Domain 54 Transitions
Step1: Testing of the finalized methods in local_complexity.py
Rule 54 domain, should be no non-unifilar transitions
Step2: Rule 18 domain, should be non-unifilar tra... | Python Code:
dom_test = ECA(54,domain_54(20*4, 'a'))
dom_test.evolve(20*4)
diagram(dom_test.get_spacetime())
np.random.seed(0)
domain_states = epsilon_field(dom_test.get_spacetime())
domain_states.estimate_states(3,3,1)
domain_states.filter_data()
a = domain_states.state_transition((10,10), 'forward')
print a
b = domai... |
6,611 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Convolutional Generative Adversarial Network
Learning Objectives
Build a GAN architecture (consisting of a generator and discriminator) in Keras
Define the loss for the generator and d... | Python Code:
try:
%tensorflow_version 2.x
except Exception:
pass
import tensorflow as tf
tf.__version__
# To generate GIFs
!python3 -m pip install -q imageio
import glob
import os
import time
import imageio
import matplotlib.pyplot as plt
import numpy as np
import PIL
from IPython import display
from tensorflow... |
6,612 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Compute effect-matched-spatial filtering (EMS)
This example computes the EMS to reconstruct the time course of the
experimental effect as described in
Step1: Note that a similar transforma... | Python Code:
# Author: Denis Engemann <denis.engemann@gmail.com>
# Jean-Remi King <jeanremi.king@gmail.com>
#
# License: BSD-3-Clause
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne import io, EvokedArray
from mne.datasets import sample
from mne.decoding import EMS, compute_ems
from sklea... |
6,613 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MC855 - Data analysis pyspark
Initializing spark and data
Spark version 2.2.0
Change /home/henrique/Downloads/spark to the path you downloaded and extracted spark
You may need to export hado... | Python Code:
# Import findspark
import findspark
# Initialize and provide path
findspark.init("/home/henrique/Downloads/spark")
# Or use this alternative
#findspark.init()
# Import SparkSession
from pyspark.sql import SparkSession
# Build the SparkSession
spark = SparkSession.builder \
.master("local") \
... |
6,614 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Vertex AI
Step1: Install the latest GA version of google-cloud-storage library as well.
Step2: Restart the kernel
Once you've installed the additional packages, you need to restart the not... | Python Code:
import os
# Google Cloud Notebook
if os.path.exists("/opt/deeplearning/metadata/env_version"):
USER_FLAG = "--user"
else:
USER_FLAG = ""
! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG
Explanation: Vertex AI: Vertex AI Migration: AutoML Video Classificaton
<table align="left">
<td>
... |
6,615 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tensor Products & Partial Traces
Contents
Tensor Products
Partial Trace
Super Operators & Tensor Manipulations
Step1: <a id='tensor'></a>
Tensor Products
To describe the states of multipart... | Python Code:
import numpy as np
from qutip import *
Explanation: Tensor Products & Partial Traces
Contents
Tensor Products
Partial Trace
Super Operators & Tensor Manipulations
End of explanation
tensor(basis(2, 0), basis(2, 0))
Explanation: <a id='tensor'></a>
Tensor Products
To describe the states of multipartite quan... |
6,616 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Speci... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'messy-consortium', 'emac-2-53-aerchem', 'atmoschem')
Explanation: ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era: CMIP6
Institute: MESSY-CONSORTIUM
Source ID: EMAC-2-53-AERCHEM
Top... |
6,617 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Statistical Analysis
In this notebook, we'll use selected statistical algorithms to analyze our dataset. Specifically, we'll do the following
Step1: Perform a Distribution Analysis
A distri... | Python Code:
# Import the Python libraries we need
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
%matplotlib inline
# Define a variable for the accidents data file
accidents_data_file = '/Users/robert.dempsey/Dropbox/Private/Art of Skill Hacking/Books/' \
... |
6,618 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<p><font size="6"><b>Jupyter notebook INTRODUCTION </b></font></p>
DS Data manipulation, analysis and visualisation in Python
December, 2017
© 2016, Joris Van den Bossche and Stijn Van Hoey ... | Python Code:
from IPython.display import Image
Image(url='http://python.org/images/python-logo.gif')
Explanation: <p><font size="6"><b>Jupyter notebook INTRODUCTION </b></font></p>
DS Data manipulation, analysis and visualisation in Python
December, 2017
© 2016, Joris Van den Bossche and Stijn Van Hoey (jo&#... |
6,619 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Monte Carlo simulation
Please cite
Step1: Station coordinates and thresholds from a set of log files
Specify
Step2: Station coordinates from csv file
Input network title and csv file here
... | Python Code:
%pylab inline
import pyproj as proj4
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import datetime
# import read_logs
from mpl_toolkits.basemap import Basemap
from coordinateSystems import TangentPlaneCartesianSystem, GeographicSystem, MapProjection
import scipy.stats as st
from mp... |
6,620 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
proper reading of biom table (output
Step1: biom table
Step2: mapping file
Step3: add two ratio variables of Vitamin D | Python Code:
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
Explanation: proper reading of biom table (output: biomtable.txt)
proper distinguishment between categorical and continous variables in mapping file
(output: mapping_cleaned_MrOS.txt)
End of explanation
# conve... |
6,621 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
General Concepts
Step1: Let's get started with some basic imports
Step2: If running in IPython notebooks, you may see a "ShimWarning" depending on the version of Jupyter you are using - th... | Python Code:
#!pip install -I "phoebe>=2.3,<2.4"
Explanation: General Concepts: The PHOEBE Bundle
HOW TO RUN THIS FILE: if you're running this in a Jupyter notebook or Google Colab session, you can click on a cell and then shift+Enter to run the cell and automatically select the next cell. Alt+Enter will run a cell an... |
6,622 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Solving the differential equations
Step1: Solving the two differential equations given
Step3: To solve these, I first define a derivative function
Step5: Then I use odeint to solve the eq... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import odeint
Explanation: Solving the differential equations
End of explanation
gamma = 4.4983169634398596e-06
Explanation: Solving the two differential equations given:
$$ \ddot{\mathbf{r}} = -\gamma \left{ \frac{M... |
6,623 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step2: Distributed Estimation
This notebook goes through a couple of examples to show how to use distributed_estimation. We import the DistributedModel class and make the exog and endog gen... | Python Code:
import numpy as np
from scipy.stats.distributions import norm
from statsmodels.base.distributed_estimation import DistributedModel
def _exog_gen(exog, partitions):
partitions exog data
n_exog = exog.shape[0]
n_part = np.ceil(n_exog / partitions)
ii = 0
while ii < n_exog:
jj = in... |
6,624 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Outline
Glossary
7. Observing Systems
Previous
Step1: Import section specific modules | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from IPython.display import HTML
HTML('../style/course.css') #apply general CSS
Explanation: Outline
Glossary
7. Observing Systems
Previous: 7.7 Propagation Effects
Next: 7.x Further Reading and References
Import standard modules:
End... |
6,625 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Seaice
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', 'snu', 'sandbox-1', 'seaice')
Explanation: ES-DOC CMIP6 Model Properties - Seaice
MIP Era: CMIP6
Institute: SNU
Source ID: SANDBOX-1
Topic: Seaice
Sub-Topics: Dynamics, Thermodynamics,... |
6,626 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ABC calibration of $I_\text{to}$ in standardised model to unified dataset.
Step1: Initial set-up
Load experiments used for unified dataset calibration
Step2: Plot steady-state and tau func... | Python Code:
import os, tempfile
import logging
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from ionchannelABC import theoretical_population_size
from ionchannelABC import IonChannelDistance, EfficientMultivariateNormalTransition, IonChannelAcceptor
from ionchannelA... |
6,627 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Facies classification using Machine Learning- Majority voting
Contest entry by Priyanka Raghavan and Steve Hall
This notebook demonstrates how to train a machine learning algorithm to predic... | Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.colors as colors
from mpl_toolkits.axes_grid1 import make_axes_locatable
from pandas import set_option
set_option("display.max_rows", 10)
pd.options.mode.chained_assignment =... |
6,628 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Graded = 7/7
HOMEWORK 06
You'll be using the Dark Sky Forecast API from Forecast.io, available at https
Step1: 2) What's the current wind speed? How much warmer does it feel than it actuall... | Python Code:
import requests
url="https://api.forecast.io/forecast/64f4867f7d4c86182f3d1c6ed881dbfc/17.3850,78.4867"
response=requests.get(url)
data=response.json()
data.keys()
data['currently'].keys()
Explanation: Graded = 7/7
HOMEWORK 06
You'll be using the Dark Sky Forecast API from Forecast.io, available at https:/... |
6,629 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Predicting uncertainties on measured bandpowers
This notebook shows you how to predict the errors on auto-correlation and cross-correlation bandpowers.
You need to install this Python packag... | Python Code:
%load_ext autoreload
%autoreload 2
from __future__ import print_function
from orphics import cosmology,io
import numpy as np
import matplotlib.pyplot as plt
# First initialize a cosmology object with default params
lc = cosmology.LimberCosmology(lmax=3000,pickling=True)
# Let's define a mock dndz
def dndz(... |
6,630 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
You'll be using the Dark Sky Forecast API from Forecast.io, available at https
Step1: 2) What's the current wind speed? How much warmer does it feel than it actually is?
Step2: 3) The firs... | Python Code:
apikey = '34b41fe7b9db6c1bd5f8ea3492bca332'
coordinates = {'San Antonio': '29.4241,-98.4936', 'Miami': '25.7617,-80.1918', 'Central Park': '40.7829,-73.9654'}
import requests
url = 'https://api.forecast.io/forecast/' + apikey + '/' + coordinates['San Antonio']
response = requests.get(url)
data = response.j... |
6,631 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Import pixiedust
Start by importing pixiedust which if all bootstrap and install steps were run correctly.
You should see below for opening the pixiedust database successfully with no errors... | Python Code:
#!pip install --user --upgrade pixiedust
import pixiedust
import geowave_pyspark
pixiedust.enableJobMonitor()
Explanation: Import pixiedust
Start by importing pixiedust which if all bootstrap and install steps were run correctly.
You should see below for opening the pixiedust database successfully with no ... |
6,632 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Authors.
Step1: SavedModel 形式の使用
<table class="tfo-notebook-buttons" align="left">
<td> <a target="_blank" href="https
Step2: 実行例として、グレース・ホッパーの画像と Keras... | 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... |
6,633 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A Short Introduction to netCDF
What is netCDF?
"NetCDF is an abstraction that supports a view of data as a collection of self-describing, portable objects that can be accessed through a sim... | Python Code:
from netCDF4 import Dataset
import numpy as np
import numpy.ma as ma
filename = "tos_O1_2001-2002.nc"
ds = Dataset(filename, mode="r")
Explanation: A Short Introduction to netCDF
What is netCDF?
"NetCDF is an abstraction that supports a view of data as a collection of self-describing, portable objects tha... |
6,634 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Freedom exploration
Data exploration
Step1: <a id='data_exploration'></a>
Data exploration
Step2: We are dealing with many NaN values, but its not clear how to treat them all.
I will take... | Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib as plt
import seaborn as sns
filename='TABLE_III._Deaths_in_122_U.S._cities.csv'
df = pd.read_csv(filename)
df = df[:1000]
Explanation: Freedom exploration
Data exploration
End of explanation
df.describe()
Explanation: <a id='data_... |
6,635 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Project Euler
Step1: Add the products of all 3-digit numbers to the list
Step2: Create empty list of palindromes
Step3: Check if number is a palindrome, return list of palindromes
Step4: ... | Python Code:
products = []
Explanation: Project Euler: Problem 4
https://projecteuler.net/problem=4
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
Create empty... |
6,636 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Important prerequisite
The package doesn't work with the newest version of Jupyter Notebook, run the following commands in your terminal before initiating the Notebook
pip install notebook==... | Python Code:
# uncomment the following line if you haven't installed bte_schema
# !pip install git+https://github.com/kevinxin90/bte_schema#egg=bte_schema
# uncomment the following line if you haven't installed biothings_schema
#pip install git+https://github.com/biothings/biothings_schema.py#egg=biothings_schema.py
# ... |
6,637 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step2: Resonant Sequences
(from http
Step3: Generating resonance sequences is fast
Try it!
Note
Step4: ..., but plotting can be slow for large N (N > 10)
Try it, but be patient ... (lots o... | Python Code:
!date
%matplotlib inline
from __future__ import division
import math
def fareySequence(N, k=1):
Generate Farey sequence of order N, less than 1/k
# assert type(N) == int, "Order (N) must be an integer"
a, b = 0, 1
c, d = 1, N
seq = [(a,b)]
while c/d <= 1/k:
seq.app... |
6,638 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Element
Import modules/packages
Step1: Model Machine
Step2: Get Element by type
Step3: Example
Step4: Investigate the equad
Step5: Dynamic field
Step6: Get values
If only readback valu... | Python Code:
import phantasy
Explanation: Element
Import modules/packages
End of explanation
mp = phantasy.MachinePortal(machine='FRIB_FE', segment='LEBT')
Explanation: Model Machine
End of explanation
mp.get_all_types()
Explanation: Get Element by type
End of explanation
equads = mp.get_elements(type='EQUAD')
equads
#... |
6,639 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Feature Engineering
Learning Objectives
* Improve the accuracy of a model by using feature engineering
* Understand there's two places to do feature engineering in Tensor... | Python Code:
import tensorflow as tf
import numpy as np
import shutil
print(tf.__version__)
Explanation: Introduction to Feature Engineering
Learning Objectives
* Improve the accuracy of a model by using feature engineering
* Understand there's two places to do feature engineering in Tensorflow
1. Using the tf.... |
6,640 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Time to add SciPy to our toolbox
In this session you will learn some of the functions available in SciPy package.
What is SciPy?
General purpose scientific library (that consist of bunch of ... | Python Code:
# import os
# import numpy as np
# import matplotlib.pyplot as plt
# from scipy import interpolate # import submodule for interpolation and regridding
## make figures appear within the notebook
# %matplotlib inline
Explanation: Time to add SciPy to our toolbox
In this session you will learn some of the fu... |
6,641 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Experiments collected data
Data required to run this notebook are available for download at this link
Step1: Loading support data collected from the target
Step2: Trace analysis
We want to... | Python Code:
res_dir = '../../results/SchedTuneAnalysis/'
!tree {res_dir}
noboost_trace = res_dir + 'trace_noboost.dat'
boost15_trace = res_dir + 'trace_boost15.dat'
boost25_trace = res_dir + 'trace_boost25.dat'
# trace_file = noboost_trace
trace_file = boost15_trace
# trace_file = boost25_trace
Explanation: Experiment... |
6,642 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simple Aggregation
Thanks, Monte!
Step1: Pandas
Step2: What is the row sum?
Step3: Column sum?
Step4: Spark
Step5: How do we skip the header? How about using find()? What is Boolean v... | Python Code:
import numpy as np
data = np.arange(1000).reshape(100,10)
print data.shape
Explanation: Simple Aggregation
Thanks, Monte!
End of explanation
import pandas as pd
pand_tmp = pd.DataFrame(data,
columns=['x{0}'.format(i) for i in range(data.shape[1])])
pand_tmp.head()
Explanation: Pandas
End of e... |
6,643 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
14.1
Задані виміри економіки країни
Step1: Модель міжгалузевої залежності цін
Нехай $X$ - це матриця в якій $x_{i j}$ елемент позначає витрати продукції $i$-ї галузі на потреби $j$-ї.
y - в... | Python Code:
X = np.array([
[1320, 1170],
[1060, 965]
])
y = np.array([
[1075],
[1185]
])
s = np.array([0.45, 0.2])
Explanation: 14.1
Задані виміри економіки країни
End of explanation
x = (np.sum(X, axis=1).reshape(-1, 1) + y)
print(x)
A = X / x.T
print(A)
M = np.eye(A.shape[0]) - A.T
p = np.linalg.solv... |
6,644 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Getting Started with Accelerated Computing
In this self-paced, hands-on lab, we will briefly explore some methods for accelerating applications on a GPU.
Lab created by Mark Ebersole (Follow... | Python Code:
print "The answer should be three: " + str(1+2)
Explanation: Getting Started with Accelerated Computing
In this self-paced, hands-on lab, we will briefly explore some methods for accelerating applications on a GPU.
Lab created by Mark Ebersole (Follow @CUDAHamster on Twitter)
The following timer counts dow... |
6,645 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fractional Anisotropy Maps - Steps and Results
On Thursday, we showed Greg the output of the first step of the CAPTURE pipeline - namely, after modifying the CAPTURE MATLAB pipeline to accep... | Python Code:
from dipy.reconst.dti import fractional_anisotropy, color_fa
from argparse import ArgumentParser
from scipy import ndimage
import os
import re
import numpy as np
import nibabel as nb
import sys
import matplotlib
matplotlib.use('Agg') # very important above pyplot import
import matplotlib.pyplot as plt
imp... |
6,646 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Convolutional Neural Network in TensorFlow
In this notebook, we convert our LeNet-5-inspired, MNIST-classifying, deep convolutional network from Keras to TensorFlow (compare them side b... | Python Code:
import numpy as np
np.random.seed(42)
import tensorflow as tf
tf.set_random_seed(42)
Explanation: Deep Convolutional Neural Network in TensorFlow
In this notebook, we convert our LeNet-5-inspired, MNIST-classifying, deep convolutional network from Keras to TensorFlow (compare them side by side) following A... |
6,647 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Analyzing IMDB Data in Keras
Step1: 1. Loading the data
This dataset comes preloaded with Keras, so one simple command will get us training and testing data. There is a parameter for how ma... | Python Code:
# Imports
import numpy as np
import keras
from keras.datasets import imdb
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.preprocessing.text import Tokenizer
import matplotlib.pyplot as plt
%matplotlib inline
np.random.seed(42)
Explanation: Analyzing IMDB ... |
6,648 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Quantum SVM kernel algorithm
Step1: Here we choose the Wine dataset which has 3 classes.
Step2: Now we setup an Aqua configuration dictionary to use the quantum QSVM.Kernel algorithm and a... | Python Code:
from datasets import *
from qiskit_aqua.utils import split_dataset_to_data_and_labels
from qiskit_aqua.input import get_input_instance
from qiskit_aqua import run_algorithm
import numpy as np
Explanation: Quantum SVM kernel algorithm: multiclass classifier extension
A multiclass extension works in conjunc... |
6,649 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TF Custom Estimator to Build a NN Autoencoder for Feature Extraction
Step1: 1. Define Dataset Metadata
Step2: 2. Define CSV Data Input Function
Step3: 3. Define Feature Columns
a. Load no... | Python Code:
MODEL_NAME = 'auto-encoder-01'
TRAIN_DATA_FILES_PATTERN = 'data/data-*.csv'
RESUME_TRAINING = False
MULTI_THREADING = True
Explanation: TF Custom Estimator to Build a NN Autoencoder for Feature Extraction
End of explanation
FEATURE_COUNT = 64
HEADER = ['key']
HEADER_DEFAULTS = [[0]]
UNUSED_FEATURE_NAMES = ... |
6,650 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Classification
Load the data
Build features from the data and format for model
Load and fit the data with the random forest model
Display results
Code
Import Necessary Tools and Libraries
St... | Python Code:
import sys
import os
sys.path.append(os.environ.get('NOTEBOOK_ROOT'))
import datacube
import datetime
import folium
import numpy as np
import pandas as pd
import utils.data_cube_utilities.dc_display_map as dm
import xarray as xr
from folium import plugins
from sklearn.externals import joblib
from sklearn.... |
6,651 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Segmentation
Step1: Read Data and Select Seed Point(s)
We first load a T1 MRI brain scan and select our seed point(s). If you are unfamiliar with the anatomy you can use the preselected see... | Python Code:
# To use interactive plots (mouse clicks, zooming, panning) we use the notebook back end. We want our graphs
# to be embedded in the notebook, inline mode, this combination is defined by the magic "%matplotlib notebook".
%matplotlib notebook
import SimpleITK as sitk
%run update_path_to_download_script
from... |
6,652 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
An example of using Jupyter for Documenting and Automating BDD Style Tests
This is a sample document which contains both software feature requirements and its corresponding manual and automa... | Python Code:
from marigoso import Test
browser = Test().launch_browser("Firefox")
browser.get_url("https://www.blogger.com/")
header = browser.get_element("tag=h2")
assert header.text == "Sign in to continue to Blogger"
Explanation: An example of using Jupyter for Documenting and Automating BDD Style Tests
This is a sa... |
6,653 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Create some text
Step2: Apply regex | Python Code:
# Load regex package
import re
Explanation: Title: Match Any Of A List Of Characters
Slug: match_any_of_a_list_of_symbols
Summary: Match Any Of A List Of Characters
Date: 2016-05-01 12:00
Category: Regex
Tags: Basics
Authors: Chris Albon
Based on: Regular Expressions Cookbook
Preliminaries
End of explana... |
6,654 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CB Model
The following tries to reproduce Fig 10 from Hawkes, Jalali, Colquhoun (1992). First we create the $Q$-matrix for this particular model from Hawkes, Jalali, Colquhoun (1992). First ... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from dcprogs.likelihood import QMatrix
tau = 0.2
qmatrix = QMatrix([ [-2, 1, 1, 0],
[ 1, -101, 0, 100],
[50, 0, -50, 0],
[ 0, 5.6, 0, -5.6]], 1)
Explanatio... |
6,655 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Examples and Exercises from Think Stats, 2nd Edition
http
Step1: Least squares
One more time, let's load up the NSFG data.
Step2: The following function computes the intercept and slope of... | Python Code:
from __future__ import print_function, division
%matplotlib inline
import numpy as np
import random
import thinkstats2
import thinkplot
Explanation: Examples and Exercises from Think Stats, 2nd Edition
http://thinkstats2.com
Copyright 2016 Allen B. Downey
MIT License: https://opensource.org/licenses/MIT
En... |
6,656 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Download the HTML and create a Beautiful Soup object
Step2: If we looked at the soup object, we'd see that the names we want are in a heirarchical list. In psuedo-code, it loo... | Python Code:
# Import required modules
import requests
from bs4 import BeautifulSoup
import pandas as pd
Explanation: Title: Drilling Down With Beautiful Soup
Slug: beautiful_soup_drill_down
Summary: Drilling Down With Beautiful Soup
Date: 2016-05-01 12:00
Category: Python
Tags: Web Scraping
Authors: Chris Albon
Prel... |
6,657 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exploring the Labyrinth
Chapter 2 of Real World Algorithms.
Panos Louridas<br />
Athens University of Economics and Business
Graphs in Python
The most common way to represent graphs in Pytho... | Python Code:
g = {
0: [1, 2, 3],
1: [0, 4],
2: [0],
3: [0, 5],
4: [1, 5],
5: [3, 4, 6, 7],
6: [5],
7: [5],
}
# print whole graph
print(g)
# print adjacency list of node 0
print(g[0])
# print adjacency list of node 5
print(g[5])
Explanation: Exploring the Labyrinth
Chapter 2 of Real World... |
6,658 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Detached Binary
Step1: As always, let's do imports and initialize a logger and a new bundle. See Building a System for more details.
Step2: Adding Datasets
Now we'll create an empty mesh ... | Python Code:
!pip install -I "phoebe>=2.0,<2.1"
%matplotlib inline
Explanation: Detached Binary: Roche vs Rotstar
Setup
Let's first make sure we have the latest version of PHOEBE 2.0 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 ... |
6,659 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
OpenAI Gym 入門
OpenAI Gym 公式ホームページ
OpenAI Gym 公式ドキュメント ← このノートブックはこの公式ドキュメントの日本語訳+α
OpenAI Gym GitHub
OpenAI Gym で提供されている全環境
OpenAI Gym 公開についての公式ブログ 2016/04/27
OpenAI Universe
OpenAI Gymとは?
O... | Python Code:
# gym オープンソースライブラリの読み込み
import gym
# 環境を作る
env = gym.make('CartPole-v0') # 'CartPole-v0' は環境ID
#env = gym.make('MountainCar-v0') # 'MountainCar-v0'という別の環境
#env = gym.make('MsPacman-v0') # 'MsPacman-v0'という別の環境
env.seed(42)
# 環境の初期化(最初の観測が得られる)
env.reset()
# 描画
env.render()
# 行動選択(手動)
action = 0 #... |
6,660 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fonksiyonlar
Şu ana kadar zengin Python kütüphaneleri sayesinde pek çok fonksiyonu kolayca kullandık. Öte yandan bazı durumlarda kendi fonksiyonlarımızı yazmak isteyebiliriz. Mesela Python'd... | Python Code:
meyva = "ARMUT"
print meyva.lower()
Explanation: Fonksiyonlar
Şu ana kadar zengin Python kütüphaneleri sayesinde pek çok fonksiyonu kolayca kullandık. Öte yandan bazı durumlarda kendi fonksiyonlarımızı yazmak isteyebiliriz. Mesela Python'da kullanılan standart dize fonksiyonları Türkçe harfler ile başa çık... |
6,661 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<center>Introduction to Machine Learning with Neuroimaging</center>
<center><b>Written by Luke Chang (luke.j.chang@dartmouth.edu)</b></center>
<center><p>This tutorial will provide a quick i... | Python Code:
# iPython notebook magic commands
%load_ext autoreload
%autoreload 2
%matplotlib inline
#General modules
import os
from os.path import join, basename, isdir
from os import makedirs
import pandas as pd
import matplotlib.pyplot as plt
import time
import pickle
# Supervised Modules
from pyneurovault import ap... |
6,662 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Analyzing the Impact of Failures (and letting loose a Chaos Monkey)
Planned (maintenance) and unplanned failure of nodes and interfaces in the network is a frequent occurrence. While most ne... | Python Code:
# Import packages
%run startup.py
bf = Session(host="localhost")
# Initialize the example network and snapshot
NETWORK_NAME = "example_network"
BASE_SNAPSHOT_NAME = "base"
SNAPSHOT_PATH = "networks/failure-analysis"
bf.set_network(NETWORK_NAME)
bf.init_snapshot(SNAPSHOT_PATH, name=BASE_SNAPSHOT_NAME, overw... |
6,663 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Various t0s
Setup
Let's first make sure we have the latest version of PHOEBE 2.1 installed. (You can comment out this line if you don't use pip for your installation or don't want to update ... | Python Code:
!pip install -I "phoebe>=2.1,<2.2"
Explanation: Various t0s
Setup
Let's first make sure we have the latest version of PHOEBE 2.1 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
%matplotlib inline
import ... |
6,664 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TensorFlow Classification
Data
https
Step1: Clean the Data
Step2: Feature Columns
Step3: Continuous Features
Number of times pregnant
Plasma glucose concentration a 2 hours in an oral glu... | Python Code:
import pandas as pd
diabetes = pd.read_csv('data/pima-indians-diabetes.csv')
diabetes.head()
diabetes.columns
Explanation: TensorFlow Classification
Data
https://archive.ics.uci.edu/ml/datasets/pima+indians+diabetes
Title: Pima Indians Diabetes Database
Sources:
(a) Original owners: National Institute o... |
6,665 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TUTORIAL 05 - Empirical Interpolation Method for non-affine elliptic problems
Keywords
Step1: 3. Affine decomposition
The paramtrized bilinear form $a(\cdot, \cdot; \boldsymbol{\mu})$ is tr... | Python Code:
from dolfin import *
from rbnics import *
Explanation: TUTORIAL 05 - Empirical Interpolation Method for non-affine elliptic problems
Keywords: empirical interpolation method
1. Introduction
In this Tutorial, we consider steady heat conduction in a two-dimensional square domain $\Omega = (-1, 1)^2$.
The bou... |
6,666 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Python
A Tutorial by Jacob Gerace
Why Python?
Clean syntax
The same code can run on all Operating Systems
Extensive first and third party libraries (of particular note for ou... | Python Code:
#A variable stores a piece of data and gives it a name
answer = 42
#answer contained an integer because we gave it an integer!
is_it_tuesday = True
is_it_wednesday = False
#these both are 'booleans' or true/false values
pi_approx = 3.1415
#This will be a floating point number, or a number containing digits... |
6,667 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial
Step1: Gibbs samples
It's nice to start with the Gibbs sampled chains, since they almost certainly look nicer. First, read them in.
Read in your conjugate Gibbs chains.
Step2: Vis... | Python Code:
exec(open('tbc.py').read()) # define TBC and TBC_above
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
%matplotlib inline
from glob import glob
import incredible as cr
Explanation: Tutorial: MCMC Diagnostics
You should already have run two different MCMC algorithms to generate chains... |
6,668 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Read HYDRAD Results
In our paper, we make various comparisons between EBTEL and the field-aligned code HYDRAD. However, runs of HYDRAD are computationally expensive and it is not feasible to... | Python Code:
import os
import pickle
import numpy as np
Explanation: Read HYDRAD Results
In our paper, we make various comparisons between EBTEL and the field-aligned code HYDRAD. However, runs of HYDRAD are computationally expensive and it is not feasible to do these on the fly. We are in the process of making HYDRAD ... |
6,669 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Minimal example
Generate a .csv file that is accepted as input to SmartVA-Analyze 1.1
Step1: Example of simple, hypothetical mapping
If we have data on a set of verbal autopsies (VAs) that ... | Python Code:
# SmartVA-Analyze 1.1 accepts a csv file as input
# and expects a column for every field name in the "Guide for data entry.xlsx" spreadsheet
df = pd.DataFrame(index=[0], columns=cb.index.unique())
# SmartVA-Analyze 1.1 also requires a handful of columns that are not in the Guide
df['child_3_10'] = np.nan
d... |
6,670 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Ocean
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify d... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'ec-earth-consortium', 'ec-earth3-gris', 'ocean')
Explanation: ES-DOC CMIP6 Model Properties - Ocean
MIP Era: CMIP6
Institute: EC-EARTH-CONSORTIUM
Source ID: EC-EARTH3-GRIS
Topic: Ocea... |
6,671 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Train a Simple Audio Recognition model for microcontroller use
This notebook demonstrates how to train a 20kb Simple Audio Recognition model for TensorFlow Lite for Microcontrollers. It will... | Python Code:
import os
# A comma-delimited list of the words you want to train for.
# The options are: yes,no,up,down,left,right,on,off,stop,go
# All other words will be used to train an "unknown" category.
os.environ["WANTED_WORDS"] = "yes,no"
# The number of steps and learning rates can be specified as comma-separate... |
6,672 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Processing LexisNexus results
Step1: Dictionary
name
Step2: Spreadsheet structure
col1 col2 col3
row1 1 t 2
row2 2 x 5
row3 3 a 5
Step3: Some regular ex... | Python Code:
# import the modules we need
import os
import re
os.listdir('data')
data = open('data/LexisNexis practice.TXT').read()
# 5 of 54 DOCUMENTS
data.count('of 54 DOCUMENTS')
'This is a string of words'.split('i')
docs = data.split('of 54 DOCUMENTS')
len(docs)
for dnum in [1,2,3,4]:
print('This is doc number... |
6,673 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Analysis of the final catalogue of matched sources
We will analyse the changes in the classification using the new sigma and the new catalogue without the galaxies that went to LGZ
Configura... | Python Code:
import numpy as np
from astropy.table import Table, join
from astropy import units as u
from astropy.coordinates import SkyCoord, search_around_sky
from IPython.display import clear_output
import pickle
import os
from mltier1 import (get_center, Field, parallel_process, describe)
%load_ext autoreload
%auto... |
6,674 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Let's take a closer look again on our PC versus Mac menu bar example. Here are the measurements for the first experiments (between-subject, randomized) (we first import some stuff to make pl... | Python Code:
%pylab inline
import matplotlib.pyplot as plt
#use a nicer plotting style
plt.style.use(u'fivethirtyeight')
print(plt.style.available)
#change figure size
pylab.rcParams['figure.figsize'] = (10, 6)
Explanation: Let's take a closer look again on our PC versus Mac menu bar example. Here are the measurements ... |
6,675 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
import fgm tables
Step1: Function libaries
ResBlock
res_block is the backbone of the resnet structure. The resblock has multi branch, bottle neck layer and skip connection build in. This m... | Python Code:
!pip install gdown
!mkdir ./data
import gdown
def data_import():
ids = {
"tables_of_fgm.h5":"1XHPF7hUqT-zp__qkGwHg8noRazRnPqb0"
}
url = 'https://drive.google.com/uc?id='
for title, g_id in ids.items():
try:
output_file = open("/content/data/" + title, 'wb')
gdown.download(url... |
6,676 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exercise Introduction
The cameraman who shot our deep learning videos mentioned a problem that we can solve with deep learning.
He offers a service that scans photographs to store them dig... | Python Code:
# Set up code checking
from learntools.core import binder
binder.bind(globals())
from learntools.deep_learning.exercise_4 import *
print("Setup Complete")
Explanation: Exercise Introduction
The cameraman who shot our deep learning videos mentioned a problem that we can solve with deep learning.
He offers... |
6,677 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
What Happens If I Make a Mistake?
This notebook contains an interactive introduction to the OFTR language.
ZOF Codec
For the first step, we are going to show how to use zof.codec. This is a ... | Python Code:
import zof.codec
Explanation: What Happens If I Make a Mistake?
This notebook contains an interactive introduction to the OFTR language.
ZOF Codec
For the first step, we are going to show how to use zof.codec. This is a tool for translating OpenFlow messages from YAML to binary and back again.
First, impor... |
6,678 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Visualizing attention on self driving car
So far we have seen many examples of attention and activation maximization on Dense layers that outputs a probability distribution. What if we have ... | Python Code:
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline
from model import build_model, FRAME_W, FRAME_H
from keras.preprocessing.image import img_to_array
from vis.utils import utils
model = build_model()
model.load_weights('weights.hdf5')
img = utils.load_img('images/left.png', target_s... |
6,679 | 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... |
6,680 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simple example to compute derivatives of any Fortran routine with DNAD
<hr>
James C. Orr$^1$, Jean-Marie Epitalon$^2$, and James Kermode$^3$
$^1$Laboratoire des Sciences du Climat et de l'E... | Python Code:
# Working directory (change as needed)
#cylynder_dnad_dir = "/home/my-user-name/etc/"
cylynder_dnad_dir = "."
import sys
sys.path.append(cylynder_dnad_dir)
Explanation: Simple example to compute derivatives of any Fortran routine with DNAD
<hr>
James C. Orr$^1$, Jean-Marie Epitalon$^2$, and James Kermode$... |
6,681 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example data from the Death Implicit Association Test
Nock, M.K., Park, J.M., Finn, C.T., Deliberto, T.L., Dour, H.J., & Banaji, M.R. (2010). Measuring the suicidal mind
Step1: <blockquote>... | Python Code:
d=pd.read_csv('iat_data.csv',index_col=0)
d.head()
#Number of trials per subject
#Note that Subject 1 has too few trials
d.groupby('subjnum').subjnum.count().head()
#Number of subjects in this data set
d.subjnum.unique()
#Conditions
d.condition.unique()
#Blocks
d.block.unique()
#Correct coded as 1, errors ... |
6,682 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Toplevel
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specif... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'bnu', 'bnu-esm-1-1', 'toplevel')
Explanation: ES-DOC CMIP6 Model Properties - Toplevel
MIP Era: CMIP6
Institute: BNU
Source ID: BNU-ESM-1-1
Sub-Topics: Radiative Forcings.
Properties... |
6,683 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Intrinsic dispersion
Likelihood minimization of Gaussian Distribution
The data
Step6: Formula to adjust
The Probability to measure x with and error dx
The Theory
The probability p to observ... | Python Code:
sigma_int = 0.10
mu = -0.5
error = 0.12
error_noise = 0.03 # This means that the errors will be 0.12 +/- 0,03
npoints = 1000
errors = np.random.normal(loc=error, scale=error_noise, size=npoints)
data = np.random.normal(loc=mu, scale=sigma_int, size=npoints) + np.random.normal(loc=0,scale=errors)
fig = mp... |
6,684 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Master Telefónica Big Data & Analytics
Prueba de Evaluación del Tema 4
Step1: Para evitar problemas de sobrecarga de memoria, o de tiempo de procesado, puede reducir el tamaño el corpus, m... | Python Code:
#nltk.download()
mycorpus = nltk.corpus.reuters
Explanation: Master Telefónica Big Data & Analytics
Prueba de Evaluación del Tema 4:
Topic Modelling.
Date: 2016/04/10
Para realizar esta prueba es necesario tener actualizada la máquina virtual con la versión más reciente de MLlib.
Para la actualización, de... |
6,685 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Use this to keep track of useful code bits as I learn Python
Krista, August 19, 2015
Shortcut Action
Shift-Enter run cell
Ctrl-Enter run cell in-place
Alt-Enter run cell, insert be... | Python Code:
#First up...list the files in a directory
import os,sys
os.listdir(os.getcwd())
#read the CSV file into a data frame and use the pandas head tool to show me the first five rows.
#note that this doesn't seem to work: pd.head(CO_RawData)
CO_RawData=pd.read_csv(mtabFile, index_col='RInumber')
CO_RawData.head... |
6,686 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Applying classifiers to Shalek2013
We're going to use the classifier knowledge that we've learned so far and apply it to the shalek2013 and macaulay2016 datasets.
For the GO analysis, we'll ... | Python Code:
# Alphabetical order is standard
# We're doing "import superlongname as abbrev" for our laziness - this way we don't have to type out the whole thing each time.
# From python standard library
import collections
# Python plotting library
import matplotlib.pyplot as plt
# Numerical python library (pronounced... |
6,687 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Intorduction to PyMC2
Balint Szoke
Installation
Step1: Probabilistic model
Suppose you have a sample ${y_t}_{t=0}^{T}$ and want to characeterize it by the following probabilistic model; for... | Python Code:
%matplotlib inline
import numpy as np
import scipy as sp
import pymc as pm
import seaborn as sb
import matplotlib.pyplot as plt
Explanation: Intorduction to PyMC2
Balint Szoke
Installation:
>> conda install pymc
End of explanation
def sample_path(rho, sigma, T, y0=None):
'''
Simulates the sa... |
6,688 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Homework 6
Step1: Observa-se no gráfico uma relação clara entre o número de reinvidicações e o pagamento total.
Step2: Como esperado, o modelo de regressão linear explica bem os dados, ten... | Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
% matplotlib inline
# Define uma função para carregar os dados
def load_csv(path):
df = pd.read_csv(path,names=['num_reinv','pag_total'])
return df
insdf = load_csv('insurance.csv')
insdf.head()
plt.scatter(insdf.num_rei... |
6,689 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
3-Way Merge Sort
Step1: The function mergeSort is called with 4 arguments.
- The first parameter L is the list that is to be sorted.
However, the task of mergeSort is not to sort the ... | Python Code:
def sort(L):
A = L[:]
mergeSort(L, 0, len(L), A)
Explanation: 3-Way Merge Sort: An Array-Based Implementation
The function $\texttt{sort}(L)$ sorts the list $L$ in place using merge sort.
It takes advantage of the fact that, in Python, lists are stored internally as arrays.
The function sort is a w... |
6,690 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Network Data Access - USGS NWIS Service-based Data Access
Karl Benedict
Director, Earth Data Analysis Center
Associate Professor, University Libraries
University of New Mexico
kbene@unm.edu
... | Python Code:
import urllib
import zipfile
import StringIO
import string
import pandas
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import HTML
import json
Explanation: Network Data Access - USGS NWIS Service-based Data Access
Karl Benedict
Director, Earth Data Analysis Center
Associate Profes... |
6,691 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example for kNearestNeighbor using the Iris Data
First we need the standard import
Step1: Load the Data
Step2: Look at the data
it's a good idea to look at the data a little bit, know the ... | Python Code:
%pylab inline
from classy import *
Explanation: Example for kNearestNeighbor using the Iris Data
First we need the standard import
End of explanation
data=load_excel('data/iris.xls',verbose=True)
Explanation: Load the Data
End of explanation
print(data.vectors.shape)
print(data.targets)
print(data.target_n... |
6,692 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Gaussian Process Latent Variable Model
The Gaussian Process Latent Variable Model (GPLVM) is a dimensionality reduction method that uses a Gaussian process to learn a low-dimensional represe... | Python Code:
import os
import matplotlib.pyplot as plt
import pandas as pd
import torch
from torch.nn import Parameter
import pyro
import pyro.contrib.gp as gp
import pyro.distributions as dist
import pyro.ops.stats as stats
smoke_test = ('CI' in os.environ) # ignore; used to check code integrity in the Pyro repo
asse... |
6,693 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Filtering Sequence Elements
Problem
You have data inside of a sequence, and need to extract values or reduce the sequence using some criteria.
Solution
The easiest way to filter sequence dat... | Python Code:
mylist = [1, 4, -5, 10, -7, 2, 3, -1]
# All positive values
pos = [n for n in mylist if n > 0]
print(pos)
# All negative values
neg = [n for n in mylist if n < 0]
print(neg)
# Negative values clipped to 0
neg_clip = [n if n > 0 else 0 for n in mylist]
print(neg_clip)
# Positive values clipped to 0
pos_clip... |
6,694 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Preprocessing Data with Simple Example using TensorFlow Transform
Learning objectives
Create a preprocessing function.
Use the resulting transform_fn directory.
Export the model.
In this not... | Python Code:
!pip install --upgrade pip
Explanation: Preprocessing Data with Simple Example using TensorFlow Transform
Learning objectives
Create a preprocessing function.
Use the resulting transform_fn directory.
Export the model.
In this notebook, you learn a very simple example of how <a target='_blank' href='https:... |
6,695 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
So 1.0.0 doesn't actually convincingly perform better than 0.2.1 (RF) so I'm seeing if more hidden layers changes anything
Step1: DO NOT FORGET TO DROP ISSUE_D AFTER PREPPING
Step2: Until ... | Python Code:
import data_science.lendingclub.dataprep_and_modeling.modeling_utils.data_prep_new as data_prep
import dir_constants as dc
from sklearn.externals import joblib
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
import torch.nn.functional as F
from torch.utils... |
6,696 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Enter State Farm
Step1: Create sample
The following assumes you've already created your validation set - remember that the training and validation set should contain different drivers, as m... | Python Code:
from theano.sandbox import cuda
cuda.use('gpu1')
%matplotlib inline
from __future__ import print_function, division
#path = "data/state/"
path = "data/state/sample/"
import utils; reload(utils)
from utils import *
from IPython.display import FileLink
batch_size=64
Explanation: Enter State Farm
End of expla... |
6,697 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Vidic, Fajfar and Fischinger (1994)
This procedure, proposed by Vidic, Fajfar and Fischinger (1994), aims to determine the displacements from an inelastic design spectra for systems with a ... | Python Code:
from rmtk.vulnerability.derivation_fragility.equivalent_linearization.vidic_etal_1994 import vidic_etal_1994
from rmtk.vulnerability.common import utils
%matplotlib inline
Explanation: Vidic, Fajfar and Fischinger (1994)
This procedure, proposed by Vidic, Fajfar and Fischinger (1994), aims to determine t... |
6,698 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using python
Python is an interpreted language. This means that there is a "python program" that reads your input and excecutes it. If you open your ipython interpreter, you'll see the follo... | Python Code:
1 + 1
Explanation: Using python
Python is an interpreted language. This means that there is a "python program" that reads your input and excecutes it. If you open your ipython interpreter, you'll see the following message (or something very similar):
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
Type "cop... |
6,699 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Webscraping with Selenium
When the data that you want exists on a website with heavy JavaScript and requires interaction from the user, BeautifulSoup will not be enough. This is when you nee... | Python Code:
from selenium import webdriver # powers the browser interaction
from selenium.webdriver.support.ui import Select # selects menu options
from pyvirtualdisplay import Display # for JHub environment
from bs4 import BeautifulSoup # to parse HTML
import csv # to write CSV
import pandas # to see CSV
Explan... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.