Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
4,900
Given the following text description, write Python code to implement the functionality described below step by step Description: CrowdTruth for Sparse Multiple Choice Tasks Step1: Declaring a pre-processing configuration The pre-processing configuration defines how to interpret the raw crowdsourcing input. To do this...
Python Code: import pandas as pd test_data = pd.read_csv("../data/relex-sparse-multiple-choice.csv") test_data.head() Explanation: CrowdTruth for Sparse Multiple Choice Tasks: Relation Extraction In this tutorial, we will apply CrowdTruth metrics to a sparse multiple choice crowdsourcing task for Relation Extraction fr...
4,901
Given the following text description, write Python code to implement the functionality described below step by step Description: Blind Source Separation with the Shogun Machine Learning Toolbox By Kevin Hughes This notebook illustrates <a href="http Step1: Next we're going to need a way to play the audio files we're ...
Python Code: import numpy as np import os SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data') from scipy.io import wavfile from scipy.signal import resample import shogun as sg def load_wav(filename,samplerate=44100): # load file rate, data = wavfile.read(filename) # convert stereo to mono ...
4,902
Given the following text description, write Python code to implement the functionality described below step by step Description: Setting things up Let's load the data and give it a quick look. Step1: Checking out correlations Let's start looking at how variables in our dataset relate to each other so we know what to ...
Python Code: df = pd.read_csv('data/apib12tx.csv') df.describe() Explanation: Setting things up Let's load the data and give it a quick look. End of explanation df.corr() Explanation: Checking out correlations Let's start looking at how variables in our dataset relate to each other so we know what to expect when we sta...
4,903
Given the following text description, write Python code to implement the functionality described below step by step Description: CDR EDA First, import relevant libraries Step1: Then, load the data (takes a few moments) Step2: This create a calls-per-person frequency distribution, which is the first thing we want to ...
Python Code: import warnings warnings.filterwarnings('ignore') import numpy as np import pandas as pd %matplotlib inline import matplotlib.pyplot as plt Explanation: CDR EDA First, import relevant libraries: End of explanation # Load data df = pd.read_csv("./aws-data/firence_foreigners_3days_past_future.csv", header=No...
4,904
Given the following text description, write Python code to implement the functionality described below step by step Description: Factorization Factorization is the process of restating an expression as the product of two expressions (in other words, expressions multiplied together). For example, you can make the value...
Python Code: from random import randint x = randint(1,100) y = randint(1,100) (2*x*y**2)*(-3*x*y) == -6*x**2*y**3 Explanation: Factorization Factorization is the process of restating an expression as the product of two expressions (in other words, expressions multiplied together). For example, you can make the value 16...
4,905
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Aerosol MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'mri', 'sandbox-1', 'aerosol') Explanation: ES-DOC CMIP6 Model Properties - Aerosol MIP Era: CMIP6 Institute: MRI Source ID: SANDBOX-1 Topic: Aerosol Sub-Topics: Transport, Emissions, ...
4,906
Given the following text description, write Python code to implement the functionality described below step by step Description: Pore Scale Models Pore scale models are one of the more important facets of OpenPNM, but they can be a bit confusing at first, since they work 'behind-the-scenes'. They offer 3 main advantag...
Python Code: import numpy as np np.random.seed(0) import openpnm as op %config InlineBackend.figure_formats = ['svg'] pn = op.network.Cubic(shape=[5, 5, 1], spacing=1e-4) geo = op.geometry.SpheresAndCylinders(network=pn, pores=pn.Ps, throats=pn.Ts) Explanation: Pore Scale Models Pore scale models are one of the more im...
4,907
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Python and Natural Language Technologies Lecture 5 Decorators and packaging March 7, 2018 Let's create a greeter function takes another function as a parameter greets the cal...
Python Code: def greeter(func): print("Hello") func() def say_something(): print("Let's learn some Python.") greeter(say_something) # greeter(12) Explanation: Introduction to Python and Natural Language Technologies Lecture 5 Decorators and packaging March 7, 2018 Let's create a greeter function t...
4,908
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: TV Script Generation In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Ne...
Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper data_dir = './data/simpsons/moes_tavern_lines.txt' text = helper.load_data(data_dir) # Ignore notice, since we don't use it for analysing the data text = text[81:] text[:100] Explanation: TV Script Generation In this project, you'll generate your own Simpson...
4,909
Given the following text description, write Python code to implement the functionality described below step by step Description: Content under Creative Commons Attribution license CC-BY 4.0, code under BSD 3-Clause License © 2018 by D. Koehn, notebook style sheet by L.A. Barba, N.C. Clementi Step1: Performance optim...
Python Code: # Execute this cell to load the notebook's style sheet, then ignore it from IPython.core.display import HTML css_file = '../../style/custom.css' HTML(open(css_file, "r").read()) Explanation: Content under Creative Commons Attribution license CC-BY 4.0, code under BSD 3-Clause License © 2018 by D. Koehn, n...
4,910
Given the following text description, write Python code to implement the functionality described below step by step Description: 데이터 분석의 소개 데이터 분석이란 용어는 상당히 광범위한 용어이므로 여기에서는 통계적 분석과 머신 러닝이라는 두가지 세부 영역에 국한하여 데이터 분석을 설명하도록 한다. 데이터 분석이란 데이터 분석이란 어떤 데이터가 주어졌을 때 데이터 간의 관계를 파악하거나 파악된 관계를 사용하여 원하는 데이터를 만들어 내는 과정 으로 볼 수 있다. ...
Python Code: from sklearn.datasets import load_digits digits = load_digits() plt.imshow(digits.images[0], interpolation='nearest'); plt.grid(False) digits.images[0] from sklearn.datasets import fetch_20newsgroups news = fetch_20newsgroups() print(news.data[0]) from sklearn.feature_extraction.text import TfidfVectorizer...
4,911
Given the following text description, write Python code to implement the functionality described below step by step Description: Principal Component Analysis in Shogun By Abhijeet Kislay (GitHub ID Step1: Some Formal Background (Skip if you just want code examples) PCA is a useful statistical technique that has found...
Python Code: %pylab inline %matplotlib inline # import all shogun classes from modshogun import * Explanation: Principal Component Analysis in Shogun By Abhijeet Kislay (GitHub ID: <a href='https://github.com/kislayabhi'>kislayabhi</a>) This notebook is about finding Principal Components (<a href="http://en.wikipedia.o...
4,912
Given the following text description, write Python code to implement the functionality described below step by step Description: To build an automaton, simply call translate() with a formula, and a list of options to characterize the automaton you want (those options have the same name as the long options name of the ...
Python Code: a = spot.translate('(a U b) & GFc & GFd', 'BA', 'complete'); a Explanation: To build an automaton, simply call translate() with a formula, and a list of options to characterize the automaton you want (those options have the same name as the long options name of the ltl2tgba tool, and they can be abbreviate...
4,913
Given the following text description, write Python code to implement the functionality described below step by step Description: Example 1 Step1: Then, create the cell object using the LFPy.Cell class, specifying the morphology file. The passive mechanisms are not switched on by default. Step2: Then, align apical d...
Python Code: import matplotlib.pyplot as plt import numpy as np import LFPy Explanation: Example 1: Post-synaptic response of a single synapse This is an example of LFPy running in an Jupyter notebook. To run through this example code and produce output, press &lt;shift-Enter&gt; in each code block below. First step is...
4,914
Given the following text description, write Python code to implement the functionality described below step by step Description: Step2: Some Bayesian AB testing. Thanks to my overly talented friend Maciej Kula for this example. We'll reproduce some of his work from a blog post, and learn how to do AB testing with PyM...
Python Code: def generate_data(no_samples, treatment_proportion=0.1, treatment_mu=1.2, control_mu=1.0, sigma=0.4): Generate sample data from the experiment. rnd = np.random.RandomState(seed=12345) treatment = rnd.binomial(1, t...
4,915
Given the following text description, write Python code to implement the functionality described below step by step Description: 内容索引 通用函数 创建通用函数 --- frompyfunc工厂函数 通用函数的方法 --- reduce函数、accumulate函数、reduceat函数、outer函数 数组的除法运算 --- divide函数、true_divide函数、floor_divide函数 数组的模运算 --- mod函数、remainder函数、fmod函数 位操作函数和比较函数 --- ...
Python Code: import numpy as np Explanation: 内容索引 通用函数 创建通用函数 --- frompyfunc工厂函数 通用函数的方法 --- reduce函数、accumulate函数、reduceat函数、outer函数 数组的除法运算 --- divide函数、true_divide函数、floor_divide函数 数组的模运算 --- mod函数、remainder函数、fmod函数 位操作函数和比较函数 --- End of explanation # 定义一个Python函数 def pyFunc(a): result = np.zeros_like(a) # ...
4,916
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 1 - Data Structures and Algorithms 1.1 Unpacking a Sequence into Separate Variables Step4: 1.2 Unpacking Elements from Iterables of Arbitrary Length Step6: Discussion Step8: 1.3 K...
Python Code: p = (4, 5, 6, 7) x, y, z, w = p # x -> 4 data = ['ACME', 50, 91.1, (2012, 12, 21)] name, _, price, date = data # name -> 'ACME', data -> (2012, 12, 21) s = 'Hello' a, b, c, d, e = s # a -> H p = (4, 5) x, y, z = p # "ValueError" Explanation: Chapter 1 - Data Structures and Algorithms 1.1 Unpacking a Seque...
4,917
Given the following text description, write Python code to implement the functionality described below step by step Description: Loading a single rate Step1: the original reaclib source Step2: evaluate the rate at a given temperature (in K) Step3: a human readable string describing the rate, and the nuclei involved...
Python Code: r = reaclib.Rate("reaclib-rates/c13-pg-n14-nacr") Explanation: Loading a single rate End of explanation print(r.original_source) Explanation: the original reaclib source End of explanation r.eval(1.e9) Explanation: evaluate the rate at a given temperature (in K) End of explanation print(r) print(r.reactant...
4,918
Given the following text description, write Python code to implement the functionality described below step by step Description: TRAPpy Step1: Interactive Line Plotting of Data Frames Interactive Line Plots Supports the same API as the LinePlot but provide an interactive plot that can be zoomed by clicking and draggi...
Python Code: import sys,os sys.path.append("..") import numpy.random import pandas as pd import shutil import tempfile import trappy trace_thermal = "./trace.txt" trace_sched = "../tests/raw_trace.dat" TEMP_BASE = "/tmp" def setup_thermal(): tDir = tempfile.mkdtemp(dir="/tmp", prefix="trappy_doc", suffix = ".tempDi...
4,919
Given the following text description, write Python code to implement the functionality described below step by step Description: Recommendations on GCP with TensorFlow and WALS with Cloud Composer This lab is adapted from the original solution created by lukmanr This project deploys a solution for a recommendation se...
Python Code: %%bash pip install sh --upgrade pip # needed to execute shell scripts later Explanation: Recommendations on GCP with TensorFlow and WALS with Cloud Composer This lab is adapted from the original solution created by lukmanr This project deploys a solution for a recommendation service on GCP, using the WALS...
4,920
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Download and get info from all EIA-923 Excel files This setup downloads all the zip files, extracts the contents, and identifies the correct header row in the correct file. I'm only g...
Python Code: %matplotlib inline import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import os import glob import numpy as np import requests from bs4 import BeautifulSoup from urllib import urlretrieve import zipfile import fnmatch url = 'https://www.eia.gov/electricity/data/eia923' r = requests.g...
4,921
Given the following text description, write Python code to implement the functionality described below step by step Description: Day 11 - pre-class assignment Goals for today's pre-class assignment Use random number generators to create a sequence of random floats and integers Create a function and use it to do someth...
Python Code: # Imports the functionality that we need to display YouTube videos in a Jupyter Notebook. # You need to run this cell before you run ANY of the YouTube videos. from IPython.display import YouTubeVideo # WATCH THE VIDEO IN FULL-SCREEN MODE YouTubeVideo("fF841G53fGo",width=640,height=360) # random number...
4,922
Given the following text description, write Python code to implement the functionality described below step by step Description: Orientation with IKPy In this Notebook, we'll demonstrate inverse kinematics on orientation on a baxter robot Step1: Inverse Kinematics with Orientation Step2: Mastering orientation Orient...
Python Code: # Some necessary imports import numpy as np from ikpy.chain import Chain from ikpy.utils import plot # Optional: support for 3D plotting in the NB %matplotlib widget # turn this off, if you don't need it # First, let's import the baxter chains baxter_left_arm_chain = Chain.from_json_file("../resources/baxt...
4,923
Given the following text description, write Python code to implement the functionality described below step by step Description: Boosting a decision stump The goal of this notebook is to implement your own boosting module. Brace yourselves! This is going to be a fun and challenging assignment. Use SFrames to do some f...
Python Code: import numpy as np import pandas as pd import json import matplotlib.pyplot as plt %matplotlib inline Explanation: Boosting a decision stump The goal of this notebook is to implement your own boosting module. Brace yourselves! This is going to be a fun and challenging assignment. Use SFrames to do some fea...
4,924
Given the following text description, write Python code to implement the functionality described below step by step Description: Wayne H Nixalo - 13 June 2017 Practical Deep Learning I Lesson 5 - RNNs, NLP Code along of char-rnn.ipynb Step1: Setup We haven't really looked into the detail of how this works yet - so th...
Python Code: import theano %matplotlib inline import os, sys sys.path.insert(1, os.path.join('utils')) import utils; reload(utils) from utils import * from __future__ import print_function, division from keras.layers import TimeDistributed, Activation # https://keras.io/layers/wrappers/ # [Doc:TimeDistributed] this wra...
4,925
Given the following text description, write Python code to implement the functionality described below step by step Description: Working Dir Step1: Filename Step2: Output Prefix Step3: Others Step4: Parse CUE Step5: Covert Files
Python Code: WORKING_DIR = u"/path/to/folder/to/music" Explanation: Working Dir: It's supposed that your commands are run under this folder. End of explanation FILENAME_PREFIX = u"filename_without_ext" FILENAME_EXTENSION = u"wav" Explanation: Filename: This is the filename prefix. For example, if your files are CDImage...
4,926
Given the following text description, write Python code to implement the functionality described below step by step Description: Item cold-start Step1: Let's examine the data Step2: The training and test set are divided chronologically Step3: As a means of sanity checking, let's calculate the model's AUC on the tra...
Python Code: import numpy as np from lightfm.datasets import fetch_stackexchange data = fetch_stackexchange('crossvalidated', test_set_fraction=0.1, indicator_features=False, tag_features=True) train = data['train'] test = data['test'] Exp...
4,927
Given the following text description, write Python code to implement the functionality described below step by step Description: Report03 - Nathan Yee This notebook contains report03 for computational baysian statistics fall 2016 MIT License Step2: The sock problem Created by Yuzhong Huang There are two drawers of so...
Python Code: from __future__ import print_function, division % matplotlib inline import warnings warnings.filterwarnings('ignore') import math import numpy as np from thinkbayes2 import Pmf, Cdf, Suite, Joint import thinkplot Explanation: Report03 - Nathan Yee This notebook contains report03 for computational baysian s...
4,928
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>**ReadMe**</h1> An important part in the profitability of a credit card product is the issuer's ability to detect and deny fraud. Purchase fraud can cost as much as 0.10% of purchase vol...
Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import matplotlib.gridspec as gridspec import xgboost as xgb from sklearn.model_selection import train_test_split transactions = pd.read_csv('creditcard.csv') Explanation: <h1>**ReadMe**</h1> An important part in ...
4,929
Given the following text description, write Python code to implement the functionality described below step by step Description: This is a utility notebook/script that goes through and writes all of the possible combinations of solutions to npz files. Hyperbolic/Parabolic Retrograde/Direct CM Frame/M Frame Equal Mass ...
Python Code: import numpy as np import seaborn as sns from scipy.integrate import odeint from solve import * M = 1e1 S = 1e1 Rmin = 25 e = 7 #Eccentricity r_array = np.array([.2,.3,.4,.5,.6])*Rmin N_array = np.array([12,18,24,30,36]) steps = 1e3 t = np.linspace(0,.4,steps) #Timescale of 1 billion years atol=1e-6 rtol=1...
4,930
Given the following text description, write Python code to implement the functionality described below step by step Description: Exercises Step1: Exercise 1 Step2: b. Spearman Rank Correlation Find the Spearman rank correlation coefficient for the relationship between x and y using the stats.rankdata function and th...
Python Code: import numpy as np import pandas as pd import scipy.stats as stats import matplotlib.pyplot as plt import math Explanation: Exercises: Spearman Rank Correlation Lecture Link This exercise notebook refers to this lecture. Please use the lecture for explanations and sample code. https://www.quantopian.com/le...
4,931
Given the following text description, write Python code to implement the functionality described below step by step Description: Advanced Step1: As always, let's do imports and initialize a logger and a new Bundle. See Building a System for more details. Step2: And we'll attach some dummy datasets. See Datasets fo...
Python Code: !pip install -I "phoebe>=2.0,<2.1" Explanation: Advanced: Alternate Backends 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 ph...
4,932
Given the following text description, write Python code to implement the functionality described below step by step Description: Вычисление элементарных функций Вычисление значения функции на данном аргументе является одной из важнейших задач численных методов. Несмотря на то, что вы уже огромное число раз вычисляли з...
Python Code: y=np.linspace(-2,3,100) x=np.exp(y) plt.plot(x,y) plt.xlabel('$x$') plt.ylabel('$y=\ln x$') plt.show() Explanation: Вычисление элементарных функций Вычисление значения функции на данном аргументе является одной из важнейших задач численных методов. Несмотря на то, что вы уже огромное число раз вычисляли зн...
4,933
Given the following text description, write Python code to implement the functionality described below step by step Description: Running a model and loading the simulation it produces Very simple example with the stationary dynamic system defined in test_lake.yaml. Basically it represents a stationary reservoir whose ...
Python Code: from subprocess import Popen, PIPE, STDOUT p = Popen(["../pydmmt/pydmmt.py", "test_lake.yml"], stdin=PIPE, stdout=PIPE, stderr=STDOUT) output = p.communicate(".3".encode('utf-8'))[0] # trim the '\n' newline char print(output[:-1].decode('utf-8')) Explanation: Running a model and loading the simulation it p...
4,934
Given the following text description, write Python code to implement the functionality described below step by step Description: 3. How to Setup the Initial Condition Here, we explain the basics of World classes. In E-Cell4, six types of World classes are supported now Step1: 3.1. Common APIs of World Even though Wor...
Python Code: from ecell4_base.core import * Explanation: 3. How to Setup the Initial Condition Here, we explain the basics of World classes. In E-Cell4, six types of World classes are supported now: spatiocyte.SpatiocyteWorld, egfrd.EGFRDWorld, bd.BDWorld, meso.MesoscopicWorld, gillespie.GillespieWorld, and ode.ODEWorl...
4,935
Given the following text description, write Python code to implement the functionality described below step by step Description: Rømer and Light Travel Time Effects (ltte) Setup Let's first make sure we have the latest version of PHOEBE 2.1 installed. (You can comment out this line if you don't use pip for your instal...
Python Code: !pip install -I "phoebe>=2.1,<2.2" Explanation: Rømer and Light Travel Time Effects (ltte) Setup Let's first make sure we have the latest version of PHOEBE 2.1 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 explana...
4,936
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Programming Step1: Question Step2: Passing values to functions Step3: Conclusion Step4: Initialization of variables within function definition Step5: * operator 1. Unpa...
Python Code: #Example_1: return keyword def straight_line(slope,intercept,x): "Computes straight line y value" y = slope*x + intercept return y print("y =",straight_line(1,0,5)) #Actual Parameters print("y =",straight_line(0,3,10)) #By default, arguments have a positional behaviour #Each of the parameters h...
4,937
Given the following text description, write Python code to implement the functionality described below step by step Description: Hough Transform Step1: Hough transform combined with a polygonal mask Notice that lines are more well-defined
Python Code: import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import cv2 # convert to grayscale and smooth with a Gaussian img = mpimg.imread('testimg.jpg') gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) kernel_size = 5 blurred = cv2.GaussianBlur(gray_img, (kernel_size, kernel_size)...
4,938
Given the following text description, write Python code to implement the functionality described below step by step Description: Prepare babyweight dataset. Learning Objectives Setup up the environment Preprocess natality dataset Augment natality dataset Create the train and eval tables in BigQuery Export data from Bi...
Python Code: !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst !pip install --user google-cloud-bigquery==1.25.0 Explanation: Prepare babyweight dataset. Learning Objectives Setup up the environment Preprocess natality dataset Augment natality dataset Create the train and eval tables in BigQuery Export...
4,939
Given the following text description, write Python code to implement the functionality described below step by step Description: FastText Model Introduces Gensim's fastText model and demonstrates its use on the Lee Corpus. Step1: Here, we'll learn to work with fastText library for training word-embedding models, savi...
Python Code: import logging logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) Explanation: FastText Model Introduces Gensim's fastText model and demonstrates its use on the Lee Corpus. End of explanation from pprint import pprint as print from gensim.models.fasttext import Fast...
4,940
Given the following text description, write Python code to implement the functionality described below step by step Description: Head model and forward computation The aim of this tutorial is to be a getting started for forward computation. For more extensive details and presentation of the general concepts for forwar...
Python Code: import os.path as op import mne from mne.datasets import sample data_path = sample.data_path() # the raw file containing the channel location + types sample_dir = op.join(data_path, 'MEG', 'sample',) raw_fname = op.join(sample_dir, 'sample_audvis_raw.fif') # The paths to Freesurfer reconstructions subjects...
4,941
Given the following text description, write Python code to implement the functionality described below step by step Description: Enter Team Member Names here (double click to edit) Step1: Question 1 Step2: Question 3 Step3: <a id="svm_using"></a> <a href="#top">Back to Top</a> Using Linear SVMs Exercise 1 Step4: O...
Python Code: # fetch the images for the dataset # this will take a long time the first run because it needs to download # after the first time, the dataset will be save to your disk (in sklearn package somewhere) # if this does not run, you may need additional libraries installed on your system (install at your own ri...
4,942
Given the following text description, write Python code to implement the functionality described below step by step Description: Creación de las imágenes georreferenciadas El resultado final de la selección de puntos en NightCitiesISS y su correspondencia con las coordenadas, permite crear un fichero en formato GeoTIF...
Python Code: import urllib2 import json import asciitable import time import Image idISS = 'ISS030-E-211378' dirImagenesISS = 'images/' dirGeoTIFF = 'geotiff/' dirPuntosQGIS = 'puntosQGIS/' dirPuntosGlobal = 'puntosGlobal/' dirScriptsGDAL = 'scriptsGdal/' def getKey(item): return item[0] hayProxy = False # cargo las t...
4,943
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: Load and preprocess images <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: Download the flo...
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...
4,944
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>Содержание<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Форматирование" data-toc-modified-id="Форматирование-1">Форматирование</a></span><u...
Python Code: # Правильно if 1 == 3: print(1) if 2 == 3: print(2) # Неверно if 1 == 3: print(1) if 2 == 3: print(2) Explanation: <h1>Содержание<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Форматирование" data-toc-modified-id="Форматирование-...
4,945
Given the following text description, write Python code to implement the functionality described below step by step Description: Advanced SQLAlchemy Queries Step1: Using MySql Import the create_engine function from the sqlalchemy library. Create an engine to the census database by concatenating the following strings ...
Python Code: # import Explanation: Advanced SQLAlchemy Queries End of explanation # # Import create_engine function # from sqlalchemy import create_engine # # Create an engine to the census database # engine = create_engine('mysql+pymysql://student:datacamp@courses.csrrinzqubik.us-east-1.rds.amazonaws.com:3306/census')...
4,946
Given the following text description, write Python code to implement the functionality described below step by step Description: The Info data structure This tutorial describes the Step1: As seen in the introductory tutorial &lt;tut-overview&gt;, when a Step2: However, it is not strictly necessary to load the Step...
Python Code: import os import mne sample_data_folder = mne.datasets.sample.data_path() sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample', 'sample_audvis_filt-0-40_raw.fif') raw = mne.io.read_raw_fif(sample_data_raw_file) Explanation: The Info data structure This...
4,947
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Seaice MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify ...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'nasa-giss', 'sandbox-3', 'seaice') Explanation: ES-DOC CMIP6 Model Properties - Seaice MIP Era: CMIP6 Institute: NASA-GISS Source ID: SANDBOX-3 Topic: Seaice Sub-Topics: Dynamics, The...
4,948
Given the following text description, write Python code to implement the functionality described below step by step Description: Model Architectures Step1: We also set up the backend and load the data. Step2: Now its your turn! Set up the branch nodes and layer structure above. Some tips Step3: Now let's fit our mo...
Python Code: from neon.callbacks.callbacks import Callbacks from neon.initializers import Gaussian from neon.layers import GeneralizedCost, Affine, BranchNode, Multicost, SingleOutputTree from neon.models import Model from neon.optimizers import GradientDescentMomentum from neon.transforms import Rectlin, Logistic, Sof...
4,949
Given the following text description, write Python code to implement the functionality described below step by step Description: Dans ce notebook, nous allons essayer de faire du text mining pour récuper des versions locales des programmes des présidentielles 2017 des candidats suivants Step1: François Fillon Le pro...
Python Code: from bs4 import BeautifulSoup import requests import re import pandas as pd from ipywidgets import interact def make_df_from_props_sources(props_sources): "Makes a big dataframe from props_sources." dfs = [] for key in props_sources: df = pd.DataFrame(props_sources[key], columns=['propo...
4,950
Given the following text description, write Python code to implement the functionality described below step by step Description: PyTorch Implementation Simple version 가장 일반적인 파이토치 구현 방법으로 케라스된 예제 1-1을 변환한다. Step1: Detail version with monitoring variables 파이토치로 변환된 코드가 제대로 동작하는지 중간 중간을 모니터링 한다. Step2: Compatible vers...
Python Code: import torch import numpy as np x = np.array([0, 1, 2, 3, 4]).astype('float32').reshape(-1,1) y = x * 2 + 1 class Model(torch.nn.Module): def __init__(self): super(Model,self).__init__() self.layer = torch.nn.Linear(1,1) def forward(self, x): return self.layer(x) model = Mo...
4,951
Given the following text description, write Python code to implement the functionality described below step by step Description: Model checking and diagnostics Convergence Diagnostics Valid inferences from sequences of MCMC samples are based on the assumption that the samples are derived from the true posterior distri...
Python Code: %matplotlib inline from pymc.examples import gelman_bioassay from pymc import MCMC, Matplot, Metropolis import seaborn as sns; sns.set_context('notebook') M = MCMC(gelman_bioassay) M.use_step_method(Metropolis, M.alpha, scale=0.001) M.sample(1000, tune_interval=1000) Matplot.plot(M.alpha) Explanation: Mode...
4,952
Given the following text description, write Python code to implement the functionality described below step by step Description: Homework #4 These problem sets focus on list comprehensions, string operations and regular expressions. Problem set #1 Step1: In the following cell, complete the code with an expression tha...
Python Code: numbers_str = '496,258,332,550,506,699,7,985,171,581,436,804,736,528,65,855,68,279,721,120' Explanation: Homework #4 These problem sets focus on list comprehensions, string operations and regular expressions. Problem set #1: List slices and list comprehensions Let's start with some data. The following cell...
4,953
Given the following text description, write Python code to implement the functionality described below step by step Description: Exporting Epochs to Pandas DataFrames This tutorial shows how to export the data in Step1: Next we'll load a list of events from file, map them to condition names with an event dictionary,...
Python Code: import os import matplotlib.pyplot as plt import seaborn as sns import mne sample_data_folder = mne.datasets.sample.data_path() sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample', 'sample_audvis_filt-0-40_raw.fif') raw = mne.io.read_raw_fif(sample_da...
4,954
Given the following text description, write Python code to implement the functionality described below step by step Description: Ejemplo de word2vec con gensim En la siguiente celda, importamos las librerías necesarias y configuramos los mensajes de los logs. Step1: Entrenamiento de un modelo Implemento una clase Cor...
Python Code: import gensim, logging, os logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) Explanation: Ejemplo de word2vec con gensim En la siguiente celda, importamos las librerías necesarias y configuramos los mensajes de los logs. End of explanation class Corpus(object): ...
4,955
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: What is an efficient way of splitting a column into multiple rows using dask dataframe? For example, let's say I have a csv file which I read using dask to produce the following das...
Problem: import pandas as pd df = pd.DataFrame([["A", "Z,Y"], ["B", "X"], ["C", "W,U,V"]], index=[1,2,3], columns=['var1', 'var2']) def g(df): return df.drop('var2', axis=1).join(df.var2.str.split(',', expand=True).stack(). reset_index(drop=True, level=1).rename('var2')) resu...
4,956
Given the following text description, write Python code to implement the functionality described below step by step Description: ..# Activ Spyder - Captura de página do ActivUfrj * This file is part of program Activ Spyder * Copyright © 2022 Carlo Oliveira &#99;&#97;&#114;&#108;&#111;&#64;&#110;&#99;&#101;&#46;&#11...
Python Code: import pandas as pd df = pd.read_json("../author_data.json") df.info() df Explanation: ..# Activ Spyder - Captura de página do ActivUfrj * This file is part of program Activ Spyder * Copyright © 2022 Carlo Oliveira &#99;&#97;&#114;&#108;&#111;&#64;&#110;&#99;&#101;&#46;&#117;&#102;&#114;&#106;&#46;&#98;...
4,957
Given the following text description, write Python code to implement the functionality described below step by step Description: Programming hands on 習うより慣れろ!(narau yori narero) more practice, less learning; practice makes perfect. a + b input Step1: a+b modified (1) Add grand total at the end of line. input Step2:...
Python Code: # write answer Explanation: Programming hands on 習うより慣れろ!(narau yori narero) more practice, less learning; practice makes perfect. a + b input: each line contains 2 integer output: print sum of the 2 integer input: input_ab.txt, output: standard out ``` sample input: 1 1 100 150 123 321 11112222 22223333...
4,958
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Hub Authors. Licensed under the Apache License, Version 2.0 (the "License"); Step3: 使用膨胀 3D CNN 进行动作识别 <table class="tfo-notebook-buttons" align="left"> <td>...
Python Code: # Copyright 2018 The TensorFlow Hub Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
4,959
Given the following text description, write Python code to implement the functionality described below step by step Description: Transfer Learning Most of the time you won't want to train a whole convolutional network yourself. Modern ConvNets training on huge datasets like ImageNet take weeks on multiple GPUs. Instea...
Python Code: from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm vgg_dir = 'tensorflow_vgg/' # Make sure vgg exists if not isdir(vgg_dir): raise Exception("VGG directory doesn't exist!") class DLProgress(tqdm): last_block = 0 def hook(self, block_num=1, block_size=...
4,960
Given the following text description, write Python code to implement the functionality described below step by step Description: Class Session 4 Exercise Step1: Now, define a function that returns the index numbers of the neighbors of a vertex i, when the graph is stored in adjacency matrix format. So your function...
Python Code: import numpy as np import igraph import timeit import itertools Explanation: Class Session 4 Exercise: Comparing asymptotic running time for enumerating neighbors of all vertices in a graph We will measure the running time for enumerating the neighbor vertices for three different data structures for repres...
4,961
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Lecture 7 Software design, documentation, and testing Design of a program From the Practice of Programming Step3: Documenting Invariants An invariant is something that is true at som...
Python Code: def quad_roots(a=1.0, b=2.0, c=0.0): Returns the roots of a quadratic equation: ax^2 + bx + c = 0. INPUTS ======= a: float, optional, default value is 1 Coefficient of quadratic term b: float, optional, default value is 2 Coefficient of linear term c: float, optio...
4,962
Given the following text description, write Python code to implement the functionality described below step by step Description: Parse_data_to_tfrecord_library Test This file consists several function test for the functions in the Parse_data_to_tfrecord_lib file. Step1: Test function img_to_example() Step2: Function...
Python Code: from parse_data_to_tfrecord_lib import img_to_example, read_tfrecord, generate_tfexamples_from_detections, batch_read_write_tfrecords from PIL import Image # used to read images from directory import tensorflow as tf import os import io import IPython.display as display import numpy as np tf.enable_eager_...
4,963
Given the following text description, write Python code to implement the functionality described below step by step Description: <img src=images/continuum_analytics_b&w.png align="left" width="15%" style="margin-right Step1: Exercise Step2: Exercise
Python Code: # Import the functions from your file # Create your plots with your new functions # Test the visualizations in the notebook from bokeh.plotting import show, output_notebook # Show climate map # Show legend # Show timeseries Explanation: <img src=images/continuum_analytics_b&w.png align="left" width="15%" s...
4,964
Given the following text description, write Python code to implement the functionality described below step by step Description: Showcase of various CogStat analyses Below you can see a few examples what analyses are perfomed for a specific task in CogStat. Note that the specific analyses that are applied depend on th...
Python Code: %matplotlib inline import os import warnings warnings.filterwarnings('ignore') from cogstat import cogstat as cs print(cs.__version__) cs_dir, dummy_filename = os.path.split(cs.__file__) # We use this for the demo data Explanation: Showcase of various CogStat analyses Below you can see a few examples what...
4,965
Given the following text description, write Python code to implement the functionality described below step by step Description: Train nodule detector with LUNA16 dataset Step1: Analyse input data Let us import annotations Step2: Lets take a look at some images Step3: Classes are heaviliy unbalanced, hardly 0.2% pe...
Python Code: INPUT_DIR = '../../input/' OUTPUT_DIR = '../../output/lung-cancer/01/' IMAGE_DIMS = (50,50,50,1) %matplotlib inline import numpy as np import pandas as pd import h5py import matplotlib.pyplot as plt import sklearn import os import glob from modules.logging import logger import modules.utils as utils from m...
4,966
Given the following text description, write Python code to implement the functionality described below step by step Description: Automatically find the center of the speckle pattern and most intense rings Step1: Two examples to demonstarte automatically find the center of the speckle pattern and most intense 4 rings ...
Python Code: import skbeam.core.roi as roi import numpy as np import matplotlib.pyplot as plt %matplotlib notebook x = np.linspace(-5,5,200) X,Y = np.meshgrid(x,x) Z = 100*np.cos(np.sqrt(x**2 + Y**2))**2 + 50 center, image, radii = roi.auto_find_center_rings(Z, sigma=20, no_rings=5) fig, ax = plt.subplots() ax.scatter(...
4,967
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Generation Step1: Solution Step2: Use matching indices Instead of iterating through indices, one can use them directly to parallelize the operations with Numpy. Step3: Use a library ...
Python Code: np.random.seed(10) p, q = (np.random.rand(i, 2) for i in (4, 5)) p_big, q_big = (np.random.rand(i, 80) for i in (100, 120)) print(p, "\n\n", q) Explanation: Data Generation End of explanation def naive(p, q): ''' fill your code in here... ''' Explanation: Solution End of explanation rows, cols = np...
4,968
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial Brief This tutorial is an introduction to Python 3. This should give you the set of pythonic skills that you will need to proceed with this tutorial series. If you don't have the Ju...
Python Code: 1+2 1+1 1+2 Explanation: Tutorial Brief This tutorial is an introduction to Python 3. This should give you the set of pythonic skills that you will need to proceed with this tutorial series. If you don't have the Jupyter installed, shame on you. No just kidding you can follow this tutorial using an online ...
4,969
Given the following text description, write Python code to implement the functionality described below step by step Description: No Show Appointments Analysis <a id='intro'></a> Introduction Purpose To perform a Data analysis on a sample Dataset of No-show Appointments This Dataset contains the records of the patients...
Python Code: # Render plots inline %matplotlib inline # Import Libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns # Set style for all graphs sns.set(style="whitegrid") # Read in the Dataset, creat dataframe appointment_data = pd.read_csv('noshow.csv') # Print the firs...
4,970
Given the following text description, write Python code to implement the functionality described below step by step Description: How to Compare LDA Models Demonstrates how you can visualize and compare trained topic models. Step2: First, clean up the 20 Newsgroups dataset. We will use it to fit LDA. Step3: Second, f...
Python Code: # sphinx_gallery_thumbnail_number = 2 import logging logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) Explanation: How to Compare LDA Models Demonstrates how you can visualize and compare trained topic models. End of explanation from string import punctuation from...
4,971
Given the following text description, write Python code to implement the functionality described below step by step Description: Problem The number of shoes sold by an e-commerce company during the first three months(12 weeks) of the year were Step1: On average, the sales after optimization is more than the sales bef...
Python Code: import numpy as np import seaborn as sns sns.set(color_codes=True) %matplotlib inline #Load the data before_opt = np.array([23, 21, 19, 24, 35, 17, 18, 24, 33, 27, 21, 23]) after_opt = np.array([31, 28, 19, 24, 32, 27, 16, 41, 23, 32, 29, 33]) before_opt.mean() after_opt.mean() observed_difference = after_...
4,972
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 The TensorFlow Authors. Licensed under the Apache License, Version 2.0 (the "License"); Step1: 使用 tf.data 加载 pandas dataframes <table class="tfo-notebook-buttons" align="left...
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...
4,973
Given the following text description, write Python code to implement the functionality described below step by step Description: Advent of Code 2017 December 4th To ensure security, a valid passphrase must contain no duplicate words. For example Step1: I'll assume the input is a Joy sequence of sequences of integers....
Python Code: from notebook_preamble import J, V, define Explanation: Advent of Code 2017 December 4th To ensure security, a valid passphrase must contain no duplicate words. For example: aa bb cc dd ee is valid. aa bb cc dd aa is not valid - the word aa appears more than once. aa bb cc dd aaa is valid - aa and aaa coun...
4,974
Given the following text description, write Python code to implement the functionality described. Description: Number of ways to arrange a word such that no vowels occur together Function to check if a character is vowel or consonent ; Function to calculate factorial of a number ; Calculating no of ways for arranging v...
Python Code: def isVowel(ch ) : if(ch == ' a ' or ch == ' e ' or ch == ' i ' or ch == ' o ' or ch == ' u ' ) : return True  else : return False   def fact(n ) : if(n < 2 ) : return 1  return n * fact(n - 1 )  def only_vowels(freq ) : denom = 1 cnt_vwl = 0 for itr in freq : if(isVow...
4,975
Given the following text description, write Python code to implement the functionality described below step by step Description: Example with real audio recordings The iterations are dropped in contrast to the offline version. To use past observations the correlation matrix and the correlation vector are calculated re...
Python Code: channels = 8 sampling_rate = 16000 delay = 3 alpha=0.9999 taps = 10 frequency_bins = stft_options['size'] // 2 + 1 Explanation: Example with real audio recordings The iterations are dropped in contrast to the offline version. To use past observations the correlation matrix and the correlation vector are ca...
4,976
Given the following text description, write Python code to implement the functionality described below step by step Description: qp Demo Alex Malz & Phil Marshall In this notebook we use the qp module to approximate some simple, standard, 1-D PDFs using sets of quantiles, samples, and histograms, and assess their rela...
Python Code: import numpy as np import scipy.stats as sps import scipy.interpolate as spi import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt %matplotlib inline import qp Explanation: qp Demo Alex Malz & Phil Marshall In this notebook we use the qp module to approximate some simple, standard, 1-D PD...
4,977
Given the following text description, write Python code to implement the functionality described below step by step Description: Stats practice Testing for normality Step1: Make probability plots Step2: Interesting. Normal distribution follows the quantiles well and has the highest $R^2$ value, but both the uniform ...
Python Code: %matplotlib inline from matplotlib import pyplot as plt from random import normalvariate, uniform, weibullvariate # Make several sets of data; one randomly sampled # from a normal distribution and others that aren't. n = 100 d_norm = [normalvariate(0,1) for x in range(n)] d_unif = [uniform(0,1) for x in r...
4,978
Given the following text description, write Python code to implement the functionality described below step by step Description: Modelado de un sistema con ipython Para el correcto funcionamiento del extrusor de filamento, es necesario regular correctamente la temperatura a la que está el cañon. Por ello se usará un s...
Python Code: #Importamos las librerías utilizadas import numpy as np import pandas as pd import seaborn as sns import matplotlib.pylab as plt #Mostramos las versiones usadas de cada librerías print ("Numpy v{}".format(np.__version__)) print ("Pandas v{}".format(pd.__version__)) print ("Seaborn v{}".format(sns.__version...
4,979
Given the following text description, write Python code to implement the functionality described below step by step Description: EEG forward operator with a template MRI This tutorial explains how to compute the forward operator from EEG data using the standard template MRI subject fsaverage. .. caution Step1: Load t...
Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Joan Massich <mailsik@gmail.com> # # License: BSD Style. import os.path as op import mne from mne.datasets import eegbci from mne.datasets import fetch_fsaverage # Download fsaverage files fs_dir = fetch_fsaverage(verbose=True) subjects...
4,980
Given the following text description, write Python code to implement the functionality described below step by step Description: Topic Modelling Author Step1: 1. Corpus acquisition. In this notebook we will explore some tools for text processing and analysis and two topic modeling algorithms available from Python too...
Python Code: # %matplotlib inline import numpy as np import matplotlib.pyplot as plt # import pylab # Required imports from wikitools import wiki from wikitools import category import nltk from nltk.tokenize import word_tokenize from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer import gensim imp...
4,981
Given the following text description, write Python code to implement the functionality described below step by step Description: Usage example To showcase the use of this toolkit, we first create a simple learning task, and then learn an OOM model using spectral learning. We start by importing the toolkit and initiali...
Python Code: import tom import numpy as np import matplotlib.pyplot as plt %matplotlib inline rand = tom.Random(1234567) Explanation: Usage example To showcase the use of this toolkit, we first create a simple learning task, and then learn an OOM model using spectral learning. We start by importing the toolkit and init...
4,982
Given the following text description, write Python code to implement the functionality described below step by step Description: Gradient Boosting From Scratch Let's implement gradient boosting from scratch. Step1: Exploration Let explore the data before building a model. The goal is to predict the median value of ow...
Python Code: from __future__ import print_function import numpy as np import pandas as pd import seaborn as sns from matplotlib import pyplot as plt from sklearn.tree import DecisionTreeRegressor from tensorflow.keras.datasets import boston_housing np.random.seed(0) plt.rcParams['figure.figsize'] = (8.0, 5.0) plt.rcPar...
4,983
Given the following text description, write Python code to implement the functionality described below step by step Description: Custom Jupyter Widgets The Hello World Example of the Cookie Cutter The widget framework is built on top of the Comm framework (short for communication). The Comm framework is a framework t...
Python Code: import ipywidgets as widgets from traitlets import Unicode class HelloWidget(widgets.DOMWidget): _view_name = Unicode('HelloView').tag(sync=True) _view_module = Unicode('hello').tag(sync=True) Explanation: Custom Jupyter Widgets The Hello World Example of the Cookie Cutter The widget framework is b...
4,984
Given the following text description, write Python code to implement the functionality described below step by step Description: MNIST Image Classification with TensorFlow on Cloud AI Platform This notebook demonstrates how to implement different image models on MNIST using the tf.keras API. Learning objectives Unders...
Python Code: !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst # Here we'll show the currently installed version of TensorFlow import tensorflow as tf print(tf.__version__) from datetime import datetime import os PROJECT = "your-project-id-here" # REPLACE WITH YOUR PROJECT ID BUCKET = "your-bucket-id-...
4,985
Given the following text description, write Python code to implement the functionality described below step by step Description: Sebastian Raschka, 2015 Python Machine Learning Chapter 13 - Parallelizing Neural Network Training with Theano Note that the optional watermark extension is a small IPython notebook plugin t...
Python Code: %load_ext watermark %watermark -a 'Sebastian Raschka' -u -d -v -p numpy,matplotlib,theano,keras # to install watermark just uncomment the following line: #%install_ext https://raw.githubusercontent.com/rasbt/watermark/master/watermark.py Explanation: Sebastian Raschka, 2015 Python Machine Learning Chapter ...
4,986
Given the following text description, write Python code to implement the functionality described below step by step Description: Sentiment analysis with TFLearn In this notebook, we'll continue Andrew Trask's work by building a network for sentiment analysis on the movie review data. Instead of a network written with ...
Python Code: import pandas as pd import numpy as np import tensorflow as tf import tflearn from tflearn.data_utils import to_categorical Explanation: Sentiment analysis with TFLearn In this notebook, we'll continue Andrew Trask's work by building a network for sentiment analysis on the movie review data. Instead of a n...
4,987
Given the following text description, write Python code to implement the functionality described below step by step Description: First TensorFlow Graphs In this notebook, we execute elementary TensorFlow computational graphs. Load dependencies Step1: Simple arithmetic Step2: Simple array arithmetic
Python Code: import numpy as np import tensorflow as tf Explanation: First TensorFlow Graphs In this notebook, we execute elementary TensorFlow computational graphs. Load dependencies End of explanation x1 = tf.placeholder(tf.float32) x2 = tf.placeholder(tf.float32) sum_op = tf.add(x1, x2) product_op = tf.multiply(x1, ...
4,988
Given the following text description, write Python code to implement the functionality described below step by step Description: Lecture 2 Step1: Mass-spring-damper system The differential equation that governs an unforced, single degree-of-freedom mass-spring-damper system is $$ m \frac{d^{2}y}{dt^{2}} + \lambda \fr...
Python Code: from sympy import * # This initialises pretty printing init_printing() from IPython.display import display # This command makes plots appear inside the browser window %matplotlib inline Explanation: Lecture 2: second-order ordinary differential equations We now look at solving second-order ordinary differe...
4,989
Given the following text description, write Python code to implement the functionality described below step by step Description: Regression Week 3 Step1: Next we're going to write a polynomial function that takes an SArray and a maximal degree and returns an SFrame with columns containing the SArray to all the powers...
Python Code: import graphlab Explanation: Regression Week 3: Assessing Fit (polynomial regression) In this notebook you will compare different regression models in order to assess which model fits best. We will be using polynomial regression as a means to examine this topic. In particular you will: * Write a function t...
4,990
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Image Classification In this project, you'll classify images from the CIFAR-10 dataset. The dataset consists of airplanes, dogs, cats, and other objects. You'll preprocess the images...
Python Code: DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm import problem_unittests as tests import tarfile cifar10_dataset_folder_path = 'cifar-10-batches-py' # Use Floyd's cifar-10 dataset if present floyd_cifa...
4,991
Given the following text description, write Python code to implement the functionality described below step by step Description: 3. Data preparation Step1: 3.1 Select Data Outputs Step2: 3.3 Construct Data Outputs
Python Code: import nltk import pandas as pd import math %matplotlib inline import matplotlib import matplotlib.pyplot as plt from matplotlib import gridspec from sklearn import datasets, linear_model import numpy as np from numbers import Number from sklearn import preprocessing def correlation_matrix(df,figsize=(15,1...
4,992
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', 'nerc', 'sandbox-3', 'land') Explanation: ES-DOC CMIP6 Model Properties - Land MIP Era: CMIP6 Institute: NERC Source ID: SANDBOX-3 Topic: Land Sub-Topics: Soil, Snow, Vegetation, Energ...
4,993
Given the following text description, write Python code to implement the functionality described below step by step Description: Today's meeting opened the topic of building interactive figures in Python. This notebook will show an example of using ipywidgets module, more specifically interact() function. The full doc...
Python Code: import warnings warnings.filterwarnings('ignore') Explanation: Today's meeting opened the topic of building interactive figures in Python. This notebook will show an example of using ipywidgets module, more specifically interact() function. The full documentation can be found on the ipywidgets website, but...
4,994
Given the following text description, write Python code to implement the functionality described below step by step Description: Integration Exercise 1 Imports Step2: Trapezoidal rule The trapezoidal rule generates a numerical approximation to the 1d integral Step3: Now use scipy.integrate.quad to integrate the f an...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from scipy import integrate Explanation: Integration Exercise 1 Imports End of explanation def trapz(f, a, b, N): Integrate the function f(x) over the range [a,b] with N points. k = np.arange(1,N) h = (b-a)/N I = h*0.5*f(...
4,995
Given the following text description, write Python code to implement the functionality described below step by step Description: Live-updating multi-tau one-time correlation with synthetic and real data Step1: First, let's demo with synthetic data. The plot a few cells down should live update with the first value of ...
Python Code: from skbeam.core.correlation import lazy_one_time import numpy as np import time as ttime import matplotlib.pyplot as plt %matplotlib notebook Explanation: Live-updating multi-tau one-time correlation with synthetic and real data End of explanation num_levels = 5 num_bufs = 4 # must be even xdim = 512 ydi...
4,996
Given the following text description, write Python code to implement the functionality described below step by step Description: MatPlotLib Basics Draw a line graph Step1: Mutiple Plots on One Graph Step2: Save it to a File Step3: Adjust the Axes Step4: Add a Grid Step5: Change Line Types and Colors Step6: Label...
Python Code: %matplotlib inline from scipy.stats import norm import matplotlib.pyplot as plt import numpy as np x = np.arange(-3, 3, 0.001) plt.plot(x, norm.pdf(x)) plt.show() Explanation: MatPlotLib Basics Draw a line graph End of explanation plt.plot(x, norm.pdf(x)) plt.plot(x, norm.pdf(x, 1.0, 0.5)) plt.show() Expla...
4,997
Given the following text description, write Python code to implement the functionality described below step by step Description: Basic Concepts What is "learning from data"? In general Learning from Data is a scientific discipline that is concerned with the design and development of algorithms that allow computers to ...
Python Code: # numerical derivative at a point x def f(x): return x**2 def fin_dif(x, f, h = 0.00001): ''' This method returns the derivative of f at x by using the finite difference method ''' return (f(x+h) - f(x))/h x = 2.0 print "{:2.4f}".format(fin_dif(x,f)) Explan...
4,998
Given the following text description, write Python code to implement the functionality described below step by step Description: 1A.e - Correction de l'interrogation écrite du 14 novembre 2014 coût algorithmique, calcul de séries mathématiques Step1: Enoncé 1 Q1 Le code suivant produit une erreur. Corrigez le program...
Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() Explanation: 1A.e - Correction de l'interrogation écrite du 14 novembre 2014 coût algorithmique, calcul de séries mathématiques End of explanation nbs = [ 1, 5, 4, 7 ] # for n in nbs: # s += n # Explanation: Enoncé 1...
4,999
Given the following text description, write Python code to implement the functionality described below step by step Description: From raw data to dSPM on SPM Faces dataset Runs a full pipeline using MNE-Python Step1: Load and filter data, set up epochs Step2: Visualize fields on MEG helmet Step3: Look at the whiten...
Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Denis Engemann <denis.engemann@gmail.com> # # License: BSD (3-clause) import matplotlib.pyplot as plt import mne from mne.datasets import spm_face from mne.preprocessing import ICA, create_eog_epochs from mne import io, combine_evoked f...