Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
5,300
Given the following text description, write Python code to implement the functionality described below step by step Description: Note Step1: The ImageCollection class provides an easy way of loading and representing multiple images. Images are not read from disk until accessed. Step2: Credit Step3: For this demo, ...
Python Code: import numpy as np import matplotlib.pyplot as plt from skimage import io, transform from skimage.color import rgb2gray from skdemo import imshow_all ic = io.ImageCollection('../images/pano/DFM_*') Explanation: Note: This example has been significantly expanded and enhanced. The new, recommended version is...
5,301
Given the following text description, write Python code to implement the functionality described below step by step Description: 2.3 Python语言基础 1 语言语义(Language Semantics) 缩进,而不是括号 Python使用空格(tabs or spaces)来组织代码结构,而不是像R,C++,Java那样用括号。 建议使用四个空格来作为默认的缩进,设置tab键为四个空格 另外可以用分号隔开多个语句: Step1: 所有事物都是对象(object) 在python中,number...
Python Code: a = 5; b = 6; c = 7 Explanation: 2.3 Python语言基础 1 语言语义(Language Semantics) 缩进,而不是括号 Python使用空格(tabs or spaces)来组织代码结构,而不是像R,C++,Java那样用括号。 建议使用四个空格来作为默认的缩进,设置tab键为四个空格 另外可以用分号隔开多个语句: End of explanation result = f(x, y, z) Explanation: 所有事物都是对象(object) 在python中,number,string,data structure,function,class,mo...
5,302
Given the following text description, write Python code to implement the functionality described below step by step Description: Variables and 3D Shapes In the last class we used functions and arguments to build circles, spheres and hollow spheres of different radii. Lets go ahead and build some 3D solid shapes as wel...
Python Code: import sys sys.path.append('/home/pi/minecraft-programming') import mcpi.block as block import time import drawings Explanation: Variables and 3D Shapes In the last class we used functions and arguments to build circles, spheres and hollow spheres of different radii. Lets go ahead and build some 3D solid s...
5,303
Given the following text description, write Python code to implement the functionality described below step by step Description: Sta 663 Final Project by Hao Sheng, Xiaozhou Wang netid Step1: Benchmark of vectorization Step2: As for the optimization, we employed vectorization to avoid the use of triple for-loops und...
Python Code: import numpy as np from numpy import random from collections import deque import matplotlib.pyplot as plt import HMM import pandas as pd from hmmlearn import hmm Explanation: Sta 663 Final Project by Hao Sheng, Xiaozhou Wang netid: hs220, xw106 email: {hao.sheng,xiaozhou.wang}@duke.edu Please make sure you...
5,304
Given the following text description, write Python code to implement the functionality described below step by step Description: 用ConfigParser模块读写conf配置文件 ConfigParser是Python内置的一个读取配置文件的模块,用它来读取和修改配置文件非常方便,本文介绍一下它的基本用法。 数据准备 假设当前目录下有一个名为sys.conf的配置文件,其内容如下: ```bash [db] db_host=127.0.0.1 db_port=22 db_user=root db_pas...
Python Code: import ConfigParser cf = ConfigParser.ConfigParser() cf.read('./sys.conf') Explanation: 用ConfigParser模块读写conf配置文件 ConfigParser是Python内置的一个读取配置文件的模块,用它来读取和修改配置文件非常方便,本文介绍一下它的基本用法。 数据准备 假设当前目录下有一个名为sys.conf的配置文件,其内容如下: ```bash [db] db_host=127.0.0.1 db_port=22 db_user=root db_pass=root123 [concurrent] thread...
5,305
Given the following text description, write Python code to implement the functionality described below step by step Description: Using Interrupts and asyncio for Buttons and Switches This notebook provides a simple example for using asyncio I/O to interact asynchronously with multiple input devices. A task is created ...
Python Code: from pynq import PL from pynq.overlays.base import BaseOverlay base = BaseOverlay("base.bit") Explanation: Using Interrupts and asyncio for Buttons and Switches This notebook provides a simple example for using asyncio I/O to interact asynchronously with multiple input devices. A task is created for each i...
5,306
Given the following text description, write Python code to implement the functionality described below step by step Description: Building a System 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 u...
Python Code: !pip install -I "phoebe>=2.0,<2.1" Explanation: Building a System 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 import phoebe from p...
5,307
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Implicit generative model An implicit generative model only provides us with samples. Here for simplicity, we use a different set of samples obtained from the data dis...
Python Code: import random import numpy as np import seaborn as sns import matplotlib.pyplot as plt import scipy sns.set(rc={"lines.linewidth": 2.8}, font_scale=2) sns.set_style("whitegrid") # We implement our own very simple mixture, relying on scipy for the mixture # components. class SimpleGaussianMixture(object): ...
5,308
Given the following text description, write Python code to implement the functionality described below step by step Description: Função para codificar rótulos inteiros na codificação one-hot Esta função é também chamada de conversão para dados categóricos. Temos 3 classes de flores Step1: Primeira solução Step2: Seg...
Python Code: import numpy as np Explanation: Função para codificar rótulos inteiros na codificação one-hot Esta função é também chamada de conversão para dados categóricos. Temos 3 classes de flores: Iris setosa, Iris virginica and Iris versicolor. Estas classes podem ser codificadas como classes 0, 1 e 2 (rótulos numé...
5,309
Given the following text description, write Python code to implement the functionality described below step by step Description: Andreas Alexopoulos 30 / 08 / 2016 Introduction The Beam Loss Monitoring system of the Large Hadron Collider close to the interaction points contains mostly gas ionization chambers working a...
Python Code: from __future__ import print_function, division import warnings from collections import deque from datetime import datetime, timedelta from time import ctime from os.path import abspath, join from itertools import cycle import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Patch...
5,310
Given the following text description, write Python code to implement the functionality described below step by step Description: Using the trained weights in an ensemble of neurons On the function points branch of nengo On the vision branch of nengo_extras Step1: Load the MNIST database Step2: Each digit is represen...
Python Code: import nengo import numpy as np import cPickle from nengo_extras.data import load_mnist from nengo_extras.vision import Gabor, Mask from matplotlib import pylab import matplotlib.pyplot as plt import matplotlib.animation as animation import scipy.ndimage from scipy.ndimage.interpolation import rotate Expla...
5,311
Given the following text description, write Python code to implement the functionality described below step by step Description: Useful Scripts Location of the scripts Here are some scripts that you may find useful. They are in the folder "./eppy/useful_scripts" And now for some housekeeping before we start off Step1:...
Python Code: import os os.chdir("../eppy/useful_scripts") # changes directory, so we are where the scripts are located # you would normaly install eppy by doing # python setup.py install # or # pip install eppy # or # easy_install eppy # if you have not done so, the following three lines are needed import sys # pathnam...
5,312
Given the following text description, write Python code to implement the functionality described below step by step Description: Smart Underwriter! Step1: Underwrting Step2: Let's take a peek at the data. Step3: How many morgages have been prepaid in these three years? Step4: Remember prepay includes a common case...
Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib import seaborn as sns pd.options.display.max_columns = 999 %matplotlib inline matplotlib.rcParams['savefig.dpi'] = 1.5 * matplotlib.rcParams['savefig.dpi'] Explanation: Smart Underwriter! End of explanation # Read the ...
5,313
Given the following text description, write Python code to implement the functionality described below step by step Description: <H1>Pattern similarities</H1> <P>We will compare similarities between the patterns in a network before (input) and after (output) the effect of inhibition.</P> <P> If patterns of activity ar...
Python Code: # load necessary modules %pylab inline import numpy as np np.random.seed(0) from __future__ import division from inet import __version__ from inet.plots import separation_plot print(__version__) Explanation: <H1>Pattern similarities</H1> <P>We will compare similarities between the patterns in a network be...
5,314
Given the following text description, write Python code to implement the functionality described below step by step Description: 2A.ML101.1 Step1: Numpy Arrays Manipulating numpy arrays is an important part of doing machine learning (or, really, any type of scientific computation) in Python. This will likely be revi...
Python Code: # Start pylab inline mode, so figures will appear in the notebook %matplotlib inline Explanation: 2A.ML101.1: Introduction to data manipulation with scientific Python In this section we'll go through the basics of the scientific Python stack for data manipulation: using numpy and matplotlib. Source: Course...
5,315
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Slider Example This example will allow the user to use sliders to interact with the ISR spectra. Currently this notebook creates two images. The first is a dual plot of the ACF and Po...
Python Code: import numpy as np import matplotlib as mpl import scipy.fftpack as scfft import scipy.constants as spconst import matplotlib.pylab as plt import seaborn as sns sns.set_style("white") sns.set_context("notebook") # from ISRSpectrum import Specinit import ipywidgets from IPython.display import display #%mat...
5,316
Given the following text description, write Python code to implement the functionality described below step by step Description: Machine Learning Engineer Nanodegree Unsupervised Learning Project 3 Step1: Data Exploration In this section, you will begin exploring the data through visualizations and code to understand...
Python Code: # Import libraries necessary for this project import numpy as np import pandas as pd import renders as rs from IPython.display import display # Allows the use of display() for DataFrames # Show matplotlib plots inline (nicely formatted in the notebook) %matplotlib inline # Load the wholesale customers data...
5,317
Given the following text description, write Python code to implement the functionality described below step by step Description: Numpy Exercise 4 Imports Step1: Complete graph Laplacian In discrete mathematics a Graph is a set of vertices or nodes that are connected to each other by edges or lines. If those edges don...
Python Code: import numpy as np %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns Explanation: Numpy Exercise 4 Imports End of explanation import networkx as nx K_5=nx.complete_graph(5) nx.draw(K_5) Explanation: Complete graph Laplacian In discrete mathematics a Graph is a set of vertices or node...
5,318
Given the following text description, write Python code to implement the functionality described below step by step Description: WARNING It is a non-public API. It may change with no previous notice We are going to show how to work with the CARTO custom visualizations (aka Kuviz). We are going to start creating tje Au...
Python Code: USERNAME = "" BASE_URL = "https://{u}.carto.com".format(u=USERNAME) API_KEY = "" from carto.auth import APIKeyAuthClient auth_client = APIKeyAuthClient(api_key=API_KEY, base_url=BASE_URL) Explanation: WARNING It is a non-public API. It may change with no previous notice We are going to show how to work wit...
5,319
Given the following text description, write Python code to implement the functionality described below step by step Description: Xhistogram Tutorial Histograms are the foundation of many forms of data analysis. The goal of xhistogram is to make it easy to calculate weighted histograms in multiple dimensions over n-dim...
Python Code: import xarray as xr import numpy as np %matplotlib inline nt, nx = 100, 30 da = xr.DataArray(np.random.randn(nt, nx), dims=['time', 'x'], name='foo') # all inputs need a name display(da) da.plot() Explanation: Xhistogram Tutorial Histograms are the foundation of many forms of data analysi...
5,320
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Project Euler Step2: I realize this probably isn't the fastest or most concise code, but it works. Now write a set of assert tests for your number_to_words function that verifies tha...
Python Code: def number_to_words(n): Given a number n between 1-1000 inclusive return a list of words for the number. words = {0:'',1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',9:'nine',10:'ten',11:'eleven',12:'twelve',13:'thirteen',14:'fourteen',15:'fifteen',16:'sixteen',17:'seventee...
5,321
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="http Step1: Pick the initial and run conditions Step2: Elapsed time starts at 1 second. This prevents errors when setting our boundary conditions. Step3: Use Landlab methods to i...
Python Code: from landlab.components.overland_flow import OverlandFlow from landlab.plot.imshow import imshow_grid from landlab.plot.colors import water_colormap from landlab import RasterModelGrid from landlab.io.esri_ascii import read_esri_ascii from matplotlib.pyplot import figure import numpy as np from time import...
5,322
Given the following text description, write Python code to implement the functionality described below step by step Description: Umbrella sampling simulations The bias is computed via a harmonic potential based on the deviation of a frame from a reference structure. In the usual one-dimensional case, this reads $$b^{(...
Python Code: adw_x, adw_f, adw_pi = shortcuts.adw_reference(-1, 5, 100) fig, ax = plt.subplots(1, 2, figsize=(2 * pw, ph)) ax[0].plot(adw_x, adw_pi, linewidth=3, color='black') ax[0].set_ylabel(r"$\pi(x)$", fontsize=20) ax[0].semilogy() ax[1].plot(adw_x, adw_f, linewidth=3, color='black') ax[1].set_ylabel(r"$f(x)$ / kT...
5,323
Given the following text description, write Python code to implement the functionality described below step by step Description: TinyDB TinyDB is a small and lightweight NoSQL database framework based on simple JSON files. Source Official Website Step1: Insert some data into db. Step2: Fill with some data (iris). St...
Python Code: path = './testData.json' from tinydb import TinyDB, where db = TinyDB(path) Explanation: TinyDB TinyDB is a small and lightweight NoSQL database framework based on simple JSON files. Source Official Website: - getting started - advanced usage Code Some examples to create a database and insert, delete and s...
5,324
Given the following text description, write Python code to implement the functionality described below step by step Description: Variational Autoencoder Step5: Task Step6: Visualize reconstruction quality Step7: Illustrating latent space Next, we train a VAE with 2d latent space and illustrates how the encoder (the...
Python Code: import numpy as np import tensorflow as tf import tensorflow.contrib.slim as slim from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets import matplotlib.pyplot as plt %matplotlib inline import input_data mnist = input_data.read_data_sets('fashion-mnist/data/fashion', one_hot=True...
5,325
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial 2 Step1: Parametrization (recap of Tutorial 1) We'll rerun the parametrization performed in Tutorial 1. Step2: Highlighting atoms and CG beads To link atoms to coarse-grained bead...
Python Code: import auto_martini as am import numpy as np from rdkit import Chem from rdkit.Chem.Draw import IPythonConsole from IPython.display import Image import rdkit from rdkit.Chem import Draw from rdkit.Chem import AllChem from rdkit.Chem import rdDepictor from rdkit.Chem.Draw import rdMolDraw2D print(rdkit.__ve...
5,326
Given the following text description, write Python code to implement the functionality described below step by step Description: Exact solution used in MES runs We would like to MES the operation $$ \partial_\theta f^2 $$ Using cylindrical geometry. Step1: Initialize Step2: Define the variables Step3: Define the fu...
Python Code: %matplotlib notebook from sympy import init_printing from sympy import S from sympy import sin, cos, tanh, exp, pi, sqrt from boutdata.mms import x, y, z, t from boutdata.mms import DDZ import os, sys # If we add to sys.path, then it must be an absolute path common_dir = os.path.abspath('./../../../../comm...
5,327
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial Brief numpy is a powerful set of tools to perform mathematical operations of on lists of numbers. It works faster than normal python lists operations and can manupilate high dimenti...
Python Code: import numpy as np Explanation: Tutorial Brief numpy is a powerful set of tools to perform mathematical operations of on lists of numbers. It works faster than normal python lists operations and can manupilate high dimentional arrays too. Finding Help: http://wiki.scipy.org/Tentative_NumPy_Tutorial http://...
5,328
Given the following text description, write Python code to implement the functionality described below step by step Description: Video 1 Step1: Simply printing out the DataFrame will give us similar information to R's str() Step2: And for the summary we'll use an equivalent method, DataFrame.describe() Step3: Video...
Python Code: NBA = pd.read_csv("NBA_train.csv") Explanation: Video 1 End of explanation NBA Explanation: Simply printing out the DataFrame will give us similar information to R's str(): End of explanation NBA.describe() Explanation: And for the summary we'll use an equivalent method, DataFrame.describe(): End of explan...
5,329
Given the following text description, write Python code to implement the functionality described below step by step Description: Rydberg Pair Potentials Near Surfaces This tutorial is based on results that were published by J. Block and S. Scheel, "van der Waals interaction potential between Rydberg atoms near surface...
Python Code: %matplotlib inline # Arrays import numpy as np # Plotting import matplotlib.pyplot as plt from itertools import product # Operating system interfaces import os, sys # Parallel computing from multiprocessing import Pool # pairinteraction :-) from pairinteraction import pireal as pi # Create cache for matrix...
5,330
Given the following text description, write Python code to implement the functionality described below step by step Description: Homework 14 (or so) Step1: You can explore the files if you'd like, but we're going to get the ones from convote_v1.1/data_stage_one/development_set/. It's a bunch of text files. Step2: So...
Python Code: # If you'd like to download it through the command line... !curl -O http://www.cs.cornell.edu/home/llee/data/convote/convote_v1.1.tar.gz # And then extract it through the command line... !tar -zxf convote_v1.1.tar.gz Explanation: Homework 14 (or so): TF-IDF text analysis and clustering Hooray, we kind of f...
5,331
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Decorator Pattern 1 Step2: Tip. 튜플 결합 Step3: Decorator Step4: 중첩된 decorator python @decorator3 @decorator2 @decorator1 [function, method, class] 적용순서
Python Code: def mean(first, second, *rest): 평균값 반환 함수 numbers = (first, second) + rest return sum(numbers) / len(numbers) Explanation: Decorator Pattern 1 End of explanation (1, 2) + (3,) Explanation: Tip. 튜플 결합 End of explanation def float_args_and_return(function): def wrapper(*args, **kwargs): ...
5,332
Given the following text description, write Python code to implement the functionality described below step by step Description: Submit Structures to MPComplete This notebook documents the process of 1. Taking and validating a collection of CIFs (e.g. in a ZIP file), creating pymatgen Structure objects 3. Filtering fo...
Python Code: zipfilename = '/Users/dwinston/Dropbox/best/structures/ever.zip' Explanation: Submit Structures to MPComplete This notebook documents the process of 1. Taking and validating a collection of CIFs (e.g. in a ZIP file), creating pymatgen Structure objects 3. Filtering for structures that are submittable to MP...
5,333
Given the following text description, write Python code to implement the functionality described below step by step Description: Source alignment and coordinate frames This tutorial shows how to visually assess the spatial alignment of MEG sensor locations, digitized scalp landmark and sensor locations, and MRI volume...
Python Code: import os.path as op import numpy as np import nibabel as nib from scipy import linalg import mne from mne.io.constants import FIFF data_path = mne.datasets.sample.data_path() subjects_dir = op.join(data_path, 'subjects') raw_fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif') trans_fname ...
5,334
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: The Fashion MNIST data is available directly in the tf.keras datasets API. You load it like this Step2: Calling load_data on this object will give you two sets of two...
Python Code: import tensorflow as tf print(tf.__version__) Explanation: <a href="https://colab.research.google.com/github/leopardbruce/FileFun/blob/master/%E2%80%9CCourse_1_Part_4_Lesson_2_Notebook_ipynb%E2%80%9D.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Co...
5,335
Given the following text description, write Python code to implement the functionality described below step by step Description: Spatiotemporal permutation F-test on full sensor data Tests for differential evoked responses in at least one condition using a permutation clustering test. The FieldTrip neighbor templates ...
Python Code: # Authors: Denis Engemann <denis.engemann@gmail.com> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable from mne.viz import plot_topomap import mne from mne.stats import spatio_temporal_cluster_test from mne.datasets import...
5,336
Given the following text description, write Python code to implement the functionality described. Description: Arrangement of the characters of a word such that all vowels are at odd places Python3 program to find the number of ways in which the characters of the word can be arranged such that the vowels occupy only th...
Python Code: import math def fact(n ) : f = 1 ; for i in range(2 , n + 1 ) : f = f * i ;  return f ;  def npr(n , r ) : return fact(n ) / fact(n - r ) ;  def countPermutations(str ) : even = math . floor(len(str ) / 2 ) ; odd = len(str ) - even ; ways = 0 ; freq =[0 ] * 26 ; for i in ra...
5,337
Given the following text description, write Python code to implement the functionality described below step by step Description: With this post I explore an alternative to ol' numpy; xarray. Numpy is still running under the hood but this very handy library applies the pandas concept of labeled dimension to large N-dim...
Python Code: import xarray as xr import os import seaborn from matplotlib import rcParams import matplotlib.pyplot as pl %matplotlib inline rcParams['font.size']=16 rcParams['xtick.labelsize']=14 rcParams['ytick.labelsize']=14 rcParams['legend.fontsize']=14 rcParams['axes.formatter.limits'] = (-3,3) Explanation: With t...
5,338
Given the following text description, write Python code to implement the functionality described below step by step Description: ABU量化系统使用文档 <center> <img src="./image/abu_logo.png" alt="" style="vertical-align Step1: 算法交易之父托马斯•彼得菲最成功的一段经历是利用当时最快的计算机,租赁独享电话线以保证数据传输畅通无阻,甚至超越时代定制平叛电脑,使用统计套利在不同市场进行对冲策略。 这是最有保证的一...
Python Code: # 基础库导入 from __future__ import print_function from __future__ import division import warnings warnings.filterwarnings('ignore') warnings.simplefilter('ignore') import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import os import sys # 使用insert 0即只使用github,避免交叉使用了pip安装的...
5,339
Given the following text description, write Python code to implement the functionality described below step by step Description: Notebook to retrieve gridded climate time-series data sets Case study Step1: Establish a secure connection with HydroShare by instantiating the hydroshare class that is defined within hs_ut...
Python Code: # data processing import os import pandas as pd, numpy as np, dask, json import ogh import geopandas as gpd # data migration library from utilities import hydroshare # plotting and shape libraries %matplotlib inline import warnings warnings.filterwarnings("ignore") Explanation: Notebook to retrieve gridded...
5,340
Given the following text description, write Python code to implement the functionality described below step by step Description: 独立成分分析 Lab 在此 notebook 中,我们将使用独立成分分析方法从三个观察结果中提取信号,每个观察结果都包含不同的原始混音信号。这个问题与 ICA 视频中解释的问题一样。 数据集 首先看看手头的数据集。我们有三个 WAVE 文件,正如我们之前提到的,每个文件都是混音形式。如果你之前没有在 python 中处理过音频文件,没关系,它们实际上就是浮点数列表。 首先加载第...
Python Code: import numpy as np import wave # Read the wave file mix_1_wave = wave.open('ICA_mix_1.wav','r') Explanation: 独立成分分析 Lab 在此 notebook 中,我们将使用独立成分分析方法从三个观察结果中提取信号,每个观察结果都包含不同的原始混音信号。这个问题与 ICA 视频中解释的问题一样。 数据集 首先看看手头的数据集。我们有三个 WAVE 文件,正如我们之前提到的,每个文件都是混音形式。如果你之前没有在 python 中处理过音频文件,没关系,它们实际上就是浮点数列表。 首先加载第一个音频文件 I...
5,341
Given the following text description, write Python code to implement the functionality described below step by step Description: M-Estimators for Robust Linear Modeling Step1: An M-estimator minimizes the function $$Q(e_i, \rho) = \sum_i~\rho \left (\frac{e_i}{s}\right )$$ where $\rho$ is a symmetric function of the...
Python Code: %matplotlib inline from statsmodels.compat import lmap import numpy as np from scipy import stats import matplotlib.pyplot as plt import statsmodels.api as sm Explanation: M-Estimators for Robust Linear Modeling End of explanation norms = sm.robust.norms def plot_weights(support, weights_func, xlabels, xti...
5,342
Given the following text description, write Python code to implement the functionality described below step by step Description: Problem setup Step1: Traditional model-fitting explanation Step2: Here a polynomial won't be look great, but it's relatively stable in the region around the data. However, the fit becomes ...
Python Code: X_MAX = 2 * np.pi def make_data(m): # Make Xs scattered on interval [0, 2pi] X = X_MAX * np.random.rand(m,) # Y's are all zero (1e-10 for plotting purposes) Y = 1e-9 + np.zeros((m,)) # ...except for one noise point Y[m//2] = 1 return X, Y Explanation: Problem setup: We're going ...
5,343
Given the following text description, write Python code to implement the functionality described below step by step Description: Multiple Kernel Learning By Saurabh Mahindre - <a href="https Step1: Introduction <em>Multiple kernel learning</em> (MKL) is about using a combined kernel i.e. a kernel consisting of a line...
Python Code: %pylab inline %matplotlib inline import os SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data') # import all shogun classes from modshogun import * Explanation: Multiple Kernel Learning By Saurabh Mahindre - <a href="https://github.com/Saurabh7">github.com/Saurabh7</a> This notebook is about multi...
5,344
Given the following text description, write Python code to implement the functionality described below step by step Description: Ant Colony Optimization for Energy Systems Research This notebook explores using Ant Colony Optimization to solve the combinatorial optimization problem of optimally configuring a branch of ...
Python Code: a, b, P_el = sympy.symbols("a b P_el ") eta_el = a * sympy.log(P_el) + b t_op, E_th, eta_th = sympy.symbols("t_op E_th eta_th") P_th = P_el / eta_el * (1 - eta_el) * eta_th sols = sympy.solve(sympy.Eq(P_th, E_th/t_op), sympy.log(P_el)) assert len(sols) == 1 sols[0] Explanation: Ant Colony Optimization for ...
5,345
Given the following text description, write Python code to implement the functionality described below step by step Description: Period Change (dpdt) Setup Let's first make sure we have the latest version of PHOEBE 2.4 installed (uncomment this line if running in an online notebook session such as colab). Step1: As a...
Python Code: #!pip install "phoebe>=2.4,<2.5" Explanation: Period Change (dpdt) Setup Let's first make sure we have the latest version of PHOEBE 2.4 installed (uncomment this line if running in an online notebook session such as colab). End of explanation import phoebe from phoebe import u # units import numpy as np im...
5,346
Given the following text description, write Python code to implement the functionality described below step by step Description: Rechunker Tutorial This tutorial notebook explains how to use rechunker with real datasets. We will also use xarray to make some things easier and prettier, but we note that xarray is not a ...
Python Code: import xarray as xr xr.set_options(display_style='text') import zarr import dask.array as dsa ds = xr.tutorial.open_dataset("air_temperature") # create initial chunk structure ds = ds.chunk({'time': 100}) ds.air.encoding = {} # helps when writing to zarr ds Explanation: Rechunker Tutorial This tutorial not...
5,347
Given the following text description, write Python code to implement the functionality described below step by step Description: Taxi Fare Prediction Using Realtime Traffic Data This will be the same as our previous taxi fare model, but with the addition of ‘trips_last_5min’ data as a feature. This is our proxy for tr...
Python Code: import tensorflow as tf import numpy as np import shutil print(tf.__version__) Explanation: Taxi Fare Prediction Using Realtime Traffic Data This will be the same as our previous taxi fare model, but with the addition of ‘trips_last_5min’ data as a feature. This is our proxy for traffic End of explanation ...
5,348
Given the following text description, write Python code to implement the functionality described below step by step Description: <table align="left"> <td> <a href="https Step3: Clone and build tensorflow_enterprise_addons To use the latest version of the tensorflow_enterprise_addons, we will clone and bui...
Python Code: import sys # If you are running this notebook in Colab, run this cell and follow the # instructions to authenticate your Google Cloud account. This provides access # to your Cloud Storage bucket and lets you submit training jobs and prediction # requests. if 'google.colab' in sys.modules: from google.c...
5,349
Given the following text description, write Python code to implement the functionality described. Description: Remove recurring digits in a given number Removes recurring digits in num [ ] ; Index in modified string ; Traverse digits of given number one by one ; Copy the first occurrence of new digit ; Remove repeating...
Python Code: def removeRecurringDigits(num ) : l = len(num ) (i , j ) =(0 , 0 ) str = ' ' while i < l : str += num[i ] j += 1 while(i + 1 < l and num[i ] == num[i + 1 ] ) : i += 1  i += 1  return str  if __name__== ' __main __' : num = '1299888833' print(' Modified ▁ number ▁ is ▁ { } ' ...
5,350
Given the following text description, write Python code to implement the functionality described below step by step Description: Clustering comparison Generate datasets We choose the size big enough to see the scalability of the algorithms, but we don't want the example to take too long. Step1: Enumerate clustering c...
Python Code: import numpy as np from sklearn import datasets from collections import OrderedDict np.random.seed(0) n_samples = 2500 ds = OrderedDict() ds['noisy_circles'] = datasets.make_circles( n_samples=n_samples, factor=.5, noise=.05) ds['noisy_moons'] = datasets.make_moons( n_samples=n_samples, noise=.05) ...
5,351
Given the following text description, write Python code to implement the functionality described below step by step Description: 1H Magnetic Resonance Spectroscopy (1H-MRS) Measuring GABA concentrations in vivo in human Principles of MRS measurement Following a $90^\circ$ square (broadband) pulse Step1: Fourier trans...
Python Code: def FID(t, M0=1, omega_0=128, omega=150, phi=0, T2_star=1.0): Mx = M0 * np.sin((omega_0 - omega) * t + phi) * np.exp(-(t / T2_star)) My = M0 * np.cos((omega_0 - omega) * t + phi) * np.exp(-(t / T2_star)) return Mx, My def plot_fid(t, FID, omega=None, omega_0=None): fig = plt.figure() ax...
5,352
Given the following text description, write Python code to implement the functionality described below step by step Description: Sensivity analysis with python using SALib Written by Sarah Juricic September 21st 2018 Step1: Objectives Step2: Draw a number of samples from your problem definition Step4: Run your own...
Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt Explanation: Sensivity analysis with python using SALib Written by Sarah Juricic September 21st 2018 End of explanation # STATE THE PROBLEM DICTIONNARY # what will be varying (=inputs) ? in what bounds ? problem = { 'num_vars': 3, ...
5,353
Given the following text description, write Python code to implement the functionality described below step by step Description: Currenlty the market basket analysis we are performing is only looking within a time slice to determin if thigs are occuring at the same time, not if they can be used to predict what is in t...
Python Code: import itertools for p in procLine: l = p.split(' ') if len(l) > 1: comb = itertools.combinations(l, 2) for start,finish in comb: val = (start,finish) edgeDict[val] += 1 edgeSet.add(val) Explanation: Currenlty the market basket analysis we are...
5,354
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: We import all the necessary packages. We are going to work with the fastai V1 library which sits on top of Pytorch 1.0. The fastai library provides many useful functio...
Python Code: %reload_ext autoreload %autoreload 2 %matplotlib inline Explanation: <a href="https://colab.research.google.com/github/astronstar/astronstar.github.io/blob/master/%E2%80%9Clesson1_pets_ipynb%E2%80%9D%E7%9A%84%E5%89%AF%E6%9C%AC.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab...
5,355
Given the following text description, write Python code to implement the functionality described below step by step Description: Példa 1 Step1: A stack egymásra rakja az oszlopokat. Step2: Most nem teljesen jó, mert előbb az országot és a tevékenységet ki kellene ragadjuk onnan. Ezért indexet csinálunk belőlük. Step...
Python Code: df=pd.read_excel('formazottbi2.xlsx') df Explanation: Példa 1 End of explanation pd.DataFrame(df.stack()).head() Explanation: A stack egymásra rakja az oszlopokat. End of explanation df.columns df.set_index(['Tevékenység','Ország']).head(2) Explanation: Most nem teljesen jó, mert előbb az országot és a tev...
5,356
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 2 This chapter introduces more PyMC syntax and design patterns, and ways to think about how to model a system from a Bayesian perspective. It also contains tips and data visualizatio...
Python Code: import pymc as pm parameter = pm.Exponential("poisson_param", 1) data_generator = pm.Poisson("data_generator", parameter) data_plus_one = data_generator + 1 Explanation: Chapter 2 This chapter introduces more PyMC syntax and design patterns, and ways to think about how to model a system from a Bayesian per...
5,357
Given the following text description, write Python code to implement the functionality described below step by step Description: Neighborhood Structures in the ArcGIS Spatial Statistics Library Spatial Weights Matrix On-the-fly Neighborhood Iterators [GA Table] Contructing PySAL Spatial Weights Spatial Weight Matrix ...
Python Code: import Weights as WEIGHTS import os as OS inputFC = r'../data/CA_Polygons.shp' fullFC = OS.path.abspath(inputFC) fullPath, fcName = OS.path.split(fullFC) masterField = "MYID" Explanation: Neighborhood Structures in the ArcGIS Spatial Statistics Library Spatial Weights Matrix On-the-fly Neighborhood Iterato...
5,358
Given the following text description, write Python code to implement the functionality described below step by step Description: Python Metaprogramming (the sometimes useful but often interesting) Why? Repetative code is an excuse to waste time? Might allow you to control functions, classes behavior at a higher level ...
Python Code: from functools import wraps def debug_on(func): @wraps(func) #preserving the metadata for func def debugging(*args,**kwargs): retval = func(*args,**kwargs); print('Scope: debugging %s:%s:%s'%(func,func.__name__,retval)); return retval; print('Scope: debug_on',debugging) ...
5,359
Given the following text description, write Python code to implement the functionality described below step by step Description: Create a classifier to predict the wine color from wine quality attributes using this dataset Step1: Split the data into features (x) and target (y, the last column in the table) Remember y...
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline import dateutil.parser import pg8000 from pandas import DataFrame from sklearn.externals.six import StringIO import pydotplus from sklearn import tree from sklearn.cross_validation import train_test_split from sklearn...
5,360
Given the following text description, write Python code to implement the functionality described below step by step Description: TO DO Step1: This notebook calculates and plots the theoretical tilt angles. It will also plot the alpha and p0 factors vs temperature that are given in the cell below this. Material Charac...
Python Code: import numpy as np from scipy.integrate import quad, dblquad %matplotlib inline import matplotlib.pyplot as plt import scipy.optimize as opt Explanation: TO DO: Need to be able to scatter plot measured values of Psi on top of the current Psi plot. Alpha and rho LaTeX not working in plots. Legend needs to b...
5,361
Given the following text description, write Python code to implement the functionality described below step by step Description: One vs All Step1: Loading and visualizing training data The training data is 5000 digit images of digits of size 20x20. We will display a random selection of 25 of them. Step2: Part 2 Step...
Python Code: import pandas import numpy as np import scipy.io import scipy.optimize import functools import matplotlib.pyplot as plt %matplotlib inline Explanation: One vs All End of explanation ex3data1 = scipy.io.loadmat("./ex3data1.mat") X = ex3data1['X'] y = ex3data1['y'][:,0] y[y==10] = 0 m, n = X.shape m, n fig =...
5,362
Given the following text description, write Python code to implement the functionality described below step by step Description: <table align="left"> <td> <a href="https Step1: Restart the kernel After you install the additional packages, you need to restart the notebook kernel so it can find the packages. Step...
Python Code: import os # The Vertex AI Workbench Notebook product has specific requirements IS_WORKBENCH_NOTEBOOK = os.getenv("DL_ANACONDA_HOME") IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists( "/opt/deeplearning/metadata/env_version" ) # Vertex AI Notebook requires dependencies to be installed with '--user' U...
5,363
Given the following text description, write Python code to implement the functionality described below step by step Description: Sentiment Analysis with an RNN In this notebook, you'll implement a recurrent neural network that performs sentiment analysis. Using an RNN rather than a feedfoward network is more accurate ...
Python Code: import numpy as np import tensorflow as tf with open('../sentiment-network/reviews.txt', 'r') as f: reviews = f.read() with open('../sentiment-network/labels.txt', 'r') as f: labels = f.read() reviews[:2000] Explanation: Sentiment Analysis with an RNN In this notebook, you'll implement a recurrent ...
5,364
Given the following text description, write Python code to implement the functionality described below step by step Description: Step 0 - hyperparams vocab_size is all the potential words you could have (classification for translation case) and max sequence length are the SAME thing decoder RNN hidden units are usuall...
Python Code: input_len = 60 target_len = 30 batch_size = 50 with_EOS = False csv_in = '../price_history_03_seq_start_suddens_trimmed.csv' Explanation: Step 0 - hyperparams vocab_size is all the potential words you could have (classification for translation case) and max sequence length are the SAME thing decoder RNN hi...
5,365
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Estimators Most of sklearn is designed around the concept of "estimators", which are objects that can transform data. That is, we can think of an estimator as a functi...
Python Code: # Standard Python libraries from __future__ import absolute_import, division, print_function, unicode_literals import os import time import numpy as np import glob import matplotlib.pyplot as plt import PIL import imageio from IPython import display import sklearn import seaborn as sns sns.set(style="ticks...
5,366
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: 1 Least squares and linear basis functions models 1.1 Least squares Step2: Load the data Here we will reuse the dataset height_weight_genders.csv from previous exercise section to ch...
Python Code: def least_squares(y, tx): calculate the least squares solution. a = tx.T.dot(tx) b = tx.T.dot(y) return np.linalg.solve(a, b) Explanation: 1 Least squares and linear basis functions models 1.1 Least squares End of explanation from helpers import * def test_your_least_squares(): height, ...
5,367
Given the following text description, write Python code to implement the functionality described below step by step Description: LeNet Lab Solution Source Step1: Basic Info of the Dataset Step2: Visualize Data View a sample from the dataset. You do not need to modify this section. Step3: Preprocess Data Shuffle the...
Python Code: # Load pickled data import pickle # TODO: Fill this in based on where you saved the training and testing data training_file = 'train.p' validation_file= 'valid.p' testing_file = 'test.p' with open(training_file, mode='rb') as f: train = pickle.load(f) with open(validation_file, mode='rb') as f: val...
5,368
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction In the exercise, you will work with data from the TalkingData AdTracking competition. The goal of the competition is to predict if a user will download an app after clicking th...
Python Code: # Set up code checking from learntools.core import binder binder.bind(globals()) from learntools.feature_engineering.ex1 import * Explanation: Introduction In the exercise, you will work with data from the TalkingData AdTracking competition. The goal of the competition is to predict if a user will downloa...
5,369
Given the following text description, write Python code to implement the functionality described below step by step Description: Vertex pipelines Learning Objectives Step1: Restart the kernel After you install the additional packages, you need to restart the notebook kernel so it can find the packages. Import librari...
Python Code: !pip3 install --user google-cloud-pipeline-components==0.1.1 --upgrade Explanation: Vertex pipelines Learning Objectives: Use components from google_cloud_pipeline_components to create a Vertex Pipeline which will 1. train a custom model on Vertex AI 1. create an endpoint to host the model 1. upload...
5,370
Given the following text description, write Python code to implement the functionality described below step by step Description: DAY 11 - Mar 7, 2017 Today I'll do something a little different. This morning I tweeted something along the lines of "will be working with matplotlib." In terms of visualization, I'm more fa...
Python Code: website_base_stats = "http://leagueoflegends.wikia.com/wiki/Base_champion_statistics" # Save HTML to soup html_data = requests.get(website_base_stats).text soup = BeautifulSoup(html_data, "html5lib") # Parse table table = soup.find('table', attrs={'class' : 'wikitable'}) # Parse table header lol_thead = [h...
5,371
Given the following text description, write Python code to implement the functionality described below step by step Description: Matrix Factorization In a recommendation system, there is a group of users and a set of items. Given that each users have rated some items in the system, we would like to predict how the use...
Python Code: class Batch(object): def __init__(self, data_names, data, label_names, label): self.data = data self.label = label self.data_names = data_names self.label_names = label_names @property def provide_data(self): return [(n, x.shape) for n, x in zip(...
5,372
Given the following text description, write Python code to implement the functionality described below step by step Description: Making New Layers and Models via Subclassing Learning Objectives Use Layer class as the combination of state (weights) and computation. Defer weight creation until the shape of the inputs is...
Python Code: # Import necessary libraries import tensorflow as tf from tensorflow import keras Explanation: Making New Layers and Models via Subclassing Learning Objectives Use Layer class as the combination of state (weights) and computation. Defer weight creation until the shape of the inputs is known. Build recursiv...
5,373
Given the following text description, write Python code to implement the functionality described below step by step Description: Algorithm comparison This notebook contains the algorithm comparison for the measurements done with the DySpan 2017 testbed N_FRAMES = 50 comparison is based on different aspects, such as St...
Python Code: %load_ext autoreload %autoreload 2 import sys print(sys.version) import sys sys.path.append("../python") import setup_dataset data, labels = setup_dataset.setup_simple_iterables("with_dc") X_train, X_test, y_train, y_test = setup_dataset.slice_data(data, labels) # Setting up various complexities for the di...
5,374
Given the following text description, write Python code to implement the functionality described below step by step Description: User Defined Materials Overview Materials are implemented by subclassing the matmodlab.core.Material base class. The user material is called at each frame of every step. It is provided with...
Python Code: %pycat ../matmodlab2/materials/elastic3.py %pylab inline from matmodlab2 import * Explanation: User Defined Materials Overview Materials are implemented by subclassing the matmodlab.core.Material base class. The user material is called at each frame of every step. It is provided with the material state at...
5,375
Given the following text description, write Python code to implement the functionality described below step by step Description: 列表生成式和生成式表达式 我们可以用 map 和 filter 达到 列表生成式的效果 Step1: 对于上面的例子来说, filter/map 并不比 listcomp(列表生成式) 快, 后面的章节我们进一步讨论 列表生成式的多层循环 假如我们要制作两种颜色三种大小组成的 T 恤, 下面的代码是生成 T 恤的序列 Step2: Python中,[], {}, () 内的...
Python Code: symbols = "a%b&c$de$" beyond_ascii = [ord(s) for s in symbols if ord(s) > 50] beyond_ascii beyond_ascii = list(filter(lambda c: c > 50, map(ord, symbols))) beyond_ascii Explanation: 列表生成式和生成式表达式 我们可以用 map 和 filter 达到 列表生成式的效果 End of explanation colors = ['black', 'white'] sizes = ['S', 'M', 'L'] tshirts = ...
5,376
Given the following text description, write Python code to implement the functionality described below step by step Description: The Traveling Salesman problem Names of group members // put your names here! Goals of this assignment The main goal of this assignment is to use Monte Carlo methods to find the shortest pat...
Python Code: import numpy as np %matplotlib inline import matplotlib.pyplot as plt from IPython.display import display, clear_output def calc_total_distance(table_of_distances, city_order): ''' Calculates distances between a sequence of cities. Inputs: N x N table containing distances between each pair...
5,377
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', 'cmcc', 'cmcc-cm2-hr5', 'land') Explanation: ES-DOC CMIP6 Model Properties - Land MIP Era: CMIP6 Institute: CMCC Source ID: CMCC-CM2-HR5 Topic: Land Sub-Topics: Soil, Snow, Vegetation,...
5,378
Given the following text description, write Python code to implement the functionality described below step by step Description: Imports Step1: Useful functions Step2: Reading the data Step3: Analysis of coverage Step4: Diversity plot Step5: Positions that increase in frequency in the different replicates and con...
Python Code: from collections import Counter import pandas as pd import matplotlib.pyplot as plt import matplotlib.ticker as mticker from pylab import rcParams import seaborn as sns from array import array import numpy as np from scipy.stats import ttest_ind from scipy.stats import linregress from scipy.stats import ma...
5,379
Given the following text description, write Python code to implement the functionality described below step by step Description: COLOP in Spectral Blueing Mode IPython notebook to calculate operator for spectral blueing using seismic amplitude spectrum and well AI spectrum exported from OpendTect. First sample of the ...
Python Code: import sys import numpy as np from scipy.stats import linregress import matplotlib.pyplot as plt %matplotlib inline Explanation: COLOP in Spectral Blueing Mode IPython notebook to calculate operator for spectral blueing using seismic amplitude spectrum and well AI spectrum exported from OpendTect. First sa...
5,380
Given the following text description, write Python code to implement the functionality described below step by step Description: Modeling and Simulation in Python Case Study Step1: One queue or two? This notebook presents a solution to an exercise from Modeling and Simulation in Python. It uses features from the fir...
Python Code: # Configure Jupyter so figures appear in the notebook %matplotlib inline # Configure Jupyter to display the assigned value after an assignment %config InteractiveShell.ast_node_interactivity='last_expr_or_assign' # import functions from the modsim.py module from modsim import * # set the random number gene...
5,381
Given the following text description, write Python code to implement the functionality described below step by step Description: This will lean heavily on Tom Augspurger's excellent series on Modern Pandas. Quote Step2: In the original example from Tom, the code is written out as such Step3: Our function may be a bi...
Python Code: import os import zipfile import requests import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt Explanation: This will lean heavily on Tom Augspurger's excellent series on Modern Pandas. Quote: Method chaining, where you call methods on an object one after another, is ...
5,382
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction Step1: In this chapter, we will look at the relationship between graphs and linear algebra. The deep connection between these two topics is super interesting, and I'd like to s...
Python Code: from IPython.display import YouTubeVideo YouTubeVideo(id="uTHihJiRELc", width="100%") Explanation: Introduction End of explanation import networkx as nx nodes = list(range(4)) G1 = nx.Graph() G1.add_nodes_from(nodes) G1.add_edges_from(zip(nodes, nodes[1:])) Explanation: In this chapter, we will look at the...
5,383
Given the following text description, write Python code to implement the functionality described below step by step Description: Filtering and resampling data Some artifacts are restricted to certain frequencies and can therefore be fixed by filtering. An artifact that typically affects only some frequencies is due to...
Python Code: import numpy as np import mne from mne.datasets import sample data_path = sample.data_path() raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif' proj_fname = data_path + '/MEG/sample/sample_audvis_eog_proj.fif' tmin, tmax = 0, 20 # use the first 20s of data # Setup for reading the raw data (save m...
5,384
Given the following text description, write Python code to implement the functionality described below step by step Description: Train Model with XLA_GPU (and CPU*) Some operations do not have XLA_GPU equivalents, so we still need to use CPU. IMPORTANT Step1: Reset TensorFlow Graph Useful in Jupyter Notebooks Step2: ...
Python Code: import tensorflow as tf from tensorflow.python.client import timeline import pylab import numpy as np import os %matplotlib inline %config InlineBackend.figure_format = 'retina' tf.logging.set_verbosity(tf.logging.INFO) Explanation: Train Model with XLA_GPU (and CPU*) Some operations do not have XLA_GPU eq...
5,385
Given the following text description, write Python code to implement the functionality described below step by step Description: Please find jax implementation of this notebook here Step2: Implementation Utility functions. Step6: Main function. Step7: Example The shape of the multi-head attention output is (batch_s...
Python Code: import numpy as np import matplotlib.pyplot as plt np.random.seed(seed=1) import math import collections try: import torch except ModuleNotFoundError: %pip install -qq torch import torch from torch import nn from torch.nn import functional as F !mkdir figures # for saving plots Explanation: Ple...
5,386
Given the following text description, write Python code to implement the functionality described below step by step Description: Softmax exercise Adapt from the Stanford CS231n assignment1, find the original version on the course website. In this exercise we will Step5: Load CIFAR-10 data Load the data and split into...
Python Code: import random import time import numpy as np import matplotlib.pyplot as plt from cs231n.data_utils import load_CIFAR10 from cs231n.gradient_check import grad_check_sparse # plotting setting %matplotlib inline plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots plt.rcParams['image.inte...
5,387
Given the following text description, write Python code to implement the functionality described below step by step Description: Preparing the data Data loading and putting it into a suitable format Parsing chord labels to binary pitch class sets for chord label dataset [x] see tools/add_pitch_class_sets.sh Joining Da...
Python Code: def impute_missing_key_files(): path = 'data/beatles/keylab/The_Beatles/10CD2_-_The_Beatles/CD2_-_12_-_Revolution_9.lab' if not os.path.exists(path): df = pd.DataFrame.from_records( [("0.0", "502.204082", "Silence", None)], columns=['start', 'end', 'key_indicator', '...
5,388
Given the following text description, write Python code to implement the functionality described below step by step Description: Исследование поведения предложенного функционала. Часть I. Возьмем в качестве базисных функций $\cos(x)$, $\sin(x)$, $\cos(2x)$, $\sin(2x)$. Стоит посмотреть, как будет вести себя предлженна...
Python Code: import numpy as np import tensorflow as tf from matplotlib import pylab as plt %matplotlib inline m = 4500 M = 4 a = -10 b = 10 x_grid = np.linspace(a, b, m, endpoint=True) sess = tf.Session() x = tf.placeholder(tf.double) trial_func = [tf.sin(x), tf.cos(x), tf.sin(2*x), tf.cos(2*x)] alpha = tf.Variable(...
5,389
Given the following text description, write Python code to implement the functionality described below step by step Description: Estimating Counts Think Bayes, Second Edition Copyright 2020 Allen B. Downey License Step1: In the previous chapter we solved problems that involve estimating proportions. In the Euro probl...
Python Code: # If we're running on Colab, install empiricaldist # https://pypi.org/project/empiricaldist/ import sys IN_COLAB = 'google.colab' in sys.modules if IN_COLAB: !pip install empiricaldist # Get utils.py from os.path import basename, exists def download(url): filename = basename(url) if not exists(...
5,390
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright (c) 2015, 2016 Sebastian Raschka <br> 2016 Li-Yi Wei https Step1: The use of watermark is optional. You can install this IPython extension via "pip install watermark". For more in...
Python Code: %load_ext watermark %watermark -a '' -u -d -v -p numpy,pandas,matplotlib,scipy,sklearn Explanation: Copyright (c) 2015, 2016 Sebastian Raschka <br> 2016 Li-Yi Wei https://github.com/1iyiwei/pyml MIT License Python Machine Learning - Code Examples Chapter 7 - Combining Different Models for Ensemble Learning...
5,391
Given the following text description, write Python code to implement the functionality described below step by step Description: Step2: Please find torch implementation of this notebook here Step4: Basics This section is based on sec 8.2 of http Step6: Tokenization Step9: Vocabulary We map each word to a unique int...
Python Code: import os import numpy as np import jax import jax.numpy as jnp import matplotlib.pyplot as plt import math try: import torch except ModuleNotFoundError: %pip install -qq torch import torch from torch.utils import data if not os.path.exists("figures"): os.makedirs("figures") # for saving p...
5,392
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Machine-Translation-with-Huggingface-Transformer" data-toc-modified-id="Mach...
Python Code: # code for loading the format for the notebook import os # path : store the current path to convert back to it later path = os.getcwd() os.chdir(os.path.join('..', '..', 'notebook_format')) from formats import load_style load_style(css_style='custom2.css', plot_style=False) os.chdir(path) # 1. magic for in...
5,393
Given the following text description, write Python code to implement the functionality described below step by step Description: Self-Driving Car Engineer Nanodegree Project Step1: Read in an Image Step10: Ideas for Lane Detection Pipeline Some OpenCV functions (beyond those introduced in the lesson) that might be u...
Python Code: #importing some useful packages import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import cv2 %matplotlib inline Explanation: Self-Driving Car Engineer Nanodegree Project: Finding Lane Lines on the Road In this project, you will use the tools you learned about in the lesson...
5,394
Given the following text description, write Python code to implement the functionality described below step by step Description: Resources http Step1: Compute the traces of cross-sections
Python Code: fin = open('./../data/trench.xy', 'r') trench = [] for line in fin: aa = re.split('\s+', re.sub('^\s+', '', line)) trench.append((float(aa[0]), float(aa[1]))) fin.close() trench = Trench(numpy.array(trench)) cat = pickle.load(open("./../data/catalogue_ext_cac.p", "rb" )) Explanation: Resources htt...
5,395
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook shows how to extract information from a spectral line using the weak-field approximation. It uses a Bayesian approach to the problem. Index Simple case Biases Errors in both co...
Python Code: lambda0 = 6301.5080 JUp = 2.0 JLow = 2.0 gUp = 1.5 gLow = 1.833 lambdaStart = 6300.8 lambdaStep = 0.03 nLambda = 50 lineInfo = np.asarray([lambda0, JUp, JLow, gUp, gLow, lambdaStart, lambdaStep]) s = pymilne.milne(nLambda, lineInfo) stokes = np.zeros((4,nLambda)) BField = 100.0 BTheta = 20.0 BChi = 0.0 VMa...
5,396
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', 'fio-ronm', 'sandbox-2', 'ocnbgchem') Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem MIP Era: CMIP6 Institute: FIO-RONM Source ID: SANDBOX-2 Topic: Ocnbgchem Sub-Topics: Tracer...
5,397
Given the following text description, write Python code to implement the functionality described below step by step Description: In this notebook a simple Q learner will be trained and evaluated. The Q learner recommends when to buy or sell shares of one particular stock, and in which quantity (in fact it determines t...
Python Code: # Basic imports import os import pandas as pd import matplotlib.pyplot as plt import numpy as np import datetime as dt import scipy.optimize as spo import sys from time import time from sklearn.metrics import r2_score, median_absolute_error from multiprocessing import Pool %matplotlib inline %pylab inline ...
5,398
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: റെൻസോർഫ്ളോ വിളിക്കുന്നു tf എന്നു പേരിടുന്നു Step2: ഡേറ്റയെ വിളിക്കുന്നു.... ചിത്രങ്ങൾ ...കൈയ്യെഴുത്ത് അക്കങ്ങളുടെ മെനിസ്റ്റ് ഡാറ്റാബേസ്, 60,000 ഉദാഹരണങ്ങൾ, ഒപ്പം 10...
Python Code: print ("Gods name is Jehova") Explanation: <a href="https://colab.research.google.com/github/Graphitenet/Fun-CSS-Java-Clock/blob/master/%E0%B4%B1%E0%B5%86%E0%B5%BB%E0%B4%B8%E0%B5%8B%E0%B5%BC%E0%B4%AB%E0%B5%8D%E0%B4%B3%E0%B5%8B_.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/cola...
5,399
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: 15. 다중 회귀 분석 Step3: 14장의 내용을 추가 데이터를 사용해 모델의 성능을 높이기 위해, 더 많은 독립 변수를 사용하는 선형 모델을 시험 14장에서 다뤘던 모델 $y_i=\alpha+\beta x_i+\epsilon_i$ 여기에 독립 변수를 추가하면 $\Rightarrow$시간(분)= $\alpha+\beta_1...
Python Code: from __future__ import division from collections import Counter from functools import partial from linear_algebra import dot, vector_add from stats import median, standard_deviation, de_mean from probability import normal_cdf from gradient_descent import minimize_stochastic #from simple_linear_regression i...