Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
15,000 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Reading and writing files in Python
Goals for this assignment
Most of the data that you will use will come in a file of some sort. In fact, we've used data from files at various points duri... | Python Code:
# put your code here!
Explanation: Reading and writing files in Python
Goals for this assignment
Most of the data that you will use will come in a file of some sort. In fact, we've used data from files at various points during this class, but have mostly glossed over how we actually work with those files.... |
15,001 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Siegert neuron integration
Alexander van Meegen, 2020-12-03
This notebook describes how NEST handles the numerical integration of the 'Siegert' function.
For an alternative approach, which w... | Python Code:
import numpy as np
from scipy.special import erf, erfcx
import matplotlib.pyplot as plt
Explanation: Siegert neuron integration
Alexander van Meegen, 2020-12-03
This notebook describes how NEST handles the numerical integration of the 'Siegert' function.
For an alternative approach, which was implemented i... |
15,002 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
14 - Kaggle Competition
Fraud Detection
https
Step1: Estimate aggregated features
Step2: Split for each account and create the date as index
Step3: Create Aggregated Features for one acco... | Python Code:
import pandas as pd
import zipfile
with zipfile.ZipFile('../datasets/fraud_transactions_kaggle.csv.zip', 'r') as z:
f = z.open('fraud_transactions_kaggle.csv')
data = pd.read_csv(f, index_col=0)
data.head()
data.tail()
data.fraud.value_counts(dropna=False)
Explanation: 14 - Kaggle Competition
Fraud... |
15,003 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
An Astronomical Application of Machine Learning
Step1: Problem 1) Examine the Training Data
For this problem the training set, i.e. sources with known labels, includes stars and galaxies th... | Python Code:
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: An Astronomical Application of Machine Learning:
Separating Stars and Galaxies from SDSS
Version 0.1
By AA Miller 2018 Nov 06
The problems in the following notebook develop an end-to... |
15,004 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step2: Ridge regression and model selection
Modified from the github repo
Step3: Ridge Regression
Step4: The above plot shows that the Ridge coefficients get larger when we decrease lambda... | Python Code:
# %load ../standard_import.txt
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import scale
from sklearn.linear_model import LinearRegression, Ridge, RidgeCV, Lasso, LassoCV
from sklearn.decomposition import PCA
from sklearn.metrics import mean_squared_err... |
15,005 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Loading, reshaping, visualizing data using pycroscopy
Suhas Somnath, Chris R. Smith and Stephen Jesse
The Center for Nanophase Materials Science and The Institute for Functional Imaging for ... | Python Code:
# Make sure pycroscopy and wget are installed
!pip install pycroscopy
!pip install -U wget
# Ensure python 3 compatibility
from __future__ import division, print_function, absolute_import
# Import necessary libraries:
import h5py
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches ... |
15,006 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Properties of Rectangular Waveguide
Introduction
This example demonstrates how to use scikit-rf to calculate some properties of rectangular waveguide. For more information regarding the theo... | Python Code:
%matplotlib inline
import skrf as rf
rf.stylely()
# imports
from scipy.constants import mil,c
from skrf.media import RectangularWaveguide, Freespace
from skrf.frequency import Frequency
import matplotlib.pyplot as plt
import numpy as np
# plot formatting
plt.rcParams['lines.linewidth'] = 2
# create frequ... |
15,007 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Algorithms.md
Describe Approach
Algorithm
Description
Step3: 1. Generate simulated data for both settings
Step5: 2. Plotting code for simulated data
Step7: 3. Algorithm code
Step9: 4. Qu... | Python Code:
import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
%matplotlib inline
import warnings
warnings.filterwarnings("ignore")
# Fix random seed
np.random.seed(123456789)
Explanation: Algorithms.md
Describe Approach
Algorithm
Description: Groups scalars into $k$ clusters. Inital... |
15,008 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Moving the sensor away from the ESP8266
The previous experiment showed that adding a piece of foam core board between the ESP8266 board and SHT30 temperature sensor board reduced spread in t... | Python Code:
%matplotlib inline
import matplotlib
matplotlib.rcParams['figure.figsize'] = (12, 5)
import pandas as pd
df = pd.read_csv('movesensors.csv', header=None, names=['time', 'mac', 'f', 'h'], parse_dates=[0])
per_sensor_f = df.pivot(index='time', columns='mac', values='f')
downsampled_f = per_sensor_f.resample(... |
15,009 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using Selenium to Test User Interactions
Where were we at the end of the last chapter? Let’s rerun the test and find out
Step1: Did you try it, and get an error saying Problem loading page ... | Python Code:
%cd ../examples/superlists/
!python3 functional_tests.py
Explanation: Using Selenium to Test User Interactions
Where were we at the end of the last chapter? Let’s rerun the test and find out:
End of explanation
%%writefile functional_tests.py
from selenium import webdriver
from selenium.webdriver.common.ke... |
15,010 | Given the following text description, write Python code to implement the functionality described.
Description: | Python Code:
def closest_integer(value):
'''
Create a function that takes a value (string) representing a number
and returns the closest integer to it. If the number is equidistant
from two integers, round it away from zero.
Examples
>>> closest_integer("10")
10
>>> closest_integer("15.3... |
15,011 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
$\newcommand{\Reals}{\mathbb{R}}
\newcommand{\Nats}{\mathbb{N}}
\newcommand{\PDK}{{k}}
\newcommand{\IS}{\mathcal{X}}
\newcommand{\FM}{\Phi}
\newcommand{\Gram}{G}
\newcommand{\RKHS}{\mathc... | Python Code:
### FIRST SOME CODE ####
from __future__ import division, print_function, absolute_import
from IPython.display import SVG, display, Image, HTML
import numpy as np, scipy as sp, pylab as pl, matplotlib.pyplot as plt, scipy.stats as stats, sklearn, sklearn.datasets
from scipy.spatial.distance import squarefo... |
15,012 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Model 1 with FPC mask
Level 1
Step2: Model results
Rule learning and rule application in the matching task
Rule Learning > Rule Application
Step3: Rule Application > Rule Learning
S... | Python Code:
import os
from IPython.display import IFrame
from IPython.display import Image
# This function renders interactive brain images
def render(name,brain_list):
#prepare file paths
brain_files = []
for b in brain_list:
brain_files.append(os.path.join("data",b))
wdata =
<!... |
15,013 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SAS Viya, CAS & Python Integration Workshop
Notebook Summary
Set Up
Exploring CAS Action Sets and the CASResults Object
Working with a SASDataFrame
Exploring the CAS File Structure
Loading D... | Python Code:
## Data Management
import swat
import pandas as pd
## Data Visualization
from matplotlib import pyplot as plt
import seaborn as sns
%matplotlib inline
## Global Options
swat.options.cas.trace_actions = False # Enabling tracing of actions (Default is False. Will change to true later)
swat.options.cas.t... |
15,014 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright (c) 2015, 2016 Sebastian Raschka
Li-Yi Wei
https
Step1: The use of watermark is optional. You can install this IPython extension via "pip install watermark". For more information,... | Python Code:
%load_ext watermark
%watermark -a '' -u -d -v -p numpy,matplotlib,theano,keras
Explanation: Copyright (c) 2015, 2016 Sebastian Raschka
Li-Yi Wei
https://github.com/1iyiwei/pyml
MIT License
Python Machine Learning - Code Examples
Chapter 13 - Parallelizing Neural Network Training with Theano
We have seen ho... |
15,015 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exploring Titanic Dataset
Questions
Step1: Not really what I was looking for. Was hoping to see survived and died side by side. | Python Code:
# Import magic
%matplotlib inline
# More imports
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
#Set general plot properties
sns.set_style("white")
sns.set_context({"figure.figsize": (18, 8)})
# Load CSV data
titanic_data = pd.read_csv('titanic_data.csv')
survi... |
15,016 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have a Dataframe as below. | Problem:
import pandas as pd
df = pd.DataFrame({'Name': ['Name1', 'Name2', 'Name3'],
'2001': [2, 1, 0],
'2002': [5, 4, 5],
'2003': [0, 2, 0],
'2004': [0, 0, 0],
'2005': [4, 4, 0],
'2006': [6, 0, 2]})
def g(... |
15,017 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
New functions
These are recently written functions that have not made it into the main documentation
Python Lesson
Step1: When things go wrong in your eppy script, you get "Errors and Excep... | Python Code:
# you would normaly install eppy by doing #
# python setup.py install
# or
# pip install eppy
# or
# easy_install eppy
# if you have not done so, uncomment the following three lines
import sys
# pathnameto_eppy = 'c:/eppy'
pathnameto_eppy = '../'
sys.path.append(pathnameto_eppy)
Explanation: New functions... |
15,018 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Bastion hosts
There are many reasons for using bastion hosts
Step1: ssh_config
Instead of continuously passing options to ssh, we can use -F ssh_config and put configurations there.
Step2: ... | Python Code:
cd /notebooks/exercise-06/
Explanation: Bastion hosts
There are many reasons for using bastion hosts:
security access eg in cloud environment
vpn eg via windows hosts
The latter case is quite boring as ansible doesn't support windows as a client platform.
A standard approach is:
have a ssh server or a prox... |
15,019 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Alternate PowerShell Hosts
Metadata
| | |
|
Step1: Download & Process Mordor Dataset
Step2: Analytic I
Within the classic PowerShell log, event ID 400 indicates when a... | Python Code:
from openhunt.mordorutils import *
spark = get_spark()
Explanation: Alternate PowerShell Hosts
Metadata
| | |
|:------------------|:---|
| collaborators | ['@Cyb3rWard0g', '@Cyb3rPandaH'] |
| creation date | 2019/08/15 |
| modification date | 2020/09/20 |
| playbook related | ... |
15,020 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Solution of Lahti et al. 2014
Write a function that takes as input a dictionary of constraints (i.e., selecting a specific group of records) and returns a dictionary tabulating the BMI group... | Python Code:
import csv # Import csv modulce for reading the file
Explanation: Solution of Lahti et al. 2014
Write a function that takes as input a dictionary of constraints (i.e., selecting a specific group of records) and returns a dictionary tabulating the BMI group for all the records matching the constraints. For ... |
15,021 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This spark notebook connects to BigInsights on Cloud using BigSQL.
This notebook runs succesfully on stand alone spark-1.6.1-bin-hadoop2.6 and will output a dataframe like this
Step1: Code ... | Python Code:
cluster = '10451' # E.g. 10000
username = 'biadmin' # E.g. biadmin
password = '' # Please request password from chris.snow@uk.ibm.com
table = 'biadmin.rowapplyout' # BigSQL table to query
Explanation: This spark notebook connects to BigInsights on Cloud using BigSQL.
This notebook runs... |
15,022 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Train/Dev/Test split of AotM-2011/30Music songs/playlists in setting I & II
Step1: Load playlists
Load playlists.
Step2: check duplicated songs in the same playlist.
Step3: Load song feat... | Python Code:
%matplotlib inline
%load_ext autoreload
%autoreload 2
import os, sys
import gzip
import pickle as pkl
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import precision_recall_fscore_support, roc_auc_score, average_precision_score
from scipy.op... |
15,023 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Experiments with Similarity Encoders
...to show that SimEc can create similarity preserving embeddings based on human ratings
In this iPython Notebook are some examples to illustrate the pot... | Python Code:
from __future__ import unicode_literals, division, print_function, absolute_import
from builtins import range
import numpy as np
np.random.seed(28)
import matplotlib.pyplot as plt
from sklearn.linear_model import Ridge
from sklearn.decomposition import PCA, KernelPCA
from sklearn.datasets import load_digit... |
15,024 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Modeling and Simulation in Python
Case study
Step1: I'll start by getting the units we'll need from Pint.
Step2: Spider-Man
In this case study we'll develop a model of Spider-Man swinging ... | Python Code:
# Configure Jupyter so figures appear in the notebook
%matplotlib inline
# Configure Jupyter to display the assigned value after an assignment
%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'
# import functions from the modsim.py module
from modsim import *
Explanation: Modeling and Si... |
15,025 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1 entity referent
self ("me")
addressee ("you here")
other ("somebody else")
2+ entity referent
self, addressee ("me and you here" / inclusive we)
self, other ("me and somebody else" / exclu... | Python Code:
from itertools import combinations, combinations_with_replacement
referents = []
for i in xrange(1, len(entities) * 2):
for combo in combinations_with_replacement(entities, i):
# choral we is impossible
if combo.count('self') > 1:
continue
# onl... |
15,026 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="images/logo.jpg" style="display
Step1: <p style="text-align
Step2: <p style="text-align
Step3: <p style="text-align
Step5: <div class="align-center" style="display
Step6: <div... | Python Code:
print("Let's print a newline\nVery good. Now let us create a newline\n\twith a nested text!")
Explanation: <img src="images/logo.jpg" style="display: block; margin-left: auto; margin-right: auto;" alt="לוגו של מיזם לימוד הפייתון. נחש מצויר בצבעי צהוב וכחול, הנע בין האותיות של שם הקורס: לומדים פייתון. הסלוג... |
15,027 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step4: Implement a custom pytoch Dataset to load image frames from a remote DICOM VL Whole Slide Microscopy Image instance
Step6: Implement a simple binary image segmentation model
Step7: ... | Python Code:
class Dataset(torch.utils.data.Dataset):
Class for getting individual Pixel Data element frame items of a DICOM VL Whole Slide Microscocpy Image data set stored on a remote server.
def __init__(self, url: str, study_id: str, series_id: str, instance_id: str):
Parameters
... |
15,028 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Image Registration Exercise
Written by Gautham Narayan (gnarayan@stsci.edu) for LSST DSFP #5
In this directory, you should be able to find two fits file from one of the projects I worked on
... | Python Code:
!ls *fits
Explanation: Image Registration Exercise
Written by Gautham Narayan (gnarayan@stsci.edu) for LSST DSFP #5
In this directory, you should be able to find two fits file from one of the projects I worked on
End of explanation
import astropy.io.fits as afits
from astropy.wcs import WCS
from astropy.vi... |
15,029 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Тест. Доверительные интервалы для долей
Step1: Большая часть млекопитающих неспособны во взрослом возрасте переваривать лактозу, содержащуюся в молоке. У людей за расщепление лактозы отвеча... | Python Code:
import numpy as np
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
Explanation: Тест. Доверительные интервалы для долей
End of explanation
size = 50
data_gen = np.zeros(size)
data_gen[0] = 1
data_gen
from statsmodels.stats.proportion import proport... |
15,030 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
write a code on how to use pretrained gpt2 on custom data
| Python Code::
import numpy as np
import gpt_2_simple as gpt2
from datetime import datetime
from google.colab import files
from tensorflow.python.framework import ops
gpt2.download_gpt2(model_name="124M")
from transformers import GPT2Tokenizer
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
sess = gpt2.start_tf_sess()... |
15,031 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Practical MCMC in Python
by Dan Foreman-Mackey
A worksheet for the Local Group Astrostatistics workshop at the University of Michigan, June 2015.
Introduction
In this notebook, we'll implem... | Python Code:
name = "YOUR NAME HERE"
print("Hello {0}!".format(name))
Explanation: Practical MCMC in Python
by Dan Foreman-Mackey
A worksheet for the Local Group Astrostatistics workshop at the University of Michigan, June 2015.
Introduction
In this notebook, we'll implement a Markov Chain Monte Carlo (MCMC) algorithm... |
15,032 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 5
Step2: Leave One Out Cross Validation (LOOCV)
Instead of R's glm, we use Scikit-Learn's LinearRegression to arrive at very similar results.
Step3: K-Fold Cross Validation
Step5: ... | Python Code:
from __future__ import division
import pandas as pd
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.cross_validation import LeaveOneOut
from sklearn.cross_validation import KFold
from sklearn.cross_validation import Bootst... |
15,033 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Comment mettre en oeuvre une régression linéaire avec python ?
Germain Salvato-Vallverdu germain.vallverdu@univ-pau.fr
L'objectif de ce TP est de mettre en pratique le langage python pour ré... | Python Code:
cat data/donnees.dat
Explanation: Comment mettre en oeuvre une régression linéaire avec python ?
Germain Salvato-Vallverdu germain.vallverdu@univ-pau.fr
L'objectif de ce TP est de mettre en pratique le langage python pour réaliser une regression linéaire. L'idée est, dans un premier temps, de reprendre les... |
15,034 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Label and feature engineering
This lab is optional. It demonstrates advanced SQL queries for time-series engineering. For real-world problems, this type of feature engineering code is essent... | Python Code:
PROJECT = 'your-gcp-project' # Replace with your project ID.
import pandas as pd
from google.cloud import bigquery
from IPython.core.magic import register_cell_magic
from IPython import get_ipython
bq = bigquery.Client(project = PROJECT)
# Allow you to easily have Python variables in SQL query.
@register_... |
15,035 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Facies classification using Random Forest
Contest entry by
Step1: Exploring the dataset
First, we will examine the data set we will use to train the classifier.
Step2: This data is from t... | Python Code:
%matplotlib inline
# to install watermark magic command: pip install ipyext
%load_ext watermark
%watermark -v -p numpy,scipy,pandas,matplotlib,seaborn,sklearn
Explanation: Facies classification using Random Forest
Contest entry by :geoLEARN
Martin Blouin, Lorenzo Perozzi, Antoine Caté <br>
in collaboratio... |
15,036 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Decision Analysis
Think Bayes, Second Edition
Copyright 2020 Allen B. Downey
License
Step1: This chapter presents a problem inspired by the game show The Price is Right.
It is a silly examp... | Python Code:
# If we're running on Colab, install empiricaldist
# https://pypi.org/project/empiricaldist/
import sys
IN_COLAB = 'google.colab' in sys.modules
if IN_COLAB:
!pip install empiricaldist
# Get utils.py
from os.path import basename, exists
def download(url):
filename = basename(url)
if not exists(... |
15,037 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Collating XML with embedded markup
This notebook illustrates one strategy for collating XML with embedded markup. It flattens the markup into milestones and retains the milestones in the "t"... | Python Code:
#!/usr/bin/env python
# Filename: xml_and_python.py
# Developer: David J. Birnbaum (djbpitt@gmail.com)
# First version: 2017-07-23
# Last revised: 2017-07-27
#
# Syntax: python xml_and_python.py
# Input: Representative input is embedded in the Python script
# Output: stdout
#
# Synopsis: Collate XML around... |
15,038 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interact Exercise 4
Imports
Step2: Line with Gaussian noise
Write a function named random_line that creates x and y data for a line with y direction random noise that has a normal distribut... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from IPython.html.widgets import interact, interactive, fixed
from IPython.display import display
Explanation: Interact Exercise 4
Imports
End of explanation
def random_line(m, b, sigma, size=10):
Create a line y = m*x + b + N(0,sigm... |
15,039 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Regular Expressions
A regular expression (RegEx) is a sequence of chatacters that expresses a pattern to be searched withing a longer piece of text. re is a Python library for regular expres... | Python Code:
import re
with open("financier.txt","r") as f:
financier = f.readlines()
print financier[2:4]
type(financier)
Explanation: Regular Expressions
A regular expression (RegEx) is a sequence of chatacters that expresses a pattern to be searched withing a longer piece of text. re is a Python library for regu... |
15,040 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have a set of data and I want to compare which line describes it best (polynomials of different orders, exponential or logarithmic). | Problem:
import numpy as np
import scipy.optimize
y = np.array([1, 7, 20, 50, 79])
x = np.array([10, 19, 30, 35, 51])
p0 = (4, 0.1, 1)
result = scipy.optimize.curve_fit(lambda t,a,b, c: a*np.exp(b*t) + c, x, y, p0=p0)[0] |
15,041 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Reageren op de Raspberry Pi GPIO pins
Met deze IPython Notebook verbinden we hardware met software. We zullen een knop verbinden met de General Purpose Input/Output (GPIO) pinnen* op de Rasp... | Python Code:
import pygame.mixer
pygame.mixer.init()
Explanation: Reageren op de Raspberry Pi GPIO pins
Met deze IPython Notebook verbinden we hardware met software. We zullen een knop verbinden met de General Purpose Input/Output (GPIO) pinnen* op de Raspberry Pi en wanneer de knop ingedrukt wordt, de Pi een functie l... |
15,042 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Environment Preparation
Install Java 8
Run the cell on the Google Colab to install jdk 1.8.
Note
Step2: Install BigDL Orca
Conda is needed to prepare the Python envir... | 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... |
15,043 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A note about sigmas
We are regularly asked about the "sigma" levels in the 2D histograms. These are not the 68%, etc. values that we're used to for 1D distributions. In two dimensions, a Gau... | Python Code:
import corner
import numpy as np
import matplotlib.pyplot as pl
# Generate some fake data from a Gaussian
np.random.seed(42)
x = np.random.randn(50000, 2)
Explanation: A note about sigmas
We are regularly asked about the "sigma" levels in the 2D histograms. These are not the 68%, etc. values that we're use... |
15,044 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Conditional Execution
Boolean Expressions
We introduce a new value type, the boolean. A boolean can have one of two values
Step1: Comparison Operators
You can compare values together and ge... | Python Code:
cleaned_room = True
took_out_trash = False
print(cleaned_room)
print(type(took_out_trash))
Explanation: Conditional Execution
Boolean Expressions
We introduce a new value type, the boolean. A boolean can have one of two values: True or False
End of explanation
print(5 == 6)
print("Coke" != "Pepsi")
# You c... |
15,045 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A sample of plots
The idea of this notebook is to show off a number of plot types, and act as a simple check of the plotting output. It requires matplotlib and does not attempt to describe t... | Python Code:
import numpy as np
%matplotlib inline
from sherpa import data
from sherpa.astro import data as astrodata
from sherpa import plot
from sherpa.astro import plot as astroplot
Explanation: A sample of plots
The idea of this notebook is to show off a number of plot types, and act as a simple check of the plotti... |
15,046 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Supply curve figures of coal and petroleum resources
Sources I used for parts of this, and other things that might be helpful
Step1: Load coal data
Data is from
Step2: Fortuntely the Cost ... | Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.path as path
from palettable.colorbrewer.qualitative import Paired_11
Explanation: Supply curve figures of coal and petroleum resources
Sour... |
15,047 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="https
Step1: %%stata magic
In order to use ipystata you will need to use the %%stata magic. Let's see the help for it.
Step2: First example
Let's run some commands in Stata from ... | Python Code:
import numpy as np
import pandas as pd
import ipystata
%pylab --no-import-all
%matplotlib inline
Explanation: <img src="https://www.stata.com/includes/images/stata-fb.jpg" alt="Stata" width="200"/> in a <img src="https://www.python.org/static/community_logos/python-logo-inkscape.svg" alt="Python" width=200... |
15,048 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exercises for Chapter 1
Training Machine Learning Algorithms for Classification
Question 1. In the file algos/blank/perceptron.py, implement Rosenblatt's perceptron algorithm by fleshing out... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from algos.blank.perceptron import Perceptron
df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', header=None)
y = df.iloc[0:100, 4].values
y = np.where(y == 'Iris-setosa', 1, ... |
15,049 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Basic statistics
Step1: Applicant-apply-Job matrix
A. Number of times an applicant applies a specific job title (position).
Step2: As the number of active days changes with users, we need ... | Python Code:
n_application, n_applicant, n_job, n_job_title = apps.shape[0], apps['uid'].nunique(), apps['job_id'].nunique(), apps['job_title'].nunique()
n_company = apps['reg_no_uen_ep'].nunique()
stats = pd.DataFrame({'n_application': n_application, 'n_applicant': n_applicant,
'n_job': n_job, '... |
15,050 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CARTO Data Observatory
This is a basic template notebook to start exploring your new Dataset from CARTO's Data Observatory via the Python library CARTOframes.
You can find more details about... | Python Code:
!pip install -U cartoframes
# Note: a kernel restart is required after installing the library
import cartoframes
cartoframes.__version__
Explanation: CARTO Data Observatory
This is a basic template notebook to start exploring your new Dataset from CARTO's Data Observatory via the Python library CARTOframes... |
15,051 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This is the <a href="https
Step1: How do we define direction of an earth magnetic field?
Earth magnetic field is a vector. To define a vector we need to choose a coordinate system. We use r... | Python Code:
import numpy as np
from geoscilabs.mag import Mag, Simulator
%matplotlib inline
Explanation: This is the <a href="https://jupyter.org/">Jupyter Notebook</a>, an interactive coding and computation environment. For this lab, you do not have to write any code, you will only be running it.
To use the notebook... |
15,052 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ABU量化系统使用文档
<center>
<img src="./image/abu_logo.png" alt="" style="vertical-align
Step1: 受限于沙盒中数据限制,本节示例的相关性分析只限制在abupy内置沙盒数据中,完整示例以及代码请阅读后面章节的全市场回测示例或者《量化交易之路》中相关章节。
首先将内置沙盒中美股,A股,... | Python Code:
# 基础库导入
from __future__ import print_function
from __future__ import division
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import os
import sys
# 使用insert 0即只使用github,避免交叉使用了pip安装的abupy,导致的版本不一致问题
sys.path.insert(0, os.path.abspath('../'))
import abupy
# 使用沙盒数据,... |
15,053 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
讀取 Miku
Step1: Muki NN
<img width=500px src='./muki_nn.png' />
Step2: 第一層
Step3: 第二層
Step4: 第三層
Step5: 定義 Cost Function & Update Function
Step6: Training
Step7: Training - Random Suff... | Python Code:
img_count = 0
def showimg(img):
muki_pr = np.zeros((500,500,3))
l =img.tolist()
count = 0
for x in range(500):
for y in range(500):
muki_pr[y][x] = l[count]
count += 1
plt.imshow(muki_pr)
def saveimg(fname,img):
muki_pr = np.zeros((500,500,3))
l =... |
15,054 | 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
dt = 0.5
tt = arange(0, 10, dt)
# initial condition
xx = [0.1]
def f(x):
return x * (1.-x)
# loop over time
for t in tt[1:]:
xx.append(xx[-1] + dt * f(xx[-1]))
# plotting
plot(tt, xx, '.-')
ta = arange(0, 10, 0.... |
15,055 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial
This Python notebook demonstrates how OASIS can be used to efficiently evaluate a classifier, based on an example dataset from the entity resolution domain.
We begin by loading the ... | Python Code:
import numpy as np
import random
import oasis
import matplotlib.pyplot as plt
%matplotlib inline
np.random.seed(319158)
random.seed(319158)
Explanation: Tutorial
This Python notebook demonstrates how OASIS can be used to efficiently evaluate a classifier, based on an example dataset from the entity resolut... |
15,056 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Learning with TensorFlow
Credits
Step1: Reformat into a TensorFlow-friendly shape
Step2: Let's build a small network with two convolutional layers, followed by one fully connected lay... | 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
pickle_file = 'notMNIST.pickle'
with open(pickle_file, 'rb') as f:
save = pickle.load(f)
train_dataset = save['train_dataset']... |
15,057 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Motor imagery decoding from EEG data using the Common Spatial Pattern (CSP)
Decoding of motor imagery applied to EEG data decomposed using CSP.
Here the classifier is applied to features ext... | Python Code:
# Authors: Martin Billinger <martin.billinger@tugraz.at>
#
# License: BSD (3-clause)
import numpy as np
import matplotlib.pyplot as plt
from sklearn.pipeline import Pipeline
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.model_selection import ShuffleSplit, cross_val_scor... |
15,058 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Manipulation de séries financières avec la classe StockPrices
La classe StockPrices facilite la récupération de données financières via différents sites. Le site Yahoo Finance requiet mainte... | Python Code:
import pyensae
from jyquickhelper import add_notebook_menu
add_notebook_menu()
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('ggplot')
Explanation: Manipulation de séries financières avec la classe StockPrices
La classe StockPrices facilite la récupération de données financières via diff... |
15,059 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This is an example for the displaytools extension for the IPython Notebook.
The extension introduces some "magic" comments (like ## and ##
Step1: Note that the equation sign (i.e., =) must ... | Python Code:
%load_ext displaytools3
%reload_ext displaytools3
import sympy as sp
from sympy import sin, cos
from sympy.abc import t, pi
x = 2*pi*t
y1 = cos(x)
y2 = cos(x)*t
ydot1 = y1.diff(t) ##
ydot2 = y2.diff(t) ##
ydot1_obj = y1.diff(t, evaluate=False) ##
Explanation: This is an example for the displaytools extensi... |
15,060 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
$$ \LaTeX \text{ command declarations here.}
\newcommand{\R}{\mathbb{R}}
\renewcommand{\vec}[1]{\mathbf{#1}}
\newcommand{\X}{\mathcal{X}}
\newcommand{\D}{\mathcal{D}}
\newcommand{\G}{\mathca... | Python Code:
from __future__ import division
# plotting
%matplotlib inline
from matplotlib import pyplot as plt;
import matplotlib as mpl;
from mpl_toolkits.mplot3d import Axes3D
# scientific
import numpy as np;
import sklearn as skl;
import sklearn.datasets;
import sklearn.cluster;
import sklearn.mixture;
# ipython
im... |
15,061 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="images/mcg.jpg", style="width
Step1: Linear Gaussian Models - The Process
The linear gaussian model in supervised learning scheme is nothing but a linear regression where inputs a... | Python Code:
# from pgmpy.factors.continuous import LinearGaussianCPD
import sys
import numpy as np
import pgmpy
sys.path.insert(0, "../pgmpy/")
from pgmpy.factors.continuous import LinearGaussianCPD
mu = np.array([7, 13])
sigma = np.array([[4, 3], [3, 6]])
cpd = LinearGaussianCPD(
"Y", evidence_mean=mu, evidence_v... |
15,062 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Modelado de un sistema con ipython
Para el correcto funcionamiento del extrusor de filamento, es necesario regular correctamente la temperatura a la que está el cañon. Por ello se usará un s... | Python Code:
#Importamos las librerías utilizadas
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pylab as plt
#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... |
15,063 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 2 Distributions
Histograms
The most common representation of a distribution is a histogram. which is a graph that shows the frequency of each value
Step1: NSFG variables
Step2: Hi... | Python Code:
from matplotlib import pyplot as plt
%matplotlib inline
import seaborn as sns
import numpy as np
import pandas as pd
import thinkstats2
import thinkplot
hist = thinkstats2.Hist([1, 2, 2, 3, 5])
hist
hist.Freq(2) # hist[2]
hist.Values()
thinkplot.Hist(hist)
thinkplot.Show(xlabel='value', ylabel='frequency... |
15,064 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dynamic hedge
It's somewhat hard to find data about historical prices of options, so I will proceed differently as promissed. I will work on the following problem
Step1: For the interest ra... | Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
data = pd.read_csv("../data/GOOG.csv").ix[:,["Date", "Open"]]
data.sort_values(by="Date", inplace=True)
data.reset_index(inplace=True)
Explanation: Dynamic hedge
It's somewhat hard to find data about historical prices... |
15,065 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Machine Learning Engineer Nanodegree
Model Evaluation & Validation
Project
Step1: Data Exploration
In this first section of this project, you will make a cursory investigation about the Bos... | Python Code:
# Import libraries necessary for this project
import numpy as np
import pandas as pd
from sklearn.cross_validation import ShuffleSplit
# Import supplementary visualizations code visuals.py
import visuals as vs
# Pretty display for notebooks
%matplotlib inline
# Load the Boston housing dataset
data = pd.rea... |
15,066 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TensorFlow Tutorial #02
Convolutional Neural Network
by Magnus Erik Hvass Pedersen
/ GitHub / Videos on YouTube
Introduction
The previous tutorial showed that a simple linear model had about... | Python Code:
from IPython.display import Image
Image('images/02_network_flowchart.png')
Explanation: TensorFlow Tutorial #02
Convolutional Neural Network
by Magnus Erik Hvass Pedersen
/ GitHub / Videos on YouTube
Introduction
The previous tutorial showed that a simple linear model had about 91% classification accuracy ... |
15,067 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Линейная регрессия и основные библиотеки Python для анализа данных и научных вычислений
Это задание посвящено линейной регрессии. На примере прогнозирования роста человека по его весу Вы уви... | Python Code:
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Линейная регрессия и основные библиотеки Python для анализа данных и научных вычислений
Это задание посвящено линейной регрессии. На примере прогнозирования роста человека по его вес... |
15,068 | Given the following text description, write Python code to implement the functionality described.
Description:
You're a hungry rabbit, and you already have eaten a certain number of carrots,
but now you need to eat more carrots to complete the day's meals.
you should return an array of [ total number of eat... | Python Code:
def eat(number, need, remaining):
if(need <= remaining):
return [ number + need , remaining-need ]
else:
return [ number + remaining , 0] |
15,069 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Multiple Regression using Statsmodels
This tutorial comes from datarobot's blog post on multi-regression using statsmodel. I only fixed the broken links to the data.
This is part of a serie... | Python Code:
import pandas as pd
import numpy as np
import statsmodels.api as sm
import matplotlib.pyplot as plt
%matplotlib inline
df_adv = pd.read_csv('http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv', index_col=0)
X = df_adv[['TV', 'Radio']]
y = df_adv['Sales']
df_adv.head()
Explanation: Multiple Regression using... |
15,070 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Churn Prediction - Predicting when your customers will churn
1 - Introduction
A software as a service (SaaS) company provides a suite of products for Small-to-Medium enterprises, such as dat... | Python Code:
# Importing modules
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
from pysurvival.datasets import Dataset
%pylab inline
# Reading the dataset
raw_dataset = Dataset('churn').load()
print("The raw_dataset has the following shape: {}.".format(raw_dataset.shape))
raw_dataset.head(... |
15,071 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The following notebook is a tutorial on machine learning to detect change using geospatial_learn
Documentation on the lib can be found here
Step1: Before we begin!
In jupyter, to see the do... | Python Code:
%matplotlib inline
Explanation: The following notebook is a tutorial on machine learning to detect change using geospatial_learn
Documentation on the lib can be found here:
http://geospatial-learn.readthedocs.io/en/latest/
Please use QGIS to visualise results as this is quicker than plotting them in the no... |
15,072 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sealevel monitor
This document is used to monitor the current sea level along the Dutch coast. The sea level is measured using a number of tide gauges. Six long running tide gauges are consi... | Python Code:
# this is a list of packages that are used in this notebook
# these come with python
import io
import zipfile
import functools
# you can install these packages using pip or anaconda
# (requests numpy pandas bokeh pyproj statsmodels)
# for downloading
import requests
# computation libraries
import numpy as ... |
15,073 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sentiment analysis with TFLearn
In this notebook, we'll continue Andrew Trask's work by building a network for sentiment analysis on the movie review data. Instead of a network written with ... | Python Code:
import pandas as pd
import numpy as np
import tensorflow as tf
import tflearn
from tflearn.data_utils import to_categorical
Explanation: Sentiment analysis with TFLearn
In this notebook, we'll continue Andrew Trask's work by building a network for sentiment analysis on the movie review data. Instead of a n... |
15,074 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Use-case
Step1: Storing of video data
Step2: Tracking data
Step3: Addtional Information | Python Code:
import nixio as nix
import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from utils.notebook import print_stats
from utils.video_player import Playback
nix_file = nix.File.open('data/tracking_data.h5', nix.FileMode.ReadOnly)
print_stats(nix_file.blocks)
b = nix_file.... |
15,075 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Seismic petrophysics, part 2
In part 1 we loaded some logs and used a data framework called Pandas pandas to manage them. We made a lithology–fluid class (LFC) log, and used it to color a cr... | Python Code:
def frm(vp1, vs1, rho1, rho_f1, k_f1, rho_f2, k_f2, k0, phi):
vp1 = vp1 / 1000.
vs1 = vs1 / 1000.
mu1 = rho1 * vs1**2.
k_s1 = rho1 * vp1**2 - (4./3.)*mu1
# The dry rock bulk modulus
kdry = (k_s1 * ((phi*k0)/k_f1+1-phi)-k0) / ((phi*k0)/k_f1+(k_s1/k0)-1-phi)
# Now we can a... |
15,076 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Intro to Data Wrangling
Data Wrangling is the concept of arranging your dataset into a workable format for analysis. When retreiving data from various sources, it is not always in a format ... | Python Code:
import numpy as np
import pandas as pd
df = pd.read_csv('Master.csv')
df.head(5)
Explanation: Intro to Data Wrangling
Data Wrangling is the concept of arranging your dataset into a workable format for analysis. When retreiving data from various sources, it is not always in a format that is ready to be ana... |
15,077 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Displacement-based Earthquake Loss Assessment - Silva et al. 2013
In this fragility method, thousands of synthetic buildings can be produced considering probabilistic distributions for the v... | Python Code:
import DBELA
from rmtk.vulnerability.common import utils
%matplotlib inline
Explanation: Displacement-based Earthquake Loss Assessment - Silva et al. 2013
In this fragility method, thousands of synthetic buildings can be produced considering probabilistic distributions for the variability in the geometric... |
15,078 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Hash Tables (Open Hashing)
This notebook provides a simple implementation of a hash table that uses open hashing.
The class ListMap from the notebook ListMap.ipynb implements a map as a link... | Python Code:
%run ListMap.ipynb
Explanation: Hash Tables (Open Hashing)
This notebook provides a simple implementation of a hash table that uses open hashing.
The class ListMap from the notebook ListMap.ipynb implements a map as a linked list.
End of explanation
import string
for c in string.ascii_letters:
print(f'... |
15,079 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MIMO Least Squares Detection
This code is provided as supplementary material of the lecture Machine Learning and Optimization in Communications (MLOC).<br>
This code illustrates
Step1: We w... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: MIMO Least Squares Detection
This code is provided as supplementary material of the lecture Machine Learning and Optimization in Communications (MLOC).<br>
This code illustrates:
* Toy example of MIMO Detection with constra... |
15,080 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Visualising statistical significance thresholds on EEG data
MNE-Python provides a range of tools for statistical hypothesis testing
and the visualisation of the results. Here, we show a few ... | Python Code:
import matplotlib.pyplot as plt
from scipy.stats import ttest_ind
import numpy as np
import mne
from mne.channels import find_layout, find_ch_connectivity
from mne.stats import spatio_temporal_cluster_test
np.random.seed(0)
# Load the data
path = mne.datasets.kiloword.data_path() + '/kword_metadata-epo.fif... |
15,081 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A Two-Level, Six-Factor Full Factorial Design
<br />
<br />
<br />
Table of Contents
Introduction
Factorial Experimental Design
Step1: <a name="fullfactorial"></a>
Two-Level Six-Factor Full... | Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
from numpy.random import rand, seed
import seaborn as sns
import scipy.stats as stats
from matplotlib.pyplot import *
seed(10)
Explanation: A Two-Level, Six-Factor Full Factorial Design
<br />
<br />
<br />
Table of Contents
Introduction
Factorial E... |
15,082 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Spelling Bee
This notebook starts our deep dive (no pun intended) into NLP by introducing sequence-to-sequence learning on Spelling Bee.
Data Stuff
We take our data set from The CMU pronounc... | Python Code:
%matplotlib inline
import importlib
import utils2; importlib.reload(utils2)
from utils2 import *
np.set_printoptions(4)
PATH = 'data/spellbee/'
limit_mem()
from sklearn.model_selection import train_test_split
Explanation: Spelling Bee
This notebook starts our deep dive (no pun intended) into NLP by introdu... |
15,083 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PyTorch Dataset and Dataloader Demo
We illustrate how to build a custom dataset and dataloader for object detection.
We will use our collected and labeled images for object detection. Over ... | Python Code:
import torch
import numpy as np
import wandb
import label_utils
from torch.utils.data import DataLoader
from torchvision import transforms
from PIL import Image
Explanation: PyTorch Dataset and Dataloader Demo
We illustrate how to build a custom dataset and dataloader for object detection.
We will use our... |
15,084 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lightweight python components
Lightweight python components do not require you to build a new container image for every code change.
They're intended to use for fast iteration in notebook en... | Python Code:
# Install the SDK
#!pip3 install 'kfp>=0.1.31.2' --quiet
import kfp
import kfp.components as comp
Explanation: Lightweight python components
Lightweight python components do not require you to build a new container image for every code change.
They're intended to use for fast iteration in notebook environm... |
15,085 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Notebook Analyzes Duplication in Motif Defintions
Step1: Import Motif Definitions
Step2: Convert to DataFrame for Analysis of Duplication
Step3: Move On | Python Code:
import venusar
import motif
import thresholds
import motifs
import activity
import tf_expression
import gene_expression
# to get code changes
import imp
imp.reload(motif)
Explanation: Notebook Analyzes Duplication in Motif Defintions
End of explanation
motif_f_base='../../data/HOCOMOCOv10.JASPAR_FORMAT... |
15,086 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
SciPy has three methods for doing 1D integrals over samples (trapz, simps, and romb) and one way to do a 2D integral over a function (dblquad), but it doesn't seem to have methods f... | Problem:
import numpy as np
x = np.linspace(0, 1, 20)
y = np.linspace(0, 1, 30)
from scipy.integrate import simpson
z = np.cos(x[:,None])**4 + np.sin(y)**2
result = simpson(simpson(z, y), x) |
15,087 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Probability Calibration using ML-Insights
On Example of Mortality Model Using MIMIC ICU Data*
This workbook is intended to demonstrate why probability calibration may be useful, and how to d... | Python Code:
# "pip install ml_insights" in terminal if needed
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import ml_insights as mli
%matplotlib inline
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.cross_validation import train_test_split, Strati... |
15,088 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Now, I'm going to learn Beautiful Soup
Step1: A tag has a name (say, "someTag"). It contains a set of attribute
Step2: i.e. we can use .attrs to show the dictionary of a specified tag (at... | Python Code:
soup = BeautifulSoup('<b class="boldest">Extremely bold</b>',"html.parser")
tag = soup.b
type(tag)
Explanation: Now, I'm going to learn Beautiful Soup:
Tag:
End of explanation
print tag.name
print tag["class"]
print tag.attrs
Explanation: A tag has a name (say, "someTag"). It contains a set of attribute:v... |
15,089 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ordinary Least Squares
Step1: OLS estimation
Artificial data
Step2: Our model needs an intercept so we add a column of 1s
Step3: Fit and summary
Step4: Quantities of interest can be extr... | Python Code:
%matplotlib inline
from __future__ import print_function
import numpy as np
import statsmodels.api as sm
import matplotlib.pyplot as plt
from statsmodels.sandbox.regression.predstd import wls_prediction_std
np.random.seed(9876789)
Explanation: Ordinary Least Squares
End of explanation
nsample = 100
x = np.... |
15,090 | 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', 'cams', 'sandbox-2', 'ocnbgchem')
Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem
MIP Era: CMIP6
Institute: CAMS
Source ID: SANDBOX-2
Topic: Ocnbgchem
Sub-Topics: Tracers.
Prop... |
15,091 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Bucles
Los bucles permiten iterar rápidamente una y otra vez sobre una estructura de datos. En Python hay dos tipos de bucles
Step1: Si necesitamos recorrer todos y cada uno de los elemento... | Python Code:
# antes de nada, creo unas cuantas variables con listas para jugar
numeros = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(numeros)
# fíjate en esta forma nueva de crear una lista a partir de una cadena
# el método .split() me permite "romper" una cadena en una lista de cadenas
# cuando usamos .split() sin más, es... |
15,092 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Runtime Cythonize in QuTiP
Prepared for EuroSciPy 2019
Alex Pitchford (alex.pitchford@gmail.com)
Two types of time-dependent dynamics solving
'function' type and 'string' type
pros and cons ... | Python Code:
# Imports and utility functions
import time
import numpy as np
import matplotlib.pyplot as plt
from qutip.sesolve import sesolve
from qutip.solver import Options, solver_safe
from qutip import sigmax, sigmay, sigmaz, identity, tensor, basis, Bloch
def timing_val(func):
def wrapper(*arg, **kw):
... |
15,093 | 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... |
15,094 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Detecting Encrypted TOR Traffic with Boosting and Topological Data Analysis
HJ van Veen - MLWave
We establish strong baselines for both supervised and unsupervised detection of encrypted TOR... | Python Code:
import numpy as np
import pandas as pd
import xgboost
from sklearn import model_selection, metrics
Explanation: Detecting Encrypted TOR Traffic with Boosting and Topological Data Analysis
HJ van Veen - MLWave
We establish strong baselines for both supervised and unsupervised detection of encrypted TOR traf... |
15,095 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Neural networks with PyTorch
Deep learning networks tend to be massive with dozens or hundreds of layers, that's where the term "deep" comes from. You can build one of these deep networks us... | Python Code:
# Import necessary packages
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import numpy as np
import torch
import helper
import matplotlib.pyplot as plt
Explanation: Neural networks with PyTorch
Deep learning networks tend to be massive with dozens or hundreds of layers, that's where the... |
15,096 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introductory Geocoding and Mapping
Juan Shishido, Andrew Chong, Patty Frontiera
Adapted from Juan Shishido's tutorial at
Step1: Using A Geocoding APIs
There are a number of Geocoding APIs t... | Python Code:
import json
import requests
import pandas as pd
import geopy
from pprint import pprint
Explanation: Introductory Geocoding and Mapping
Juan Shishido, Andrew Chong, Patty Frontiera
Adapted from Juan Shishido's tutorial at: http://people.ischool.berkeley.edu/~juanshishido/geocoding-workshop/intro-geocoding.h... |
15,097 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TensorFlow Transfer Learning
This notebook shows how to use pre-trained models from TensorFlowHub. Sometimes, there is not enough data, computational resources, or time to train a model from... | Python Code:
import os
import pathlib
from PIL import Image
import IPython.display as display
import matplotlib.pylab as plt
import numpy as np
import tensorflow as tf
from tensorflow.keras import Sequential
from tensorflow.keras.layers import (
Conv2D, Dense, Dropout, Flatten, MaxPooling2D, Softmax)
import tensorf... |
15,098 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: MLP in vanilla JAX
We construct a simple MLP with L hidden layers (relu activation), and scalar output (linear activation).
Note
Step2: Our first flax model
Here we r... | Python Code:
import numpy as np
# np.set_printoptions(precision=3)
np.set_printoptions(formatter={"float": lambda x: "{0:0.5f}".format(x)})
import matplotlib.pyplot as plt
import jax
print(jax.__version__)
print(jax.devices())
from jax import lax, random, numpy as jnp
key = random.PRNGKey(0)
from typing import Any, Cal... |
15,099 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Create dataframe
Step2: Select a random subset of 2 without replacement | Python Code:
import pandas as pd
import numpy as np
Explanation: Title: Random Sampling Dataframe
Slug: pandas_sampling_dataframe
Summary: Random Sampling Dataframe
Date: 2016-05-01 12:00
Category: Python
Tags: Data Wrangling
Authors: Chris Albon
import modules
End of explanation
raw_data = {'first_name': ['Jason', '... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.