Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
14,400 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Nearest Neighbors
sklearn.neighbors provides functionality for unsupervised and supervised neighbors-based learning methods. Supervised neighbors-based learning comes in two flavors
Step1: ... | Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Nearest Neighbors
sklearn.neighbors provides functionality for unsupervised and supervised neighbors-based learning methods. Supervised neighbors-based learning comes in two flavors: classification for da... |
14,401 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Get the dispersion relation for slab geometry
We will here calculate the real and imaginary part of the dispersion relation given in
Pécseli, H -Low Frequency Waves and Turbulence in Magnet... | Python Code:
from sympy import init_printing
from sympy import Eq, I
from sympy import re, im
from sympy import symbols
from sympy.solvers import solve
from IPython.display import display
from sympy import latex
om = symbols('omega')
omI = symbols('omega_i', real=True)
omStar = symbols('omega_S', real=True)
sigm... |
14,402 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Part 3 - Expanded Query Builder Functions
Step1: More Query Builders
match_exists
match_exists() matches entries where there is any value in the field. As long as the field exists in the en... | Python Code:
from mdf_forge.forge import Forge
mdf = Forge()
Explanation: Part 3 - Expanded Query Builder Functions
End of explanation
mdf.match_exists("services.globus_publish")
mdf.search(limit=10)
Explanation: More Query Builders
match_exists
match_exists() matches entries where there is any value in the field. As l... |
14,403 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Transpressional deformation
Step1: Here we will examine strain evolution during transpression deformation. Transpression (Sanderson and Marchini, 1984) is considered as a wrench or transcur... | Python Code:
%pylab inline
from scipy import linalg as la
Explanation: Transpressional deformation
End of explanation
def KDparams(F):
u, s, v = svd(F)
Rxy = s[0]/s[1]
Ryz = s[1]/s[2]
K = (Rxy-1)/(Ryz-1)
D = sqrt((Rxy-1)**2 + (Ryz-1)**2)
return K, D
Explanation: Here we will examine strain evolu... |
14,404 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Visualize channel over epochs as an image
This will produce what is sometimes called an event related
potential / field (ERP/ERF) image.
2 images are produced. One with a good channel and on... | Python Code:
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#
# License: BSD (3-clause)
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne import io
from mne.datasets import sample
print(__doc__)
data_path = sample.data_path()
Explanation: Visualize channel over epochs as an... |
14,405 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 12
Examples and Exercises from Think Stats, 2nd Edition
http
Step1: Time series analysis
NOTE
Step3: The following function takes a DataFrame of transactions and compute daily aver... | Python Code:
from os.path import basename, exists
def download(url):
filename = basename(url)
if not exists(filename):
from urllib.request import urlretrieve
local, _ = urlretrieve(url, filename)
print("Downloaded " + local)
download("https://github.com/AllenDowney/ThinkStats2/raw/master... |
14,406 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Likelihood Functions and Confidence Intervals
by Alex Drlica-Wagner
Introduction
This notebook attempts to pragmatically address several questions about deriving uncertainty intervals from a... | Python Code:
%matplotlib inline
import numpy as np
import pylab as plt
import scipy.stats as stats
from scipy.stats import multivariate_normal as mvn
try:
import emcee
got_emcee = True
except ImportError:
got_emcee = False
try:
import corner
got_corner = True
except ImportError:
got_corner = Fal... |
14,407 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SMC2017
Step1: II.1 Likelihood estimates for the stochastic volatility model
Consider the stochastic volatility model
$$
\begin{align}
x_t\,|\,x_{t - 1} &\sim \mathcal{N}\left(\phi \cdot x_... | Python Code:
import numpy as np
from scipy import stats
import pandas as pd
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style()
path = '..\\..\\..\\..\\course_material\\exercise_sheets\\'
Explanation: SMC2017: Exercise set II
Setup
End of explanation
data = pd.read_csv(path + 'seOMX... |
14,408 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exercise from Think Stats, 2nd Edition (thinkstats2.com)<br>
Allen Downey
Read the female respondent file.
Step2: Make a PMF of <tt>numkdhh</tt>, the number of children under 18 in the resp... | Python Code:
%matplotlib inline
import chap01soln
resp = chap01soln.ReadFemResp()
Explanation: Exercise from Think Stats, 2nd Edition (thinkstats2.com)<br>
Allen Downey
Read the female respondent file.
End of explanation
def BiasPmf(pmf, label=''):
Returns the Pmf with oversampling proportional to value.
If pmf... |
14,409 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Homework 14 (or so)
Step1: You can explore the files if you'd like, but we're going to get the ones from convote_v1.1/data_stage_one/development_set/. It's a bunch of text files.
Step2: So... | Python Code:
# If you'd like to download it through the command line...
!curl -O http://www.cs.cornell.edu/home/llee/data/convote/convote_v1.1.tar.gz
# And then extract it through the command line...
!tar -zxf convote_v1.1.tar.gz
Explanation: Homework 14 (or so): TF-IDF text analysis and clustering
Hooray, we kind of f... |
14,410 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Image Super-Resolution using an Efficient Sub-Pixel CNN
Author
Step1: Load data
Step2: We create training and validation datasets via image_dataset_from_directory.
Step3: We rescale the i... | Python Code:
import tensorflow as tf
import os
import math
import numpy as np
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.preprocessing.image import load_img
from tensorflow.keras.preprocessing.image import array_to_img
from tensorflow.keras.preprocessing.image import img_to_a... |
14,411 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
LSTM
[recurrent.LSTM.0] units=4, activation='tanh', recurrent_activation='hard_sigmoid'
Note dropout_W and dropout_U are only applied during training phase
Step1: [recurrent.LSTM.1] units=5... | Python Code:
data_in_shape = (3, 6)
rnn = LSTM(4, activation='tanh', recurrent_activation='hard_sigmoid')
layer_0 = Input(shape=data_in_shape)
layer_1 = rnn(layer_0)
model = Model(inputs=layer_0, outputs=layer_1)
# set weights to random (use seed for reproducibility)
weights = []
for i, w in enumerate(model.get_weights... |
14,412 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Numpy testing
Step1: jsum testing
jsum is very basic function for testing cython. It should be mcuh faster in cython than in python. | Python Code:
A = [2,2,3]
jcy.f_test(A)
print A
C = np.array([0,0], dtype = np.float64)
A = np.array([1,2], dtype = np.float64)
B = np.array([3,5], dtype = np.float64)
%timeit jcy.jsum_float( C, A, B, 1000)
print C
%timeit jpy.jsum_float( C, A, B, 1000)
print C
Explanation: Numpy testing
End of explanation
%timeit jcy.j... |
14,413 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Modeling and Simulation in Python
Chapter 13
Copyright 2017 Allen Downey
License
Step6: Code from previous chapters
make_system, plot_results, and calc_total_infected are unchanged.
Step7: ... | 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... |
14,414 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Create a variable of the true number of deaths of an event
Step2: Create a variable that is denotes if the while loop should keep running
Step3: while running is True | Python Code:
import random
Explanation: Title: while Statement
Slug: while_statements
Summary: while Statement
Date: 2016-05-01 12:00
Category: Python
Tags: Basics
Authors: Chris Albon
A while loop loops while a condition is true, stops when the condition becomes false
Import the random module
End of explanation
deat... |
14,415 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ejemplo de word2vec con gensim
En la siguiente celda, importamos las librerías necesarias y configuramos los mensajes de los logs.
Step1: Entrenamiento de un modelo
Implemento una clase Cor... | Python Code:
import gensim, logging, os
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
Explanation: Ejemplo de word2vec con gensim
En la siguiente celda, importamos las librerías necesarias y configuramos los mensajes de los logs.
End of explanation
class Corpus(object):
... |
14,416 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fit the flight acquisition probability model in 2017
Fit values here were computed 2017-Aug-9
This version introduces a dependence on the search box size. Search box sizes of 160 or 180 arc... | Python Code:
from __future__ import division
import re
import numpy as np
import matplotlib.pyplot as plt
from astropy.table import Table
from astropy.time import Time
import tables
from scipy import stats
import tables3_api
from chandra_aca.dark_model import get_warm_fracs
%matplotlib inline
Explanation: Fit the fligh... |
14,417 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
========================================================
Time-frequency on simulated data (Multitaper vs. Morlet)
========================================================
This examples demon... | Python Code:
# Authors: Hari Bharadwaj <hari@nmr.mgh.harvard.edu>
# Denis Engemann <denis.engemann@gmail.com>
#
# License: BSD (3-clause)
import numpy as np
from mne import create_info, EpochsArray
from mne.time_frequency import tfr_multitaper, tfr_stockwell, tfr_morlet
print(__doc__)
Explanation: ============... |
14,418 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The following will download a pretrained neural net model for the notebook on image classification.
Step1: The following checks that scikit-image is properly installed
Step2: Optional | Python Code:
import sys
print("python command used for this notebook:")
print(sys.executable)
import tensorflow as tf
print("tensorflow:", tf.__version__)
from tensorflow.keras.applications.resnet50 import preprocess_input, ResNet50
model = ResNet50(weights='imagenet')
Explanation: The following will download a pretrai... |
14,419 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Objective
Load Data, vectorize reviews to numbers
Build a basic model based on counting
Evaluate the Model
Make a first Kaggle Submission
Download Data from Kaggle
Step1: Load Data
Step2: ... | Python Code:
from __future__ import print_function # Python 2/3 compatibility
import numpy as np
import pandas as pd
from collections import Counter
from IPython.display import Image
Explanation: Objective
Load Data, vectorize reviews to numbers
Build a basic model based on counting
Evaluate the Model
Make a first Kag... |
14,420 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Background
This notebook seeks to quantify the value of leaving a certain number of tiles in the bag during the pre-endgame based on a repository of games. We will then implement these value... | Python Code:
from copy import deepcopy
import csv
from datetime import date
import numpy as np
import pandas as pd
import seaborn as sns
import time
log_folder = '../logs/'
log_file = log_folder + 'log_20200515_preendgames.csv'
todays_date = date.today().strftime("%Y%m%d")
final_spread_dict = {}
out_first_dict = {}
win... |
14,421 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Your first neural network
In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementat... | Python Code:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
Explanation: Your first neural network
In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of t... |
14,422 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
蓍草卜卦
大衍之数五十,其用四十有九。分而为二以象两,挂一以象三,揲之以四以象四时,归奇于扐以象闰。五岁再闰,故再扐而后挂。天一,地二;天三,地四;天五,地六;天七,地八;天九,地十。天数五,地数五。五位相得而各有合,天数二十有五,地数三十,凡天地之数五十有五,此所以成变化而行鬼神也。乾之策二百一十有六,坤之策百四十有四,凡三百六十,当期之日。二篇之策,万有一千五百二十,当万物... | Python Code:
import random
def sepSkyEarth(data):
sky = random.randint(1, data-2)
earth = data - sky
earth -= 1
return sky , earth
def getRemainder(num):
rm = num % 4
if rm == 0:
rm = 4
return rm
def getChange(data):
sky, earth = sepSkyEarth(data)
skyRemainder = getRemaind... |
14,423 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Toplevel
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specif... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'pcmdi', 'pcmdi-test-1-0', 'toplevel')
Explanation: ES-DOC CMIP6 Model Properties - Toplevel
MIP Era: CMIP6
Institute: PCMDI
Source ID: PCMDI-TEST-1-0
Sub-Topics: Radiative Forcings.
... |
14,424 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Mining used-car sales
This is a running log of some work on used-car saled. I have no intention to use this information for financial purposes, rather I'd like to ask the question "is there ... | Python Code:
from BeautifulSoup import BeautifulSoup
import urllib
import pandas as pd
import seaborn
import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize as so
%matplotlib inline
import seaborn as sns
sns.set_style(rc={'font.family': ['sans-serif'],'axis.labelsize': 25})
sns.set_context("notebook"... |
14,425 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Aerosol
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'ncc', 'noresm2-lmec', 'aerosol')
Explanation: ES-DOC CMIP6 Model Properties - Aerosol
MIP Era: CMIP6
Institute: NCC
Source ID: NORESM2-LMEC
Topic: Aerosol
Sub-Topics: Transport, Emiss... |
14,426 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
[2-1] 動画作成用のモジュールをインポートして、動画を表示可能なモードにセットします。
Step1: [2-2] x軸方向に移動しながら、y軸方向に落下する物体の動きを描きます。
動画のGIFファイル「animation03.gif」も同時に作成します。
Step2: [2-3] 斜め上に投げ上げた物体の動きを描きます。
動画のGIFファイル「animation04.g... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
%matplotlib nbagg
Explanation: [2-1] 動画作成用のモジュールをインポートして、動画を表示可能なモードにセットします。
End of explanation
fig = plt.figure(figsize=(4,4))
x = 0
y, vy = 0, 0
images = []
for _ in range(25):
image = plt.scatter([x],[y])
... |
14,427 | 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="#Working-with-Python-Classes" data-toc-modified-id="Working-with-Python-Class... | 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(plot_style=False)
os.chdir(path)
# 1. magic to print version
# 2. magic so that t... |
14,428 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2021 Google LLC.
Step1: Hourglass
Step2: Download ImageNet32/64 data
Downloading the datasets for evaluation requires some hacks because URLs from tensorflow_datasets are invalid... | 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
# distributed und... |
14,429 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Kód k vylepšení
Step3: Vylepšená verze
Step4: Co je tady navíc? | Python Code:
import ai
import utils
from random import randrange
def vyhodnot(pole):
# Funkce vezme hrací pole a vrátí výsledek
# na základě aktuálního stavu hry
if "xxx" in pole: #Vyhrál hráč s křížky
return "x"
elif "ooo" in pole: #Vyhrál hráč s kolečky.
return "o"
elif "-" not in ... |
14,430 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Ocean
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify d... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'nerc', 'hadgem3-gc31-hm', 'ocean')
Explanation: ES-DOC CMIP6 Model Properties - Ocean
MIP Era: CMIP6
Institute: NERC
Source ID: HADGEM3-GC31-HM
Topic: Ocean
Sub-Topics: Timestepping F... |
14,431 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have a data frame with one (string) column and I'd like to split it into two (string) columns, with one column header as 'fips' and the other 'row' | Problem:
import pandas as pd
df = pd.DataFrame({'row': ['114 AAAAAA', '514 ENENEN',
'1926 HAHAHA', '0817 O-O,O-O',
'998244353 TTTTTT']})
def g(df):
return pd.DataFrame(df.row.str.split(' ',1).tolist(), columns = ['fips','row'])
df = g(df.copy()) |
14,432 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Authors.
Step1: Install TensorFlow for C
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: Linker
On Linux/ma... | 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... |
14,433 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Differential Analysis with both GEO and RNA-Seq
Import everything from the imports notebook. This reads in all of the expression data as well as the functions needed to analyse differential ... | Python Code:
import NotebookImport
from Imports import *
import seaborn as sns
sns.set_context('paper',font_scale=1.5)
sns.set_style('white')
Explanation: Differential Analysis with both GEO and RNA-Seq
Import everything from the imports notebook. This reads in all of the expression data as well as the functions needed... |
14,434 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
jPCA
Churchland, Mark M., et al. "Neural population dynamics during reaching." Nature 487.7405 (2012)
Step1: The data can be loaded with pandas
Step2: It's the responses of theta-modulate... | Python Code:
import numpy as np
from sklearn.decomposition import PCA
import pandas as pd
from pylab import *
Explanation: jPCA
Churchland, Mark M., et al. "Neural population dynamics during reaching." Nature 487.7405 (2012): 51.
End of explanation
data = pd.read_hdf("swr_modth.h5")
Explanation: The data can be loaded ... |
14,435 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Validation of MCOE
This notebook runs sanity checks on the results of the calculations of marginal cost of electricity (MCOE) that we do based on EIA 923 and EIA 860. Currently this only inc... | Python Code:
%load_ext autoreload
%autoreload 2
import sys
import pandas as pd
import numpy as np
import sqlalchemy as sa
import pudl
import warnings
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
handler = logging.StreamHandler(stream=sys.stdout)
formatter = logging.Formatter('%(message)s')
... |
14,436 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<span style="font-size
Step2: Важно
- Не забывайте делать GradCheck, чтобы проверить численно что производные правильные, обычно с первого раза не выходит никогда, пример тут https
Step4:... | Python Code:
%matplotlib inline
from time import time, sleep
import numpy as np
import matplotlib.pyplot as plt
from IPython import display
Explanation: <span style="font-size: 14pt">MIPT, Advanced ML, Spring 2018</span>
<h1 align="center">Organization Info</h1>
Дедлайн 20 апреля 2018 23:59 для всех групп.
В качестве р... |
14,437 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="imgs/header.png">
Visualization techniques for scalar fields in VTK + Python
Goals
Inspect VTK Objects via the qtconsole for Jupyter (using the magic %qtconsole)
Including a new fi... | Python Code:
import vtk
#help(vtk.vtkRectilinearGridReader())
rectGridReader = vtk.vtkRectilinearGridReader()
rectGridReader.SetFileName("data/jet4_0.500.vtk")
# do not forget to call "Update()" at the end of the reader
rectGridReader.Update()
rectGridOutline = vtk.vtkRectilinearGridOutlineFilter()
rectGridOutline.SetI... |
14,438 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Optimization of Non-Differentiable Functions Using Differential Evolution
This code is provided as supplementary material of the lecture Machine Learning and Optimization in Communications (... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
Explanation: Optimization of Non-Differentiable Functions Using Differential Evolution
This code is provided as supplementary material of the lecture Machine Learning and Optimization in Communications (MLOC).<br>
This code illustrates:
* Use of differenti... |
14,439 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Demonstrate impact of whitening on source estimates
This example demonstrates the relationship between the noise covariance
estimate and the MNE / dSPM source amplitudes. It computes source ... | Python Code:
# Author: Denis A. Engemann <denis.engemann@gmail.com>
#
# License: BSD (3-clause)
import os
import os.path as op
import numpy as np
from scipy.misc import imread
import matplotlib.pyplot as plt
import mne
from mne import io
from mne.datasets import spm_face
from mne.minimum_norm import apply_inverse, make... |
14,440 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Batch Normalization – Lesson
What is it?
What are it's benefits?
How do we add it to a network?
Let's see it work!
What are you hiding?
What is Batch Normalization?<a id='theory'></a>
Batch ... | Python Code:
# Import necessary packages
import tensorflow as tf
import tqdm
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# Import MNIST data so we have something for our experiments
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_... |
14,441 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Errors and Crashes
Probably the most important chapter in this section is about how to handle error and crashes. Because at the beginning you will run into a few.
For example
Step1: Investi... | Python Code:
from nipype import SelectFiles, Node, Workflow
from os.path import abspath as opap
from nipype.interfaces.fsl import MCFLIRT, IsotropicSmooth
# Create SelectFiles node
templates={'func': '{subject_id}/func/{subject_id}_task-flanker_run-1_bold.nii.gz'}
sf = Node(SelectFiles(templates),
name='selec... |
14,442 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial
Step1: 1. Produce some samples
Recalling our Probability Essentials tutorial, let's jump right into the case of 2 correlated Gaussian variables.
First we need some samples to work ... | Python Code:
exec(open('tbc.py').read()) # define TBC and TBC_above
import numpy as np
import scipy.stats as st
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Tutorial: Working with Samples
In practice, we almost always work with samples from probability distri... |
14,443 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Problem Statement
There are influenza viruses that are collected from the "environment", or have an "unknown" host. How do we infer which hosts it came from? Well, that sounds like a Classif... | Python Code:
# Load the sequences into memory
sequences = [s for s in SeqIO.parse('data/20160127_HA_prediction.fasta', 'fasta') if len(s.seq) == 566] # we are cheating and not bothering with an alignment.
len(sequences)
# Load the sequence IDs into memory
seqids = [s.id for s in SeqIO.parse('data/20160127_HA_predictio... |
14,444 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
911 Calls Capstone Project
For this capstone project we will be analyzing some 911 call data from Kaggle. The data contains the following fields
Step1: Import visualization libraries and se... | Python Code:
import numpy as np
import pandas as pd
Explanation: 911 Calls Capstone Project
For this capstone project we will be analyzing some 911 call data from Kaggle. The data contains the following fields:
lat : String variable, Latitude
lng: String variable, Longitude
desc: String variable, Description of the Eme... |
14,445 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Mover contenido de un usuario existente a otro nuevo
Step1: Cree una conexión con el portal.
Step2: Establecer variables para el usuario actual que se está realizando la transición y para ... | Python Code:
from arcgis.gis import *
Explanation: Mover contenido de un usuario existente a otro nuevo
End of explanation
gis = GIS("https://ags-enterprise4.aeroterra.com/arcgis/", "PythonApi", "test123456", verify_cert=False)
Explanation: Cree una conexión con el portal.
End of explanation
orig_userid = "afernandez"
... |
14,446 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data Science Summer School - Split '17
5. Generating images of digits with Generative Adversarial Networks
Step1: Goals
Step5: What are we going to do with the data?
We have $70000$ images... | Python Code:
%matplotlib inline
%load_ext autoreload
%autoreload 2
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import os, util
Explanation: Data Science Summer School - Split '17
5. Generating images of digits with Generative Adversarial Networks
End of explanation
data_folder = 'data'; d... |
14,447 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Advanced
Step1: Default Animations
By passing animate=True to b.show(), b.savefig(), or the final call to b.plot() along with save=filename or show=True will create an animation instead of ... | Python Code:
#!pip install -I "phoebe>=2.4,<2.5"
import phoebe
from phoebe import u # units
import numpy as np
import matplotlib.pyplot as plt
logger = phoebe.logger()
b = phoebe.default_binary()
times = np.linspace(0,1,51)
b.add_dataset('lc', compute_times=times, dataset='lc01')
b.add_dataset('orb', compute_times=time... |
14,448 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Phylogenetics Tutorial
Run a phylogenetics project, all in one place!
This tutorial will cover
Step1: 1. Inititialize a phylogenetics project
This creates a folder in your current working d... | Python Code:
# import packages
import phylogenetics as phy
import phylogenetics.tools as tools
import phylopandas as ph
import pandas as pd
from phylovega import TreeChart
Explanation: Phylogenetics Tutorial
Run a phylogenetics project, all in one place!
This tutorial will cover:
Project initialization and data input/o... |
14,449 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This script shows how to use the existing code in opengrid
to create (a) a timeseries plot and (b) a load curve of gas, water or elektricity usage.
Todo
Step1: Script settings
Step2: Fill ... | Python Code:
import os
import sys
import inspect
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.dates import HourLocator, DateFormatter, AutoDateLocator
import datetime as dt
import pytz
import pandas as pd
import pdb
import tmpo
from opengrid import config
from opengrid.library import houseprint
c ... |
14,450 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generated Data Extrapolation
In this example you will be generating some example data and extrapolate this
using the basic potential extrapolator.
You can start by importing the necessary mo... | Python Code:
# Module imports
from solarbextrapolation.map3dclasses import Map3D
#from solarbextrapolation.potential_field_extrapolator import PotentialExtrapolator
from solarbextrapolation.extrapolators import PotentialExtrapolator
from solarbextrapolation.example_data_generator import generate_example_data, dummyData... |
14,451 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Langevin Integrator Check
The toy_dynamics subpackage provides an integrator called LangevinBAOABIntegrator, which is based on a paper by Leimkuhler and Matthews. This notebook uses the toy_... | Python Code:
import openpathsampling.engines.toy as toys
import openpathsampling as paths
import numpy as np
Explanation: Langevin Integrator Check
The toy_dynamics subpackage provides an integrator called LangevinBAOABIntegrator, which is based on a paper by Leimkuhler and Matthews. This notebook uses the toy_dynamics... |
14,452 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generators
A generator is essentially an iterator over an object (say a dataset). You get a small chunk of data obtained through "iterating over the larger object" every time you make a call... | Python Code:
## Example from PEP 0255
def fib():
a, b = 0, 1
while 1:
yield b
a, b = b, a + b
Explanation: Generators
A generator is essentially an iterator over an object (say a dataset). You get a small chunk of data obtained through "iterating over the larger object" every time you make a cal... |
14,453 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python analysis of output from MATLAB CNMF-E implementation
Analyze tif stacks using batch_cnmf.py and then open the resultant analysis products using a workflow like the one shown below.
Th... | Python Code:
import sys
import os
from matplotlib import pyplot as plt
import scipy.sparse as sparse
import scipy.io as sio
import numpy as np
import python_utils as utils
%matplotlib inline
Explanation: Python analysis of output from MATLAB CNMF-E implementation
Analyze tif stacks using batch_cnmf.py and then open the... |
14,454 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Installation
Make sure to have all the required software installed after proceeding.
For installation help, please consult the school guide.
Python Basics
Step1: Basic Math Operations
Step... | Python Code:
print('Hello World!')
Explanation: Installation
Make sure to have all the required software installed after proceeding.
For installation help, please consult the school guide.
Python Basics
End of explanation
print(3 + 5)
print(3 - 5)
print(3 * 5)
print(3 ** 5)
# Observation: this code gives different res... |
14,455 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
python introduction
analyzing patient data
Step1: data types
Step2: indices start at 0
and intervals exclude the last value
Step3: calculations on arrays of values
Step4: importing modul... | Python Code:
import numpy
data = numpy.loadtxt(fname='inflammation-01.csv', delimiter=',')
data
%whos
print(data)
Explanation: python introduction
analyzing patient data
End of explanation
print(type(data))
print(data.dtype)
print(data.shape)
Explanation: data types
End of explanation
print('first value in data:', data... |
14,456 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Intermediate Python - List Comprehension
In this Colab, we will discuss list comprehension, an extremely useful and idiomatic way to process lists in Python.
List Comp... | 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... |
14,457 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Table of Contents
Intro
Regression
Data
Residuals and Cost
Regression (Scipy)
Polynomial Regression
Solve (SKlearn)
Gradient Descent
Training Animation
Intro
Exploratory notebook related to ... | Python Code:
import numpy as np
import seaborn as sns
import pandas as pd
from matplotlib import pyplot as plt, animation, rc
%matplotlib notebook
#%matplotlib inline
Explanation: Table of Contents
Intro
Regression
Data
Residuals and Cost
Regression (Scipy)
Polynomial Regression
Solve (SKlearn)
Gradient Descent
Trainin... |
14,458 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Opreaciones Matematicas
Suma
Step1: Multiplicación
Step2: División
Step3: Potencia
Step4: Funciones Trigonometricas
En las siguientes celdas vamos a calcular los valores de funciones co... | Python Code:
2+3
Explanation: Opreaciones Matematicas
Suma : $2+3$
End of explanation
2*3
Explanation: Multiplicación: $2x3$
End of explanation
2/3
Explanation: División: $\frac{2}{3}$
End of explanation
2**3
Explanation: Potencia: $ 2^{3}$
End of explanation
# Importar una libreria en Python
import numpy as np # el co... |
14,459 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Landice
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', 'csir-csiro', 'sandbox-3', 'landice')
Explanation: ES-DOC CMIP6 Model Properties - Landice
MIP Era: CMIP6
Institute: CSIR-CSIRO
Source ID: SANDBOX-3
Topic: Landice
Sub-Topics: Glaciers... |
14,460 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Measuring monotonic relationships
By Evgenia "Jenny" Nitishinskaya and Delaney Granizo-Mackenzie with example algorithms by David Edwards
Reference
Step1: Spearman Rank Correlation
Intuitio... | Python Code:
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
import math
# Example of ranking data
l = [10, 9, 5, 7, 5]
print 'Raw data: ', l
print 'Ranking: ', list(stats.rankdata(l, method='average'))
Explanation: Measuring monotonic relationships
By Evgenia "Jenny" Nitishinskaya and De... |
14,461 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using GeoPandas with Rasterio to sample point data
This example shows how to use GeoPandas with Rasterio. Rasterio is a package for reading and writing raster data.
In this example a set of... | Python Code:
import geopandas
import rasterio
import matplotlib.pyplot as plt
from shapely.geometry import Point
Explanation: Using GeoPandas with Rasterio to sample point data
This example shows how to use GeoPandas with Rasterio. Rasterio is a package for reading and writing raster data.
In this example a set of vec... |
14,462 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Vertex SDK
Step1: Install the latest GA version of google-cloud-storage library as well.
Step2: Restart the kernel
Once you've installed the additional packages, you need to restart the no... | Python Code:
import os
# Google Cloud Notebook
if os.path.exists("/opt/deeplearning/metadata/env_version"):
USER_FLAG = "--user"
else:
USER_FLAG = ""
! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG
Explanation: Vertex SDK: Custom training tabular regression model for online prediction
<table align="... |
14,463 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Rock, Paper, Scissors or... People are Predictable
The NY Times created a Rock, Paper, Scissors bot. If you try it, chances are it'll win handily. No matter how hard you try, you're going to... | Python Code:
import numpy as np
from numpy.linalg import matrix_power
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Rock, Paper, Scissors or... People are Predictable
The NY Times created a Rock, Paper, Scissors bot. If you try it, chances are it'll win handily. No matter how hard you try, you're goin... |
14,464 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sentiment Classification & How To "Frame Problems" for a Neural Network
by Andrew Trask
Twitter
Step1: Note
Step2: Lesson
Step3: Project 1
Step4: We'll create three Counter objects, one ... | Python Code:
def pretty_print_review_and_label(i):
print(labels[i] + "\t:\t" + reviews[i][:80] + "...")
g = open('reviews.txt','r') # What we know!
reviews = list(map(lambda x:x[:-1],g.readlines()))
g.close()
g = open('labels.txt','r') # What we WANT to know!
labels = list(map(lambda x:x[:-1].upper(),g.readlines())... |
14,465 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial
Step1: Initializing a new function
There are two ways to create a function $f
Step2: Notice how the print built-in and the to_latex() method will show human-readable output.
With ... | Python Code:
# Imports from abelian
from abelian import LCA, HomLCA, LCAFunc
# Other imports
import math
import matplotlib.pyplot as plt
from IPython.display import display, Math
def show(arg):
return display(Math(arg.to_latex()))
Explanation: Tutorial: Functions on LCAs
This is an interactive tutorial written with... |
14,466 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial 1 - Geometry
In this tutorial we explore how simulated geometries can be defined and initial magnetisation states specified. The package we use to define finite difference meshes an... | Python Code:
import discretisedfield as df
%matplotlib inline
Explanation: Tutorial 1 - Geometry
In this tutorial we explore how simulated geometries can be defined and initial magnetisation states specified. The package we use to define finite difference meshes and fields is discretisedfield.
End of explanation
L = 10... |
14,467 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Bar Chart Race in Python with Matplotlib
~In roughly less than 50 lines of code.
How easy would it be to re-create bar chart race in Python using Jupyter and Matplotlib?
Turns out, in less t... | Python Code:
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib.animation as animation
from IPython.display import HTML
Explanation: Bar Chart Race in Python with Matplotlib
~In roughly less than 50 lines of code.
How easy would it be to re-create bar chart race in ... |
14,468 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Teknisk Tirsdag
Step1: Hvordan ser vores originale datasæt ud?
nb! Der kommer en advarsel når dette køres, og dette er måske en ikke dårlig ting.
Step3: Resning af data
Du konstatere hurti... | Python Code:
#PURE PYTHON!!!!
from IPython.display import display, Markdown
import numpy as np
import pandas as pd
import os
import re
# path = %pwd
# path += '/fifa-18-demo-player-dataset/CompleteDataset.csv'
# Til Windows
path = '.\\Downloads\\Fifa2018-master\\Fifa2018-master'
path += '\\fifa-18-demo-player-dataset\\... |
14,469 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Ocean
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify d... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'ec-earth-consortium', 'sandbox-3', 'ocean')
Explanation: ES-DOC CMIP6 Model Properties - Ocean
MIP Era: CMIP6
Institute: EC-EARTH-CONSORTIUM
Source ID: SANDBOX-3
Topic: Ocean
Sub-Topi... |
14,470 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Backscattering Efficiency Validation
Scott Prahl
Apr 2021
If miepython is not installed, uncomment the following cell (i.e., delete the #) and run (shift-enter)
Step1: Wiscombe tests
Since ... | Python Code:
#!pip install --user miepython
import numpy as np
import matplotlib.pyplot as plt
try:
import miepython
except ModuleNotFoundError:
print('miepython not installed. To install, uncomment and run the cell above.')
print('Once installation is successful, rerun this cell again.')
Explanation: Backs... |
14,471 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I am trying to groupby counts of dates per month and year in a specific output. I can do it per day but can't get the same output per month/year. | Problem:
import pandas as pd
d = ({'Date': ['1/1/18','1/1/18','1/1/18','2/1/18','3/1/18','1/2/18','1/3/18','2/1/19','3/1/19'],
'Val': ['A','A','B','C','D','A','B','C','D']})
df = pd.DataFrame(data=d)
def g(df):
df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%y')
y = df['Date'].dt.year
m = df['D... |
14,472 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Imports
Step1: Read the data
This a breast cancer diagnostic dataset
Step2: Train/test split
Step3: Modelling with standard train/test split
Step4: Modelling with k-fold cross validation | Python Code:
# Import pandas and numpy
import pandas as pd
import numpy as np
# Import the classifiers we will be using
from sklearn.naive_bayes import GaussianNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
# Impo... |
14,473 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
shellOneLiner モジュールの紹介
Python を通じて大量のデータを扱う場合には、 Unix コマンドを利用する事で素早く処理を行う事が出来る場合がある。
shellOneLiner モジュールは、 Python コード中からシェルのワンライナーを呼び出し、 Python から Unix コマンドへのデータの受け渡し、ファイルからのデータの読み出し、 Unix コ... | Python Code:
ol = shellOneLiner.ShellOneLiner('echo Hello; LANG=C date; cat datafile')
head(ol,5)
Explanation: shellOneLiner モジュールの紹介
Python を通じて大量のデータを扱う場合には、 Unix コマンドを利用する事で素早く処理を行う事が出来る場合がある。
shellOneLiner モジュールは、 Python コード中からシェルのワンライナーを呼び出し、 Python から Unix コマンドへのデータの受け渡し、ファイルからのデータの読み出し、 Unix コマンドによるデータの処理、 Pytho... |
14,474 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Intro
At the end of this lesson, you will be able to use transfer learning to build highly accurate computer vision models for your custom purposes, even when you have relatively little data... | Python Code:
from IPython.display import YouTubeVideo
YouTubeVideo('mPFq5KMxKVw', width=800, height=450)
Explanation: Intro
At the end of this lesson, you will be able to use transfer learning to build highly accurate computer vision models for your custom purposes, even when you have relatively little data.
Lesson
End... |
14,475 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Advanced Topics
Step1: Frequency tables
Ibis provides the value_counts API, just like pandas, for computing a frequency table for a table column or array expression. You might have seen it ... | Python Code:
import os
import ibis
ibis.options.interactive = True
connection = ibis.sqlite.connect(os.path.join('data', 'geography.db'))
Explanation: Advanced Topics: Analytics Tools
Setup
End of explanation
countries = connection.table('countries')
countries.continent.value_counts()
Explanation: Frequency tables
Ibis... |
14,476 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Load, filter, export the NSQD Dataset
The cell below imports the libaries we need and defines some function that help up clean up the NSQD
Step1: Create a raw data set, then compute season ... | Python Code:
import numpy
import wqio
import pynsqd
import pycvc
def get_cvc_parameter(nsqdparam):
try:
cvcparam = list(filter(
lambda p: p['nsqdname'] == nsqdparam, pycvc.info.POC_dicts
))[0]['cvcname']
except IndexError:
cvcparam = numpy.nan
return cvcparam
def fix_nsq... |
14,477 | 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', 'cccma', 'canesm5', 'seaice')
Explanation: ES-DOC CMIP6 Model Properties - Seaice
MIP Era: CMIP6
Institute: CCCMA
Source ID: CANESM5
Topic: Seaice
Sub-Topics: Dynamics, Thermodynamics,... |
14,478 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Dreams (with Caffe)
This notebook demonstrates how to use the Caffe neural network framework to
produce "dream" visuals shown in the
Google Research blog post. #deepdream
Dependencies... | Python Code:
# imports and basic notebook setup
from cStringIO import StringIO
import numpy as np
import scipy.ndimage as nd
import PIL.Image
from IPython.display import clear_output, Image, display
from google.protobuf import text_format
import caffe
# If your GPU supports CUDA and Caffe was built with CUDA support,
#... |
14,479 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exam
Problem 2. Interpolation
Linear Spline Interpolation visualization, courtesy of codecogs
Interpolation is a method of curve fitting.
In this problem, spline interpolation is considered
... | Python Code:
from IPython.display import display
import pandas as pd
import matplotlib.pyplot
%matplotlib inline
index = ['f(x)']
columns = [-2, 0, 2, 3]
data = [[-3, -5, 9, 22]]
df = pd.DataFrame(data, index=index, columns=columns)
print(df)
# for brevity, we will write it like this
index = [' x', 'f(x)']
columns = [... |
14,480 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Speci... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'cmcc', 'sandbox-1', 'atmoschem')
Explanation: ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era: CMIP6
Institute: CMCC
Source ID: SANDBOX-1
Topic: Atmoschem
Sub-Topics: Transport, Emi... |
14,481 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Recreating Ling IMMI (2017)
In this notebook, we will recreate some key results from Ling et al. IMMI (2017). We will show that the errors produced from the Random Forest implemented in lolo... | Python Code:
%matplotlib inline
from matplotlib import pyplot as plt
from matminer.data_retrieval.retrieve_Citrine import CitrineDataRetrieval
from matminer.featurizers.base import MultipleFeaturizer
from matminer.featurizers import composition as cf
from lolopy.learners import RandomForestRegressor
from sklearn.model_... |
14,482 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Image Classification
In this project, you'll classify images from the CIFAR-10 dataset. The dataset consists of airplanes, dogs, cats, and other objects. You'll preprocess the images... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
from urllib.request import urlretrieve
from os.path import isfile, isdir
from tqdm import tqdm
import problem_unittests as tests
import tarfile
cifar10_dataset_folder_path = 'cifar-10-batches-py'
# Use Floyd's cifar-10 dataset if present
floyd_cifa... |
14,483 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pandas
Fast, flexible, and expressive data structures designed to make working with “relational” or “labeled” data both easy and intuitive. It aims to be the fundamental high-level building ... | Python Code:
import pandas as pd
import numpy as np
Explanation: Pandas
Fast, flexible, and expressive data structures designed to make working with “relational” or “labeled” data both easy and intuitive. It aims to be the fundamental high-level building block for doing practical, real world data analysis in Python.
pa... |
14,484 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Tuples
"Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogene... | Python Code:
# Create a list of countries, then print the results
allies = ['USA','UK','France','New Zealand',
'Australia','Canada','Poland']; allies
# Print the length of the list
len(allies)
# Add an item to the list, then print the results
allies.append('China'); allies
# Sort list, then print the results
... |
14,485 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Forecast to Power Tutorial
This tutorial will walk through the process of going from Unidata forecast model data to AC power using the SAPM.
Table of contents
Step1: Load Forecast data
pvli... | Python Code:
# built-in python modules
import datetime
import inspect
import os
# scientific python add-ons
import numpy as np
import pandas as pd
# plotting stuff
# first line makes the plots appear in the notebook
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib as mpl
# seaborn makes your plots ... |
14,486 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Objetive of the NMF is Find two non-negative matrices (W, H) whose product approximates the non-negative matrix X.
This factorization can be used for example for dimensionality reduction... | Python Code:
import numpy as np
from sklearn.decomposition import NMF
Explanation: The Objetive of the NMF is Find two non-negative matrices (W, H) whose product approximates the non-negative matrix X.
This factorization can be used for example for dimensionality reduction, source separation or topic extraction.
Using ... |
14,487 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
About
This notebook demonstrates stacking machine learning algorithm - folding, which physics use in their analysis.
Step1: Loading data
Step2: Training variables
Step3: Folding strategy ... | Python Code:
%pylab inline
Explanation: About
This notebook demonstrates stacking machine learning algorithm - folding, which physics use in their analysis.
End of explanation
import numpy, pandas
from rep.utils import train_test_split
from sklearn.metrics import roc_auc_score
sig_data = pandas.read_csv('toy_datasets/t... |
14,488 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
REINFORCE in Sonnet
This notebook implements a basic reinforce algorithm a.k.a. policy gradient for CartPole env.
It has been deliberately written to be as simple and human-readable.
Authors... | Python Code:
import gym
import numpy as np, pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
env = gym.make("CartPole-v0")
#gym compatibility: unwrap TimeLimit
if hasattr(env,'env'):
env=env.env
env.reset()
n_actions = env.action_space.n
state_dim = env.observation_space.shape
plt.imshow(env.render("... |
14,489 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Checkerboard Microstructure
Introduction - What are 2-Point Spatial Correlations (also called 2-Point Statistics)?
The purpose of this example is to introduce 2-point spatial correlations an... | Python Code:
%matplotlib inline
%load_ext autoreload
%autoreload 2
import numpy as np
import matplotlib.pyplot as plt
Explanation: Checkerboard Microstructure
Introduction - What are 2-Point Spatial Correlations (also called 2-Point Statistics)?
The purpose of this example is to introduce 2-point spatial correlations a... |
14,490 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Neural Networks
Step1: Part 01a -- Simple neural network as XOR gate using sigmoid activation function
Step3: Create sigmoid function
Step4: Plotting sigmoid activation fu... | Python Code:
if input_1 == input_2:
output = 0
else:
output = 1
Explanation: Introduction to Neural Networks:
Author:
Dr. Rahul Remanan
Dr. Jesse Kanter
CEO and Chief Imagination Officer
Moad Computer
Launch this notebook in Google Colab
This is a hands-on workshop notebook on deep-learning using python 3. In this... |
14,491 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ipytest Summary
ipytest aims to make testing code in IPython notebooks easy. At its core, it offers a way to run pytest tests inside the notebook environment. It is also designed to make the... | Python Code:
import ipytest
ipytest.autoconfig()
Explanation: ipytest Summary
ipytest aims to make testing code in IPython notebooks easy. At its core, it offers a way to run pytest tests inside the notebook environment. It is also designed to make the transfer of the tests into proper python modules easy by supporting... |
14,492 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Load Data
Step2: Split Data For Cross Validation
Step3: Standardize Feature Data | Python Code:
from sklearn import datasets
import numpy as np
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import StandardScaler
Explanation: Title: Preprocessing Iris Data
Slug: preprocessing_iris_data
Summary: Preprocessing iris data using scikit learn.
Date: 2016-09-21 12:00
Catego... |
14,493 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
QuTiP example
Step1: Hamiltonian
Step2: Software version | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from qutip import *
Explanation: QuTiP example: Dynamics of a Spin Chain
J.R. Johansson and P.D. Nation
For more information about QuTiP see http://qutip.org
End of explanation
def integrate(N, h, Jx, Jy, Jz, psi0, tlist, gamma, solver):... |
14,494 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Teori dan Praktek Alokasi Aset Portfolio yang Optimal
Referensi dan Atribusi
Materi dari studi ini diambil dari minggu kedua kursus Introduction to Portfolio Construction and Analysis with P... | Python Code:
import pandas as pd
import numpy as np
%matplotlib inline
# Load data returns dari sektor2
ind = pd.read_csv("ind30_m_vw_rets.csv", header=0, index_col=0)/100
# Ubah index jadi perioda bulanan
ind.index = pd.to_datetime(ind.index, format="%Y%m").to_period('M')
# Hilangkan spasi pada kolom
ind.columns = ind... |
14,495 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Day 18
Step1: Edge cases
There are edge cases when generating tiles that are in the first or the last position. In the first position, the left upper tile does not exist, in which case, we ... | Python Code:
SAFE = '.'
TRAP = '^'
def is_safe(tile):
return tile == SAFE
def is_trap(tile):
return tile == TRAP
Explanation: Day 18: Like a Rogue
author: Harshvardhan Pandit
license: MIT
link to problem statement
As you enter this room, you hear a loud click! Some of the tiles in the floor here seem to be pres... |
14,496 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1. Aggregate all blast results
Step1: 2. Write annotated results out | Python Code:
blast_file_regex = re.compile(r"(blast[np])_vs_([a-zA-Z0-9_]+).tsv")
blast_cols = ["query_id","subject_id","pct_id","ali_len","mism",
"gap_open","q_start","q_end","s_start","s_end",
"e_value","bitscore","q_len","s_len","s_gi",
"s_taxids","s_scinames","s_names","q_co... |
14,497 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Cosmological Analysis with SNe (Topic Five)
Renée Hložek
Preparing for SN Science in the LSST era
Step1: Now that we have called our distance modulus once and know how to do it, we can also... | Python Code:
%matplotlib inline
import sys, platform, os
from matplotlib import pyplot as plt
import numpy as np
import astropy as ap
import pylab as pl
# we start by setting the cosmological parameters of interest, and reading in our data
cosmoparams_orig = [70., 0.3, 0.7, -0.9, 0.2]
redshift=np.arange(0.001,1.3,0.01)... |
14,498 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Development Notes
This notebook documents Daniel's attempt to re-create Evan's box-model.
LOG
1/14 12
Step3: The model itself is a simple, one-box model tracking the volume ($V$, in m$^3$)... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style='ticks', context='talk')
import numpy as np
import pandas as pd
Explanation: Development Notes
This notebook documents Daniel's attempt to re-create Evan's box-model.
LOG
1/14 12:45PM - initial setup, reading code
End o... |
14,499 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Subset the genes based on their total number of transcripts
Step1: Look at gene's median transcript count
Step2: Clean data matrix to be compatible with the cluster labels and identities
C... | Python Code:
(n_transcripts_per_gene > 1e3).sum()
n_transcripts_per_gene[n_transcripts_per_gene > 1e4]
Explanation: Subset the genes based on their total number of transcripts
End of explanation
median_transcripts_per_gene = table1_t.median()
median_transcripts_per_gene.head()
sns.distplot(median_transcripts_per_gene)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.