Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
0 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Homework 1
Step1: If you've set up your environment properly, this cell should run without problems
Step2: Now, run this cell to log into OkPy.
This is the submission system for the class;... | Python Code:
!pip install -U okpy
Explanation: Homework 1: Setup and (Re-)Introduction to Python
Course Policies
Here are some important course policies. These are also located at
http://www.ds100.org/sp17/.
Tentative Grading
There will be 7 challenging homework assignments. Homeworks must be completed
individually and... |
1 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Accessing C Struct Data
This notebook illustrates the use of @cfunc to connect to data defined in C.
Via CFFI
Numba can map simple C structure types (i.e. with scalar members only) in... | Python Code:
from cffi import FFI
src =
/* Define the C struct */
typedef struct my_struct {
int i1;
float f2;
double d3;
float af4[7];
} my_struct;
/* Define a callback function */
typedef double (*my_func)(my_struct*, size_t);
ffi = FFI()
ffi.cdef(src)
Explanation: Accessing C Struct Data
This n... |
2 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pandas and Friends
Austin Godber
Mail
Step1: Background - NumPy - Arrays
Step2: Background - NumPy - Arrays
Arrays have NumPy specific types, dtypes, and can be operated on.
Step3: Now, o... | Python Code:
import numpy as np
# np.zeros, np.ones
data0 = np.zeros((2, 4))
data0
# Make an array with 20 entries 0..19
data1 = np.arange(20)
# print the first 8
data1[0:8]
Explanation: Pandas and Friends
Austin Godber
Mail: godber@uberhip.com
Twitter: @godber
Presented at DesertPy, Jan 2015.
What does it do?
Pandas i... |
3 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
k-Nearest Neighbor (kNN) exercise
Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet) with your assignment submission. For ... | Python Code:
# Run some setup code for this notebook.
import random
import numpy as np
from cs231n.data_utils import load_CIFAR10
import matplotlib.pyplot as plt
# This is a bit of magic to make matplotlib figures appear inline in the notebook
# rather than in a new window.
%matplotlib inline
plt.rcParams['figure.figsi... |
4 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
正向传播和反向传播实现
反向传播算法
之前我们在计算神经网络预测结果的时候我们采用了一种正向传播方法,我们从第一层开始正向一层一层进行计算,直到最后一层的$h_{\theta}\left(x\right)$。
现在,为了计算代价函数的偏导数$\frac{\partial}{\partial\Theta^{(l)}_{ij}}J\left(\Theta\right)$,我们需要采... | Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
from scipy.io import loadmat
from sklearn.preprocessing import OneHotEncoder
data = loadmat('../data/andrew_ml_ex33507/ex3data1.mat')
data
X = data['X']
y = data['y']
X.shape, y.shape#看下维度
# 目前考虑输入是图片的像素值,20*20像素的图片有40... |
5 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Skip-gram word2vec
In this notebook, I'll lead you through using TensorFlow to implement the word2vec algorithm using the skip-gram architecture. By implementing this, you'll learn about emb... | Python Code:
import time
import numpy as np
import tensorflow as tf
import utils
Explanation: Skip-gram word2vec
In this notebook, I'll lead you through using TensorFlow to implement the word2vec algorithm using the skip-gram architecture. By implementing this, you'll learn about embedding words for use in natural lang... |
6 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The goal of this post is to investigate if it is possible to query the NGDC CSW Catalog to extract records matching an IOOS RA acronym, like SECOORA for example.
In the cell above we do the ... | Python Code:
from owslib.csw import CatalogueServiceWeb
endpoint = 'http://www.ngdc.noaa.gov/geoportal/csw'
csw = CatalogueServiceWeb(endpoint, timeout=30)
Explanation: The goal of this post is to investigate if it is possible to query the NGDC CSW Catalog to extract records matching an IOOS RA acronym, like SECOORA fo... |
7 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
One Dimensional Visualisation
Data from https
Step1: Assign column headers to the dataframe
Step2: Refine the Data
Step3: Clean Rows & Columns
Lets start by dropping redundant columns - i... | Python Code:
import pandas as pd
# Read in the airports data.
airports = pd.read_csv("../data/airports.dat.txt", header=None, na_values=['\\N'], dtype=str)
# Read in the airlines data.
airlines = pd.read_csv("../data/airlines.dat.txt", header=None, na_values=['\\N'], dtype=str)
# Read in the routes data.
routes = pd.re... |
8 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="images/JHI_STRAP_Web.png" style="width
Step1: Microarray data <a id="microarray_data"></a>
<div class="alert alert-warning">
Raw array data was previously converted to plain text ... | Python Code:
%pylab inline
import os
import random
import warnings
warnings.filterwarnings('ignore')
import numpy as np
import pandas as pd
import scipy
import seaborn as sns
from Bio import SeqIO
import tools
Explanation: <img src="images/JHI_STRAP_Web.png" style="width: 150px; float: right;">
Supplementary Informatio... |
9 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a id="navigation"></a>
Hi-C data analysis
Welcome to the Jupyter notebook dedicated to Hi-C data analysis. Here we will be working in interactive Python environment with some mixture of bas... | Python Code:
# This is regular Python comment inside Jupyter "Code" cell.
# You can easily run "Hello world" in the "Code" cell (focus on the cell and press Shift+Enter):
print("Hello world!")
Explanation: <a id="navigation"></a>
Hi-C data analysis
Welcome to the Jupyter notebook dedicated to Hi-C data analysis. Here w... |
10 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Download and Explore the Data
Step2: <h6> Plot the Data Points </h6>
Step3: Looking at the scatter plot we can analyse that there is a linear relationship between th... | Python Code:
import tensorflow as tf
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
pd.__version__
Explanation: <a href="https://www.bigdatauniversity.com"><img src = "https://ibm.box.com/shared/static/jvcqp2iy2jlx2b32rmzdt0tx8lvxgzkp.png" width = 300, align = "center"></a>
<h1 align=center> <fo... |
11 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
xpath always returns a list of results, but there's only one, so we'll use that
Step2: Why is there only one element? I don't know and don't have the time to care, so I'll write
a helper fu... | Python Code:
xpath_result = tree.xpath('/html/body/div[3]/div[3]/div[4]/div/table[2]')
table = xpath_result[0]
for elem in table:
print(elem)
Explanation: xpath always returns a list of results, but there's only one, so we'll use that:
End of explanation
def print_outline(tree, indent=0):
print the outline of t... |
12 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Import required packages
Step5: Create a utility class for camera calibration
This is used for calibrating camera and undistorting the images
Step13: Create a class to keep track of lane d... | Python Code:
import os
import math
import glob
import cv2
from collections import deque
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from moviepy.editor import VideoFileClip
%matplotlib inline
Explanation: Import required packages
End of explanation
class cam_util():
... |
13 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Incorporating the Parasitoid Model into a Stochastic Model for Parameter Estimation
We have two main tasks here
Step1: $\lambda$ is a probability, so it can only take on continuous values b... | Python Code:
%matplotlib inline
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
a, b = 5,1
plt.figure()
x = np.linspace(0,1,100)
plt.plot(x,stats.beta.pdf(x,a,b),label='beta pdf')
plt.legend(loc='best')
plt.show()
Explanation: Incorporating the Parasitoid Model into a Stochastic Model for... |
14 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Anna KaRNNa
In this notebook, we'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book... | Python Code:
import time
from collections import namedtuple
import numpy as np
import tensorflow as tf
Explanation: Anna KaRNNa
In this notebook, we'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book.
This network... |
15 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Demonstration of pdfplumber's table-extraction options
This notebook uses a report from the FBI's National Instant Criminal Background Check System.
Import pdfplumber
Step1: Load the PDF
St... | Python Code:
import pdfplumber
print(pdfplumber.__version__)
Explanation: Demonstration of pdfplumber's table-extraction options
This notebook uses a report from the FBI's National Instant Criminal Background Check System.
Import pdfplumber
End of explanation
pdf = pdfplumber.open("../pdfs/background-checks.pdf")
Expla... |
16 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Online CNMF-E
This demo shows an example of doing online analysis on one-photon data. We compare offline and online approaches. The dataset used is courtesy of the Miniscope project.
Step1: ... | Python Code:
get_ipython().magic('load_ext autoreload')
get_ipython().magic('autoreload 2')
from IPython.display import display, clear_output
import glob
import logging
import numpy as np
import os
import scipy
logging.basicConfig(format=
"%(relativeCreated)12d [%(filename)s:%(funcName)10s():%... |
17 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Modeling dynamics of FS Peptide
This example shows a typical, basic usage of the MSMBuilder command line to model dynamics of a protein system.
Step1: Get example data
Step2: Featurization... | Python Code:
# Work in a temporary directory
import tempfile
import os
os.chdir(tempfile.mkdtemp())
# Since this is running from an IPython notebook,
# we prefix all our commands with "!"
# When running on the command line, omit the leading "!"
! msmb -h
Explanation: Modeling dynamics of FS Peptide
This example shows a... |
18 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using a support vector machine for sweep model selection
This example is similar to demographicModelSelectionExample.ipynb in that we are going to use supervised machine learning to discrimi... | Python Code:
#untar and compile sample_stats
!tar zxf ms.tar.gz; cd msdir; gcc -o sample_stats sample_stats.c tajd.c -lm
#now move the program into the current working dir
!mv msdir/sample_stats .
Explanation: Using a support vector machine for sweep model selection
This example is similar to demographicModelSelectionE... |
19 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Dawid-Skene model with priors
The Dawid-Skene model (1979) is perhaps one of the first models to discover true item states/effects from multiple noisy measurements. Since then, there hav... | Python Code:
%matplotlib inline
import pymc3 as pm
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
Explanation: The Dawid-Skene model with priors
The Dawid-Skene model (1979) is perhaps one of the first models to discover true item states/effects from multiple noisy measu... |
20 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Quick Intro to Python
Math and Modules
In the space below and use Python as a calculator.
Now let's try some more advanced funtions.
Step1: The standard Python distribution only comes with ... | Python Code:
log10(10)
Explanation: Quick Intro to Python
Math and Modules
In the space below and use Python as a calculator.
Now let's try some more advanced funtions.
End of explanation
import math
math.log10(10)
Explanation: The standard Python distribution only comes with the bare-bone capabilities. Other functiona... |
21 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
What is Machine Learning ?
The umbrella term "machine learning" describes methods for automated data analysis, developed by computer scientists and statisticians in response to the appearanc... | Python Code:
% matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import load_digits
digits = load_digits()
digits.keys()
digits.images.shape
print(digits.images[0])
plt.matshow(digits.images[23], cmap=plt.cm.Greys)
digits.data.shape
digits.target.shape
digits.target[23]
Explanat... |
22 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Emojify!
Welcome to the second assignment of Week 2. You are going to use word vector representations to build an Emojifier.
Have you ever wanted to make your text messages more expressive?... | Python Code:
import numpy as np
from emo_utils import *
import emoji
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Emojify!
Welcome to the second assignment of Week 2. You are going to use word vector representations to build an Emojifier.
Have you ever wanted to make your text messages more expressi... |
23 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
On-Axis Field Due to a Current Loop
This simple formula uses the Law of Biot Savart, integrated over a circular current loop to obtain the magnetic field at any point along the axis of the l... | Python Code:
%matplotlib inline
from scipy.special import ellipk, ellipe, ellipkm1
from numpy import pi, sqrt, linspace
from pylab import plot, xlabel, ylabel, suptitle, legend, show
uo = 4E-7*pi # Permeability constant - units of H/m
# On-Axis field = f(current and radius of loop, x of measurement point)
def Baxia... |
24 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
★ Ordinary Differential Equations ★
Step1: 6.1 Initial Value Problem
Euler's Method
Step2: Example
Apply Euler's Method to initial value problem
$
\begin{cases}
& y' = ty + t^3\
& y(0) ... | Python Code:
# Import modules
import math
import numpy as np
import scipy
from scipy.integrate import ode
from matplotlib import pyplot as plt
Explanation: ★ Ordinary Differential Equations ★
End of explanation
def euler_method(f, a, b, y0, step=10):
t = a
w = y0
ws = np.zeros(step + 1)
ws[0] = y0
h... |
25 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Object Relational Tutorial
cf. https
Step1: The return value of create_engine() is an instance of Engine, and it represents the core interface to the database.
The first time a method like ... | Python Code:
# Version Check
import sqlalchemy
print(sqlalchemy.__version__)
sqlite_engine_prefix_for_relative_paths = 'sqlite://'
sqlite_engine_prefix_for_absolute_paths = 'sqlite:///'
print(Path.cwd())
print(str(Path.cwd() / "example.db"))
# Create subdirectory if it doesn't exists
data_path = Path.cwd() / "data"
if ... |
26 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
UrbanAccess Demo
Author
Step1: The settings object
The settings object is a global urbanaccess_config object that can be used to set default options in UrbanAccess. In general, these option... | Python Code:
import matplotlib
matplotlib.use('agg') # allows notebook to be tested in Travis
import pandas as pd
import cartopy.crs as ccrs
import cartopy
import matplotlib.pyplot as plt
import pandana as pdna
import time
import urbanaccess as ua
from urbanaccess.config import settings
from urbanaccess.gtfsfeeds impo... |
27 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Ocnbgchem
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', 'test-institute-2', 'sandbox-1', 'ocnbgchem')
Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem
MIP Era: CMIP6
Institute: TEST-INSTITUTE-2
Source ID: SANDBOX-1
Topic: Ocnbgchem
Su... |
28 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
K-means with SDSS data
Machine learning exercise by Group 1 at AstroHackWeek 2017, Day 1.
First, we blatantly copy some of the code from the demo-SDSS notebook...
Step1: Pull color informat... | Python Code:
from os import path
from astropy.table import Table
import h5py
import matplotlib.pyplot as plt
#plt.style.use('notebook.mplstyle')
%matplotlib inline
import numpy as np
from sklearn.cluster import KMeans
data_path = '/Users/Meredith/Astronomy/astrohack/ahw2017-ml-data/' # specific to my computer
photoPos... |
29 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Finding degrees of freedom for a single mixture
$$
-\psi \bigg(\frac{v}{2} \bigg) + log \bigg(\frac{v}{2} \bigg) + 1 + \psi \bigg(\frac{v^{(k)} + p}{2} \bigg) - log \bigg(\frac{v^{(k)} + p}{... | Python Code:
def find_df(v, p, u, tau):
return -digamma(v/2.) + log(v/2.) + (tau * (log(u) - u)).sum()/tau.sum() + 1 + (digamma((v+p)/2.)-log((v+p)/2.))
u_test = np.array([[1,1], [2,2], [3,3]])
tau_test = np.array([[4,4], [5,5], [6,6]])
find_df(1, 2, u_test, tau_test)
def get_random(X):
size = len(X)
idx ... |
30 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Explore and create ML datasets
In this notebook, we will explore data corresponding to taxi rides in New York City to build a Machine Learning model in support of a fare-estimation tool. The... | Python Code:
from google.cloud import bigquery
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
Explanation: Explore and create ML datasets
In this notebook, we will explore data corresponding to taxi rides in New York City to build a Machine Learning model in support of a fa... |
31 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Permutation explainer
This notebooks demonstrates how to use the Permutation explainer on some simple datasets. The Permutation explainer is model-agnostic, so it can compute Shapley values ... | Python Code:
import shap
import xgboost
# get a dataset on income prediction
X,y = shap.datasets.adult()
# train an XGBoost model (but any other model type would also work)
model = xgboost.XGBClassifier()
model.fit(X, y);
Explanation: Permutation explainer
This notebooks demonstrates how to use the Permutation explaine... |
32 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Let's scrape the IRE homepage
Our goal
Step1: Target the headlines
View source on the IRE homepage and find the headlines. What's the pattern? | Python Code:
# use the `get()` method to fetch a copy of the IRE home page
# feed the text of the web page to a BeautifulSoup object
Explanation: Let's scrape the IRE homepage
Our goal: Print out the headlines from the IRE home page.
requests is a handy third-party library for making HTTP requests. It does the same thi... |
33 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Linear Programming with Python - Part 2
Introduction to PuLP
PuLP is an open source linear programming package for python. PuLP can be installed using pip, instructions here.... | Python Code:
import pulp
Explanation: Introduction to Linear Programming with Python - Part 2
Introduction to PuLP
PuLP is an open source linear programming package for python. PuLP can be installed using pip, instructions here.
In this notebook, we'll explore how to construct and solve the linear programming problem d... |
34 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial on how to use S-grids with time-evolving depth dimensions
Some hydrodynamic models (such as SWASH) have time-evolving depth dimensions, for example because they follow the waves on ... | Python Code:
%matplotlib inline
from parcels import FieldSet, ParticleSet, JITParticle, AdvectionRK4, ParticleFile, plotTrajectoriesFile
import numpy as np
from datetime import timedelta as delta
from os import path
Explanation: Tutorial on how to use S-grids with time-evolving depth dimensions
Some hydrodynamic models... |
35 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Probability Authors.
Licensed under the Apache License, Version 2.0 (the "License");
Step1: TFP Probabilistic Layers
Step2: Make things Fast!
Before we dive i... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" }
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... |
36 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A Python Tour of Data Science
Step1: 2 Categories
Categorical data is best represented by bar or pie charts. Reproduce the plots below using the object-oriented API of matplotlib, which is ... | Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
# Random time series.
n = 1000
rs = np.random.RandomState(42)
data = rs.randn(n, 4).cumsum(axis=0)
# plt.figure(figsize=(15,5))
# plt.plot(data[:, 0])
# df = pd.DataFrame(...)
# df.plot(...)
Explanation: A Python Tour... |
37 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Compute a sparse inverse solution using the Gamma-MAP empirical Bayesian method
See
Step1: Plot dipole activations
Step2: Show the evoked response and the residual for gradiometers
Step3:... | Python Code:
# Author: Martin Luessi <mluessi@nmr.mgh.harvard.edu>
# Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de>
#
# License: BSD-3-Clause
import numpy as np
import mne
from mne.datasets import sample
from mne.inverse_sparse import gamma_map, make_stc_from_dipoles
from mne.viz import (plot_sparse_source... |
38 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Relative position and orientation between nucleobases
The relative position of a nucleobase i in the reference frame constructed on the base j carries interesting information, as described i... | Python Code:
# import barnaba
import barnaba as bb
pdb = "../test/data/1S72.pdb"
rvecs,res = bb.dump_rvec(pdb,cutoff=3.5)
Explanation: Relative position and orientation between nucleobases
The relative position of a nucleobase i in the reference frame constructed on the base j carries interesting information, as descri... |
39 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SWI2 Example 4. Upconing Below a Pumping Well in a Two-Aquifer Island System
This example problem is the fourth example problem in the SWI2 documentation (http
Step1: Define model name of y... | Python Code:
%matplotlib inline
import os
import platform
import numpy as np
import matplotlib.pyplot as plt
import flopy.modflow as mf
import flopy.utils as fu
Explanation: SWI2 Example 4. Upconing Below a Pumping Well in a Two-Aquifer Island System
This example problem is the fourth example problem in the SWI2 docume... |
40 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Reciprocal Best Blast CDS Feature Comparisons
Introduction
We often wish to establish an equivalence between the CDS features on two genomes - by which we mean some assertion that sequence A... | Python Code:
%pylab inline
# Import helper module
from helpers import rbbh
Explanation: Reciprocal Best Blast CDS Feature Comparisons
Introduction
We often wish to establish an equivalence between the CDS features on two genomes - by which we mean some assertion that sequence A on genome 1 is the "same thing" (in some ... |
41 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Poynting-Robertson drag
Here we will examine a simple orbital dynamics problem with Poynting-Robertson drag in order to characterize the slimplectic Galerkin-Gauss-Lobatto integrator. The La... | Python Code:
%matplotlib inline
from __future__ import print_function
import numpy as np, matplotlib.pyplot as plt
import slimplectic, orbit_util as orbit
plot_path = './'
# Parameters
G = 39.478758435 #(in AU^3/M_sun/yr^2))
M_Sun = 1.0 #(in solar masses)
rho = 2.0 #(in g/cm^3)
d = 5.0e-3 #(in cm)
beta = 0.0576906*... |
42 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
General Instructions
For full credit, you must have the following items for each problem
Step1: zM Test because it's a single sample against a normal population with known parameters
Sample... | Python Code:
import scipy.stats as ss
import numpy as np
Z = (1070 - 1064) / 7
p = 1 - (ss.norm.cdf(Z - ss.norm.cdf(-Z)))
print(p)
Explanation: General Instructions
For full credit, you must have the following items for each problem:
[1 point] Describe what and why the method you're using is applicable. For example, '... |
43 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Getting started with the Stackdriver Monitoring API
Cloud Datalab provides an environment for working with your data. This includes data that is being managed within the Stackdriver Monitori... | Python Code:
# set_datalab_project_id('my-project-id')
Explanation: Getting started with the Stackdriver Monitoring API
Cloud Datalab provides an environment for working with your data. This includes data that is being managed within the Stackdriver Monitoring API. This notebook introduces some of the APIs that Cloud D... |
44 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Monte Carlo Integration
Inspired from the following posts
Step1: What is Monte Carlo (MC) Integration?
Let us say that we want to approximate the area between the curve defi... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from numba import jit # Use it for speed
from scipy import stats
Explanation: Introduction to Monte Carlo Integration
Inspired from the following posts:
http://nbviewer.jupyter.org/github/cs109/content/blob/master/labs/lab7/GibbsSampler.... |
45 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href='http
Step1: Universal Array Functions
Numpy comes with many universal array functions, which are essentially just mathematical operations you can use to perform the operation acros... | Python Code:
import numpy as np
arr = np.arange(0,10)
arr + arr
arr * arr
arr - arr
# Warning on division by zero, but not an error!
# Just replaced with nan
arr/arr
# Also warning, but not an error instead infinity
1/arr
arr**3
Explanation: <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></... |
46 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 Google LLC
Step1: scikit-learn HP Tuning on AI Platform
This notebook trains a model on Ai Platform using Hyperparameter Tuning to predict a car's Miles Per Gallon. It uses A... | Python Code:
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distribute... |
47 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: [Py-OO] Aula 02
Herança
O que você vai aprender nesta aula?
Após o término da aula você terá aprendido
Step2: Vamos brincar um pouco com o cão
Step5: Agora vamos criar a classe Gold... | Python Code:
class Cão:
qtd_patas = 4
carnívoro = True
nervoso = False
def __init__(self, nome):
self.nome = nome
def latir(self, vezes=1):
Latir do cão. Quanto mais nervoso mais late.
vezes += self.nervoso * vezes
latido = 'Au! ' * vezes
... |
48 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Transformer with non-trivial phase shift and tap ratio
This example is a copy of pandapower's minimal example.
Step1: Now play with tap changer on LV side
Step2: Now make sure that the pha... | Python Code:
import pypsa
import numpy as np
import pandas as pd
network = pypsa.Network()
network.add("Bus", "MV bus", v_nom=20, v_mag_pu_set=1.02)
network.add("Bus", "LV1 bus", v_nom=0.4)
network.add("Bus", "LV2 bus", v_nom=0.4)
network.add(
"Transformer",
"MV-LV trafo",
type="0.4 MVA 20/0.4 kV",
bus0... |
49 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: TV Script Generation
In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Ne... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
data_dir = './data/simpsons/moes_tavern_lines.txt'
text = helper.load_data(data_dir)
# Ignore notice, since we don't use it for analysing the data
text = text[81:]
Explanation: TV Script Generation
In this project, you'll generate your own Simpsons TV script... |
50 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook demonstrates some basic post-processing tasks that can be performed with the Python API, such as plotting a 2D mesh tally and plotting neutron source sites from an eigenvalue c... | Python Code:
%matplotlib inline
from IPython.display import Image
import numpy as np
import matplotlib.pyplot as plt
import openmc
Explanation: This notebook demonstrates some basic post-processing tasks that can be performed with the Python API, such as plotting a 2D mesh tally and plotting neutron source sites from a... |
51 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 8 - Local Realism
with Alice and Bob
Step2: First define the projection operator for a state at angle $\theta$
Step3: Create the projection operators for each of the angles, two fo... | Python Code:
from numpy import sin,cos,pi,sqrt,angle,exp,deg2rad,arange,rad2deg
import matplotlib.pyplot as plt
from qutip import *
%matplotlib inline
H = Qobj([[1],[0]])
V = Qobj([[0],[1]])
Explanation: Chapter 8 - Local Realism
with Alice and Bob
End of explanation
def P(theta):
The projection operator for a stat... |
52 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Maps
1. Introduction
Maps are a way to present information on a (roughly) spherical earth on a flat plane, like a page or a screen. Here are two examples of common map projections. The proje... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import cartopy
import cartopy.crs as ccrs # commonly used shorthand
import cartopy.feature as cfeature
Explanation: Maps
1. Introduction
Maps are a way to present information on a (roughly) spherical earth on a flat plane, like a page o... |
53 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Create Feature Matrix
Step2: Normalize Observations
Normalizer rescales the values on individual observations to have unit norm (the sum of their lengths is one). | Python Code:
# Load libraries
from sklearn.preprocessing import Normalizer
import numpy as np
Explanation: Title: Normalizing Observations
Slug: normalizing_observations
Summary: How to normalize observations for machine learning in Python.
Date: 2016-09-06 12:00
Category: Machine Learning
Tags: Preprocessing Structur... |
54 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Python
by Maxwell Margenot
Part of the Quantopian Lecture Series
Step2: You may hear text enclosed in triple quotes (
Step4: Make sure you read the comments within each cod... | Python Code:
# This is a comment
# These lines of code will not change any values
# Anything following the first # is not run as code
Explanation: Introduction to Python
by Maxwell Margenot
Part of the Quantopian Lecture Series:
www.quantopian.com/lectures
github.com/quantopian/research_public
Notebook released under t... |
55 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Target distribution
We use the peaks function from matlab, modified so it is positive
Step2: Heat bath
The "heat bath" refers to a modified version of the distributi... | Python Code:
import jax
import jax.numpy as jnp
import numpy as np
import matplotlib
import seaborn as sns
import matplotlib.pyplot as plt
from IPython import display
try:
import probml_utils as pml
except:
%pip install -qq git+https://github.com/probml/probml-utils.git
import probml_utils as pml
from mpl_t... |
56 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Training a Generative Adversarial Network on MNIST
In this tutorial, we will train a Generative Adversarial Network (GAN) on the MNIST dataset. This is a large collection of 28x28 pixel ima... | Python Code:
!pip install --pre deepchem
import deepchem
deepchem.__version__
Explanation: Training a Generative Adversarial Network on MNIST
In this tutorial, we will train a Generative Adversarial Network (GAN) on the MNIST dataset. This is a large collection of 28x28 pixel images of handwritten digits. We will try... |
57 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<p><font size="6"><b> Python rehearsal</b></font></p>
DS Data manipulation, analysis and visualization in Python
May/June, 2021
© 2021, Joris Van den Bossche and Stijn Van Hoey (jo... | Python Code:
pressure_hPa = 1010 # hPa
Explanation: <p><font size="6"><b> Python rehearsal</b></font></p>
DS Data manipulation, analysis and visualization in Python
May/June, 2021
© 2021, Joris Van den Bossche and Stijn Van Hoey (jorisvandenboss&... |
58 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Causal discovery with TIGRAMITE
TIGRAMITE is a time series analysis python module. It allows to reconstruct graphical models (conditional independence graphs) from discrete or continuously-v... | Python Code:
# Imports
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
%matplotlib inline
## use `%matplotlib notebook` for interactive figures
# plt.style.use('ggplot')
import sklearn
import tigramite
from tigramite import data_processing as pp
from tigramite.toymodels import structural_... |
59 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Organized high-throughput calculations
Step3: This functional takes a few arguments, amongst which an output directory, and writes a file to disk. That's pretty much it.
However, you... | Python Code:
%%writefile dummy.py
def functional(structure, outdir=None, value=False, **kwargs):
A dummy functional
from copy import deepcopy
from pickle import dump
from random import random
from py.path import local
structure = deepcopy(structure)
structure.value = value
outdir = loc... |
60 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Review Classification using Active Learning
Author
Step1: Loading and preprocessing the data
We will be using the IMDB reviews dataset for our experiments. This dataset has 50,000
reviews i... | Python Code:
import tensorflow_datasets as tfds
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import matplotlib.pyplot as plt
import re
import string
tfds.disable_progress_bar()
Explanation: Review Classification using Active Learning
Author: Darshan Deshpande<br>
Date created... |
61 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Get Data
Step1: Basic Heat map
Step2: Hide tick_labels and color axis using 'axes_options'
Step3: Non Uniform Heat map
Step4: Alignment of the data with respect to the grid
For a N-by-N ... | Python Code:
np.random.seed(0)
data = np.random.randn(10, 10)
Explanation: Get Data
End of explanation
from ipywidgets import *
fig = plt.figure(padding_y=0.0)
grid_map = plt.gridheatmap(data)
fig
grid_map.display_format = '.2f'
grid_map.font_style = {'font-size': '16px', 'fill':'blue', 'font-weight': 'bold'}
Explanati... |
62 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tarea 5
Luego de descargar las imágenes en los filtros F475W y F850LP del objeto VCC1316 (M87) se siguen los pasos de la primera tarea para generar el catálogo.
De Sirianni et. al (2005) se ... | Python Code:
from astropy.io import fits
import numpy as np
f475 = fits.open('hst_9401_02_acs_wfc_f475w_drz.fits')
f850 = fits.open('hst_9401_02_acs_wfc_f850lp_drz.fits')
f475[1].writeto('sci_f475w_m87.fits',clobber=True)
f475[2].writeto('invvar_f475w_m87.fits',clobber=True)
f850[1].writeto('sci_f850lp_m87.fits',clobbe... |
63 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
3.4 build a spam classifier (a more challenging exercise)
3.4.1 Download examples of spam and ham from Apache SpamAssassin’s public datasets.
Downloaded 20021010 dataset
Unzip the datasets a... | Python Code:
import os
import glob
HAM_DIR = os.path.join('datasets', 'easy_ham')
SPAM_DIR = os.path.join('datasets', 'spam')
ham_files = [name for name in sorted(os.listdir(HAM_DIR)) if len(name) > 20]
spam_files = [name for name in sorted(os.listdir(SPAM_DIR)) if len(name) > 20]
len(ham_files), ham_files[0], ham_fi... |
64 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Limpieza del dataset de Mortalidad de INEGI
1. Introduccion
Indicadores que salen de este dataset
Step1: Descarga de datos
Todos los datos se encuentran en un solo archivo
Step2: Exploraci... | Python Code:
descripciones = {
'P0813' : 'Homicidios Intencionales',
}
# Librerías utilizadas
import pandas as pd
import sys
import urllib
import os
import csv
import zipfile
from simpledbf import Dbf5
import matplotlib.pyplot as plt
%matplotlib inline
# Configuracion del sistema
print('Python {} on {}'.format(sys.... |
65 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Class 12
Step1: Computers by definition cannot generate truly random numbers. The Mersenne Twister is a widely-used algorithm for generating pseudo random numbers form a deterministic proce... | Python Code:
# Create an array with 5 draws from the normal(0,1) distribution and print
np.random.normal(size=5)
# Create an array with 5 draws from the normal(0,1) distribution and print
np.random.normal(size=5)
Explanation: Class 12: Stochastic Time Series Processes
Simulating normal random variables with Numpy
The n... |
66 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Widgets and Interactions
Step1: Add to the function to allow amplitude to be varied and aadd in an additional slider to vary both f and a
may want to limit ylim
Step2: Climate data
Step3: ... | Python Code:
!conda install -y netcdf4
from netCDF4 import Dataset, num2date, date2num
from numpy import *
import matplotlib.pyplot as plt
%matplotlib inline
from ipywidgets import interact, interactive, fixed
import ipywidgets as widgets
x = linspace(0, 1, 100) # generates a hundred values between 0 and 1
f = 2
a =... |
67 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Image Processing in Python
Tanmoy Dasgupta
thetdg@live.com | Assistant Professor | Department of Electrical Engineering | Techno India University, Kolkata
I colud not get the sepll checekr w... | Python Code:
%pylab inline
from __future__ import division #Python 2.X and 3.X Compatibility
from __future__ import print_function #Python 2.X and 3.X Compatibility
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
Explanation: Image Processing in Python
Tanmoy Dasgupta
thetdg@live.com | Assistant P... |
68 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Extract time series from a published figure
Scott Cole
29 July 2016
Summary
Sometimes we might be interested in obtaining a precise estimate of the results published in a figure. Instead of ... | Python Code:
# Load image and libraries
%matplotlib inline
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
from scipy import misc
input_image = misc.imread('figure_processed.png')
# Convert input image from RGBA to binary
input_image = input_image - 255
input_image = np.mean(input_image,2)
... |
69 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 Google LLC.
Licensed under the Apache License, Version 2.0 (the "License");
Step1: Initialize Tensor Flow and GPU devices, import modules
Step2: Download raw images and anno... | Python Code:
@title License text
# 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, s... |
70 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Learning the parameters of a prediction function and testing it on the same data is a methodological mistake
Step1: We can now quickly sample a training set while holding out 40% of the dat... | Python Code:
import numpy as np
from sklearn import cross_validation
from sklearn import datasets
from sklearn import svm
iris = datasets.load_iris()
iris.data.shape, iris.target.shape
((150, 4), (150,))
Explanation: Learning the parameters of a prediction function and testing it on the same data is a methodological mi... |
71 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Numerically solving differential equations with python
This is a brief description of what numerical integration is and a practical tutorial on how to do it in Python.
Software required
In o... | Python Code:
%matplotlib inline
from numpy import *
from matplotlib.pyplot import *
# time intervals
tt = arange(0, 10, 0.5)
# initial condition
xx = [0.1]
def f(x):
return x * (1.-x)
# loop over time
for t in tt[1:]:
xx.append(xx[-1] + 0.5 * f(xx[-1]))
# plotting
plot(tt, xx, '.-')
ta = arange(0, 10, 0.01)
plo... |
72 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CORDEX ESGF submission form
General Information
Data to be submitted for ESGF data publication must follow the rules outlined in the Cordex Archive Design Document <br /> (https
Step1: S... | Python Code:
from dkrz_forms import form_widgets
form_widgets.show_status('form-submission')
Explanation: CORDEX ESGF submission form
General Information
Data to be submitted for ESGF data publication must follow the rules outlined in the Cordex Archive Design Document <br /> (https://verc.enes.org/data/projects/doc... |
73 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Ocnbgchem
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', 'dwd', 'mpi-esm-1-2-hr', 'ocnbgchem')
Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem
MIP Era: CMIP6
Institute: DWD
Source ID: MPI-ESM-1-2-HR
Topic: Ocnbgchem
Sub-Topics: Tracer... |
74 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img style='float
Step1: Skill 1
Step2: Skill 2
Step3: Skill 3
Step4: Skill 4
Step5: Skill 4
Step6: Save scores
Step7: Normalized Taylor diagrams
The radius is model standard deviatio... | Python Code:
import os
try:
import cPickle as pickle
except ImportError:
import pickle
run_name = '2014-07-07'
fname = os.path.join(run_name, 'config.pkl')
with open(fname, 'rb') as f:
config = pickle.load(f)
import numpy as np
from pandas import DataFrame, read_csv
from utilities import (load_secoora_ncs, ... |
75 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A new high performance and optimally cheap multivitamin. Saving the world one mixed integer program at a time
You have been tasked with developing a new superior multivitamin. You have been ... | Python Code:
df = pd.read_csv('vitamin_costs.csv')
vitamins = df.vitamin.values
vitamin_cost = df.set_index('vitamin').to_dict()['cost']
df.head()
Explanation: A new high performance and optimally cheap multivitamin. Saving the world one mixed integer program at a time
You have been tasked with developing a new superio... |
76 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
datetime
Python has the datetime module to help deal with timestamps in your code. Time values are represented with the time class. Times have attributes for hour, minute, second, and micros... | Python Code:
import datetime
t = datetime.time(4, 20, 1)
# Lets show the different compoenets
print t
print 'hour :', t.hour
print 'minute:', t.minute
print 'second:', t.second
print 'microsecond:', t.microsecond
print 'tzinfo:', t.tzinfo
Explanation: datetime
Python has the datetime module to help deal with timestamp... |
77 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Facebook Graph API v2.5
En este IPython Notebook se anotarán algunos usos básicos la API que provee Facebook.
Step1: Tomamos el access token temporal creado en Graph API Explorer. Si querem... | Python Code:
import json
import requests
BASE = "https://graph.facebook.com"
VERSION = "v2.5"
# Si queremos imprimir los json de respuesta
# de una forma mas agradable a la vista podemos usar
def print_pretty(jsonstring, indent=4, sort_keys=False):
print(json.dumps(jsonstring, indent=indent, sort_keys=sort_keys))
... |
78 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dictionary
train_direction = 0 south, 1 north
train_type = 0 Local, 1 Limited, 2 Bullet
train_
Step1: Cleanin' the data
Step2: Let's start getting some more detailed data from the trips as... | Python Code:
# Import necessary libraries
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import sys
import re
import random
import operator
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.cross_validation import KFold
from sklearn.ensemble import GradientBoosti... |
79 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sklearn control overfit example
- Use the California house database to show how to control overfit tuning the model parameters
Step1: Load data
Step2: Fit the best model
Step3: A better w... | Python Code:
from __future__ import print_function
from sklearn import __version__ as sklearn_version
print('Sklearn version:', sklearn_version)
Explanation: Sklearn control overfit example
- Use the California house database to show how to control overfit tuning the model parameters
End of explanation
from sklearn imp... |
80 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Linear Regression
In this chapter, you will learn
Step1: Based on the visualization about, we can see that there is a positive relationship between pizza diameter and price.
Training a Simp... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('ggplot')
# X is the explanatory variable data structure
X = [[6], [8], [10], [14], [18]]
# Y is the response variable data structure
y = [[7], [9], [13], [17.5], [18]]
# instantiate a pyplot figure object
plt.figure()
plt.... |
81 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python 101 - Session 2
Built-in Data Structures
Intro to PythonWin
Control Flow Statements
* Materials
Whirlwind Tour of Python, Jake VanderPlas (2016)
Book
Step1: the range() function
Step... | Python Code:
#ForLoopExample.py
# This example uses a for loop to iterate through each item in
# the "fruit" list, updating the value of the "fruit" variable and
# executing whatever lines are indented under the for statement
#Create a list of fruit
fruitList = ("apples","oranges","kiwi","grapes","blueberries")
# Lo... |
82 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plotting two variables as lines on the same graph
So you've got 2 variables and you want to plot them on the same chart? How do you do it in ggplot? Well good news is it's super easy to do w... | Python Code:
meat_subset = meat[['date', 'beef', 'pork']]
df = pd.melt(meat_subset, id_vars=['date'])
df.head()
Explanation: Plotting two variables as lines on the same graph
So you've got 2 variables and you want to plot them on the same chart? How do you do it in ggplot? Well good news is it's super easy to do with g... |
83 | 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', 'uhh', 'sandbox-2', 'seaice')
Explanation: ES-DOC CMIP6 Model Properties - Seaice
MIP Era: CMIP6
Institute: UHH
Source ID: SANDBOX-2
Topic: Seaice
Sub-Topics: Dynamics, Thermodynamics,... |
84 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Learning from Data
Decision Trees are a non-parametric supervised learning method used for classification and regression. The goal is to create a model that predicts the value of a target va... | Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
plt.style.use('fivethirtyeight')
df = pd.read_csv("data/creditRisk.csv")
df.head()
df.dtypes
Explanation: Learning from Data
Decision Trees are a non-parametric supervised learning method used for classification and r... |
85 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The PGM
For more an introduction to PGMS see Daphne Koller's Probabilistic Graphical Models. Below is the PGM that we will explore in this notebook.
Step1: We have sets of foregrounds and b... | Python Code:
%matplotlib inline
from matplotlib import rc
rc("font", family="serif", size=14)
rc("text", usetex=True)
import daft
pgm = daft.PGM([7, 6], origin=[0, 0])
#background nodes
pgm.add_plate(daft.Plate([0.5, 3.0, 5, 2], label=r"foreground galaxy $i$",
shift=-0.1))
pgm.add_node(daft.Node("theta", r"$\theta$... |
86 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lecture 17
Step1: Recalling the mechanics of file I/O, you'll see we opened up a file descriptor to alice.txt and read the whole file in a single go, storing all the text as a single string... | Python Code:
book = None
try: # Good coding practices!
f = open("Lecture17/alice.txt", "r")
book = f.read()
except FileNotFoundError:
print("Could not find alice.txt.")
else:
f.close()
print(book[:71]) # Print the first 71 characters.
Explanation: Lecture 17: Natural Language Processing I
CSCI 136... |
87 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SETUP
Step1: Autosipper
Step2: Manifold
Step3: Micromanager
Step4: Preset
Step5: ACQUISITION
Step6: MM Get info
Step7: Video
Step8: SNAP CV2
Step9: EXIT | Python Code:
import time
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
%matplotlib inline
Explanation: SETUP
End of explanation
# config directory must have "__init__.py" file
# from the 'config' directory, import the following classes:
from config import Motor, ASI_Controller, Autosipper
from ... |
88 | 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', 'csiro-bom', 'access-1-0', 'seaice')
Explanation: ES-DOC CMIP6 Model Properties - Seaice
MIP Era: CMIP6
Institute: CSIRO-BOM
Source ID: ACCESS-1-0
Topic: Seaice
Sub-Topics: Dynamics, T... |
89 | 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="#Multi-Armed-Bandits" data-toc-modified-id="Multi-Armed-Bandits-1"><span clas... | Python Code:
# code for loading the format for the notebook
import os
# path : store the current path to convert back to it later
path = os.getcwd()
os.chdir(os.path.join('..', 'notebook_format'))
from formats import load_style
load_style(css_style='custom2.css', plot_style=False)
os.chdir(path)
# 1. magic for inline p... |
90 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Imports
Step1: Default settings
Step2: Load PMT pulses
Pulse shape
One of the elements of simulted S1s is the single p.e. pulse model. We extract this from the gain calibration dataset.
St... | Python Code:
import numpy as np
import matplotlib
%matplotlib inline
import matplotlib.pyplot as plt
from scipy import stats
# import warnings
# warnings.filterwarnings('error')
from multihist import Hist1d, Histdd
Explanation: Imports
End of explanation
# Digitizer sample size
dt = 2
# Waveform time labels
spe_ts = np... |
91 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h2>3. Aproximacion de las raices para 230 x^4 + 18 x^3 + 9 x^2 - 221 x -9</h2>
A partir de métodos gráficos podemos ver que existen dos reales en los intervalos (-0.5,0) y (0.5,1.5)
<h3>Mét... | Python Code:
import math
def funcion(x):
return (230*math.pow(x,4))+(18*math.pow(x,3))+(9*math.pow(x,2))-(221*x)-9
def biseccion(intA, intB, errorA, noMaxIter):
if(funcion(intA)*funcion(intB)<0):
noIter = 0
errorTmp = 1
intTmp = 0
oldInt = intA
whi... |
92 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2021 The TensorFlow Authors.
Step1: Sparse weights using structural pruning
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: Dow... | 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... |
93 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
[PUBLIC] CLBlast vs ARM Compute Library on representative matrix sizes
Overview
Data [for developers]
Code [for developers]
Table
Plot
<a id="data"></a>
Get the experimental data
Step1: NB
... | Python Code:
repo_uoa = 'explore-matrix-size-gemm-libs-dvdt-prof-firefly-rk3399-001'
Explanation: [PUBLIC] CLBlast vs ARM Compute Library on representative matrix sizes
Overview
Data [for developers]
Code [for developers]
Table
Plot
<a id="data"></a>
Get the experimental data
End of explanation
import os
import sys
imp... |
94 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The belowing code in azure can't work, because 403 error
boston = load_boston()
california = fetch_california_housing()
In local machine å¦èµ·çç¤ï¼ä¸è½½boston,californiaåæcsvï¼ç¶... | Python Code:
from azureml import Workspace
ws = Workspace(
workspace_id='3c64d445b4c840dca9683dd47522eba3',
authorization_token='JaC5E2q5FouX14JhvCmcvmzagqV63q0oVIbu2jblLBdQ5e5wf/Y24Ed6uXLvbSUgbiao5iF85C3uufYKQgXoNw==',
endpoint='https://studioapi.azureml.net'
)
ds = ws.datasets['boston.csv']
df = ds.to_dat... |
95 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Implementing the Random Forest Classifier from sci-kit learn
1. Import dataset
This tutorial uses the iris dataset (https
Step1: 2. Prepare training and testing data
Each flower in this dat... | Python Code:
#Import dataset
from sklearn.datasets import load_iris
iris = load_iris()
Explanation: Implementing the Random Forest Classifier from sci-kit learn
1. Import dataset
This tutorial uses the iris dataset (https://en.wikipedia.org/wiki/Iris_flower_data_set) which comes preloaded with sklearn.
End of explanati... |
96 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Lasagne
There are various libaries building on top of Theano to provide easy buidling blocks for designing deep neural networks. Some of them are
Step1: Build the MLP
Now we... | Python Code:
import gzip
import cPickle
import numpy as np
import theano
import theano.tensor as T
import lasagne
# Load the pickle file for the MNIST dataset.
dataset = 'data/mnist.pkl.gz'
f = gzip.open(dataset, 'rb')
train_set, dev_set, test_set = cPickle.load(f)
f.close()
#train_set contains 2 entries, first the X v... |
97 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook should be used to debug, improve or test the log visualization maker.
Step1: Loading the data
Step2: Preparing a test sample
Let's first use a particular session as a test ca... | Python Code:
%load_ext autoreload
%autoreload 1
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
pd.options.display.max_rows = 1000
pd.options.display.max_columns = 60
#utils.py is where all our custom functions live is we set an autoreload on it.
%aimport ... |
98 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Departamento de Física - Faculdade de Ciências e Tecnologia da Universidade de Coimbra
Física Computacional - Ficha 1 - Interpolação
Rafael Isaque Santos - 2012144694 - Licenciatura em Físic... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Departamento de Física - Faculdade de Ciências e Tecnologia da Universidade de Coimbra
Física Computacional - Ficha 1 - Interpolação
Rafael Isaque Santos - 2012144694 - Licenciatura em Física
End of explanation
func_x = lamb... |
99 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generative Adversarial Network
In this notebook, we'll be building a generative adversarial network (GAN) trained on the MNIST dataset. From this, we'll be able to generate new handwritten d... | Python Code:
%matplotlib inline
import pickle as pkl
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data')
Explanation: Generative Adversarial Network
In this notebook, we'll be building a gen... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.