Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
8,000 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SMILES enumeration, vectorization and batch generation
SMILES enumeration is the process of writing out all possible SMILES forms of a molecule. It's a useful technique for data augmentation... | Python Code:
from SmilesEnumerator import SmilesEnumerator
sme = SmilesEnumerator()
print(help(SmilesEnumerator))
Explanation: SMILES enumeration, vectorization and batch generation
SMILES enumeration is the process of writing out all possible SMILES forms of a molecule. It's a useful technique for data augmentation be... |
8,001 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
'mesh' Datasets and Options
Setup
Let's first make sure we have the latest version of PHOEBE 2.0 installed. (You can comment out this line if you don't use pip for your installation or don't... | Python Code:
!pip install -I "phoebe>=2.0,<2.1"
Explanation: 'mesh' Datasets and Options
Setup
Let's first make sure we have the latest version of PHOEBE 2.0 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 explanation
%matplotli... |
8,002 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dynamic factors and coincident indices
Factor models generally try to find a small number of unobserved "factors" that influence a subtantial portion of the variation in a larger number of o... | Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt
np.set_printoptions(precision=4, suppress=True, linewidth=120)
from pandas_datareader.data import DataReader
# Get the datasets from FRED
start = '1979-01-01'
end = '2014-12-01'
indprod = ... |
8,003 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
EOF analysis in central pacific ocean
In statistics and signal processing, the method of empirical orthogonal function (EOF) analysis is a decomposition of a signal or data set in terms of o... | Python Code:
% matplotlib inline
import numpy as np
from scipy import signal
import numpy.polynomial.polynomial as poly
from netCDF4 import Dataset
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from eofs.standard import Eof
Explanation: EOF analysis in central pacific ocean
In statistics and ... |
8,004 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A Transformer-based recommendation system
Author
Step1: Prepare the data
Download and prepare the DataFrames
First, let's download the movielens data.
The downloaded folder will contain thr... | Python Code:
import os
import math
from zipfile import ZipFile
from urllib.request import urlretrieve
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.layers import StringLookup
Explanation: A Transformer-based recommen... |
8,005 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step 1
Step1: Get rid of void coordinates
Step2: Recap of step 0
Adopting building coordinates
It turns out that there is a slight mismatch between real world building coordinates w.r.t gi... | Python Code:
data_events = pd.read_csv('../data/events.csv')
data_events.head(10)
data_events.shape
# To get rid of duplicates with same coordinates and possibly different address names
building_pool = data_events.drop_duplicates(subset=['lon','lat'])
building_pool.shape
# 1. sort data according to longitude
# init ... |
8,006 | 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', 'niwa', 'sandbox-3', 'aerosol')
Explanation: ES-DOC CMIP6 Model Properties - Aerosol
MIP Era: CMIP6
Institute: NIWA
Source ID: SANDBOX-3
Topic: Aerosol
Sub-Topics: Transport, Emissions... |
8,007 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introducing AI Platform Training Service
Learning Objectives
Step1: Make code compatible with AI Platform Training Service
In order to make our code compatible with AI Platform Training Ser... | Python Code:
# Uncomment and run if you need to update your Google SDK
# !sudo apt-get update && sudo apt-get --only-upgrade install google-cloud-sdk
Explanation: Introducing AI Platform Training Service
Learning Objectives:
- Learn how to make code compatible with AI Platform Training Service
- Train your model us... |
8,008 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pixels and their neighbours
Step1: Mesh
Where we solve things! See mesh.ipynb a discussion of how we construct a mesh and the associated properties we need.
Step2: Physical Property Model
... | Python Code:
# Import numpy, python's n-dimensional array package,
# the mesh class with differential operators from SimPEG
# matplotlib, the basic python plotting package
import numpy as np
from SimPEG import Mesh, Utils
import matplotlib.pyplot as plt
%matplotlib inline
plt.set_cmap(plt.get_cmap('viridis')) # use a... |
8,009 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Potential Host Queries
Now that we're using SWIRE directly instead of querying Gator, we have to quickly find the potential hosts in a neighbourhood. I can think of two ways, one which is $O... | Python Code:
import csv
import time
import h5py
import numpy
CROWDASTRO_H5_PATH = '../crowdastro.h5'
CROWDASTRO_CSV_PATH = '../crowdastro.csv'
ARCMIN = 0.0166667
with h5py.File(CROWDASTRO_H5_PATH) as f_h5:
positions = f_h5['/swire/cdfs/catalogue'][:, :2]
times = []
for i in range(1000):
now = t... |
8,010 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Say I have two dataframes: | Problem:
import pandas as pd
df1 = pd.DataFrame({'Timestamp': ['2019/04/02 11:00:01', '2019/04/02 11:00:15', '2019/04/02 11:00:29', '2019/04/02 11:00:30'],
'data': [111, 222, 333, 444]})
df2 = pd.DataFrame({'Timestamp': ['2019/04/02 11:00:14', '2019/04/02 11:00:15', '2019/04/02 11:00:16', '2019/04/0... |
8,011 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Frequency and time-frequency sensor analysis
The objective is to show you how to explore the spectral content
of your data (frequency and time-frequency). Here we'll work on Epochs.
We will ... | Python Code:
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Stefan Appelhoff <stefan.appelhoff@mailbox.org>
# Richard Höchenberger <richard.hoechenberger@gmail.com>
#
# License: BSD (3-clause)
import os.path as op
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.ti... |
8,012 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Computational Quantum Dynamics
(Lorenzo Biasi)
Project
I upload some library and initialize settings
Step1: 1. Superexchange in a three-level system.
(a)
For calculating the occupation prob... | Python Code:
from pylab import *
from copy import deepcopy
from matplotlib import animation, rc
from IPython.display import HTML
%matplotlib inline
rc('text', usetex=True)
font = {'family' : 'normal',
'weight' : 'bold',
'size' : 15}
matplotlib.rc('font', **font)
Explanation: Computational Quantum Dyna... |
8,013 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A tutorial on Markowitz portfolio optimization in Python using cvxopt
Authors
Step1: Assume that we have 4 assets, each with a return series of length 1000. We can use numpy.random.randn to... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import cvxopt as opt
from cvxopt import blas, solvers
import pandas as pd
np.random.seed(123)
# Turn off progress printing
solvers.options['show_progress'] = False
Explanation: A tutorial on Markowitz portfolio optimization in Python us... |
8,014 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Datasets
Datasets tell PHOEBE how and at what times to compute the model. In some cases these will include the actual observational data, and in other cases may only include the times at wh... | Python Code:
#!pip install -I "phoebe>=2.3,<2.4"
import phoebe
from phoebe import u # units
logger = phoebe.logger()
b = phoebe.default_binary()
Explanation: Datasets
Datasets tell PHOEBE how and at what times to compute the model. In some cases these will include the actual observational data, and in other cases may ... |
8,015 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Review of lists, loops, and more...
Here is another broken piece of code. Using what you learned from yesterday's lessons
fix what is broken
make comments to explain what is going on line-b... | Python Code:
# build a random dna sequence...
from numpy import random
final_sequence_length = eighty
initial_sequence_length = 81
dna_sequence = ''
my_nucleotides = [a,t,g,c]
my_nucleotide_probs = [0.25,0.25,0.25,0.3]
while initial_sequence_length < final_sequence_length:
nucleotide = random.choice(my_nucleotides,p=my... |
8,016 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Natural and artificial perturbations
Step1: Atmospheric drag
The poliastro package now has several commonly used natural perturbations. One of them is atmospheric drag! See how one can moni... | Python Code:
# Temporary hack, see https://github.com/poliastro/poliastro/issues/281
from IPython.display import HTML
HTML('<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.10/require.min.js"></script>')
import numpy as np
from plotly.offline import init_notebook_mode
init_noteb... |
8,017 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Ocnbgchem
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Speci... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'noaa-gfdl', 'gfdl-esm4', 'ocnbgchem')
Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem
MIP Era: CMIP6
Institute: NOAA-GFDL
Source ID: GFDL-ESM4
Topic: Ocnbgchem
Sub-Topics: Trac... |
8,018 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: int16 활성화를 사용한 훈련 후 정수 양자화
<table class="tfo-notebook-buttons" align="left">
<td> <a target="_blank" href="https
Step2: 16x8 양자화 모드를 사용할... | 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... |
8,019 | 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', 'ec-earth-consortium', 'sandbox-3', 'aerosol')
Explanation: ES-DOC CMIP6 Model Properties - Aerosol
MIP Era: CMIP6
Institute: EC-EARTH-CONSORTIUM
Source ID: SANDBOX-3
Topic: Aerosol
Su... |
8,020 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2T_Pandas로 배우는 SQL 시작하기 (2) - JOIN ON
Step3: 텍스트 마이닝
특정 텍스트가 포함되어 있는 row를 가져오는 방법
GovernmentForm 에 "Republic"이라는 텍스트가 포함된 열 가져오기
1. pandas로
contains, startswith, endswith
Step4: JOIN(panda... | Python Code:
import pymysql
db = pymysql.connect(
"db.fastcamp.us",
"root",
"dkstncks",
"world",
charset='utf8',
)
df = pd.read_sql("SELECT * FROM Country;", db)
#cursor
cursor = db.cursor()
# 1. 실제로 명령을 수행하는 부분 - 서버
cursor.execute("SELECT * FROM Country;")
# 2. 데이터를 가져오는 부분 - 서버 => 클라이... |
8,021 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Learning and Adjusting Tuning Curves
This is a quick notebook just to sketch out some initial stages of looking at modelling Aaron Batista's data on training macaques to use BCIs, and how th... | Python Code:
%matplotlib inline
import pylab # plotting
import seaborn # plotting
import numpy as np # math functions
import nengo # neural modelling
Explanation: Learning and Adjusting Tuning Curves
This is a quick notebook just to sketch out some initial stages of looking at modelling Aaron Batist... |
8,022 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<center> Sequence classification with LSTM on MNIST</center>
<div class="alert alert-block alert-info">
<font size = 3><strong>In this notebook you will learn the How to use TensorFlow for c... | Python Code:
%matplotlib inline
import warnings
warnings.filterwarnings('ignore')
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("../../data/MNIST/", one_hot=True)
Explanation: <center> Sequence clas... |
8,023 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A Nonsensical Language Model using Theano LSTM
Today we will train a nonsensical language model !
We will first collect some language data, convert it to numbers, and then feed it to a recur... | Python Code:
## Fake dataset:
class Sampler:
def __init__(self, prob_table):
total_prob = 0.0
if type(prob_table) is dict:
for key, value in prob_table.items():
total_prob += value
elif type(prob_table) is list:
prob_table_gen = {}
for key ... |
8,024 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
HDF5
HDF5 stands for (Hierarchical Data Format 5), and it is developed by the HDF Group. From their website
Step1: HDF5 is organized in a hierarchical structure and syntax is similar to the... | Python Code:
# Import packages
import numpy as np
import tables as pt # PyTables
import h5py as hp # h5py
import pandas as pd
import rpy2
%load_ext rpy2.ipython
# Create a New HDF5 File
h5file = pt.open_file('test.h5', mode='w', title='Test file')
Explanation: HDF5
HDF5 stands for (Hierarchical Data Format 5), an... |
8,025 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Language Translation
In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset o... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
import problem_unittests as tests
source_path = 'data/small_vocab_en'
target_path = 'data/small_vocab_fr'
source_text = helper.load_data(source_path)
target_text = helper.load_data(target_path)
Explanation: Language Translation
In this project, you’re going ... |
8,026 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Google 'Image Box' analysis
First import all the libraries we want, together with some formatting options
Step1: Read in Google Scraper search results table
Step2: Programatically identify... | Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
plt.style.use('ggplot')
plt.rcParams['figure.figsize'] = (15, 3)
plt.rcParams['font.family'] = 'sans-serif'
pd.set_option('display.width', 5000)
pd.set_option('display.max_columns', 60)
Explanation: Google 'Image Box... |
8,027 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Clustering Online Retail Sales Data
Dataset
Step1: Load data
Step2: Find out if there are any nan in the columns
Step3: Drop all records having nan CustomerId
Step4: Find number of uniqu... | Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import preprocessing, metrics, cluster
%matplotlib inline
Explanation: Clustering Online Retail Sales Data
Dataset: https://archive.ics.uci.edu/ml/datasets/online+retail
End of explanation
df = pd.read_excel("/data/Online R... |
8,028 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Basic statistical analysis of time series
In this example, basic time series statistical analysis is demonstrated.
Step1: Generating a Gaussian stochastic signal
Lets start by generating a ... | Python Code:
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
%matplotlib inline
import evapy
Explanation: Basic statistical analysis of time series
In this example, basic time series statistical analysis is demonstrated.
End of explanation
t = np.arange(0., 3*3600., 0.1)
Explanation: Generati... |
8,029 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
============================================================
Define target events based on time lag, plot evoked response
============================================================
This sc... | Python Code:
# Authors: Denis Engemann <denis.engemann@gmail.com>
#
# License: BSD (3-clause)
import mne
from mne import io
from mne.event import define_target_events
from mne.datasets import sample
import matplotlib.pyplot as plt
print(__doc__)
data_path = sample.data_path()
Explanation: ==============================... |
8,030 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Notebook to add co-ordinates for 1999 Polling Places
The AEC started putting co-ordinates on polling place files from 2007.
The code below matches to 2007 polling places, where the name of t... | Python Code:
import pandas as pd
import numpy as np
from IPython.display import display, HTML
import json
import googlemaps
Explanation: Notebook to add co-ordinates for 1999 Polling Places
The AEC started putting co-ordinates on polling place files from 2007.
The code below matches to 2007 polling places, where the na... |
8,031 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lecture 10 - eigenvalues and eigenvectors
An eigenvector $\boldsymbol{x}$ and corrsponding eigenvalue $\lambda$ of a square matrix $\boldsymbol{A}$ satisfy
$$
\boldsymbol{A} \boldsymbol{x} =... | Python Code:
# Import NumPy and seed random number generator to make generated matrices deterministic
import numpy as np
np.random.seed(1)
# Create a symmetric matrix with random entries
A = np.random.rand(5, 5)
A = A + A.T
print(A)
Explanation: Lecture 10 - eigenvalues and eigenvectors
An eigenvector $\boldsymbol{x}$ ... |
8,032 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Algorithms Exercise 1
Imports
Step3: Word counting
Write a function tokenize that takes a string of English text returns a list of words. It should also remove stop words, which are common ... | Python Code:
%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
Explanation: Algorithms Exercise 1
Imports
End of explanation
def tokenize(s, stop_words=None, punctuation='`~!@#$%^&*()_-+={[}]|\:;"<,>.?/}\t'):
Split a string into a list of words, removing punctuation and stop words.
low ... |
8,033 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Illumina Overview Tutorial
Step1: You can use the FileLink and FileLinks features of the IPython notebook to view or download data. FileLinks is used for viewing or downloading directories,... | Python Code:
!(wget ftp://ftp.microbio.me/qiime/tutorial_files/moving_pictures_tutorial-1.9.0.tgz || curl -O ftp://ftp.microbio.me/qiime/tutorial_files/moving_pictures_tutorial-1.9.0.tgz)
!tar -xzf moving_pictures_tutorial-1.9.0.tgz
Explanation: Illumina Overview Tutorial: Moving Pictures of the Human Microbiome
This t... |
8,034 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TensorFlow, Mini-Batch/Stochastic GradientDescent With Moment
Step1: Input
Generamos la muestra de grado 4
Step2: Problema
Calcular los coeficientes que mejor se ajusten a la muestra sabie... | Python Code:
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(color_codes=True)
%matplotlib inline
import sys
import time
from IPython.display import Image
sys.path.append('/home/pedro/git/ElCuadernillo/ElCuadernillo/20160301_TensorFlowGradientDescentWithMomentum'... |
8,035 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Examples of pyesgf.search usage
Prelude
Step1: Warning
Step2: Find how many datasets containing humidity in a given experiment family
Step3: Search using a partial ESGF dataset ID (and ge... | Python Code:
from pyesgf.search import SearchConnection
conn = SearchConnection('http://esgf-index1.ceda.ac.uk/esg-search',
distrib=True)
Explanation: Examples of pyesgf.search usage
Prelude:
End of explanation
facets='project,experiment_family'
Explanation: Warning: don't use default search wi... |
8,036 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Representational Similarity Analysis
Representational Similarity Analysis is used to perform summary statistics
on supervised classifications where the number of classes is relatively high.
... | Python Code:
# Authors: Jean-Remi King <jeanremi.king@gmail.com>
# Jaakko Leppakangas <jaeilepp@student.jyu.fi>
# Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD-3-Clause
import os.path as op
import numpy as np
from pandas import read_csv
import matplotlib.pyplot as plt
from sklearn.... |
8,037 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lightweight python components
Lightweight python components do not require you to build a new container image for every code change. They're intended to use for fast iteration in notebook en... | Python Code:
# Install the dependency packages
!pip install --upgrade pip
!pip install numpy tensorflow kfp-tekton
Explanation: Lightweight python components
Lightweight python components do not require you to build a new container image for every code change. They're intended to use for fast iteration in notebook envi... |
8,038 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Function h2percentile
Synopse
The h2percentile function computes the percentile given an image histogram.
g = iapercentile(h,q)
Output
g
Step1: Examples
Step2: Numeric Example
Comparison w... | Python Code:
def h2percentile(h,p):
import numpy as np
s = h.sum()
k = ((s-1) * p/100.)+1
dw = np.floor(k)
up = np.ceil(k)
hc = np.cumsum(h)
if isinstance(p, int):
k1 = np.argmax(hc>=dw)
k2 = np.argmax(hc>=up)
else:
k1 = np.argmax(hc>=dw[:,np.newaxis],axis=1)
... |
8,039 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Comparing Encoder-Decoders Analysis
Model Architecture
Step1: Perplexity on Each Dataset
Step2: Loss vs. Epoch
Step3: Perplexity vs. Epoch
Step4: Generations
Step5: BLEU Analysis
Step6:... | Python Code:
report_files = ['/Users/bking/IdeaProjects/LanguageModelRNN/experiment_results/encdec_noing6_200_512_04drb/encdec_noing6_200_512_04drb.json','/Users/bking/IdeaProjects/LanguageModelRNN/experiment_results/encdec_noing10_200_512_04drb/encdec_noing10_200_512_04drb.json','/Users/bking/IdeaProjects/LanguageMode... |
8,040 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
KNN
Algumas execuções usando scikit-learn
Vamos utilizar a implementação da biblioteca K-Nearest Neighbors para descobrir qual o melhor K para o nosso dataset.
O dataset utilizado foi obtido... | Python Code:
from sklearn.neighbors import KNeighborsClassifier
import numpy as np
import math
data = np.loadtxt("haberman.data",delimiter=",")
print(data)
Explanation: KNN
Algumas execuções usando scikit-learn
Vamos utilizar a implementação da biblioteca K-Nearest Neighbors para descobrir qual o melhor K para o nosso ... |
8,041 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Librosa tutorial
Version
Step1: Documentation!
Librosa has extensive documentation with examples.
When in doubt, go to http
Step2: Resampling is easy
Step3: But what's that in seconds?
St... | Python Code:
import librosa
print(librosa.__version__)
y, sr = librosa.load(librosa.util.example_audio_file())
print(len(y), sr)
Explanation: Librosa tutorial
Version: 0.4.3
Tutorial home: https://github.com/librosa/tutorial
Librosa home: http://librosa.github.io/
User forum: https://groups.google.com/forum/#!forum/lib... |
8,042 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Das Quell-Panel Verfahren
Das Panel-Verfahren wurde Anfang der 1970er Jahre entwickelt und ist eine in der Industrie weiterhin weit verbreitete Methode zur Berechnung der Umströmung von Flüg... | Python Code:
import math
import numpy as np
from scipy import integrate
import matplotlib.pyplot as plt
%matplotlib inline
class Panel:
# Initialisiert ein Objekt der Klasse Panel
def __init__(self, ax, ay, bx, by, lamb=0):
# Panel-Stärke lambda
self.lamb = lamb
# Koordinat... |
8,043 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Requirements
From this url http
Step1: Get all the detail page links to scrape
Since the index page has multiple pages (10 pages for now), we'll need to handle pagination, and note that the... | Python Code:
from IPython.core.display import display, HTML
import urllib2
import bs4
import urlparse
import pandas as pd
import numpy as np
Explanation: Requirements
From this url http://www.5metal.com.hk/ajax/pager/company_fea?view_amount=36&page=1,
We get a list of urls for detail pages like http://www.5metal.co... |
8,044 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href='http
Step1: Now set up everything so that the figures show up in the notebook
Step2: More info on other options for Offline Plotly usage can be found here.
Choropleth US Maps
Plot... | Python Code:
import plotly.plotly as py
import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
Explanation: <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a>
Choropleth Maps
Offline Plotly Usage
Get imports and set everything up to be... |
8,045 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Working with ECoG data
MNE supports working with more than just MEG and EEG data. Here we show some
of the functions that can be used to facilitate working with
electrocorticography (ECoG) d... | Python Code:
# Authors: Eric Larson <larson.eric.d@gmail.com>
# Chris Holdgraf <choldgraf@gmail.com>
#
# License: BSD (3-clause)
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import loadmat
from mayavi import mlab
import mne
from mne.viz import plot_alignment, snapshot_brain_montage
print(__... |
8,046 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generative Adversarial Networks in Keras
Step1: The original GAN!
See this paper for details of the approach we'll try first for our first GAN. We'll see if we can generate hand-drawn numbe... | Python Code:
%matplotlib inline
import importlib
import utils2; importlib.reload(utils2)
from utils2 import *
from tqdm import tqdm
Explanation: Generative Adversarial Networks in Keras
End of explanation
from keras.datasets import mnist
(X_train, y_train), (X_test, y_test) = mnist.load_data()
X_train.shape
n = len(X_t... |
8,047 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
__getitem__ AND __len__ 方法
下面看一个生成扑克牌以及对其进行操作的例子
Step1: 迭代
Step2: in 运算符
迭代通常是隐式的,如果集合中没有 __contains__ 方法, in 操作符就会按顺序进行一次迭代搜索,于是 in 可以在 FrenchDeck 类中使用,因为它是可迭代的
Step3: 排序
扑克牌一般按照数字大小( ... | Python Code:
import collections
Card = collections.namedtuple('Card', ['rank', 'suit']) #'Card' 是 namedtuple 名字, 后面是元素
class FrenchDeck:
ranks = [str(n) for n in range(2, 11)] + list('JQKA')
suits = 'spades diamonds clubs hearts'.split() # 黑桃 钻石 梅花 红心
def __init__(self):
self._cards = [Card(ran... |
8,048 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exploring Ensemble Methods
In this assignment, we will explore the use of boosting. We will use the pre-implemented gradient boosted trees in GraphLab Create. You will
Step1: Load LendingCl... | Python Code:
import graphlab
Explanation: Exploring Ensemble Methods
In this assignment, we will explore the use of boosting. We will use the pre-implemented gradient boosted trees in GraphLab Create. You will:
Use SFrames to do some feature engineering.
Train a boosted ensemble of decision-trees (gradient boosted tree... |
8,049 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
This is a basic tutorial on getting direct info and help of python modules from within a Jupyter notebook. Some of this tutorial is specific to Linux (particularly the commands ... | Python Code:
help(abs)
Explanation: Introduction
This is a basic tutorial on getting direct info and help of python modules from within a Jupyter notebook. Some of this tutorial is specific to Linux (particularly the commands that start with "!").
Getting Basic Help from the Python interpreter
Let's get help on Python'... |
8,050 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This is a Jupyter notebook for David Dobrinskiy's HSE Thesis
How Venture Capital Affects Startups' Success
Step1: Let us look at the dynamics of total US VC investment
Step3: Deals and inv... | Python Code:
# You should be running python3
import sys
print(sys.version)
import pandas as pd # http://pandas.pydata.org/
import numpy as np # http://numpy.org/
import statsmodels.api as sm # http://statsmodels.sourceforge.net/stable/index.html
import statsmodels.formula.api as smf
import statsmodels
print("Pandas... |
8,051 | 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', 'cmcc', 'sandbox-3', 'landice')
Explanation: ES-DOC CMIP6 Model Properties - Landice
MIP Era: CMIP6
Institute: CMCC
Source ID: SANDBOX-3
Topic: Landice
Sub-Topics: Glaciers, Ice.
Prop... |
8,052 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="images/csdms_logo.jpg">
Using a BMI
Step1: Import the Waves class, and instantiate it. In Python, a model with a BMI will have no arguments for its constructor. Note that although... | Python Code:
%matplotlib inline
Explanation: <img src="images/csdms_logo.jpg">
Using a BMI: Waves
This example explores how to use a BMI implementation using the Waves model as an example.
Links
Waves source code: Look at the files that have waves in their name.
Waves description on CSDMS: Detailed information on the W... |
8,053 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
how long until I get into the Hardrock 100?
The Hardrock 100 is a 100-mile footrace through the San Juan mountains of Colorado. It is considered a "post-graduate level" event with 66000 fee... | Python Code:
import pandas as pd
import matplotlib.pyplot as plt
import pymc
import numpy as np
from scipy import stats
%matplotlib inline
Explanation: how long until I get into the Hardrock 100?
The Hardrock 100 is a 100-mile footrace through the San Juan mountains of Colorado. It is considered a "post-graduate level... |
8,054 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href='http
Step1: Of the three parts of this app, part 2 should be very familiar by now -- load some taxi dropoff locations, declare a Points object, datashade them, and set some plot op... | Python Code:
with open('./apps/server_app.py', 'r') as f:
print(f.read())
Explanation: <a href='http://www.holoviews.org'><img src="assets/hv+bk.png" alt="HV+BK logos" width="40%;" align="left"/></a>
<div style="float:right;"><h2>08. Deploying Bokeh Apps</h2></div>
In the previous sections we discovered how to use ... |
8,055 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2021 The TensorFlow Authors.
Step1: Uncertainty-aware Deep Learning with SNGP
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: D... | 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... |
8,056 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Coronagraph Wedge Masks
The notebook builds on the concepts introduced in Coronagraph_Basics.ipynb. Specifically, we concentrate on the complexities involved in simulating the wedge coronagr... | Python Code:
# Import the usual libraries
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
# Enable inline plotting at lower left
%matplotlib inline
Explanation: Coronagraph Wedge Masks
The notebook builds on the concepts introduced in Coronagraph_Basics.ipynb. Specifically, we concentrate on the co... |
8,057 | 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... |
8,058 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Multiple Routes Analysis
In this section, we are trying to answer a very interesting question
Step1: Generate Random Routes
In order to accomplish this goal, we need to have a function that... | Python Code:
## import system module
import json
import rethinkdb as r
import time
import datetime as dt
import asyncio
from shapely.geometry import Point, Polygon
import random
import pandas as pd
import os
import matplotlib.pyplot as plt
## import custom module
from streettraffic.server import TrafficServer
from stre... |
8,059 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img style="float
Step1: Select the water Station
For our example, we will query a water station called Bristol Avon Little Avon Axe and North Somerset St. This station has the station numb... | Python Code:
%load_ext watermark
import sys
from datetime import datetime
from datetime import datetime, timedelta
sys.path.append("../") # Add parent dir in the Path
from hyperstream import HyperStream, StreamId
from hyperstream import TimeInterval
from hyperstream.utils import UTC
from utils import plot_high_chart
%w... |
8,060 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
RADseq data simulations
I simulated two trees to work with. One that is completely imbalanced (ladder-like) and one that is balanced (equal number tips descended from each node). I'm using t... | Python Code:
## standard Python imports
import glob
import itertools
from collections import OrderedDict, Counter
## extra Python imports
import rpy2 ## required for tree plotting
import ete2 ## used for tree manipulation
import egglib ## used for coalescent simulations
import numpy... |
8,061 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Homework 6
Use this notebook to work on your answers and check solutions. You can then submit your functions using "hw6_submission.ipynb" or directly write your functions in a file named "hw... | Python Code:
# Loading python packages and APD data file (this step does not have to be included in hw6_answers.py)
import pandas as pd
import numpy as np
df = pd.read_csv('/home/data/APD/COBRA-YTD2017.csv.gz')
Explanation: Homework 6
Use this notebook to work on your answers and check solutions. You can then submit yo... |
8,062 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Classification problems are a broad category of machine learning problems that involve the prediction of values taken from a discrete, finite number of cases.
In this example, we'll build a... | Python Code:
import pandas as pd
iris = pd.read_csv('../datasets/iris.csv')
# Print some info about the dataset
iris.info()
iris['Class'].unique()
iris.describe()
Explanation: Classification problems are a broad category of machine learning problems that involve the prediction of values taken from a discrete, finite nu... |
8,063 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pandas is a Python Data Analysis Library. It allows you to play around with data and perform powerful data analysis.
In this example I will show you how to read data from CSV and Excel file... | Python Code:
import pandas as pd
csv_data_df = pd.read_csv('data/MOCK_DATA.csv')
Explanation: Pandas is a Python Data Analysis Library. It allows you to play around with data and perform powerful data analysis.
In this example I will show you how to read data from CSV and Excel files in Pandas. You can then save the r... |
8,064 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<!--BOOK_INFORMATION-->
<img align="left" style="padding-right
Step1: Lists have a number of useful properties and methods available to them.
Here we'll take a quick look at some of the mor... | Python Code:
L = [2, 3, 5, 7]
Explanation: <!--BOOK_INFORMATION-->
<img align="left" style="padding-right:10px;" src="fig/cover-small.jpg">
This notebook contains an excerpt from the Whirlwind Tour of Python by Jake VanderPlas; the content is available on GitHub.
The text and code are released under the CC0 license; se... |
8,065 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
sequana_coverage test case example (fungus)
This notebook creates the BED file S_pombe.filtered.bed provided in
- https
Step1: Download FastQ files (1.6Gb)
Step2: Download reference and a... | Python Code:
%pylab inline
matplotlib.rcParams['figure.figsize'] = [10,7]
Explanation: sequana_coverage test case example (fungus)
This notebook creates the BED file S_pombe.filtered.bed provided in
- https://github.com/sequana/resources/tree/master/coverage and
- https://www.synapse.org/#!Synapse:syn10638358/wiki/465... |
8,066 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tom Augspurger Dplyr/Pandas comparison (copy of 2016-01-01)
See result there
http
Step1: using an internet download to get flight.qcsv
Step2: Data
Step3: Single table verbs
dplyr has a s... | Python Code:
#%load_ext rpy2.ipython
#%R install.packages("nycflights13", repos='http://cran.us.r-project.org')
#%R library(nycflights13)
#%R write.csv(flights, "flights.csv")
Explanation: Tom Augspurger Dplyr/Pandas comparison (copy of 2016-01-01)
See result there
http://nbviewer.ipython.org/urls/gist.githubuserconten... |
8,067 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
KK's Rscript to Pyscript
Somayaji made a script in R which I am dying to reproduce in python using pandas and other great frameworks. His source file is
Step1: And the Resource for this lea... | Python Code:
ls -l *.R
Explanation: KK's Rscript to Pyscript
Somayaji made a script in R which I am dying to reproduce in python using pandas and other great frameworks. His source file is:
End of explanation
from pandas import DataFrame, read_csv
import matplotlib.pyplot as plt
import pandas as pd
import sys
%matplotl... |
8,068 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lexical Analysis of Wikipedia Abstracts
In this notebook we preprocess the biography overviews from the English DBpedia. We train a model to detect bi-grams in text, and we generate a vocabu... | Python Code:
from __future__ import print_function, unicode_literals
from dbpedia_utils import iter_entities_from
from collections import defaultdict, Counter
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import gensim
import json
import gzip
import nltk
import dbpedia_config
source_folder = db... |
8,069 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The most characteristic words in pro- and anti-feminist tweets
Attitude analysis by machine learning as an alternative to sentiment analysis in order to classify tweets as pro- or anti-femin... | Python Code:
import csv
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import re
import requests
import seaborn as sns
import shutil
import time
import urllib.request
from collections import Counter
from textblob import TextBlob
%matplotlib inline
Explanation: The most characteristic w... |
8,070 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="http
Step1: This function will plot a cubic function and the parameter values obtained via Gradient Descent.
Step2: This function will plot a 4th order function and the parameter ... | Python Code:
# These are the libraries will be used for this lab.
import torch
import torch.nn as nn
import matplotlib.pylab as plt
import numpy as np
torch.manual_seed(0)
Explanation: <a href="http://cocl.us/pytorch_link_top">
<img src="https://cocl.us/Pytorch_top" width="750" alt="IBM 10TB Storage" />
</a>
<img ... |
8,071 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Modeling 2
Step1: Fit an emission line in a stellar spectrum
M dwarfs are low mass stars (less than half of the mass of the sun). Currently we do not understand completely the physics insid... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
from astropy.io import fits
from astropy.modeling import models, fitting
from astropy.modeling.models import custom_model
from astropy.modeling import Fittable1DModel, Parameter
from astroquery.sdss import SDSS
Explanation: Modeling 2: Create a User Define... |
8,072 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Below path is a shared directory, swap to own
Step1: Replication of 'csv_to_hdf5.py'
Original repo used some bizarre tuple method of reading in data to save in a hdf5 file using fuel. The f... | Python Code:
data_path = "data/taxi/"
Explanation: Below path is a shared directory, swap to own
End of explanation
meta = pd.read_csv(data_path+'metaData_taxistandsID_name_GPSlocation.csv', header=0)
meta.head()
train = pd.read_csv(data_path+'train/train.csv', header=0)
train.head()
train['ORIGIN_CALL'] = pd.Series(pd... |
8,073 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Final SpIES High-z Quasar Selection
Notebook performing selection of $3.5<z<5$ quasars from SDSS+SpIES data.
Largely the same as SpIESHighzQuasars notebook except using the algoirthm(s) from... | Python Code:
%matplotlib inline
from astropy.table import Table
import numpy as np
import matplotlib.pyplot as plt
data = Table.read('GTR-ADM-QSO-ir-testhighz_findbw_lup_2016_starclean.fits')
# X is in the format need for all of the sklearn tools, it just has the colors
# X = np.vstack([ data['ug'], data['gr'], data['r... |
8,074 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The role of dipole orientations in distributed source localization
When performing source localization in a distributed manner (MNE/dSPM/sLORETA),
the source space is defined as a grid of di... | Python Code:
from mayavi import mlab
import mne
from mne.datasets import sample
from mne.minimum_norm import make_inverse_operator, apply_inverse
data_path = sample.data_path()
evokeds = mne.read_evokeds(data_path + '/MEG/sample/sample_audvis-ave.fif')
left_auditory = evokeds[0].apply_baseline()
fwd = mne.read_forward_... |
8,075 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
syncID
Step1: Open a GeoTIFF with GDAL
Let's look at the SERC Canopy Height Model (CHM) to start. We can open and read this in Python using the gdal.Open function
Step2: Read GeoTIFF Tags
... | Python Code:
import numpy as np
import gdal, copy
import matplotlib.pyplot as plt
%matplotlib inline
import warnings
warnings.filterwarnings('ignore')
Explanation: syncID: b0860577d1994b6e8abd23a6edf9e005
title: "Classify a Raster Using Threshold Values in Python - 2018"
description: "Learn how to read NEON lidar raste... |
8,076 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Transport Problem
Summary
The goal of the Transport Problem is to select the quantities of an homogeneous good that has several production plants and several punctiform markets as to min... | Python Code:
# Import of the pyomo module
from pyomo.environ import *
# Creation of a Concrete Model
model = ConcreteModel()
Explanation: The Transport Problem
Summary
The goal of the Transport Problem is to select the quantities of an homogeneous good that has several production plants and several punctiform markets... |
8,077 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Trying out the Transformer dataset class from Pylearn2 with our current dataset class as raw, should be able to make a block to apply to it using one of our processing functions that will pr... | Python Code:
import pylearn2.utils
import pylearn2.config
import theano
import neukrill_net.dense_dataset
import neukrill_net.utils
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import holoviews as hl
%load_ext holoviews.ipython
import sklearn.metrics
cd ..
settings = neukrill_net.utils.Settings... |
8,078 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Optically pumped magnetometer (OPM) data
In this dataset, electrical median nerve stimulation was delivered to the
left wrist of the subject. Somatosensory evoked fields were measured using
... | Python Code:
import os.path as op
import numpy as np
import mne
data_path = mne.datasets.opm.data_path()
subject = 'OPM_sample'
subjects_dir = op.join(data_path, 'subjects')
raw_fname = op.join(data_path, 'MEG', 'OPM', 'OPM_SEF_raw.fif')
bem_fname = op.join(subjects_dir, subject, 'bem',
subject + '-... |
8,079 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook will investigate instances where the river is reversed, and sewage is dumped into the lake. We will take a look at rainfall before these events, to see if there is a correlati... | Python Code:
# Get River reversals
reversals = pd.read_csv('data/lake_michigan_reversals.csv')
reversals['start_date'] = pd.to_datetime(reversals['start_date'])
reversals.head()
# Create rainfall dataframe. Create a series that has hourly precipitation
rain_df = pd.read_csv('data/ohare_hourly_20160929.csv')
rain_df['d... |
8,080 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Maren Equations Summary
This notebook is just pulling out the important figures and tables for the manuscript. For more detailed explanations and exploring see other notebooks.
Step1: Impor... | Python Code:
# Set-up default environment
%run '../ipython_startup.py'
# Import additional libraries
import sas7bdat as sas
import cPickle as pickle
import statsmodels.formula.api as smf
from ase_cisEq import marenEq
from ase_cisEq import marenPrintTable
from ase_normalization import meanCenter
from ase_normalization i... |
8,081 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Implement estimators of large-scale sparse Gaussian densities
by Soumyajit De (email
Step1: First, to keep the notion of Krylov subspace, we view the matrix as a linear operator that applie... | Python Code:
%matplotlib inline
from scipy.sparse import eye
from scipy.io import mmread
from matplotlib import pyplot as plt
import os
SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data')
matFile=os.path.join(SHOGUN_DATA_DIR, 'logdet/apache2.mtx.gz')
M = mmread(matFile)
rows = M.shape[0]
cols = M.shape[1]
A =... |
8,082 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
← Back to Index
Evaluation using mir_eval
mir_eval (documentation, paper) is a Python library containing evaluation functions for a variety of common audio and music processing tasks.
... | Python Code:
y, sr = librosa.load('audio/simple_piano.wav')
# Estimate onsets.
est_onsets = librosa.onset.onset_detect(y=y, sr=sr, units='time')
est_onsets
# Load the reference annotation.
ref_onsets = numpy.array([0.1, 0.21, 0.3])
mir_eval.onset.evaluate(ref_onsets, est_onsets)
Explanation: ← Back to Index
Evalua... |
8,083 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
how to implement the mean squared loss in TensorFlow
| Python Code::
import tensorflow as tf
from tensorflow.keras.losses import MeanSquaredError
y_true = [1., 0.]
y_pred = [2., 3.]
mse_loss = MeanSquaredError()
loss = mse_loss(y_true, y_pred).numpy()
|
8,084 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
用Python 3开发网络爬虫
By Terrill Yang (Github
Step1: 请求响应的类型是 requests.models.Response
Step2: 状态码是200
Step3: 响应体的类型是字符串str
Step4: 可以得到响应的 HTTP HEADER
Step5: 响应体内容
Step6: Cookies的类型是RequestsC... | Python Code:
import requests
r = requests.get('https://www.baidu.com/')
Explanation: 用Python 3开发网络爬虫
By Terrill Yang (Github: https://github.com/yttty)
由你需要这些:Python3.x爬虫学习资料整理 - 知乎专栏整理而来。
本篇来自requests的基本使用
用Python 3开发网络爬虫 - Chapter 04
使用requests库
在 urllib 库中,有 urllib.request.urlopen(url) 的方法,实际上它是以 GET 方式请求了一个网页。
那么在 ... |
8,085 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lab 3 - Multi Layer Perceptron with MNIST
This lab corresponds to Module 3 of the "Deep Learning Explained" course. We assume that you have successfully completed Lab 1 (Downloading the MNI... | Python Code:
# Figure 1
Image(url= "http://3.bp.blogspot.com/_UpN7DfJA0j4/TJtUBWPk0SI/AAAAAAAAABY/oWPMtmqJn3k/s1600/mnist_originals.png", width=200, height=200)
Explanation: Lab 3 - Multi Layer Perceptron with MNIST
This lab corresponds to Module 3 of the "Deep Learning Explained" course. We assume that you have succe... |
8,086 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<small><i>This notebook was prepared by Donne Martin. Source and license info is on GitHub.</i></small>
Challenge Notebook
Problem
Step1: Unit Test
The following unit test is expected to fa... | Python Code:
%run ../stack/stack.py
%load ../stack/stack.py
class MyStack(Stack):
def sort(self):
# TODO: Implement me
pass
Explanation: <small><i>This notebook was prepared by Donne Martin. Source and license info is on GitHub.</i></small>
Challenge Notebook
Problem: Sort a stack. You can use anot... |
8,087 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
mocsy examples using mocsy from IOOS channel
12/12 and 11/9/2015. Emilio Mayorga. Reproduce and extend Examples 1-3 from the mocys Python documentation page.
- mocsy Python source documentat... | Python Code:
import mocsy
Explanation: mocsy examples using mocsy from IOOS channel
12/12 and 11/9/2015. Emilio Mayorga. Reproduce and extend Examples 1-3 from the mocys Python documentation page.
- mocsy Python source documentation: http://ocmip5.ipsl.jussieu.fr/mocsy/pyth.html
- See ioos-channel implementation discus... |
8,088 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Notebook 1
Step1: Download the sequence data
Sequence data for this study is archived on the NCBI sequence read archive (SRA). The data were run in two separate Illumina runs, but are combi... | Python Code:
### Notebook 1
### Data set 1 (Viburnum)
### Language: Bash
### Data Location: NCBI SRA PRJNA299402 & PRJNA299407
%%bash
## make a new directory for this analysis
mkdir -p empirical_1/
mkdir -p empirical_1/halfrun
mkdir -p empirical_1/fullrun
## import Python libraries
import pandas as pd
import numpy as n... |
8,089 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Orientation density functions
Step1: In this Python Notebook we will show how to properly run a simulation of a composite material, providing the ODF (orientation density function) of the r... | Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from simmit import smartplus as sim
from simmit import identify as iden
import os
dir = os.path.dirname(os.path.realpath('__file__'))
Explanation: Orientation density functions
End of explanation
x = np.arange(0,182,2... |
8,090 | 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', 'test-institute-2', 'sandbox-3', 'atmoschem')
Explanation: ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era: CMIP6
Institute: TEST-INSTITUTE-2
Source ID: SANDBOX-3
Topic: Atmoschem
Su... |
8,091 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Spectral Temperature Estimation
Problem Statement
A spectral radiometer is used to determine the surface temperature of a hot object exposed to sunlight. The surface normal vector is pointi... | Python Code:
from IPython.display import display
from IPython.display import Image
from IPython.display import HTML
%matplotlib inline
import numpy as np
from scipy.optimize import curve_fit
import pyradi.ryutils as ryutils
import pyradi.ryplot as ryplot
import pyradi.ryplanck as ryplanck
#make pngs at required dpi
imp... |
8,092 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2021 The TF-Agents Authors.
Step1: Checkpointer and PolicySaver
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: DQN agent
We ar... | 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... |
8,093 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Making Inferences
Step1: Star Schema (facts vs. dimensions)
In our case, the individual review events are the facts and listings themselves are the dimensions.
Step2:
Step3: Pandas Resam... | Python Code:
import pandas as pd
import matplotlib as plt
# draw plots in notebook
%matplotlib inline
# make plots SVG (higher quality)
%config InlineBackend.figure_format = 'svg'
# more time/compute intensive to parse dates. but we know we definitely have/need them
df = pd.read_csv('data/sf_listings.csv', parse_dates=... |
8,094 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Revisão
Step1: Para acessar elementos de uma lista utilizamos [indice], com indice sendo um inteiro representando a posição que se encontra o elemento.
Nota
Step2: Também podemos especific... | Python Code:
lista1 = [1, 2, 3, 4, 5]
lista2 = ['um', 'dois', 'três', 'quatro', 'cinco']
lista3 = [1, 'dois', 3.0, 4, 'cinco']
print('lista1 é uma lista apenas do tipo int: ', lista1)
print('lista2 é uma lista apenas do tipo str: ', lista2)
print('lista3 é uma lista apenas contendo variáveis de tipos int, str e float: ... |
8,095 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python Data Algorithms Quick Reference
Table Of Contents
<a href="#1.-Manually-Consuming-an-Iterator">Manually Consuming an Iterator</a>
<a href="#2.-Delegating-Iterator">Delegating Iterator... | Python Code:
items = [1, 2, 3]
# Get the iterator
it = iter(items) # Invokes items.__iter__()
# Run the iterator
next(it) # Invokes it.__next__()
next(it)
next(it)
# if you uncomment this line it would throw a StopOperation exception
# next(it)
Explanation: Python Data Algorithms Quick Reference
Table Of Contents
<a hr... |
8,096 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Continuous Target Decoding with SPoC
Source Power Comodulation (SPoC)
Step1: Plot the contributions to the detected components (i.e., the forward model) | Python Code:
# Author: Alexandre Barachant <alexandre.barachant@gmail.com>
# Jean-Remi King <jeanremi.king@gmail.com>
#
# License: BSD-3-Clause
import matplotlib.pyplot as plt
import mne
from mne import Epochs
from mne.decoding import SPoC
from mne.datasets.fieldtrip_cmc import data_path
from sklearn.pipeline i... |
8,097 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
FDR correction on T-test on sensor data
One tests if the evoked response significantly deviates from 0.
Multiple comparison problem is addressed with
False Discovery Rate (FDR) correction.
S... | Python Code:
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD (3-clause)
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
import mne
from mne import io
from mne.datasets import sample
from mne.stats import bonferroni_correction, fdr_correction
print(__doc__)
Explana... |
8,098 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2A.ml - 2016 - Compétition ENSAE - Premiers modèles
Une compétition était proposée dans le cadre du cours Python pour un Data Scientist à l'ENSAE. Ce notebook facilite la prise en main des d... | Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
Explanation: 2A.ml - 2016 - Compétition ENSAE - Premiers modèles
Une compétition était proposée dans le cadre du cours Python pour un Data Scientist à l'ENSAE. Ce notebook facilite la prise en main des données et propose de mettre en oeuvre un... |
8,099 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Graphs and visualization
A lot of the joy of digital humanities comes in handling our material in new ways, so that we see things we wouldn't have seen before. Quite literally.
Some of the m... | Python Code:
# This is how you get the %%dot and %dotstr command that we use below.
%load_ext hierarchymagic
Explanation: Graphs and visualization
A lot of the joy of digital humanities comes in handling our material in new ways, so that we see things we wouldn't have seen before. Quite literally.
Some of the most us... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.