Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
15,500 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Import PDK
To import a PDK in gdsfactory you need 2 things
Step1: You can write GDS files only
Step2: Or GDS with YAML metadata information (ports, settings, cells ...)
Step3: This create... | Python Code:
import gdsfactory as gf
c = gf.components.mzi()
c
Explanation: Import PDK
To import a PDK in gdsfactory you need 2 things:
GDS file with all the cells that you want to import in the PDK (or separate GDS files, one per cell)
Klayout layer properties files, to define the Layers that you can use when creating... |
15,501 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Table of Contents
<p><div class="lev2 toc-item"><a href="#Setup" data-toc-modified-id="Setup-01"><span class="toc-item-num">0.1 </span>Setup</a></div><div class="lev2 toc-item"><a... | Python Code:
from theano.sandbox import cuda
%matplotlib inline
import utils; reload(utils)
from utils import *
from __future__ import division, print_function
Explanation: Table of Contents
<p><div class="lev2 toc-item"><a href="#Setup" data-toc-modified-id="Setup-01"><span class="toc-item-num">0.1 </span>S... |
15,502 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PyGSLIB
QQ and PP plots
Step1: Getting the data ready for work
If the data is in GSLIB format you can use the function pygslib.gslib.read_gslib_file(filename) to import the data into a Pand... | Python Code:
#general imports
import pygslib
Explanation: PyGSLIB
QQ and PP plots
End of explanation
#get the data in gslib format into a pandas Dataframe
cluster= pygslib.gslib.read_gslib_file('../datasets/cluster.dat')
true= pygslib.gslib.read_gslib_file('../datasets/true.dat')
true['Declustering Weight'] = 1
E... |
15,503 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Running Code
First and foremost, the Jupyter Notebook is an interactive environment for writing and running code. The notebook is capable of running code in a wide range of languages. Howeve... | Python Code:
a = 10
print(a)
Explanation: Running Code
First and foremost, the Jupyter Notebook is an interactive environment for writing and running code. The notebook is capable of running code in a wide range of languages. However, each notebook is associated with a single kernel. This notebook is associated with t... |
15,504 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: CSV 데이터 로드
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https
Step2: 데이터 로드하기
시작하려면 CSV 파일의 상단을 보고 형식이 어떻게... | 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... |
15,505 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<table>
<tr align=left><td><img align=left src="./images/CC-BY.png">
<td>Text provided under a Creative Commons Attribution license, CC-BY. All code is made available under the FSF-approve... | Python Code:
import numpy as np
import scipy.linalg as la
import matplotlib.pyplot as plt
% matplotlib inline
Explanation: <table>
<tr align=left><td><img align=left src="./images/CC-BY.png">
<td>Text provided under a Creative Commons Attribution license, CC-BY. All code is made available under the FSF-approved MIT l... |
15,506 | Given the following text description, write Python code to implement the functionality described.
Description:
Check if a matrix contains a square submatrix with 0 as boundary element
Function checks if square with all 0 's in boundary exists in the matrix ; r1 is the top row , c1 is the left col r2 is the bottom row ,... | Python Code:
def squareOfZeroes() :
global matrix , cache
lastIdx = len(matrix ) - 1
return hasSquareOfZeroes(0 , 0 , lastIdx , lastIdx )
def hasSquareOfZeroes(r1 , c1 , r2 , c2 ) :
global matrix , cache
if(r1 >= r2 or c1 >= c2 ) :
return False
key =(str(r1 ) + ' - ' + str(c1 ) + ' - ' + str(r2 )... |
15,507 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Source localization with MNE, dSPM, sLORETA, and eLORETA
The aim of this tutorial is to teach you how to compute and apply a linear
minimum-norm inverse method on evoked/raw/epochs data.
Ste... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.datasets import sample
from mne.minimum_norm import make_inverse_operator, apply_inverse
Explanation: Source localization with MNE, dSPM, sLORETA, and eLORETA
The aim of this tutorial is to teach you how to compute and apply a linear
mi... |
15,508 | 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', 'csir-csiro', 'sandbox-1', 'seaice')
Explanation: ES-DOC CMIP6 Model Properties - Seaice
MIP Era: CMIP6
Institute: CSIR-CSIRO
Source ID: SANDBOX-1
Topic: Seaice
Sub-Topics: Dynamics, T... |
15,509 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Intorduction to Pandas - Pan(el)-da(ta)-s
Laszlo Tetenyi
Step1: Survey of Consumer Finances (SCF) 2013
Load and explore data from the SCF website - note that this data cannot be loaded by 2... | Python Code:
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import requests, zipfile, io # So that we can download and unzip files
Explanation: Intorduction to Pandas - Pan(el)-da(ta)-s
Laszlo Tetenyi
End of explanation
r = requests.get('http://www.federalreserve.gov/econresdata/scf/files/scfp20... |
15,510 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Finding the closed-form solution for transition probabilities
Here we describe the process of finding all turning angle sequences and their accompanying volumes using a 2D example.
Finite d... | Python Code:
%pylab inline
from mittens.utils import *
odf_vertices, odf_faces = get_dsi_studio_ODF_geometry("odf4")
# select only the vertices in the x,y plane
ok_vertices = np.abs(odf_vertices[:,2]) < 0.01
odf_vertices = odf_vertices[ok_vertices]
def draw_vertex(ax, vertex, color="r"):
ax.plot((0,vertex[0]), (0,v... |
15,511 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Astronomical Spectroscopy
To generate publication images change Matplotlib backend to nbagg
Step1: Spectral Lines
Spectral lines can be used to identify the chemical
composition of stars. I... | Python Code:
%matplotlib inline
import numpy as np
import astropy.analytic_functions
import astropy.io.fits
import matplotlib.pyplot as plt
wavelens = np.linspace(100, 30000, num=1000)
temperature = np.array([5000, 4000, 3000]).reshape(3, 1)
with np.errstate(all='ignore'):
flux_lam = astropy.analytic_functions.blac... |
15,512 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In this exercise, you will leverage what you've learned to tune a machine learning model with cross-validation.
Setup
The questions below will give you feedback on your work. Run the followi... | Python Code:
# Set up code checking
import os
if not os.path.exists("../input/train.csv"):
os.symlink("../input/home-data-for-ml-course/train.csv", "../input/train.csv")
os.symlink("../input/home-data-for-ml-course/test.csv", "../input/test.csv")
from learntools.core import binder
binder.bind(globals())
from... |
15,513 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TensorFlow Datasets
TFDS provides a collection of ready-to-use datasets for use with TensorFlow, Jax, and other Machine Learning frameworks.
It handles downloading and preparing the data det... | Python Code:
!pip install -q tfds-nightly tensorflow matplotlib
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds
Explanation: TensorFlow Datasets
TFDS provides a collection of ready-to-use datasets for use with TensorFlow, Jax, and other Machine Learning fram... |
15,514 | 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', 'cmcc', 'cmcc-cm2-vhr4', 'aerosol')
Explanation: ES-DOC CMIP6 Model Properties - Aerosol
MIP Era: CMIP6
Institute: CMCC
Source ID: CMCC-CM2-VHR4
Topic: Aerosol
Sub-Topics: Transport, E... |
15,515 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Experiment for the paper "Features for discourse-new referent detection in Russian
Replication of CICLing-2016 paper (Toldova and Ionov 2016)
To reproduce this experiment you will need
Step1... | Python Code:
%cd '/Users/max/Projects/Coreference/'
%cd 'rucoref'
from anaphoralib.corpora import rueval
from anaphoralib.tagsets import multeast
from anaphoralib.experiments.base import BaseClassifier
from anaphoralib import utils
from anaphoralib.experiments import utils as exp_utils
%cd '..'
from sklearn.ensemble im... |
15,516 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Notebook
Step1: 1 - Exploring data with one dimension (time) with size > 1
Following cell downloads a datataset from eurostat. If the file is already downloaded use the copy presents on the... | Python Code:
# all import here
from __future__ import print_function
import os
import pandas as pd
import jsonstat
import matplotlib as plt
%matplotlib inline
Explanation: Notebook: using jsonstat.py with eurostat api
This Jupyter notebook shows the python library jsonstat.py in action.
It shows how to explore dataset... |
15,517 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SVD Practice.
2018/2/12 - WNixalo
Fastai Computational Linear Algebra (2017) §2
Step1: Wait so.. the rows of a matrix $A$ are orthogonal iff $AA^T$ is diagonal? Hmm. Math.StackEx Link
Step2... | Python Code:
from scipy.stats import ortho_group
import numpy as np
Q = ortho_group.rvs(dim=3)
B = np.random.randint(0,10,size=(3,3))
A = Q@B@Q.T
U,S,V = np.linalg.svd(A, full_matrices=False)
U
S
V
for i in range(3):
print(U[i] @ U[(i+1) % len(U)])
# wraps around
# U[0] @ U[1]
# U[1] @ U[2]
# U[2] @... |
15,518 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1. Import the necessary packages to read in the data, plot, and create a linear regression model
Step1: 2. Read in the hanford.csv file
Step2: <img src="images/hanford_variables.png">
Step... | Python Code:
import pandas as pd
%matplotlib inline
import matplotlib.pyplot as plt
import statsmodels.formula.api as smf
Explanation: 1. Import the necessary packages to read in the data, plot, and create a linear regression model
End of explanation
df = pd.read_csv("hanford.csv")
Explanation: 2. Read in the hanford.c... |
15,519 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
NumPy를 활용한 선형대수 입문
선형대수(linear algebra)는 데이터 분석에 필요한 각종 계산을 위한 기본적인 학문이다.
데이터 분석을 하기 위해서는 실제로 수많은 숫자의 계산이 필요하다. 하나의 데이터 레코드(record)가 수십개에서 수천개의 숫자로 이루어져 있을 수도 있고 수십개에서 수백만개의 이러한 데이터 레코드를 조합... | Python Code:
x = np.array([1, 2, 3, 4])
x, np.shape(x)
x = np.array([[1], [2], [3], [4]])
x, np.shape(x)
Explanation: NumPy를 활용한 선형대수 입문
선형대수(linear algebra)는 데이터 분석에 필요한 각종 계산을 위한 기본적인 학문이다.
데이터 분석을 하기 위해서는 실제로 수많은 숫자의 계산이 필요하다. 하나의 데이터 레코드(record)가 수십개에서 수천개의 숫자로 이루어져 있을 수도 있고 수십개에서 수백만개의 이러한 데이터 레코드를 조합하여 계산하는 과정이 ... |
15,520 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Image Gradients
In this notebook we'll introduce the TinyImageNet dataset and a deep CNN that has been pretrained on this dataset. You will use this pretrained model to compute gradients wit... | Python Code:
# As usual, a bit of setup
import time, os, json
import numpy as np
import skimage.io
import matplotlib.pyplot as plt
from cs231n.classifiers.pretrained_cnn import PretrainedCNN
from cs231n.data_utils import load_tiny_imagenet
from cs231n.image_utils import blur_image, deprocess_image
%matplotlib inline
pl... |
15,521 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Iterative Construction of a Penalised Vine Structure
This notebook iteratively estimate the quantile.
Libraries
Step1: Model function
This example consider the simple additive example.
Step... | Python Code:
import openturns as ot
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
%load_ext autoreload
%autoreload 2
random_state = 123
np.random.seed(random_state)
Explanation: Iterative Construction of a Penalised Vine Structure
This notebook iteratively estimate the quan... |
15,522 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Face Generation
In this project, you'll use generative adversarial networks to generate new images of faces.
Get the Data
You'll be using two datasets in this project
Step3: Explore ... | Python Code:
data_dir = './data'
# FloydHub - Use with data ID "R5KrjnANiKVhLWAkpXhNBe"
#data_dir = '/input'
DON'T MODIFY ANYTHING IN THIS CELL
import helper
helper.download_extract('mnist', data_dir)
helper.download_extract('celeba', data_dir)
Explanation: Face Generation
In this project, you'll use generative adversa... |
15,523 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Solution of Jiang et al. 2013
Write a function that takes as input the desired Taxon, and returns the mean value of r.
First, we're going to import the csv module, and read the data. We stor... | Python Code:
import csv
with open('../data/Jiang2013_data.csv') as csvfile:
reader = csv.DictReader(csvfile, delimiter = '\t')
taxa = []
r_values = []
for row in reader:
taxa.append(row['Taxon'])
r_values.append(float(row['r']))
Explanation: Solution of Jiang et al. 2013
Write a function... |
15,524 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
AutoEncoder and Deep Neural Networks
This scripts reads in the 20 newsgroup corpus from SKLearn. Each document is created to a BoW-vector over the 2000 most common words.
1) Computes a basel... | Python Code:
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np
from sklearn import metrics
import random
random.seed(1)
np.random.seed(1)
max_words = 2000
examples_per_labels = 1000
n... |
15,525 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
First, I made a mistake naming the data set! It's 2015 data, not 2014 data. But yes, still use 311-2014.csv. You can rename it.
Importing and preparing your data
Import your data, but only t... | Python Code:
df=pd.read_csv("311-2014.csv", nrows=200000)
dateutil.parser.parse(df['Created Date'][0])
def parse_date(str_date):
return dateutil.parser.parse(str_date)
df['created_datetime']=df['Created Date'].apply(parse_date)
df.index=df['created_datetime']
Explanation: First, I made a mistake naming the data set... |
15,526 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Multi-worker training with Keras
Learning Objectives
Multi-worker Configuration
Choose the right strategy
Train the model
Multi worker training in depth
Introduction
This notebook demonstrat... | Python Code:
import json
import os
import sys
Explanation: Multi-worker training with Keras
Learning Objectives
Multi-worker Configuration
Choose the right strategy
Train the model
Multi worker training in depth
Introduction
This notebook demonstrates multi-worker distributed training with Keras model using tf.distribu... |
15,527 | 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', 'mri', 'mri-agcm3-2', 'aerosol')
Explanation: ES-DOC CMIP6 Model Properties - Aerosol
MIP Era: CMIP6
Institute: MRI
Source ID: MRI-AGCM3-2
Topic: Aerosol
Sub-Topics: Transport, Emissio... |
15,528 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Golden Spirals
Steve loves nature. He likes looking at the pretty patterns in nature like the one below.
The spiral in the picture above have a special name - it is called a Golden Spiral. T... | Python Code:
# generate a list of Fibonacci series starting with 1
import itertools
import math
import numpy as np
def fib_function():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
def fib_list(n):
fib = fib_function()
return list(itertools.islice(fib,n+2))[2:]
Explanation: Golden Spir... |
15,529 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Inference Wrappers use cases
This is an example of the PySAL segregation framework to perform inference on a single value and comparative inference using simulations under the null hypothesi... | Python Code:
%matplotlib inline
import geopandas as gpd
from pysal.explore import segregation
import pysal.lib
import pandas as pd
import numpy as np
from pysal.explore.segregation.inference import SingleValueTest, TwoValueTest
Explanation: Inference Wrappers use cases
This is an example of the PySAL segregation framew... |
15,530 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
.. currentmodule
Step1: The learner doesn't do any heavy lifting itself, it manages the creation a sub-graph
of auxiliary
Step2: Fitting the learner puts three copies of the OLS estimator... | Python Code:
from mlens.utils.dummy import OLS
from mlens.parallel import Learner, Job
from mlens.index import FoldIndex
indexer = FoldIndex(folds=2)
learner = Learner(estimator=OLS(),
indexer=indexer,
name='ols')
Explanation: .. currentmodule:: mlens.parallel
Learner Mechanics
ML-En... |
15,531 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Random notes while re-studying CS and DS while job hunting.
xrange vs range looping
For long for loops with no need to track iteration use
Step1: This will loop through 10 times, but the it... | Python Code:
for _ in xrange(10):
print "Do something"
Explanation: Random notes while re-studying CS and DS while job hunting.
xrange vs range looping
For long for loops with no need to track iteration use:
End of explanation
for i in range(1,10):
vars()['x'+str(i)] = i
Explanation: This will loop through 10 t... |
15,532 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Table of Content
Overviw
Accessing Rows
Element Access
Lab
Overview
Step2: One of the most effective use of pandas is the ease at which we can select rows and coloumns in different ways, he... | Python Code:
# import the pandas package
import pandas as pd
# load in the dataset and save it to brics var.
brics = pd.read_csv("C:/Users/pySag/Documents/GitHub/Computer-Science/Courses/DAT-208x/Datasets/BRICS_cummulative.csv")
brics
# we can make the table look more better, by adding a parameter index_col = 0
brics =... |
15,533 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Code Search on Kubeflow
This notebook implements an end-to-end Semantic Code Search on top of Kubeflow - given an input query string, get a list of code snippets semantically similar to the ... | Python Code:
%%bash
echo "Pip Version Info: " && python2 --version && python2 -m pip --version && echo
echo "Google Cloud SDK Info: " && gcloud --version && echo
echo "Ksonnet Version Info: " && ks version && echo
echo "Kubectl Version Info: " && kubectl version
Explanation: Code Search on Kubeflow
This notebook implem... |
15,534 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Automatic alignment on labels
Step1: Series alignment
Let's define a table with natural increase rates in 2013 (data from World Bank)
Step2: Now we calculate the natural increae by subtrac... | Python Code:
data = {'country': ['Belgium', 'France', 'Germany', 'Netherlands', 'United Kingdom'],
'population': [11.3, 64.3, 81.3, 16.9, 64.9],
'area': [30510, 671308, 357050, 41526, 244820],
'capital': ['Brussels', 'Paris', 'Berlin', 'Amsterdam', 'London']}
countries = pd.DataFrame(data).set_i... |
15,535 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tests for QuTiP's SME solver against analytical solution for oscillator squeezing
Denis V. Vasilyev
1 August, 16 August 2013
Minor edits by Robert Johansson
5 August, 6 August 2013
Edits by... | Python Code:
%pylab inline
from qutip import *
from numpy import log2, cos, sin
from scipy.integrate import odeint
from qutip.cy.spmatfuncs import cy_expect_psi, spmv
th = 0.1 # Interaction parameter
alpha = cos(th)
beta = sin(th)
gamma = 1
# Exact steady state solution for Vc
Vc = (alpha*beta - gamma + sqrt((gamma-alp... |
15,536 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Futures Trading Considerations
by Maxwell Margenot and Delaney Mackenzie
Part of the Quantopian Lecture Series
Step1: Futures Calendar
An important feature of futures markets is the calenda... | Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from quantopian.research.experimental import continuous_future, history
Explanation: Futures Trading Considerations
by Maxwell Margenot and Delaney Mackenzie
Part of the Quantopian Lecture Series:
www.quantopian.com/lectures
github.com/... |
15,537 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Figure 2 csv data generation
Figure data consolidation for Figure 2, which deals with alpha and beta diversity of samples
Figure 2a
Step1: Figure 2b
Step2: Figure 2c
Step3: Figure 2d
Step... | Python Code:
# Load up metadata map
metadata_fp = '../../../data/mapping-files/emp_qiime_mapping_qc_filtered.tsv'
metadata = pd.read_csv(metadata_fp, header=0, sep='\t')
metadata.head()
metadata.columns
# take just the columns we need for this figure panel
fig2a = metadata.loc[:,['#SampleID','empo_1','empo_3','adiv_obs... |
15,538 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Land
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify do... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'mohc', 'hadgem3-gc31-mh', 'land')
Explanation: ES-DOC CMIP6 Model Properties - Land
MIP Era: CMIP6
Institute: MOHC
Source ID: HADGEM3-GC31-MH
Topic: Land
Sub-Topics: Soil, Snow, Veget... |
15,539 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: <table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https
Step2: FASTQ 数据
FASTQ 是一种常见的基因组学文件格式,除了基本的质量信息外,还存储序列信息... | 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... |
15,540 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Random Sampling
Copyright 2016 Allen Downey
License
Step1: Part One
Suppose we want to estimate the average weight of men and women in the U.S.
And we want to quantify the uncertainty of th... | Python Code:
from __future__ import print_function, division
import numpy
import scipy.stats
import matplotlib.pyplot as pyplot
from ipywidgets import interact, interactive, fixed
import ipywidgets as widgets
# seed the random number generator so we all get the same results
numpy.random.seed(18)
# some nicer colors fro... |
15,541 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Classification and Regression
There are two major types of supervised machine learning problems, called classification and regression.
In classification, the goal is to predict a class label... | Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Classification and Regression
There are two major types of supervised machine learning problems, called classification and regression.
In classification, the goal is to predict a class label, which is a c... |
15,542 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements; and to You under the Apache License, Version 2.0.
Train a linear regression model
In this ... | Python Code:
from __future__ import division
from __future__ import print_function
from builtins import range
from past.utils import old_div
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
Explanation: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreement... |
15,543 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Working with Scikit-learn pipelines
Nearest neighbor search is a fundamental building block of many machine learning algorithms, including in supervised learning with kNN-classifiers and kNN... | Python Code:
from sklearn.manifold import Isomap, TSNE
from sklearn.neighbors import KNeighborsTransformer
from pynndescent import PyNNDescentTransformer
from sklearn.pipeline import make_pipeline
from sklearn.datasets import fetch_openml
from sklearn.utils import shuffle
import seaborn as sns
Explanation: Working with... |
15,544 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Statistical Distribution
Discrete distribution
Contious distribution
Sample(small) distribution
Discrete Distribution
Binomial distribution $B(n,p)$
Hypergeometric distribution
Geometric dis... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
n,p=50,0.1
plt.hist(np.random.binomial(n,p,size=5000))
plt.show()
Explanation: Statistical Distribution
Discrete distribution
Contious distribution
Sample(small) distribution
Discrete Distribution
Binomial distribution $B(n,p)$
Hypergeom... |
15,545 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
An Introduction to Bayesian Optimization with Emukit
Overview
Step1: Navigation
What is Bayesian optimization?
The ingredients of Bayesian optimization
Emukit's Bayesian optimization interf... | Python Code:
### General imports
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors as mcolors
### --- Figure config
LEGEND_SIZE = 15
Explanation: An Introduction to Bayesian Optimization with Emukit
Overview
End of explanation
from emukit.test_functions import forrester... |
15,546 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Create Data
Step2: Calculate Population Variance
Variance is a measurement of the spread of a data's distribution. The higher the variance, the more "spread out" the data poin... | Python Code:
# Import data
import math
Explanation: Title: Variance And Standard Deviation
Slug: variance_and_standard_deviation
Summary: Calculating Variance And Standard Deviation in Python.
Date: 2016-02-08 12:00
Category: Statistics
Tags: Basics
Authors: Chris Albon
Preliminary
End of explanation
# Create list... |
15,547 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Solver Interface
Each cobrapy solver must expose the following API. The solvers all will have their own distinct LP object types, but each can be manipulated by these functions. This API can... | Python Code:
import cobra.test
model = cobra.test.create_test_model("textbook")
solver = cobra.solvers.cglpk
Explanation: Solver Interface
Each cobrapy solver must expose the following API. The solvers all will have their own distinct LP object types, but each can be manipulated by these functions. This API can be used... |
15,548 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Basic usage
The primary object in Bolt is the Bolt array. We can construct these arrays using familiar operators (like zeros and ones), or from an existing array, and manipulate them like nd... | Python Code:
from bolt import ones
a = ones((2,3,4))
a.shape
Explanation: Basic usage
The primary object in Bolt is the Bolt array. We can construct these arrays using familiar operators (like zeros and ones), or from an existing array, and manipulate them like ndarrays whether in local or distributed settings. This no... |
15,549 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Manipulating Data in Python
Laila A. Wahedi
Massive Data Institute Postdoctoral Fellow <br>McCourt School of Public Policy
Follow along
Step1: Numbers
Step2: Lists
Declare with
Step3: Zer... | Python Code:
my_string = 'Hello World'
print(my_string)
Explanation: Manipulating Data in Python
Laila A. Wahedi
Massive Data Institute Postdoctoral Fellow <br>McCourt School of Public Policy
Follow along: Wahedi.us, Current Presentation
Installing packages:
On a Mac:
Open terminal
On Windows:
Type cmd into the start ... |
15,550 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Convolution speed tests
This Notebook compares the convolution speeds of Eniric to PyAstronomy.
Enirics rotational convolution is faster than PyAstronomy's "slow" convolution but it is sign... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
import PyAstronomy.pyasl as pyasl
import eniric
from eniric import config
from eniric.broaden import rotational_convolution, resolution_convolution
from eniric.utilities import band_limits, load_aces_spectrum, wav_selector
from scripts.phoenix_precision im... |
15,551 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Microscopic 3-Temperature-Model
Here we adapt the NTM from the last example to allow for calculations of the magnetization within the microscopic 3-temperature-model as proposed by
Step1: S... | Python Code:
import udkm1Dsim as ud
u = ud.u # import the pint unit registry from udkm1Dsim
import scipy.constants as constants
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
u.setup_matplotlib() # use matplotlib with pint units
Explanation: Microscopic 3-Temperature-Model
Here we adapt the NTM... |
15,552 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
API-REST
Step1: Obtención de un listado con todas las estaciones
Step2: Obtención de datos de una estación en concreto
Estación 111X situada en Santander
Step3: Limpiamos los datos
Se pue... | Python Code:
import requests
# Cargamos la api key
api_key = open("../../apikey-aemet.txt").read().rstrip()
querystring = {"api_key": api_key}
Explanation: API-REST: AEMET OPEN DATA
En este notebook veremos otro ejemplo de uso de la api open data de AEMET. En este caso obtendremos parámetros medidos por una estación m... |
15,553 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Display Exercise 1
Imports
Put any needed imports needed to display rich output the following cell
Step1: Basic rich display
Find a Physics related image on the internet and display it in t... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import display
from IPython.display import (
display_pretty, display_html, display_jpeg,
display_png, display_json, display_latex, display_svg
)
from IPython.display import Image
assert True # leave this to g... |
15,554 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
$$
\mathcal{L}(r, a) = \log \mathcal{N}(y_r; W_r a, q) \prod_{i\neq r} \mathcal{N}(y_i; W_i a, s)
$$
$$
\log\mathcal{N}(y_r; W_r a, q) = -\frac{1}{2}\log 2\pi q - \frac{1}{2} \frac{1}{q} (... | Python Code:
import scipy.linalg as la
LL = np.zeros(N)
for rr in range(N):
ss = s*np.ones(N)
ss[rr] = q
D_r = np.diag(1/ss)
V_r = np.dot(np.sqrt(D_r), W)
b = y/np.sqrt(ss)
a_r,re,ra, cond = la.lstsq(V_r, b)
e = (y-np.dot(W, a_r))/np.sqrt(ss)
LL[rr] = -0.5*np.dot(e.T, e)
print(LL[rr]... |
15,555 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Train Model on Distributed Cluster
IMPORTANT
Step1: Start Server "Task 0" (localhost
Step2: Start Server "Task 1" (localhost
Step3: Define Compute-Heavy TensorFlow Graph
Step4: Define Sh... | Python Code:
import tensorflow as tf
cluster = tf.train.ClusterSpec({"local": ["localhost:2222", "localhost:2223"]})
Explanation: Train Model on Distributed Cluster
IMPORTANT: You Must STOP All Kernels and Terminal Session
The GPU is wedged at this point. We need to set it free!!
Define ClusterSpec
End of explanation... |
15,556 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
LDA on vertebrates
Notes on the data
In this example the tree is contstrained
In this example we have to extract position,transition, and branch.
The total position are broken into N 'split... | Python Code:
import os
import numpy as np
from vertebratesLib import *
split = "SPLIT1"
summaryTree,summarySpecies,splitPositions = get_split_data(split)
print summaryTree.shape
Explanation: LDA on vertebrates
Notes on the data
In this example the tree is contstrained
In this example we have to extract position,transit... |
15,557 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
N2 - Eurocode 8, CEN (2005)
This simplified nonlinear procedure for the estimation of the seismic response of structures uses capacity curves and inelastic spectra. This method has been deve... | Python Code:
from rmtk.vulnerability.derivation_fragility.hybrid_methods.N2 import N2Method
from rmtk.vulnerability.common import utils
%matplotlib inline
Explanation: N2 - Eurocode 8, CEN (2005)
This simplified nonlinear procedure for the estimation of the seismic response of structures uses capacity curves and inela... |
15,558 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
So far, you've worked with many types of data, including numeric types (integers, floating point values), strings, and the DATETIME type. In this tutorial, you'll learn how to ... | Python Code:
from google.cloud import bigquery
# Create a "Client" object
client = bigquery.Client()
# Construct a reference to the "google_analytics_sample" dataset
dataset_ref = client.dataset("google_analytics_sample", project="bigquery-public-data")
# Construct a reference to the "ga_sessions_20170801" table
table_... |
15,559 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Causal Inference of Kang-Schafer simulation.
<table align="left">
<td>
<a target="_blank" href="https
Step1: Correctly Specified Model
We run the simulation 1000 times under correctly... | Python Code:
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
import patsy
import seaborn as sns
import timeit
# install and import ec
!pip install -q git+https://github.com/google/empirical_calibration
import empirical_calibration as ec
sns.set_style('whitegrid')
%config InlineBackend.figure... |
15,560 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DL Indaba Practical 3
Convolutional Neural Networks
Developed by Stephan Gouws, Avishkar Bhoopchand & Ulrich Paquet.
Introduction
In this practical we will cover the basics of convolutional ... | Python Code:
# Import TensorFlow and some other libraries we'll be using.
import datetime
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# Import Matplotlib and set some defaults
from matplotlib import pyplot as plt
plt.ioff()
%matplotlib inline
plt.rcParams['figur... |
15,561 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tidying Data
Tidying of data is required for many reasons including these
Step1: Working with Missing Data
Data is "missing" in pandas when it has a value of NaN (also seen as np.nan - the ... | Python Code:
# import pandas, numpy and datetime
import numpy as np
import pandas as pd
import datetime
# set some pandas options for controlling output
pd.set_option('display.notebook_repr_html', False)
pd.set_option('display.max_columns',10)
pd.set_option('display.max_rows',10)
Explanation: Tidying Data
Tidying of da... |
15,562 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Face Recognition for the Happy House
Welcome to the first assignment of week 4! Here you will build a face recognition system. Many of the ideas presented here are from FaceNet. In lecture, ... | Python Code:
from keras.models import Sequential
from keras.layers import Conv2D, ZeroPadding2D, Activation, Input, concatenate
from keras.models import Model
from keras.layers.normalization import BatchNormalization
from keras.layers.pooling import MaxPooling2D, AveragePooling2D
from keras.layers.merge import Concaten... |
15,563 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Committor Estimate on the Muller-Brown Potential
Step1: Load Data and set Hyperparameters
We first load in the pre-sampled data. The data consists of 1000 short trajectories, each with 5 d... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
import pyedgar
from pyedgar.data_manipulation import tlist_to_flat, flat_to_tlist
%matplotlib inline
Explanation: Committor Estimate on the Muller-Brown Potential
End of explanation
ntraj = 1000
trajectory_length = 5
dim = 10
Explanation: Load Data and set... |
15,564 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Combining arrays
Import the LArray library
Step1: The LArray library offers several methods and functions to combine arrays
Step2: See insert for more details and examples.
Append
Append o... | Python Code:
from larray import *
# load the 'demography_eurostat' dataset
demography_eurostat = load_example_data('demography_eurostat')
# load 'gender' and 'time' axes
gender = demography_eurostat.gender
time = demography_eurostat.time
# load the 'population' array from the 'demography_eurostat' dataset
population = ... |
15,565 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ML with TensorFlow Extended (TFX) -- Part 2
The puprpose of this tutorial is to show how to do end-to-end ML with TFX libraries on Google Cloud Platform. This tutorial covers
Step1: <img va... | Python Code:
import apache_beam as beam
import tensorflow as tf
import tensorflow_data_validation as tfdv
import tensorflow_transform as tft
print('TF version: {}'.format(tf.__version__))
print('TFT version: {}'.format(tft.__version__))
print('TFDV version: {}'.format(tfdv.__version__))
print('Apache Beam version: {}'.... |
15,566 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Advanced
Step1: As always, let's do imports and create a new Bundle. See Building a System for more details.
Step2: Overriding Computation Times
If compute_times is not empty (by either p... | Python Code:
!pip install -I "phoebe>=2.2,<2.3"
Explanation: Advanced: compute_times & compute_phases
Setup
Let's first make sure we have the latest version of PHOEBE 2.2 installed. (You can comment out this line if you don't use pip for your installation or don't want to update to the latest release).
End of explanati... |
15,567 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Can you beat DeepVariant?
Step1: <table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: Download file with consolidated locus information
This i... | Python Code:
# @markdown Copyright 2020 Google LLC. \
# @markdown SPDX-License-Identifier: Apache-2.0
# @markdown (license hidden in Colab)
# Copyright 2020 Google LLC
# 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 ... |
15,568 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
FloPy
Plotting SWR Process Results
This notebook demonstrates the use of the SwrObs and SwrStage, SwrBudget, SwrFlow, and SwrExchange, SwrStructure, classes to read binary SWR Process obser... | Python Code:
%matplotlib inline
from IPython.display import Image
import os
import sys
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import flopy
print(sys.version)
print('numpy version: {}'.format(np.__version__))
print('matplotlib version: {}'.format(mpl.__version__))
print('flopy versio... |
15,569 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Quantile regression
This example page shows how to use statsmodels' QuantReg class to replicate parts of the analysis published in
Koenker, Roger and Kevin F. Hallock. "Quantile Regressioin... | Python Code:
%matplotlib inline
from __future__ import print_function
import patsy
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
import matplotlib.pyplot as plt
from statsmodels.regression.quantile_regression import QuantReg
data = sm.datasets.engel.load_panda... |
15,570 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Amongst the H3N8 isolates, here is the full range of patristic distances present in the PB2 gene tree.
Step1: Because I don't have the taxa names identical between the tree and the transmis... | Python Code:
patristic_distances = dp.treecalc.PatristicDistanceMatrix(tree=tree).distances()
plt.hist(patristic_distances)
plt.xlabel('Patristic Distance')
plt.ylabel('Counts')
plt.title('Histogram of Patristic \n Distances in the PB2 Tree')
transmission_graph = nx.read_gpickle('Minto Flats.pkl')
transmission_graph.no... |
15,571 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ch 02
Step1: Below is a series of numbers. Don't worry what they mean. Just for fun, let's think of them as neural activations.
Step2: Create a boolean variable called spike to detect a su... | Python Code:
import tensorflow as tf
sess = tf.InteractiveSession()
Explanation: Ch 02: Concept 05
Using variables
Here we go, here we go, here we go! Moving on from those simple examples, let's get a better understanding of variables. Start with a session:
End of explanation
raw_data = [1., 2., 8., -1., 0., 5.5, 6., 1... |
15,572 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<b>This notebook tries to detect "special words" in a corpus of mailing lists.</b>
(for now it works with two mailing lists only)
-it computes and exports in .csv files the word counts (word... | Python Code:
from bigbang.archive import Archive
from bigbang.archive import load as load_archive
import bigbang.parse as parse
import bigbang.graph as graph
import bigbang.mailman as mailman
import bigbang.process as process
import networkx as nx
import matplotlib.pyplot as plt
import pandas as pd
from pprint import p... |
15,573 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Table of Contents
<p><div class="lev1 toc-item"><a href="#PMT/ADC" data-toc-modified-id="PMT/ADC-1"><span class="toc-item-num">1 </span>PMT/ADC</a></div><div class="lev2 toc-item"... | Python Code:
import gtk
import gobject
import threading
import datetime as dt
import matplotlib as mpl
import matplotlib.style
import numpy as np
import pandas as pd
from streaming_plot import StreamingPlot
def _generate_data(stop_event, data_ready, data):
'''
Generate random data to emulate, e.g., reading data... |
15,574 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example of how to use classification code for ship logbooks
Imports
Step1: Initialize classifier
Classification algorithm can be set to "Naive Bayes" or "Decision Tree"
Step2: Load Data, C... | Python Code:
from exploringShipLogbooks.config import non_slave_ships
from exploringShipLogbooks.classification import LogbookClassifier
Explanation: Example of how to use classification code for ship logbooks
Imports
End of explanation
cl = LogbookClassifier(classification_algorithm="Naive Bayes")
Explanation: Initial... |
15,575 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generative Adversarial Network
In this notebook, we'll be building a generative adversarial network (GAN) trained on the MNIST dataset. From this, we'll be able to generate new handwritten d... | Python Code:
%matplotlib inline
import pickle as pkl
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data')
Explanation: Generative Adversarial Network
In this notebook, we'll be building a gen... |
15,576 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
First order hold sampling of a lead compensator
\begin{equation}
F(s) = K\frac{s+b}{s+a}
\end{equation}
Step1: Sampling and taking the z-transform of the step-response
\begin{equation}
Y(z)... | Python Code:
h, b, a,K = sy.symbols('h, b, a, K', real=True, positive=True)
s, z = sy.symbols('s, z', real=False)
F = K*(s+b)/(s+a)
U = F/s/s
Up = sy.apart(U, s)
Up
from sympy.integrals.transforms import inverse_laplace_transform
from sympy.abc import t
u = sy.simplify(inverse_laplace_transform(Up, s, t))
u
Explanation... |
15,577 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Double inverted pendulum
In this Jupyter Notebook we illustrate the example DIP. This example illustrates how to use DAE models in do-mpc.
Open an interactive online Jupyter Notebook with th... | Python Code:
import numpy as np
import sys
from casadi import *
# Add do_mpc to path. This is not necessary if it was installed via pip
sys.path.append('../../../')
# Import do_mpc package:
import do_mpc
Explanation: Double inverted pendulum
In this Jupyter Notebook we illustrate the example DIP. This example illustrat... |
15,578 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<table width="100%" border="0">
<tr>
<td><img src="./images/ing.png" alt="" align="left" /></td>
<td><img src="./images/ucv.png" alt="" align="center" height="100" width="100" /></... | Python Code:
# asignaciones de variables
x = 1.0
mi_variable = 12.2
Explanation: <table width="100%" border="0">
<tr>
<td><img src="./images/ing.png" alt="" align="left" /></td>
<td><img src="./images/ucv.png" alt="" align="center" height="100" width="100" /></td>
<td><img src="./images/mec.png" alt="" alig... |
15,579 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Text Using Markdown
If you double click on this cell, you will see the text change so that all of the formatting is removed. This allows you to edit this block of text. This block of text is... | Python Code:
# Hit shift + enter or use the run button to run this cell and see the results
print 'hello world11_0_11'
print 'hello world'
# The last line of every code cell will be displayed by default,
# even if you don't print it. Run this cell to see how this works.
print 2 + 2 # The result of this line will not b... |
15,580 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
LV3 Recovery Test
This notebook will encompass all calculations regarding the LV3 Recovery/eNSR Drop Test.
Resources
[http
Step1: input parameters
flight plan
Step2: physical parameters
St... | Python Code:
import math
import sympy
from sympy import Symbol, solve
from scipy.integrate import odeint
from types import SimpleNamespace
import numpy as np
import matplotlib.pyplot as plt
sympy.init_printing()
%matplotlib inline
Explanation: LV3 Recovery Test
This notebook will encompass all calculations regarding th... |
15,581 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Implementation of a Radix-2 Fast Fourier Transform
Import standard modules
Step3: This assignment is to implement a python-based Fast Fourier Transform (FFT). Building on $\S$ 2.8 ➞ ... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from IPython.display import HTML
HTML('../style/course.css') #apply general CSS
import cmath
Explanation: Implementation of a Radix-2 Fast Fourier Transform
Import standard modules:
End of explanation
def loop_DFT(x):
Implement... |
15,582 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Practical PyTorch
Step1: Creating the Network
This network extends the last tutorial's RNN with an extra argument for the category tensor, which is concatenated along with the others. The c... | Python Code:
import glob
import unicodedata
import string
all_letters = string.ascii_letters + " .,;'-"
n_letters = len(all_letters) + 1 # Plus EOS marker
EOS = n_letters - 1
# Turn a Unicode string to plain ASCII, thanks to http://stackoverflow.com/a/518232/2809427
def unicode_to_ascii(s):
return ''.join(
... |
15,583 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
syncID
Step1: Data Institue Participants
Step3: If you get the following message
<p>
<center><strong>ModuleNotFoundError</strong></center>
<img src="No_module_named_gdal.png" style="width... | Python Code:
import sys
sys.version
Explanation: syncID: 67a5e95e1b7445aca7d7750b75c0ee98
title: "Plotting a NEON RGB Camera Image (GeoTIFF) in Python"
description: "This lesson is a brief introduction to RGB camera images and the GeoTIFF raster format in Python."
dateCreated: 2018-06-30
authors: Bridget Hass,
contrib... |
15,584 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Quick Start
Step1: Import the aggregation object from the module.
Step2: Create a few objects with various depths (number of moments) and widths (number of columns to compute statistics fo... | Python Code:
from __future__ import print_function
Explanation: Quick Start
End of explanation
from pebaystats import dstats
Explanation: Import the aggregation object from the module.
End of explanation
stats1 = dstats(2,1)
stats2 = dstats(4,4)
stats3 = dstats(2,1)
Explanation: Create a few objects with various depths... |
15,585 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
3D Grid on GPU with Kernel Tuner
In this tutorial we are going to see how to map a series of Gaussian functions, each located at a different point on a 3D a grid. We are going to optimize th... | Python Code:
import numpy as np
import numpy.linalg as la
from time import time
def compute_grid(center,xgrid,ygrid,zgrid):
x0,y0,z0 = center
beta = -0.1
f = np.sqrt( (xgrid-x0)**2 + (ygrid-y0)**2 + (zgrid-z0)**2 )
f = np.exp(beta*f)
return f
Explanation: 3D Grid on GPU with Kernel Tuner
In this tut... |
15,586 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
From VHF sources to lightning flashes
Using space-time criteria, we will group LMA data into flashes. We will also create a 2D gridded version of these flash data to look at VHF source densi... | Python Code:
import glob
import numpy as np
import datetime
import xarray as xr
import pandas as pd
import pyproj as proj4
from pyxlma.lmalib.io import read as lma_read
from pyxlma.lmalib.flash.cluster import cluster_flashes
from pyxlma.lmalib.flash.properties import flash_stats, filter_flashes
from pyxlma.lmalib.grid ... |
15,587 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ejemplo de simulación numérica
Step1: Problema físico
Definimos un SR con el origen en el orificio donde el hilo atravieza el plano, la coordenada $\hat{z}$ apuntando hacia abajo. Con esto ... | Python Code:
import numpy as np
from scipy.integrate import odeint
from matplotlib import rc
import matplotlib.pyplot as plt
%matplotlib inline
rc("text", usetex=True)
rc("font", size=18)
rc("figure", figsize=(6,4))
rc("axes", grid=True)
Explanation: Ejemplo de simulación numérica
End of explanation
# Constantes del pr... |
15,588 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
21장 네트워크 분석
많은 데이터 문제는 노드(node)와 그 사이를 연결하는 엣지(edge)로 구성된 네트워크(network)의 관점에서 볼 수 있다.
예를들어, 페이스북에서는 사용자가 노드라면 그들의 친구 관계는 엣지가 된다.
웹에서는 각 웹페이지가 노드이고 페이지 사이를 연결하는 하이퍼링크가 엣지가 된다.
페이스북의 친구 관계는 상호... | Python Code:
from __future__ import division
import math, random, re
from collections import defaultdict, Counter, deque
from linear_algebra import dot, get_row, get_column, make_matrix, magnitude, scalar_multiply, shape, distance
from functools import partial
users = [
{ "id": 0, "name": "Hero" },
{ "id": 1, "... |
15,589 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
scikits-learn is a premier machine learning library for python, with a very easy to use API and great documentation.
Step1: Lets load up our trajectory. This is the trajectory that we gener... | Python Code:
%matplotlib inline
from __future__ import print_function
import mdtraj as md
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
Explanation: scikits-learn is a premier machine learning library for python, with a very easy to use API and great documentation.
End of explanation
traj = md.l... |
15,590 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Inference
Step1: Now we set up and run a sampling routine using Monomial-Gamma HMC MCMC
Step2: Monomial-Gamma HMC on a time-series problem
We now try the same method on a time-series probl... | Python Code:
import pints
import pints.toy
import numpy as np
import matplotlib.pyplot as plt
# Create log pdf
log_pdf = pints.toy.GaussianLogPDF([2, 4], [[1, 0], [0, 3]])
# Contour plot of pdf
levels = np.linspace(-3,12,20)
num_points = 100
x = np.linspace(-1, 5, num_points)
y = np.linspace(-0, 8, num_points)
X, Y = n... |
15,591 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Compute spatial resolution metrics to compare MEG with EEG+MEG
Compute peak localisation error and spatial deviation for the point-spread
functions of dSPM and MNE. Plot their distributions ... | Python Code:
# Author: Olaf Hauk <olaf.hauk@mrc-cbu.cam.ac.uk>
#
# License: BSD (3-clause)
import mne
from mne.datasets import sample
from mne.minimum_norm.resolution_matrix import make_inverse_resolution_matrix
from mne.minimum_norm.spatial_resolution import resolution_metrics
print(__doc__)
data_path = sample.data_pa... |
15,592 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1>Listen</h1>
<li>Listen sind eine sequentielle, geordnete Sammlung von Werten, Zahlen oder strg oder boolean oder hashes etc.
['spass',[1,2,4], 3.14, [{1],[2],[3]] in eckigen Klammern
<h2... | Python Code:
x = [4,2,6,3] #Erzeugt eine Liste mit Werten
x1 = [4,2,6,3] #Erzeugt eine Liste mit den gleichen Werten
y = list() # Erzeugt eine leere Liste
y = [] #Erzeugt eine leere Liste
z = ["11","22","33","a","b","c","d"] #erzeugt eine Liste mit strg Werten
print(x)
print(id(x))
print(x1)
print(id(x1))
print(y)
prin... |
15,593 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Trends
By Evgenia "Jenny" Nitishinskaya and Delaney Granizo-Mackenzie
Notebook released under the Creative Commons Attribution 4.0 License.
Trends estimate tendencies in data over time, such... | Python Code:
import numpy as np
import math
from statsmodels import regression
import statsmodels.api as sm
import matplotlib.pyplot as plt
start = '2010-01-01'
end = '2015-01-01'
asset = get_pricing('XLY', fields='price', start_date=start, end_date=end)
dates = asset.index
def linreg(X,Y):
# Running the linear reg... |
15,594 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1T_os, shutil 모듈을 이용한 파일,폴더 관리하기 (1) - 폴더 생성 및 제거
영화별 매출 - Revenue per Film 이거 어려워. 이거 뽑아 보겠음
데이터를 저장하고 관리하기 위해서 os, shutil - python 내장 라이브러리를 쓸 것임
각 국가별 이름으로 (korea.csv / japan.csv...) 저장하는... | Python Code:
import os
#os 모듈을 통해서
#운영체제 레벨(서버는 ex.우분투)에서 다루는 파일 폴더 생성하고 삭제하기가 가능
#기존에는 ("../../~~") 이런 식으로 경로를 직접 입력 했으나
os.listdir()
#현재 폴더 안에 있는 파일들을 리스트로 뽑는 것
os.listdir("../")
for csv_file in os.listdir("../"):
pass
Explanation: 1T_os, shutil 모듈을 이용한 파일,폴더 관리하기 (1) - 폴더 생성 및 제거
영화별 매출 - Revenue per Film 이거 어려워... |
15,595 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Time Series Forecasting
Step1: Polish Weather Data
Polish Weather dataset contains 7 weather related measurements in the Warshaw area, taken between 1999 and 2004. The readings are taken da... | Python Code:
# Write code to import required libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# For visualzing plots in this notebook
%matplotlib inline
Explanation: Time Series Forecasting: Application of Regression
A time series is a series of data points indexed (or listed or graph... |
15,596 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Calculate generation capacity by month
This notebook uses the december 2017 EIA-860m file to determine operable generating capacity by fuel category in every month from 2001-2017.
Because th... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import os
import pathlib
from pathlib import Path
import sys
from os.path import join
import json
import calendar
sns.set(style='white')
idx = pd.IndexSlice
Explanation: Calculate generation capacity by month
This ... |
15,597 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Installation
Step2: Import
Step3: Run | Python Code:
#@title Default title text
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
15,598 | 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... |
15,599 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
So my the code for my solution can be found in
Step1: The above bit of boiler-plate code is useful in a number of situations. Indeed, this is a pattern I regularly find myself using when wr... | Python Code:
## Assume that this code exists in a file named example.py
def main():
print(1 + 1)
if __name__ == "__main__":
main()
Explanation: So my the code for my solution can be found in:
../misc/minesweeper.py
In this lecture I shall be going through some bits of code and explaining parts of it. I encourag... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.