Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
9,200 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
HTTP requests
In this tutorial ti is covered how to make requests via HTTP protocol.
For more informations about related stuff see
Step1: The variable data contains returned HTML code (ful... | Python Code:
from urllib.request import urlopen
r = urlopen('http://www.python.org/')
data = r.read()
print("Status code:", r.getcode())
Explanation: HTTP requests
In this tutorial ti is covered how to make requests via HTTP protocol.
For more informations about related stuff see:
* <a href="https://en.wikipedia.org/w... |
9,201 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
반복과 제어
이성주 (c) 2015
Step1: for
Step2: 들여쓰기는 문법
Step3: 들여쓰기와 스코프
Step4: 내장리스트 (list comprehension)
리스트 내에서 반복문 실행
Step5: 숫자 리스트 생성 함수
Step6: 특정 횟수 반복
Step7: 인덱스가 필요한 경우
Step8: while
S... | Python Code:
# 3버전 스타일 print 함수 사용
from __future__ import print_function
Explanation: 반복과 제어
이성주 (c) 2015
End of explanation
print([1,2,3])
for n in [1,2,3]:
print(n)
Explanation: for
End of explanation
for n in [1,2,3]:
print(n)
print(n)
for key in {'name': '이성주', 'email':'seongjoo@codebasic'}:
print(... |
9,202 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial 2 - Reti neurali convolutive in TF
Prerequisiti per il tutorial
Step1: Nell'esempio prima, abbiamo scelto di scaricare solo le immagini di persone di cui abbiamo (almeno) 70 esempi... | Python Code:
from sklearn.datasets import fetch_lfw_people
lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4)
Explanation: Tutorial 2 - Reti neurali convolutive in TF
Prerequisiti per il tutorial:
* T1 - Reti neurali feedforward
Contenuti del tutorial:
1. Concetti base delle reti neurali convolutive.
2.... |
9,203 | 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', 'mohc', 'sandbox-1', 'toplevel')
Explanation: ES-DOC CMIP6 Model Properties - Toplevel
MIP Era: CMIP6
Institute: MOHC
Source ID: SANDBOX-1
Sub-Topics: Radiative Forcings.
Properties: ... |
9,204 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Executed
Step1: Load software and filenames definitions
Step2: Data folder
Step3: List of data files
Step4: Data load
Initial loading of the data
Step5: Laser alternation selection
At t... | Python Code:
ph_sel_name = "DexDem"
data_id = "17d"
# ph_sel_name = "all-ph"
# data_id = "7d"
Explanation: Executed: Mon Mar 27 11:35:09 2017
Duration: 11 seconds.
usALEX-5samples - Template
This notebook is executed through 8-spots paper analysis.
For a direct execution, uncomment the cell below.
End of explanation
fr... |
9,205 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Matplotlib Exercise 1
Imports
Step1: Line plot of sunspot data
Download the .txt data for the "Yearly mean total sunspot number [1700 - now]" from the SILSO website. Upload the file to the ... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
Explanation: Matplotlib Exercise 1
Imports
End of explanation
import os
assert os.path.isfile('yearssn.dat')
Explanation: Line plot of sunspot data
Download the .txt data for the "Yearly mean total sunspot number [1700 - now]" from the S... |
9,206 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<div align="right">Python 2.7</div>
Indexing and Related Experiments in Python 2.7
Though this content is in Python 2.7, most if not all of it should work the same in Python 3.x.
TOC
Indexin... | Python Code:
stupidList = [[1,2,3],[4,5,6]]
print(stupidList)
stupidList[0][1]
Explanation: <div align="right">Python 2.7</div>
Indexing and Related Experiments in Python 2.7
Though this content is in Python 2.7, most if not all of it should work the same in Python 3.x.
TOC
Indexing Experiments - Explores different com... |
9,207 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exploratory Data Analysis with Python
We will explore the NYC MTA turnstile data set. These data files are from the New York Subway. It tracks the hourly entries and exits to turnstiles (UNI... | Python Code:
from collections import defaultdict
import csv
import os
import os.path as osp
from dateutil.parser import parse
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from k2datascience import nyc_mta
from IPython.core.interactiveshell import Interactiv... |
9,208 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
pd.DataFrame({'article_uni'
Step1: a=pd.pivot_table(df,index=["article_uni"],values=["article_rating"],aggfunc=[len,np.mean], columns='year')
a
Step2: b=df[df.article_pub_date>=data_first_... | Python Code:
df_ranking=pd.read_csv('article_uni.csv', index_col=0)
print(df_ranking.shape)
df_ranking.head()
df.article_uni.replace('The London School of Economics and Political Science (United-Kingdom)',
'London School of Economics and Political Science', inplace=True)
from sklearn.preprocessing import MinMaxScal... |
9,209 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Reflecting on 2017, I decided to return to my most popular blog topic (at least by the number of emails I get). Last time, I built a crude statistical model to predict the result of football... | Python Code:
# importing the tools required for the Poisson regression model
import statsmodels.api as sm
import statsmodels.formula.api as smf
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn
def get_home_team_advantage(goals_df, pval=0.05):
# extract relevant columns
... |
9,210 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Graph of iDigBio Specimens over Time
This notebook introduces the basics of loading and analyzing iDigBio data on the GUODA infrastructure hosted by the ACIS Lab and iDigBio. This service is... | Python Code:
# The Python Spark (pyspark) libraries include functions designed to be run on columns of data
# stored in Spark data frames. They need to be imported in order to use them. Here we
# are going to use
from pyspark.sql.functions import year
# The matplotlib package is used for graphing. The next line tells ... |
9,211 | Given the following text description, write Python code to implement the functionality described.
Description:
Count three
Function to count three - digit numbers having difference x with its reverse ; If x is not multiple of 99 ; No solution exists ; Generate all possible pairs of digits [ 1 , 9 ] ; If any pair is obt... | Python Code:
def Count_Number(x ) :
ans = 0 ;
if(x % 99 != 0 ) :
ans = - 1 ;
else :
diff = x / 99 ;
for i in range(1 , 10 ) :
for j in range(1 , 10 ) :
if(( i - j ) == diff ) :
ans += 10 ;
return ans ;
if __name__== ' __main __' :
x = 792 ;
print(Count_Number(x ) ) ;
|
9,212 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Work through the reduction of a single dataset
Step1: Setup files
Copy files from Dropbox to local, working folder
cd 'working_folder'
# Darks, if needed
cp -rp ~/Dropbox/COS-LRG/darksall .... | Python Code:
# imports
import os
import glob
import pdb
#from imp import reload
#from importlib import reload
from astropy.io import fits
from cosredux import utils as cr_utils
from cosredux import trace as cr_trace
from cosredux import darks as cr_darks
from cosredux import io as cr_io
from cosredux import science as ... |
9,213 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
An Introduction to pandas
Pandas! They are adorable animals. You might think they are the worst animal ever but that is not true. You might sometimes think pandas is the worst library every,... | Python Code:
# import pandas, but call it pd. Why? Because that's What People Do.
Explanation: An Introduction to pandas
Pandas! They are adorable animals. You might think they are the worst animal ever but that is not true. You might sometimes think pandas is the worst library every, and that is only kind of true.
The... |
9,214 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Analyzing dendritic data with CaImAn
This notebook shows an example on how to analyze two-photon dendritic data with CaImAn. It follows closely the other notebooks.
Step1: Selecting the dat... | Python Code:
import cv2
import glob
import logging
import matplotlib.pyplot as plt
import numpy as np
import os
try:
cv2.setNumThreads(0)
except():
pass
try:
if __IPYTHON__:
get_ipython().magic('load_ext autoreload')
get_ipython().magic('autoreload 2')
except NameError:
pass
import caima... |
9,215 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ROOT dataframe tutorial
Step1: Create a ROOT dataframe in Python
First we will create a ROOT dataframe that is connected to a dataset named Events stored in a ROOT file. The file is pulled ... | Python Code:
import ROOT
Explanation: ROOT dataframe tutorial: Dimuon spectrum
This tutorial shows you how to analyze datasets using RDataFrame from a Python notebook. The example analysis performs the following steps:
Connect a ROOT dataframe to a dataset containing 61 mio. events recorded by CMS in 2012
Filter the... |
9,216 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Leitura e display de imagens com matplotlib
importando
Step1: Leitura usando matplotlib native e com PIL
O matplotlib possui a leitura nativa de imagens no formato png. Quando este formato ... | Python Code:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
Explanation: Leitura e display de imagens com matplotlib
importando
End of explanation
f = mpimg.imread('../data/cameraman.tif')
print(f.dtype,f.shape,f.max(),f.min())
Explanation: Leitura usando matplotlib native e com PIL... |
9,217 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A primer on numerical differentiation
In order to numerically evaluate a derivative $y'(x)=dy/dx$ at point $x_0$, we approximate is by using finite differences
Step1: Why is it that the seq... | Python Code:
dx = 1.
x = 1.
while(dx > 1.e-10):
dy = (x+dx)*(x+dx)-x*x
d = dy / dx
print("%6.0e %20.16f %20.16f" % (dx, d, d-2.))
dx = dx / 10.
Explanation: A primer on numerical differentiation
In order to numerically evaluate a derivative $y'(x)=dy/dx$ at point $x_0$, we approximate is by using f... |
9,218 | 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', 'inm', 'inm-cm5-h', 'land')
Explanation: ES-DOC CMIP6 Model Properties - Land
MIP Era: CMIP6
Institute: INM
Source ID: INM-CM5-H
Topic: Land
Sub-Topics: Soil, Snow, Vegetation, Energy ... |
9,219 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Oregon Curriculum Network <br />
Discovering Math with Python
Chapter 6
Step1: We're going to want to see our vectors rendered in some way. Visual Python, or VPython, provides an excellent... | Python Code:
class Vector:
"A point in space"
pass
Explanation: Oregon Curriculum Network <br />
Discovering Math with Python
Chapter 6: VECTORS IN SPACE
A point vector is simply an object that points, from the origin to a specific location. We usually represent such an object with an arrow, with its tail at (0... |
9,220 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Part of Neural Network Notebook (3nb) project.
Copyright (C) 2014 Eka A. Kurniawan
eka.a.kurniawan(ta)gmail(tod)com
This program is free software
Step1: Display Settings
Step2: Housekeepi... | Python Code:
import sys
print("Python %d.%d.%d" % (sys.version_info.major, \
sys.version_info.minor, \
sys.version_info.micro))
import numpy as np
print("NumPy %s" % np.__version__)
# Display graph inline
%matplotlib inline
import matplotlib
import matplotlib.pyplot... |
9,221 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TinyImageNet and Ensembles
So far, we have only worked with the CIFAR-10 dataset. In this exercise we will introduce the TinyImageNet dataset. You will combine several pretrained models into... | Python Code:
# A bit of setup
import numpy as np
import matplotlib.pyplot as plt
from time import time
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
# for auto-reloading extenrnal modules
# ... |
9,222 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Doc2Vec trained on recipe instructions
Objectives
Create word embeddings for recipes.
Use word vectors for (traditional) segmentation, classification, and retrieval of recipes.
Based on http... | Python Code:
import re # Regular Expressions
import os.path # File Operations
import pandas as pd # DataFrames & Manipulation
from gensim.models.doc2vec import LabeledSentence, Doc2V... |
9,223 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A Workshop Introduction to NumPy
The Python language is an excellent tool for general-purpose programming, with a highly readable syntax, rich and powerful data types (strings, lists, sets, ... | Python Code:
# NumPy is generally imported as 'np'.
import numpy as np
print(np)
print(np.__version__)
Explanation: A Workshop Introduction to NumPy
The Python language is an excellent tool for general-purpose programming, with a highly readable syntax, rich and powerful data types (strings, lists, sets, dictionaries, ... |
9,224 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Blind Source Separation with the Shogun Machine Learning Toolbox
By Kevin Hughes
This notebook illustrates <a href="http
Step1: Next we're going to need a way to play the audio files we're ... | Python Code:
import numpy as np
import os
SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data')
from scipy.io import wavfile
from scipy.signal import resample
import shogun as sg
def load_wav(filename,samplerate=44100):
# load file
rate, data = wavfile.read(filename)
# convert stereo to mono
... |
9,225 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Integration Exercise 1
Imports
Step2: Trapezoidal rule
The trapezoidal rule generates a numerical approximation to the 1d integral
Step3: Now use scipy.integrate.quad to integrate the f an... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from scipy import integrate
Explanation: Integration Exercise 1
Imports
End of explanation
integrate.quad?
def trapz(f, a, b, N):
Integrate the function f(x) over the range [a,b] with N points.
h=(b-a)/N
integral=0
while ... |
9,226 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
plotly
plotly has recently become open source, it proposes a large gallery of javascript graphs. plotly also offers to host dashboards built with plotly.
The first script usually returns an ... | Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
Explanation: plotly
plotly has recently become open source, it proposes a large gallery of javascript graphs. plotly also offers to host dashboards built with plotly.
The first script usually returns an exception:
But there exists an offline m... |
9,227 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Is there a relationship between GDP per capita and PISA scores?
July 2015
Written by Susan Chen at NYU Stern with help from Professor David Backus
Contact
Step1: Creating the Dataset
PISA ... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import statsmodels.formula.api as smf
from pandas.io import wb
Explanation: Is there a relationship between GDP per capita and PISA scores?
July 2015
Written by Susan Chen at NYU Stern with help from Professor David ... |
9,228 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Notes
Step1: Here the curve shows the Poisson mean as a function of $M$. Clearly, the data don't sit on the curve, nor should they. But it would be nice to represent the width of the sampli... | Python Code:
# get a bunch of imports out of the way
import matplotlib.pyplot as plt
plt.rc('text', usetex=True)
plt.rcParams['xtick.labelsize'] = 'x-large'
plt.rcParams['ytick.labelsize'] = 'x-large'
import numpy as np
import scipy.stats as st
%matplotlib inline
M = st.uniform.rvs(1.0, 100.0, size=10)
F = np.sqrt(M)
m... |
9,229 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DICS for power mapping
In this tutorial, we'll simulate two signals originating from two
locations on the cortex. These signals will be sinusoids, so we'll be looking
at oscillatory activity... | Python Code:
# Author: Marijn van Vliet <w.m.vanvliet@gmail.com>
#
# License: BSD (3-clause)
Explanation: DICS for power mapping
In this tutorial, we'll simulate two signals originating from two
locations on the cortex. These signals will be sinusoids, so we'll be looking
at oscillatory activity (as opposed to evoked a... |
9,230 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Spatial Model fitting in GLS
In this exercise we will fit a linear model using a Spatial structure as covariance matrix.
We will use GLS to get better estimators.
As always we will need to ... | Python Code:
# Load Biospytial modules and etc.
%matplotlib inline
import sys
sys.path.append('/apps')
sys.path.append('..')
sys.path.append('../spystats')
import django
django.setup()
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
## Use the ggplot style
plt.style.use('ggplot')
import tools
Exp... |
9,231 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
T81-558
Step1: Training with a Validation Set and Early Stopping
Overfitting occurs when a neural network is trained to the point that it begins to memorize rather than generalize.
It is ... | Python Code:
from sklearn import preprocessing
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Encode text values to dummy variables(i.e. [1,0,0],[0,1,0],[0,0,1] for red,green,blue)
def encode_text_dummy(df,name):
dummies = pd.get_dummies(df[name])
for x in dummies.columns:
dumm... |
9,232 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Computing for Mathematics - 2020/2021 individual coursework
Important Do not delete the cells containing
Step3: b. $1/2$
Available marks
Step5: c. $3/4$
Available marks
Step7: d. $... | Python Code:
import random
def sample_experiment():
### BEGIN SOLUTION
Returns true if a random number is less than 0
return random.random() < 0
number_of_experiments = 1000
sum(
sample_experiment() for repetition in range(number_of_experiments)
) / number_of_experiments
### END SOLUTION
Expla... |
9,233 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DeepLearning
MNIST Dataset using DeepWater and Custom MXNet Model
The MNIST database is a well-known academic dataset used to benchmark
classification performance. The data consists of 60,00... | Python Code:
import h2o
h2o.init()
import os.path
PATH = os.path.expanduser("~/h2o-3/")
test_df = h2o.import_file(PATH + "bigdata/laptop/mnist/test.csv.gz")
train_df = h2o.import_file(PATH + "/bigdata/laptop/mnist/train.csv.gz")
Explanation: DeepLearning
MNIST Dataset using DeepWater and Custom MXNet Model
The MNIST da... |
9,234 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generarea si vizualizarea curbelor
1. Curbe plane
O curba plana diferentiabila, data parametric, este imaginea, $im(r)$, a unei aplicatii diferentiabile $r
Step1: Pentru a intelege definit... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
def Curba(a, b, N):
h=(b-a)/N
t=np.arange(a,b, h)
return (np.cos(t)+t*np.sin(t), np.sin(t)-t*np.cos(t))# functia returneaza tuple (x(t), y(t))
Explanation: Generarea si vizualizarea curbelor
1. Curbe plane
O curba plana... |
9,235 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Homework 2
In this homework, we are going to play with Twitter data.
The data is represented as rows of of JSON strings.
It consists of tweets, messages, and a small amount of broken data (c... | Python Code:
import findspark
findspark.init()
import pyspark
sc = pyspark.SparkContext()
# %install_ext https://raw.github.com/cpcloud/ipython-autotime/master/autotime.py
%load_ext autotime
def print_count(rdd):
print 'Number of elements:', rdd.count()
env="local"
files=''
path = "Data/hw2-files.txt"
if env=="prod... |
9,236 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Logistics
We are going to use parallel-tempering, implemented via the python emcee package, to explore our posterior, which consists of the set of distances and gas to dust conversion coeffi... | Python Code:
import emcee
from dustcurve import model
import seaborn as sns
import numpy as np
from dustcurve import pixclass
import matplotlib.pyplot as plt
import pandas as pd
import warnings
from dustcurve import io
from dustcurve import hputils
from dustcurve import kdist
import h5py
from dustcurve import globalvar... |
9,237 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Thermal Sensor Measurements
The goal of this experiment is to measure temperature on Juno R2 board using the available sensors. In order to do that we will run a busy-loop workload of about ... | Python Code:
import logging
from conf import LisaLogging
LisaLogging.setup()
%pylab inline
import os
# Support to access the remote target
import devlib
from env import TestEnv
# Support to configure and run RTApp based workloads
from wlgen import RTA, Periodic
# Support for trace events analysis
from trace import Trac... |
9,238 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Calculating Wang's Semantic Similarity between two GO Terms
Setup
Calculate Wang's semantic similarity using optional part_of relationship
Calculate Wang's semantic similarity using research... | Python Code:
# Researcher-provided GO terms related to smell
go_a = 'GO:0007608'
go_b = 'GO:0050911'
go_c = 'GO:0042221'
# Optional relationships. (Relationship, is_a, is required and always used)
relationships = {'part_of'}
goids = {go_a, go_b, go_c}
# Annotations for plotting
go2txt = {
go_a:'GO TERM A',
go_b... |
9,239 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
scipy stats
This notebook focuses on the use of the scipy.stats module
It is built based on a learn-by-example approach So it only covers a little part of the module's functionalities but pr... | Python Code:
%matplotlib inline
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
import pandas as pd
Explanation: scipy stats
This notebook focuses on the use of the scipy.stats module
It is built based on a learn-by-example approach So it only covers a little part of the module's functionalit... |
9,240 | 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', 'inpe', 'sandbox-2', 'toplevel')
Explanation: ES-DOC CMIP6 Model Properties - Toplevel
MIP Era: CMIP6
Institute: INPE
Source ID: SANDBOX-2
Sub-Topics: Radiative Forcings.
Properties: ... |
9,241 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Implicit functions in pytorch
Thomas Viehmann, tv@lernapparat.de
Sometimes, we do not know the mapping of functions we wish to apply, but only an equation that describes the mapping. In math... | Python Code:
import torch
import numpy
from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
%matplotlib inline
Explanation: Implicit functions in pytorch
Thomas Viehmann, tv@lernapparat.de
Sometimes, we do not know the mapping of functions we wish to apply, but only an equation that describes the mappi... |
9,242 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introducing the Keras Sequential API
Learning Objectives
1. Build a DNN model using the Keras Sequential API
1. Learn how to use feature columns in a Keras model
1. Learn how to train ... | Python Code:
# Ensure the right version of Tensorflow is installed.
!pip freeze | grep tensorflow==2.0 || pip install tensorflow==2.0
Explanation: Introducing the Keras Sequential API
Learning Objectives
1. Build a DNN model using the Keras Sequential API
1. Learn how to use feature columns in a Keras model
1. Le... |
9,243 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Transforming an input to a known output
Step2: relation between input and output is linear
Step3: Defining the model to train
untrained single unit (neuron) also out... | Python Code:
!pip install -q tf-nightly-gpu-2.0-preview
import tensorflow as tf
print(tf.__version__)
# a small sanity check, does tf seem to work ok?
hello = tf.constant('Hello TF!')
print("This works: {}".format(hello))
# this should return True even on Colab
tf.test.is_gpu_available()
tf.test.is_built_with_cuda()
!n... |
9,244 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Welcome to Jupyter!
With Jupyter notebooks you can write and execute code, annotate it with Markdownd and use powerful visualization tools all in one document.
Running code
Code cells can be... | Python Code:
import math
from matplotlib import pyplot as plt
a=1
b=2
a+b
Explanation: Welcome to Jupyter!
With Jupyter notebooks you can write and execute code, annotate it with Markdownd and use powerful visualization tools all in one document.
Running code
Code cells can be executed in sequence by pressing Shift-ENT... |
9,245 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
How HDBSCAN Works
HDBSCAN is a clustering algorithm developed by Campello, Moulavi, and Sander. It extends DBSCAN by converting it into a hierarchical clustering algorithm, and then using a ... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import sklearn.datasets as data
%matplotlib inline
sns.set_context('poster')
sns.set_style('white')
sns.set_color_codes()
plot_kwds = {'alpha' : 0.5, 's' : 80, 'linewidths':0}
Explanation: How HDBSCAN Works
HDBSCAN is a clustering alg... |
9,246 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interrupted workflow
This example shows that using IO, you can easily interrupt your workflow, save it and continue some other time.
Step1: Store the histogram (and delete it to pretend we ... | Python Code:
import numpy as np
import physt
histogram = physt.h1(None, "fixed_width", bin_width=0.1, adaptive=True)
histogram
# Big chunk of data
data1 = np.random.normal(0, 1, 10000000)
histogram.fill_n(data1)
histogram
histogram.plot()
Explanation: Interrupted workflow
This example shows that using IO, you can easil... |
9,247 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
5D Example
In this notebook we will go through an example using the foxi code features to evaluate the expected utility of a mock scientific survey. This notebook will assume the reader is f... | Python Code:
import sys
path_to_foxi = '/Users/Rob/work/foxi' # Give your path to foxi here.
sys.path.append(path_to_foxi + '/foxisource/')
from foxi import foxi
# These imports aren't stricly necessary to run foxi but they will be useful in our examples.
import numpy as np
from scipy.stats import multivariate_normal
... |
9,248 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Setting a project
We need to choose a project inorder to work with buckets, if you dont have any, create a project in Gcloud Console
First we need to set a default pr... | Python Code:
from google.colab import auth
auth.authenticate_user()
Explanation: <a href="https://colab.research.google.com/github/probml/probml-notebooks/blob/main/notebooks/GCS_demo_v2.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
Authenticate in... |
9,249 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Setting things up
Step1: Timing | Python Code:
my_data = cellreader.CellpyData()
# only for my MacBook
filename = "/Users/jepe/scripting/cellpy/dev_data/out/20190204_FC_snx012_01_cc_01.h5"
assert os.path.isfile(filename)
my_data.load(filename)
Explanation: Setting things up
End of explanation
%%timeit
my_data.make_summary()
%%timeit
my_data.make_step_t... |
9,250 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
XML exercise
Using data in 'data/mondial_database.xml', the examples above, and refering to https
Step1: Not all the entries have an infant mortality rate element. So we need to make sure l... | Python Code:
document = ET.parse( './data/mondial_database.xml' )
import pandas as pd
root = document.getroot()
Explanation: XML exercise
Using data in 'data/mondial_database.xml', the examples above, and refering to https://docs.python.org/2.7/library/xml.etree.elementtree.html, find
10 countries with the lowest infan... |
9,251 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Getting Started
This tutorial describes how to use Pandas-TD in Jupyter to explore data interactively.
Set your API key to the environment variable TD_API_KEY and run "jupyter notebook"
Step... | Python Code:
%matplotlib inline
import os
import pandas_td as td
# Set engine type and database, using the default connection
engine = td.create_engine('presto:sample_datasets')
# Alternatively, initialize a connection explicitly
con = td.connect(apikey=os.environ['TD_API_KEY'], endpoint=os.environ['TD_API_SERVER'])
en... |
9,252 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Characterizing Context of Attacks
Step1: Q
Step2: Methodology 2
Step3: Q | Python Code:
%load_ext autoreload
%autoreload 2
%matplotlib inline
import warnings
warnings.filterwarnings('ignore')
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
from load_utils import *
d = load_diffs()
df_events, df_blocked_user_text = load_block_events_and_users()
Expl... |
9,253 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
QInfer
Step1: Applications in Quantum Information
Phase and Frequency Learning
Step2: State and Process Tomography
Step3: Randomized Benchmarking
Step4: Additional Functionality
Derived ... | Python Code:
from __future__ import division, print_function
%matplotlib inline
from qinfer import *
import os
import numpy as np
from scipy.linalg import expm
import matplotlib.pyplot as plt
try:
plt.style.use('ggplot-rq')
except IOError:
try:
plt.style.use('ggplot')
except:
raise RuntimeEr... |
9,254 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Finite Time of Integration (fti)
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).
... | Python Code:
#!pip install -I "phoebe>=2.3,<2.4"
Explanation: Finite Time of Integration (fti)
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
import... |
9,255 | 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.
import cPickle as pickle
import numpy as np
import tensorflow as tf
Explanation: Deep Learning
Assignment 2
Previously in 1_notmnist.ipynb, we created a pickle with formatted datasets for training, ... |
9,256 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MLE fit for two component binding - simulated and real data
In part one of this notebook we see how well we can reproduce Kd from simulated experimental data with a maximum likelihood functi... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
from scipy import optimize
import seaborn as sns
%pylab inline
Explanation: MLE fit for two component binding - simulated and real data
In part one of this notebook we see how well we can reproduce Kd from simulated experimental data with a maximum likelih... |
9,257 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exploring precision and recall
The goal of this second notebook is to understand precision-recall in the context of classifiers.
Use Amazon review data in its entirety.
Train a logistic regr... | Python Code:
import numpy as np
import pandas as pd
import json
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Exploring precision and recall
The goal of this second notebook is to understand precision-recall in the context of classifiers.
Use Amazon review data in its entirety.
Train a logistic regres... |
9,258 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Learning with TensorFlow
Credits
Step1: First reload the data we generated in notmist.ipynb.
Step2: Reformat into a shape that's more adapted to the models we're going to train | Python Code:
# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
import cPickle as pickle
import numpy as np
import tensorflow as tf
Explanation: Deep Learning with TensorFlow
Credits: Forked from TensorFlow by Google
Setup
Refer to the setup instructions.
Exerci... |
9,259 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example
Step1: Step 2
Step2: Step 3
Step3: Step 4 | Python Code:
%load_ext autoreload
%autoreload 2
%matplotlib inline
import sys, os, copy, logging, socket, time
import numpy as np
import pylab as plt
#from ndparse.algorithms import nddl as nddl
#import ndparse as ndp
sys.path.append('..'); import ndparse as ndp
try:
logger
except:
# do this precisely once
... |
9,260 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
New York University
Applied Data Science 2016 Final Project
Measuring household income under Redatam in CensusData
3. Model Evaluation and Selection
Project Description
Step1: HELPER FUNCTI... | Python Code:
import pandas as pd
import numpy as np
import os
import sys
import simpledbf
%pylab inline
import matplotlib.pyplot as plt
import statsmodels.api as sm
from sklearn.model_selection import train_test_split
from sklearn import linear_model
Explanation: New York University
Applied Data Science 2016 Final Proj... |
9,261 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Table of Contents
Nonlinear Filtering
Step1: Introduction
The Kalman filter that we have developed uses linear equations, and so the filter can only handle linear problems. But the world is... | Python Code:
from __future__ import division, print_function
%matplotlib inline
#format the book
import book_format
book_format.set_style()
Explanation: Table of Contents
Nonlinear Filtering
End of explanation
import numpy as np
from numpy.random import randn
import matplotlib.pyplot as plt
N = 5000
a = np.pi/2. + (ran... |
9,262 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Collating with CollateX
First we need to tell Python that we will be needing the Python library that holds the code for CollateX…
Step1: Now we're ready to make a collation object. We do th... | Python Code:
from collatex import *
Explanation: Collating with CollateX
First we need to tell Python that we will be needing the Python library that holds the code for CollateX…
End of explanation
collation = Collation()
Explanation: Now we're ready to make a collation object. We do this with the slightly hermetic lin... |
9,263 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python for Everyone!<br/>Oregon Curriculum Network
Extended Precision with the Native Decimal Type
With LaTeX and Generator Functions
<img src="https
Step2: Lets show setting precision to a... | Python Code:
%%latex
\begin{align}
e = lim_{n \to \infty} (1 + 1/n)^n
\end{align}
from math import e, pi
print(e) # as a floating point number
print(pi)
Explanation: Python for Everyone!<br/>Oregon Curriculum Network
Extended Precision with the Native Decimal Type
With LaTeX and Generator Functions
<img src="https://c... |
9,264 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Обнаружение статистически значимых отличий в уровнях экспрессии генов больных раком
Это задание поможет вам лучше разобраться в методах множественной проверки гипотез и позволит применить ва... | Python Code:
import pandas as pd
import scipy.stats
df = pd.read_csv("gene_high_throughput_sequencing.csv")
control_df = df[df.Diagnosis == 'normal']
neoplasia_df = df[df.Diagnosis == 'early neoplasia']
cancer_df = df[df.Diagnosis == 'cancer']
# scipy.stats.ttest_ind(data.Placebo, data.Methylphenidate, equal_var = Fals... |
9,265 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
★ Partial Differential Equations ★
Step1: 8.1 Parabolic Equations
Forward Difference Method
Step2: Backward Difference Method
Step3: Example
Apply the Backward Difference Method to solve ... | Python Code:
# Import modules
import numpy as np
import scipy
import sympy as sym
from scipy import sparse
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import axes3d
from IPython.display import Math
from IPython.display import display
sym.init_printing(use_latex=True)
Explanation: ★ Partial Differenti... |
9,266 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lecture 6
Step1: Let's break it down.
for element in range(10)
Step2: There it is
Step3: and we want to generate a list of sentences
Step4: Start with the loop header--you see it on the ... | Python Code:
squares = []
for element in range(10):
squares.append(element ** 2)
print(squares)
Explanation: Lecture 6: Advanced Data Structures
CSCI 1360: Foundations for Informatics and Analytics
Overview and Objectives
We've covered list, tuples, sets, and dictionaries. These are the foundational data structures... |
9,267 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Find Natural Neighbors Verification
Finding natural neighbors in a triangulation
A triangle is a natural neighbor of a point if that point is within a circumradius of the
circumcenter of a c... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
from scipy.spatial import Delaunay
from metpy.interpolate.geometry import find_natural_neighbors
# Create test observations, test points, and plot the triangulation and points.
gx, gy = np.meshgrid(np.arange(0, 20, 4), np.arange(0, 20, 4))
pts = np.vstack(... |
9,268 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Unsupervised Learning - Principal Components Analysis
Timothy Helton
<br>
<font color="red">
NOTE
Step1: Exercise 1 - Crowdedness at the Campus Gym
The dataset consists of 26,000 people... | Python Code:
from k2datascience import pca
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
%matplotlib inline
Explanation: Unsupervised Learning - Principal Components Analysis
Timothy Helton
<br>
<font color="red">
NOTE:
<br>
This notebook uses cod... |
9,269 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Contact Binary Hierarchy
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"
import phoebe
from phoebe import u # units
import numpy as np
import matplotlib.pyplot as plt
logger = phoebe.logger()
Explanation: Contact Binary Hierarchy
Setup
Let's first make sure we have the latest version of PHOEBE 2.3 installed (uncomment this line if running in ... |
9,270 | 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,271 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TFX Guided Project on Vertex
Learning Objectives
Step1: Step 1. Environment setup
Environment variable setup
Let's set some environment variables to use Vertex Pipelines.
Change your region... | Python Code:
import os
from google.cloud import aiplatform
Explanation: TFX Guided Project on Vertex
Learning Objectives:
Learn how to generate a standard TFX template pipeline using tfx template
Learn how to modify and run a templated TFX pipeline on Vertex
End of explanation
shell_output = !gcloud config list --forma... |
9,272 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Goal
If the DNA species distribution is truely Gaussian in a buoyant density gradient, then what sigma would be needed to reproduce the detection of all taxa > 0.1% in abundance throughout t... | Python Code:
%load_ext rpy2.ipython
workDir = '/home/nick/notebook/SIPSim/dev/fullCyc/frag_norm_9_2.5_n5/default_run/'
%%R
sigmas = seq(1, 50, 1)
means = seq(30, 70, 1) # mean GC content of 30 to 70%
## max 13C shift
max_13C_shift_in_BD = 0.036
## min BD (that we care about)
min_GC = 13.5
min_BD = min_GC/100.0 * 0.0... |
9,273 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Recap
In order of priority/time taken
basalareaincremementnonspatialaw
this is actually slow because of the number of times the BAFromZeroToDataAw function is called as shown above
relaxing ... | Python Code:
import pandas as pd
import numpy as np
Explanation: Recap
In order of priority/time taken
basalareaincremementnonspatialaw
this is actually slow because of the number of times the BAFromZeroToDataAw function is called as shown above
relaxing the tolerance may help
indeed the tolerance is 0.01 * some value ... |
9,274 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simulation Archive
A Simulation Archive (Rein & Tamayo 2017) is useful when one runs long simulations. With the Simulation Archive, one can easily take snapshots of the simulation, and then ... | Python Code:
import rebound
import numpy as np
sim = rebound.Simulation()
sim.add(m=1.)
sim.add(m=1e-3, a=1.)
sim.add(m=1e-3, a=1.9)
sim.move_to_com()
sim.dt = sim.particles[1].P*0.05 # timestep is 5% of orbital period
sim.integrator = "whfast"
sim.automateSimulationArchive("archive.bin",interval=1e3,deletefile=True)
... |
9,275 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1> Text Classification using TensorFlow/Keras on AI Platform </h1>
This notebook illustrates
Step1: Note
Step2: We will look at the titles of articles and figure out whether the article ... | Python Code:
!sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst
!pip install --user google-cloud-bigquery==1.25.0
Explanation: <h1> Text Classification using TensorFlow/Keras on AI Platform </h1>
This notebook illustrates:
<ol>
<li> Creating datasets for AI Platform using BigQuery
<li> Creating a text c... |
9,276 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Análisis de los datos obtenidos
Compararación de tres filamentos distintos
Filamento de BQ
Filamento de formfutura
Filamento de filastriuder
Step1: Representamos ambos diámetro y la velocid... | Python Code:
%pylab inline
#Importamos las librerías utilizadas
import numpy as np
import pandas as pd
import seaborn as sns
#Mostramos las versiones usadas de cada librerías
print ("Numpy v{}".format(np.__version__))
print ("Pandas v{}".format(pd.__version__))
print ("Seaborn v{}".format(sns.__version__))
#Abrimos los... |
9,277 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Literature results
Band gap engineering in amorphous $Al_xGa_{1-x}N$ Experiment and ab initio calculations, Appl. Phys. Lett. 77, 1117 (2000)
Step1: Band gap engineering of mixed Cd(1-x)Zn ... | Python Code:
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
%matplotlib inline
xs = [0.0,
0.3305234864554154,
0.5015690020887643,
0.5719846500105247,
0.6616169303259445,
0.7943943392865815,
1.0]
exp = [3.27,
3.973509933774835,
4.56953642384106,
4... |
9,278 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exercise 1
Step1: Load and explore data
Step2: Part 1
Step3: Scale features and set them to zero mean
Step4: Add intercept term to X
Step5: Part 2
Step6: Cost at initial theta
Step7: ... | Python Code:
import pandas
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Exercise 1: Linear regression with multiple variables
End of explanation
data = pandas.read_csv('ex1data2.txt', header=None, names=['x1', 'x2', 'y'])
data.head()
data.shape
X = data[['x1', 'x2']].values
Y = dat... |
9,279 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PyTorch dataset interface
In this example we will look at how a pyxis LMDB can be used with PyTorch's torch.utils.data.Dataset and torch.utils.data.DataLoader.
Step1: As usual, we will begi... | Python Code:
from __future__ import print_function
import numpy as np
import pyxis as px
Explanation: PyTorch dataset interface
In this example we will look at how a pyxis LMDB can be used with PyTorch's torch.utils.data.Dataset and torch.utils.data.DataLoader.
End of explanation
nb_samples = 10
X = np.outer(np.arange(... |
9,280 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Check Homework HW05
Use this notebook to check your solutions. This notebook will not be graded.
Step1: Now, import your solutions from hw5_answers.py. The following code looks a bit redund... | Python Code:
import pandas as pd
import numpy as np
Explanation: Check Homework HW05
Use this notebook to check your solutions. This notebook will not be graded.
End of explanation
import hw5_answers
reload(hw5_answers)
from hw5_answers import *
Explanation: Now, import your solutions from hw5_answers.py. The following... |
9,281 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Model comparison
To demonstrate the use of model comparison criteria in PyMC3, we implement the 8 schools example from Section 5.5 of Gelman et al (2003), which attempts to infer the effects... | Python Code:
%matplotlib inline
import pymc3 as pm
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_context('notebook')
Explanation: Model comparison
To demonstrate the use of model comparison criteria in PyMC3, we implement the 8 schools example from Section 5.5 of Gelman et al (2003), ... |
9,282 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
AI Explanations
Step1: Restart Kernel
Setup
Import libraries
Import the libraries for this tutorial.
Step2: Run the following cell to create your Cloud Storage bucket if it does not alread... | Python Code:
# Install needed deps
!pip install opencv-python
Explanation: AI Explanations: Deploying an Explainable Image Model with Vertex AI
Overview
This lab shows how to train a classification model on image data and deploy it to Vertex AI to serve predictions with explanations (feature attributions). In this lab ... |
9,283 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
First steps in data science with Python
Installation
For new comers, I recommend using the Anacaonda distribution. You can download it from here.
If you are familiar with Python, create a ... | Python Code:
import pandas as pd
messy_df = pd.DataFrame({'2016': [1000, 2000, 3000],
'2017': [1200, 1300, 4000],
'company':
['slack', 'twitter', 'twitch']
})
Explanation: First steps in data science with Python
Insta... |
9,284 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Validated department boundaries vs government units with highest incident share comparison
The backing theory for this notebook is proving that we will be able to use the government unit wit... | Python Code:
import psycopg2
from psycopg2.extras import RealDictCursor
import pandas as pd
# import geopandas as gpd
# from shapely import wkb
# from shapely.geometry import mapping as to_geojson
# import folium
pd.options.display.max_columns = None
pd.options.display.max_rows = None
#pd.set_option('display.float_form... |
9,285 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Practical use of Jupyter notebook
Second motivation
Step1: Expected results
Step2: Techniques used
Regular expressions
Pythonic / Functional programming
Step3: Data wrangling in action
... | Python Code:
Image("img/init.png")
Explanation: Practical use of Jupyter notebook
Second motivation : learning Python by web scraping
Scraping data from the WHO
End of explanation
Image("img/target_result.png")
Explanation: Expected results
End of explanation
# FOR WEB SCRAPING
from lxml import html
import requests
# F... |
9,286 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Near real-time HF-Radar currents in the proximity of the Deepwater Horizon site
The explosion on the Deepwater Horizon (DWH) tragically killed 11 people, and resulted in one of the largest m... | Python Code:
from IPython.display import HTML
url = (
"https://cordc.ucsd.edu/projects/mapping/maps/fullpage.php?"
"ll=29.061888,-87.373643&"
"zm=7&"
"mt=&"
"rng=0.00,50.00&"
"us=1&"
"cs=4&"
"res=6km_h&"
"ol=3&"
"cp=1"
)
iframe = (
'<iframe src="{src}" width="750" height="450... |
9,287 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: Deep & Cross Network (DCN)
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: Toy Example
To i... | 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,288 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This is an example notebook
The main purpose of this notebook is to have something to convert with gitnb. There is nothing interesting to see here. In order to make this point perfectly cle... | Python Code:
1+1
Explanation: This is an example notebook
The main purpose of this notebook is to have something to convert with gitnb. There is nothing interesting to see here. In order to make this point perfectly clear, I will start with some difficult math...
End of explanation
import numpy as np
eps=1e-10
def pre... |
9,289 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Up-sampling with Transposed Convolution
When we use neural networks to generate images, it usually involves up-sampling from low resolution to high resolution.
There are various methods to c... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import keras
import keras.backend as K
from keras.layers import Conv2D
from keras.models import Sequential
%matplotlib inline
Explanation: Up-sampling with Transposed Convolution
When we use neural networks to generate images, it usually involves up-sampli... |
9,290 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Viewing CNN Filters
Review
At this point, I've tested my CNN a little bit and learned that the hair really matters. If the CNN sees a lighter object representing a head with dark textures on... | Python Code:
import cv2
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline
# TFlearn libraries
import tflearn
from tflearn.layers.conv import conv_2d, max_pool_2d
from tflearn.layers.core import input_data, dropout, fully_connected
from tflearn.layers.estimator import regression
Explanation: Vie... |
9,291 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TensorBoard Visualizations
In this tutorial, we will learn how to visualize different types of NLP based Embeddings via TensorBoard. TensorBoard is a data visualization framework for visuali... | Python Code:
import gensim
import pandas as pd
import smart_open
import random
from smart_open import smart_open
# read data
dataframe = pd.read_csv('movie_plots.csv')
dataframe
Explanation: TensorBoard Visualizations
In this tutorial, we will learn how to visualize different types of NLP based Embeddings via TensorBoa... |
9,292 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Visualization
Introduction
When you are running a simulation, it is often useful to see what is going on
by visualizing particles in a 3D view or by plotting observables over time.
That way,... | Python Code:
from matplotlib import pyplot
import espressomd
import numpy
espressomd.assert_features("LENNARD_JONES")
# system parameters (10000 particles)
box_l = 10.7437
density = 0.7
# interaction parameters (repulsive Lennard-Jones)
lj_eps = 1.0
lj_sig = 1.0
lj_cut = 1.12246
lj_cap = 20
# integration parameters
sys... |
9,293 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Launching
Using Spark 1.4 and Python 3.4. The way of launching the ipython notebook has changed
IPYTHON=1 IPYTHON_OPTS=notebook PYSPARK_PYTHON=python3 pyspark
Step1: Create the SQLContext
S... | Python Code:
import os, sys
from pyspark.sql import SQLContext, Row
import datetime
from collections import namedtuple
import numpy as np
import pandas as pd
Explanation: Launching
Using Spark 1.4 and Python 3.4. The way of launching the ipython notebook has changed
IPYTHON=1 IPYTHON_OPTS=notebook PYSPARK_PYTHON=python... |
9,294 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<div style='background-image
Step1: Exercise 1
Define a python function call "get_cheby_matrix(nx)" that initializes the Chebyshev derivative matrix $D_{ij}$
Step2: Exercise 2
Calculate th... | Python Code:
# This is a configuration step for the exercise. Please run it before calculating the derivative!
import numpy as np
import matplotlib.pyplot as plt
# Show the plots in the Notebook.
plt.switch_backend("nbagg")
Explanation: <div style='background-image: url("../../share/images/header.svg") ; padding: 0px ;... |
9,295 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Train a gesture recognition model for microcontroller use
This notebook demonstrates how to train a 20kb gesture recognition model for TensorFlow Lite for Microcontrollers. It will produce t... | Python Code:
# Clone the repository from GitHub
!git clone --depth 1 -q https://github.com/tensorflow/tensorflow
# Copy the training scripts into our workspace
!cp -r tensorflow/tensorflow/lite/micro/examples/magic_wand/train train
Explanation: Train a gesture recognition model for microcontroller use
This notebook dem... |
9,296 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Overview
The goal of this tutorial is to provide an example of the use of SciPy. SciPy is a collection of many different algorihtms, so there's no way we can cover everything here. For more ... | Python Code:
# Set-up to have matplotlib use its IPython notebook backend
%matplotlib inline
# Convention for import of the pyplot interface
import matplotlib.pyplot as plt
import numpy as np
Explanation: Overview
The goal of this tutorial is to provide an example of the use of SciPy. SciPy is a collection of many diff... |
9,297 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Convolutional Networks
So far we have worked with deep fully-connected networks, using them to explore different optimization strategies and network architectures. Fully-connected net... | Python Code:
# As usual, a bit of setup
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
from cs231n.classifiers.cnn import *
from cs231n.data_utils import get_CIFAR10_data
from cs231n.gradient_check import eval_numerical_gradient_array, eval_numerical_gradient
from cs231n.layers... |
9,298 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simple Reinforcement Learning in Tensorflow Part 2-b
Step2: The Policy-Based Agent
Step3: Training the Agent | Python Code:
import tensorflow as tf
import tensorflow.contrib.slim as slim
import numpy as np
import gym
import matplotlib.pyplot as plt
%matplotlib inline
try:
xrange = xrange
except:
xrange = range
env = gym.make('CartPole-v0')
Explanation: Simple Reinforcement Learning in Tensorflow Part 2-b:
Vanilla Policy... |
9,299 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Branching GP Regression on synthetic data
Alexis Boukouvalas, 2017
Branching GP regression with Gaussian noise on the hematopoiesis data described in the paper "BGP
Step1: Load the data
Mon... | Python Code:
import pickle
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from BranchedGP import VBHelperFunctions as bplot
plt.style.use("ggplot")
%matplotlib inline
Explanation: Branching GP Regression on synthetic data
Alexis Boukouvalas, 2017
Branching GP regression with Gaussian noise ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.